blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ce12d0bff493879ce3a5b0be8d119b6f411abfba
jeckjeck/pythonkurs
/inlamning2.py
1,718
3.625
4
# Programmeringstek cklund # 2017-06-06 # scriptet har en klass med metoder som läser in fyra meningar och skriver ut dem som en dikt class Dikt: # Skapar klass då vi har flera metoder som är lik varann def __init__(self): """Denna metod körs automatiskt när dikt anropas""" self.meningar = None # Sätter dessa instansvariabler till None så pycharm inte varnar self.mening_ett_split = None self.forsta = None self.resten = None def inmatning(self): """Skapar första metoden med parametern self, som står för att den bara ska ta in instansvariabler""" self.meningar = [input('Skriv mening nr %s:' % i) for i in range(1, 5)] # användaren får inputta sina meningar # här, for loop för att slippa skriva flera rader, range(1,5) # betyder att det kommer skrivas in 1-4 istället för %s def dela_upp(self): """denna metod splittar 1:a meningen och slår ihop dens 4 första och sista ord till en ny instans variabel.""" self.mening_ett_split = self.meningar[0].split() self.forsta = ' '.join(self.mening_ett_split[:4]) self.resten = ' '.join(self.mening_ett_split[4:]) def skriv_ut(self): """skriver ut dikten på rätt sätt""" print(self.forsta.upper()) print("\n") print(self.forsta) print(self.resten) print(self.forsta) print('\n' .join([self.meningar[i] for i in range(1, 4)])) # print resterande meningar separerade med "ny rad" print(self.forsta) def runner(): d = Dikt() d.inmatning() d.dela_upp() d.skriv_ut() runner()
d7601439236de680d7be8dec537e5547e0bf27f0
UniBus/Server
/data_management/modules/gtfs/server/citydb.py
1,536
4.03125
4
#! /usr/bin/python ## This module creates a mySQL database # # It take one parameter, as # # create_db $dbName # import csv import MySQLdb import sys import string import os def create_db(dbhost, dbuser, dbpass, dbname): print "Create a MySQL database." try: #create database if it doesn't exist print " [*] Connecting to databae server." conn = MySQLdb.connect(host = dbhost, user = dbuser, passwd = dbpass) cursor = conn.cursor() print " [*] Createing databae %s." %dbname cursor.execute("""CREATE DATABASE IF NOT EXISTS """ + dbname) conn.commit() conn.close() print " [*] Databae created." print " [*] Done \n" except MySQLdb.Error, e: print "Error %d %s\n" % (e.args[0], e.args[1]) sys.exit(1) def drop_db(dbname): print "Delete a MySQL database." try: #create database if it doesn't exist print " [*] Connecting to databae server." conn = MySQLdb.connect(host = dbhost, user = dbuser, passwd = dbpass) cursor = conn.cursor() print " [*] Deleteing databae %s." %dbname cursor.execute("""DROP DATABASE IF EXISTS """ + dbname) conn.commit() conn.close() print " [*] Databae deleted." print " [*] Done \n" except MySQLdb.Error, e: print "Error %d %s\n" % (e.args[0], e.args[1]) sys.exit(1) def create(dbhost, dbuser, dbpass, dbname): create_db(dbhost, dbuser, dbpass, dbname) def drop(dbname): drop_db(dbhost, dbuser, dbpass, dbname)
fe46ad7776361a6476373fa89db1c3633996a245
uiandwe/TIL
/algorithm/LC/202.py
582
3.53125
4
# -*- coding: utf-8 -*- import math class Solution: def isHappy(self, n: int) -> bool: d = set() while True: n = self.cal(n) if n in d: return False elif n == 1: return True d.add(n) def cal(self, n): ret = 0 while n >= 10: ret += pow((n % 10), 2) n = n // 10 ret += pow(n, 2) return ret s = Solution() assert s.isHappy(19) is True assert s.isHappy(1) is True assert s.isHappy(2) is False assert s.isHappy(7) is True
8f3b82edf1184d92c1713399957fba7235a0b8cf
PawelGilecki/python
/list overlap.py
296
3.5
4
import random c = random.sample(range(1, 100), 15) d = random.sample(range(1, 100), 12) print(c) print(d) a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] new = [] for element in c: if element in d: new.append(element) print(new)
c981fcbbe86e834cde49392c5fb850d95d4495d9
IrisNotSiri/sort-practise
/main.py
2,094
4
4
#bubble sort def bubble_sort(nums): if nums is None: return None for n in range(len(nums)-1): for n in range(len(nums)-1): if nums[n] > nums[n+1]: nums[n], nums[n+1] = nums[n+1], nums[n] return nums def insertion_sort(nums): if nums is None: return None for i in range(1, len(nums)): key = nums[i] j = i-1 while j >= 0 and nums[j] > key: nums[j+1] = nums[j] j -= 1 nums[j+1] = key return nums def selection_sort(nums): if nums is None: return None for i in range(len(nums)): min_index = i for j in range(i+1, len(nums)): if nums[min_index] > nums[j]: min_index = j nums[i], nums[min_index] = nums[min_index], nums[i] return nums def merge_sort(nums): if nums is None: return None if len(nums) > 1: mid = len(nums)//2 left = nums[:mid] right = nums[mid:] #split list into two half with recursion merge_sort(left) merge_sort(right) # merge left and right half i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: nums[k] = left[i] i += 1 else: nums[k] = right[j] j += 1 k += 1 # check and add the remaining number in the left or right list while i < len(left): nums[k] = left[i] i += 1 k += 1 while j < len(right): nums[k] = right[j] j += 1 k += 1 return def quick_sort(nums,low,high): if nums is None: return None if low < high: i = low - 1 pivot = nums[high] for j in range(low, high): if nums[j] < pivot: i += 1 nums[i], nums[j] = nums[j], nums[i] nums[i+1], nums[high] = nums[high], nums[i+1] n = i+1 quick_sort(nums,low,n-1) quick_sort(nums,n+1,high) return nums = [9,8,7,5,4,3,6,2,1] # low = 0 # high = len(nums)-1 merge_sort(nums) print (nums) t=[3,4,5]
d4a2b559824ee4acfd061604d24643653eb2f183
hubert-cyber/ExamenEnPython
/AlgoritmoDeVacunacionCovid-19-HLT.py
611
3.5625
4
#Vacunacion contra el covid-19 #Datos de entrada sexo='femenino' sexo= 'masculino' edad=int(input("Ingrese su edad → ")) sexo=(input("Ingrese su sexo → ")) #proceso print() if edad >= 70 : vacunaS="Tipo C" if sexo== 'masculino' : print(vacunaS) vacunaS="Tipo C" if sexo== 'femenino': print(vacunaS) vacunaS="Tipo C" if edad >=16 and edad <=69: if sexo == 'masculino': vacunaB = "Tipo B" print(vacunaB) if sexo == 'femenino': vacunaA = "Tipo A" print(vacunaA) if edad <16 : vacunA= "Tipo A" print(vacunA)
8995c9c420f3869841374b53f2b7397298f0f6f6
a100kpm/daily_training
/problem 0191.py
1,293
3.6875
4
''' Good morning! Here's your coding interview problem for today. This problem was asked by Stripe. Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Intervals can "touch", such as [0, 1] and [1, 2], but they won't be considered overlapping. For example, given the intervals (7, 9), (2, 4), (5, 8), return 1 as the last interval can be removed and the first two won't overlap. The intervals are not necessarily sorted in any order. ''' interval = [(7,9),(2,4),(5,8)] import numpy as np def number_to_del(interval): graph=make_intersect_graph(interval) def make_intersect_graph(interval): lenn=len(interval) graph=np.zeros([lenn,lenn]) for i in range(lenn): min1=interval[i][0] max1=interval[i][1] for j in range(lenn): if i==j: pass else: min2=interval[j][0] max2=interval[j][1] if (min1<max2 and max1>min2) or (min2<max1 and max2>min1): graph[i][j]=1 return graph def retire_elem(graph,pos): graph=np.delete(graph,pos,0) graph=np.delete(graph,pos,1) return graph
e04e437ec5cba5579097fa35f2ed1dbcff1812c3
FerumFlex/python-pinterest
/pinterest/comment.py
4,253
3.578125
4
#!/usr/bin/env python import json class Comment(object): """ A class representing a pin Comment structure used by the pinterest API The pin Comment structure exposes the following properties: comment.id comment.text comment.type comment.created_at """ def __init__(self, **kwargs): """ Comment initializer :param kwargs: Keyword arguments """ param_defaults = { 'id': None, 'text': None, 'type': 'comment', 'created_at': None} # Override defaults for (param, default) in param_defaults.items(): setattr(self, param, kwargs.get(param, default)) @property def id(self): """ Gets the unique ID of the pin Comment :return: The unique ID of the pin Comment """ return self._id @id.setter def id(self, value): """ Sets the unique ID of the pin Comment :param value: The unique ID of the pin Comment """ self._id = value @property def text(self): """ Gets the pin Comment's text :return: The pin Comment's text """ return self._text @text.setter def text(self, value): """ Sets the pin Comment's text :param value: The pin Comment's text """ self._text = value @property def type(self): """ Gets the pin Comment's type (only known type: comment) :return: The pin Comment's type """ return self._type @type.setter def type(self, value): """ Sets the pin Comment's type (only known type: comment) :param value: The pin Comment's type """ self._type = value @property def created_at(self): """ Gets the date and time the pin Comment was created :return: The date and time the pin Comment was created """ return self._created_at @created_at.setter def created_at(self, value): """ Sets the date and time the pin Comment was created :param value: The date and time the pin Comment was created """ self._created_at = value def __ne__(self, other): """ Checks if a pin Comment is not equal to another pin Comment :param other: Other pin Comment to compare to :return: True if pin Comments are not equal, False otherwise """ return not self.__eq__(other) def __eq__(self, other): """ Checks if a pin comment is equal to another pin Comment :param other: Other pin Comment to compare to :return: True if pin Comments are equal, False otherwise """ try: return other and \ self.id == other.id except AttributeError: return False def __str__(self): """ A string representation of this pinterest.Comment instance The return value is the same as the JSON string representation :return: A string representation of this pinterest.Comment instance """ return self.asJsonString() def asJsonString(self): """ A JSON string representation of this pinterest.Comment instance :return: A JSON string representation of this pinterest.Comment instance """ return json.dumps(self.asDict(), sort_keys=True) def asDict(self): """ A dict representation of this pinterest.Comment instance The return value uses the same key names as the JSON representation :return: A dict representing this pinterest.Comment instance """ return { 'id': self.id, 'text': self.text, 'type': self.type, 'created_at': self.created_at } @staticmethod def newFromJsonDict(data): """ Create a new instance based on a JSON dict :param data: A JSON dict, as converted from the JSON in the pinterest API :return: A pinterest.Comment instance """ return Comment(id=data.get('id', None), text=data.get('text', None), type=data.get('type', 'comment'), created_at=data.get('created_at', None))
0a124068690b1e9d56bc84b924e070fb1502e4a7
mariaelizasa/aed
/ic/Pairs.py
193
3.96875
4
minimo, maximo = input("Digite dois números para definir o intervalo:").split() for numero in range(int(minimo), int(maximo) + 1): if numero % 2 == 0: print("Numero par: ", numero)
b8ddb7a54446b104570f4fbc75631004578595de
Grace-Ya-Wen/Finite-Differences
/functions_part2.py
11,438
3.796875
4
import numpy as np import matplotlib.pyplot as plt import math class Boundary(object): """ Class that stores useful information on boundary or initial conditions for a PDE mesh. Attributes: condition (str): Type of boundary condition e.g. dirichlet, neumann, robin. function (function): Function used to calculate the boundary value at a specific point. """ def __init__(self, condition, function): # set the type of boundary condition self.condition = condition # set the boundary function/equation self.function = function class MeshXT(object): """ Class that stores useful information about the current XT mesh and associated boundary conditions. Includes methods for plotting the PDE solution associated with this mesh and calculating the error relative to the analytic solution, if it is known. Attributes: nx (int): Number of mesh points along the x dimension. nt (int): Number of mesh points along the t dimension. x (numpy array): Mesh coordinates along the x dimension. t (numpy array): Mesh coordinates along the t dimension. dx (float): Mesh spacing along the x dimension. dt (float): Mesh spacing along the t dimension. boundaries (list): List of objects of Boundary class. Order is u(x0,t), u(x1,t), u(x,t0), du(x,t0)/dt, etc... solution (numpy array): PDE solution as calculated on the mesh. method (string): Name of the solution method e.g. explicit, crank-nicolson, galerkin, backward-euler. mae (float): mean absolute error of numerical/mesh solution relative to analytic/exact solution. Arguments: :param x: Lower and upper limits in x dimension. :param t: Lower and upper limits in t dimension. :param delta: Mesh spacing in x and t dimensions. :param boundaries: List of objects of the Boundary class, with same order as class attribute of same name. :type x: Numpy array with two elements. :type t: Numpy array with two elements. :type delta: Numpy array with two elements. :type boundaries: List. """ def __init__(self, x, t, delta, boundaries): # define the integer number of mesh points, including boundaries, based on desired mesh spacing self.nx = math.floor((x[1] - x[0]) / delta[0]) + 1 self.nt = math.floor((t[1] - t[0]) / delta[1]) + 1 # calculate the x and y values/coordinates of mesh as one-dimensional numpy arrays self.x = np.linspace(x[0], x[1], self.nx) self.t = np.linspace(t[0], t[1], self.nt) # calculate the actual mesh spacing in x and y, should be similar or same as the dx and dy arguments self.dx = self.x[1] - self.x[0] self.dt = self.t[1] - self.t[0] # store the boundary and initial condition as a list of Boundary class objects self.boundaries = boundaries # initialise method name - useful for plot title. Updated by solver. self.method = None # initialise mean absolute error to be None type. self.mae = None # initialise the full PDE solution matrix self.solution = np.zeros((self.nx, self.nt)) # apply dirichlet boundary conditions directly to the mesh solution if self.boundaries[0].condition == 'dirichlet': self.solution[0, :] = self.boundaries[0].function(self.x[0], self.t) if self.boundaries[1].condition == 'dirichlet': self.solution[-1, :] = self.boundaries[1].function(self.x[-1], self.t) # apply initial conditions directly to the mesh solution self.solution[:, 0] = self.boundaries[2].function(self.x, self.t[0]) # TODO: complete in Task 4 def plot_solution(self, ntimes, save_to_file=False, save_file_name='figure.png'): """ Plot the mesh solution u(x,t^n) at a fixed number of time steps. Arguments: :param ntimes: number of times at which to plot the solution, u(x,t_n). :param save_to_file: If True, save the plot to a file with pre-determined name. :param save_file_name: Name of figure to save. :type ntimes: Integer. :type save_to_file: Boolean. :type save_file_name: String. """ step = math.floor((self.nt)/(ntimes-1)) for i in range(0,self.nt,step): plt.plot(self.x,self.solution[:,i], label =r"time={}s".format(i*self.dt)) #plt.text(0.0, 1.0, 'error = %s'%(self.mae)) #plt.text(0.0, 0.9, 'delta_t = %s'%(self.dt)) plt.xlabel("x") plt.ylabel("Temperature") #plt.ylabel("Vertical Displacement") plt.title('Temperature Along x-axis Over Time') #plt.title('Vertical Displacement Along x-axis Over Time') plt.legend() # determine to save the figure or not if save_to_file: plt.savefig(save_file_name, dpi = 300) else: plt.show() # TODO: complete in Task 5 def mean_absolute_error(self, exact): """ Calculates the mean absolute error in the solution, relative to exact solution, for the final time step. Arguments: :param exact: The exact solution to the PDE. :type exact: Function. """ error = 0 # initliad total error count = 0 # number of evaluated points for i in range(self.nx): for j in range(self.nt): error += abs(self.solution[i,j] - exact(self.dx*i,self.dt*j)) count = count + 1 self.mae = error/count class SolverHeatXT(object): """ Class containing attributes and methods useful for solving the 1D heat equation. Attributes: method (string): Name of the solution method e.g. crank-nicolson, explicit, galerkin, backward-euler. r (float): ratio of mesh spacings, useful for evaluating stability of solution method. theta (float): Weighting factor used in implicit scheme e.g. Crank-Nicolson has theta=1/2. a (numpy array): Coefficient matrix in system of equations to solve for PDE solution. b (numpy array): Vector of constants in system of equations to solve for PDE solution at time t^n. Arguments: :param mesh: instance of the MeshXT class. :param alpha: reciprocal of thermal diffusivity parameter in the heat equation. :param method: Name of the solution method e.g. crank-nicolson, explicit, galerkin, backward-euler. :type mesh: Object. :type alpha: Float. :type method: String. """ def __init__(self, mesh, alpha=1., method='crank-nicolson'): # set the solution method self.method = method mesh.method = method # set the ratio of mesh spacings used in solver equations self.r = mesh.dt / (alpha * mesh.dx * mesh.dx) # initialise theta variable used in the implicit methods self.theta = None # determine if solution method requires matrix equation and set A, b accordingly if self.method == 'explicit': self.a = None self.b = None else: self.a = np.zeros((mesh.nx*2, mesh.nx*2)) self.b = np.zeros(mesh.nx*2) def solver(self, mesh): """ Run the requested solution method. Default to Crank-Nicolson implicit method if user hasn't specified. Arguments: :param mesh: Instance of the MeshXT class. """ # run the explicit solution method if self.method == 'explicit': self.explicit(mesh) # run the crank-nicolson implicit method elif self.method == 'crank-nicolson': self.theta = 0.5 self.implicit(mesh) elif self.method == 'galerkin': self.theta = 2./3. self.implicit(mesh) elif self.method == 'backward-euler': self.theta = 1. self.implicit(mesh) else: # default to crank-nicolson self.method = 'crank-nicolson' mesh.method = 'crank-nicolson' self.theta = 0.5 self.implicit(mesh) # TODO: complete in Task 4 def explicit(self, mesh): """ Solve the 1D heat equation using an explicit scheme. Arguments: :param mesh: Instance of the MeshXT class. """ # run through all the unknown mesh points for i in range(1,mesh.nt): for j in range(1,mesh.nx-1): mesh.solution[j,i] = self.r*mesh.solution[j-1,i-1] + (1-2*self.r)*mesh.solution[j,i-1]+self.r*mesh.solution[j+1,i-1] # TODO: complete in Task 4 def implicit(self, mesh): """ Solve the 1D heat equation using an implicit scheme. Accounts for different values of theta. Arguments: :param mesh: Instance of the MeshXT class. """ a = np.zeros((mesh.nx-2,mesh.nx-2)) # run through all the rows for j in range(mesh.nx-2): a[j,j] = -(1+self.r) if j > 0: a[j,j-1] = self.theta*self.r if j < mesh.nx-3 and mesh.nx>3: a[j,j+1] = self.theta*self.r for i in range (1,mesh.nt): b = np.zeros((mesh.nx-2,1)) # initialized b vector count = 0 # indexing # run through each row of a specified for j in range(1,mesh.nx-1): b[count,0] = -(1-self.theta)*self.r * mesh.solution[j-1,i-1] - (1-2*self.r*self.theta)*mesh.solution[j,i-1]-(1-self.theta)*self.r *mesh.solution[j+1,i-1] if j == 1: # for the first column b[count,0] -= self.theta*self.r*mesh.solution[0,i] # substracing additional value from vector b elif j == mesh.nx - 2: # for the last column b[count,0] -= self.theta*self.r*mesh.solution[mesh.nx-1,i] # substracing additional value from vector b count = count + 1 u1d = np.linalg.solve(a,b) # change value in solution matrix for n in range (1,mesh.nx-1): mesh.solution[n,i] = u1d[n-1] # TODO: complete in Task 6 def solver_wave_xt(mesh): """ Function used to solve the 1D wave equation (i.e. hyperbolic PDE). Assumes dx = dt and an explicit method. Has no return. Instead, it updates the mesh.solution attribute directly. Arguments: :param mesh: instance of the MeshXT class. """ # run through all the unknown mesh points for i in range(1,mesh.nt): for j in range(1,mesh.nx-1): if i == 1: # solution for initial boundary mesh.solution[j,i] = 0.5*(mesh.solution[j-1,i-1] +mesh.solution[j+1,i-1]) + mesh.dt*mesh.boundaries[3].function(j*mesh.dx,(i-1)*mesh.dt) else: # solution for others mesh.solution[j,i] = mesh.solution[j-1,i-1]+mesh.solution[j+1,i-1]- mesh.solution[j,i-2]
ef6e06b9fcd35193ae568874d98094010bc9764e
BluePinetree/BasicDeepLearning
/Lab8/Stack.py
239
3.53125
4
import tensorflow as tf with tf.Session(): x = [1, 4] y = [2, 5] z = [3, 6] #Pack along first dim print(tf.stack([x,y,z]).eval()) print(tf.stack([x,y,z], axis=-1).eval()) #-1은 제일 마지막 축을 잡는다
15f3360432a5f48e7edcdfa07834490236c067a6
DataNewbie1997/TambahMundur
/TambahMundur.py
1,518
3.53125
4
def tambahMundur (x,y): try: print('Masukan angka 1:',x) if x > 359999: print('Invalid input!') mundur = 0 while x > 0: a = x%10 #INI UNTUK MENCARI DARI ANGKA PALING BELAKANG mundur = (mundur*10) + a # INI HASIL DARI LOOPING SEHINGGA SETELAH ANGKA PALING BELAKANG, MENCARI HURUF SESUDAHNYA x = x//10 #INI AGAR MELANJUTKAN KE ANGKA SELANJUTNYA DARI BELAKANG # print (mundur) if y > 359999: print('Invalid input!') mundur2 = 0 print('Masukan angka 2:',y) while y > 0: b = y%10 #INI UNTUK MENCARI DARI ANGKA PALING BELAKANG mundur2 = (mundur2*10) + b # INI HASIL DARI LOOPING SEHINGGA SETELAH ANGKA PALING BELAKANG, MENCARI HURUF SESUDAHNYA# INI HASIL DARI LOOPING SEHINGGA SETELAH ANGKA PALING BELAKANG, MENCARI HURUF SESUDAHNYA y = y//10 #INI AGAR MELANJUTKAN KE ANGKA SELANJUTNYA DARI BELAKANG # print(mundur2) z = mundur+mundur2 # MENAMBAHKAN X DAN Y #SAMA SEPERTI X DAN Y mundur3 = 0 while z > 0: c = z%10 mundur3 = (mundur3*10) + c z = z//10 print('hasil tambah angka mundurnya:',mundur3) except ValueError: print('Invalid input!') tambahMundur(24,1) tambahMundur(4358,754) tambahMundur(1234,5678)
ae05f3903d996612c7c286f044ffbcff012a837b
WilliamRitson/letter-positon-frequency
/letter_counting.py
1,286
4.1875
4
import csv ALPHABET = 'abcdefghijklmnopqrstuvwxyz' MAX_LETTER_POSITION = 12 A_VALUE = ord('a') def is_letter_in_nth_position(word, letter, n): return n < len(word) and word[n] == letter def create_letter_table(word_list, max_letter_position=MAX_LETTER_POSITION): """ Uses a list of words to create a table with each letter of the alphabet followed by that letters frequency at the nth position in the list """ header = ['Position'] + list(ALPHABET.upper()) table = [] for _ in range(max_letter_position): table.append([]) for _ in ALPHABET: table[-1].append(0) for word, count in word_list: for letter_positon, letter in list(enumerate(word))[:max_letter_position]: letter_index = ord(letter) - A_VALUE if (letter_index >= 0 and letter_index < 26): table[letter_positon][letter_index] += count for i, row in enumerate(table): table[i] = [i + 1] + row return [header] + table def write_letter_table_as_csv(letter_table, filename): with open(filename, 'w', newline='') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in letter_table: csv_writer.writerow(row)
5825fa53978a56811f315e64b4f618307178e3b1
5l1v3r1/python-basic
/deleting dictionary items in python.py
360
4.28125
4
# we can delete an item of dictionary or entire dictionary using del keyword. stu={ 101:"rahul", 102:"raj", 103:"arpit" } print("before deletion:") print(stu) print(id(stu)) print() del stu[102] print("after delition:") print(stu) print(id(stu)) print() del(stu) print(stu) #this will give error, because we have deleted it.
c7755617042d24d5b8c90ba1e6a393997b4ecb11
TahaKhan8899/Coding-Practice
/LeetCode/MaxHeap.py
2,333
3.953125
4
class MaxHeap: def __init__(self, items=[]): # we don't use index 0 in a heap for easier indexing self.heap = [0] for i in items: self.heap.append(i) self.floatUp(len(self.heap)-1) # PUBLIC # append to the end, then float it up to the top def push(self, data): self.heap.append(data) self.floatUp(len(self.heap)-1) # PUBLIC # check is at least 1 item present, return first item def peek(self): if self.heap[1]: return self.heap[1] else: return False # PUBLIC def pop(self): # swap max to bottom, pop, it off, bubble root down if len(self.heap) > 2: self.swap(1, len(self.heap)-1) max = self.heap.pop() self.bubbleDown(1) # only 1 value, pop it elif len(self.heap) == 2: max = self.heap.pop() # empty heap else: max = False return max # PRIVATE def swap(self, i, j): self.heap[i], self.heap[j] = self.heap[j], self.heap[i] def floatUp(self, index): parent = index // 2 # index is already at root, so no float if index <= 1: return # compare to parent elif self.heap[index] > self.heap[parent]: self.swap(index, parent) self.floatUp(parent) # PRIVATE # bubble down to proper position def bubbleDown(self, index): left = index * 2 right = index * 2 + 1 largest = index # check if left is not out of range and then check if heap[largest] goes left if len(self.heap) > left and self.heap[largest] < self.heap[left]: largest = left # check if left is not out of range and then check if heap[largest] goes right if len(self.heap) > right and self.heap[largest] < self.heap[right]: largest = right # if a new largest was found, swap items and bubble down again if largest != index: self.swap(index, largest) self.bubbleDown(largest) # PRIVATE def printHeap(self): print(str(self.heap[0:len(self.heap)])) # m = MaxHeap([50, 30, 20]) # m.push(5) # print(m.printHeap()) # print(str(m.pop()))
8ade764213e6d1b518feed2ba769c6184a0eda3c
nour20-meet/meetyl1201819
/personal_project.py
780
3.9375
4
from turtle import * import turtle import random import math class Ball(Turtle): def __init__(self,x,y,dx,dy,r,color): Turtle.__init__(self) self.shape("circle") self.shapesize(r/10) self.r = r self.color(color) self.penup() self.dx = dx self.dy = dy self.goto(x,y) def move (self, screen_widht, screen_height): oldx = self.xcor() oldy = self.ycor() new = oldx + self.dx new = oldy + self.dy right_side = newx + self.radius left_side = newx - self.radius top_side = newy + self.radius bottom_side = newy - self.radius self.goto(newx, newy) if top_side > screen_height or bottom_side < screen_height: self.dx *= -1 if top_side < screen_widht or bottom_side > screen_widht: self.dy *= -1 ball1 = Ball(0,0,20,20,40,"pink")
079000049517b1aca1d08785f4eeeca83dc5ddd0
shelibenm/processingsheli
/lesson1_saturation.pyde
731
3.96875
4
barWidth = 1 # TODO-Change The barWidth to 20 def setup(): #TODO- use the barWidht variable instead of the number 20 size(20 * 32, 360) colorMode(HSB, width, height, 100) noStroke() def draw(): #TODO-replace the 1 in the WhichBar variable with the mouseX value whichBar = 1 / barWidth barX = whichBar * barWidth #TODO- replace the number 25 in the fill function with the value "barX" #TODO- replace the number 1 in the fill function with "mouseY" fill(25, 1, 66) rect(barX, 0, barWidth, height) #TODO- Explain: whats the meaning of the variable cald "barX" #TODO- read more about sturation effect #TODO- use the sturation effect on other shape or image
08eb277d93271bd3b55405d11718e6924f854356
shiksagodess/ComputerLanguages
/CS3120/tuples.py
410
4.28125
4
#This program create tuples, lists and uses slice #here we are creating tuples a=("one","two","three") b=("four","five","six","seven") c=(1,2,3,4,5,6,7) print(a) print(len(a)) print(b) print(len(b)) print(a+b) #This shows slice print(c[1:]) print(c[2:4]) list = list(b) print(list) print(list[-2]) print(list[:3]) list[3] = "7" print(list) print(list[-1]) print(list[3]) list.insert(4, "eight") print(list)
8bde01781b912d9c7d3248259128b1912fa98d23
noblejoy20/python-tutorial-college
/prelims-parttwo/zeller.py
479
3.828125
4
a=int(input("Enter the month of the year: ")) b=int(input("Enter the day of the month: ")) c=int(input("Enter the year of the century: ")) d=int(input("Enter the century: ")) if(a<=2): c=c-1 a=a+10 w=(13*a-1)//5 x=c//4 y=d//4 z=w+x+y+b+c-2*d r=z%7 if(r==0): print "Sunday" elif(r==1): print "Monday" elif(r==2): print "Tuesday" elif(r==3): print "Wednesday" elif(r==4): print "Thursday" elif(r==5): print "Friday" elif(r==6): print "Saturday"
26379839fcce7249228ead3eba4fc01edbf7f400
kenchose/Python
/Python/Python Fundamentals/Type List/type_list.py
994
3.875
4
def identitylist(lst): newStr = '' total = 0 for elem in lst: if isinstance(elem, int) or isinstance(elem, float): total += elem elif isinstance(elem, str): newStr += elem + ' ' if newStr and total: print "The list you entered is of mixed type" print "String:", newStr print 'Sum:', total elif newStr: print "The string you entered is of string type" print 'String:', newStr else: print "The list you entered is of integer type" print 'Sum:', total # #input # l = ['magical unicorns',19,'hello',98.98,'world'] # #output # "The list you entered is of mixed type" # "String: magical unicorns hello world" # "Sum: 117.98" # # input # l = [2,3,1,7,4,12] # #output # "The list you entered is of integer type" # "Sum: 29" # # input # l = ['magical','unicorns'] # #output # "The list you entered is of string type" # "String: magical unicorns"
cb958071f97d324d8b49791bea94cdb6062b8e22
chengxxi/SWEA
/D2/4866.py
2,037
3.921875
4
# 4866. 괄호검사 [D2] for test_case in range(1, int(input())+1): brackets = input() def check_bracket(string): d = {')' : '(', '}' : '{', ']' : '['} # 괄호 쌍 딕셔너리 stack = [] # 빈 스택 생성 for i in range(len(string)): # 문자열 내에서 반복 수행 if string[i] in '({[': # 열린 괄호라면 stack.append(string[i]) # push한다 elif string[i] in ')}]': # 닫힌 괄호라면 if stack: # 그런데 stack이 비어있지 않으면 top = stack.pop() # pop한다 if d[string[i]] != top: # top으로 뽑아온 것이랑 string[i] 즉 괄호 쌍이 일치하지 않으면 return False # False를 return한다 else: # stack이 비어있으면 return False return len(stack) == 0 # True / False ans = check_bracket(brackets) if ans: # True print("#{} 1".format(test_case)) else: # False print("#{} 0".format(test_case)) """ for test_case in range(1, int(input())+1): brackets = input() def check_bracket(string): stack = [] for i in range(len(string)): if string[i] == "(": stack.append(i) elif string[i] == ")": stack.pop() return stack ans = check_bracket(brackets) if not ans: print("#{} 1".format(test_case)) else: print("#{} 0".format(test_case)) """ """ 주어진 입력에서 괄호 {}, ()가 제대로 짝을 이뤘는지 검사하는 프로그램을 만드시오. 예를 들어 {( )}는 제대로 된 짝이지만, {( })는 제대로 된 짝이 아니다. 입력은 한 줄의 파이썬 코드일수도 있고, 괄호만 주어질 수도 있다. 정상적으로 짝을 이룬 경우 1, 그렇지 않으면 0을 출력한다. print(‘{‘) 같은 경우는 입력으로 주어지지 않으므로 고려하지 않아도 된다. """
e7414f7c98028ae161f82a38f4e43fd6f83aef79
tuliba1996/Testonline_python
/challenge.py
228
3.734375
4
# print out the integer numbers from 30 to 300 listofnumber = range(30,301) for i in listofnumber: if (i%7 == 0 and i%13 == 0 ): print "a-z", i else: if (i%7 == 0): print "abc", i if (i%13 == 0): print "xyz", i
aa073424dda40ac53ae13d964b769a2287245806
ohadstatman/Data_portfolio
/first1.py
280
3.546875
4
import re file = open("actual-data-1.txt") lst=list() for line in file: if re.search("[0-9]+",line): x = re.findall("[0-9]+",line) lst.append(x) numbers =[] for l in lst: for num in l: numbers.append(int(num)) print(sum(numbers))
d50ef7a9522a97add9379b1beac5df74183df3f7
thesauravs/NLP
/tokenize_TSS.py
966
4.03125
4
import re #tokenize function creates a list of distinct words in corpus #parameter for this function is the file path #it also changes all words to lower case before creating the list def tokenize(filename = 'test.txt'): with open(filename, 'r') as file: words = [] all_words = [] #Extract word from sentences for line in file: words += line.split() #print(words) #words ending with . are processed. for i in range(len(words)): if(re.findall('w*\.', words[i])): words[i] = words[i][:-1] #change all words into lower case for i in range(len(words)): words[i] = words[i].lower() #print(words) #removing duplicate words for i in range(len(words)): if(words[i] not in all_words): all_words.append(words[i]) return words, all_words
9b0d49b425db42a74940f08611dc068bb3bbefe3
udhayprakash/PythonMaterial
/python3/10_Modules/27_socket_programming/first.py
602
3.5625
4
#!/usr/bin/python import socket import sys # creating a socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as error: print(f"Failed to create a socket. {repr(error)}") sys.exit() print("socket created") host = "localhost" port = 9999 try: remote_ip = socket.gethostbyname(host) except Exception: print("Hostname could not be resolved.exiting") sys.exit() print("Ip address of " + host + " is " + remote_ip) print("connecting to the server \n") s.connect((remote_ip, port)) print("Socket Connected to " + host + " on ip " + remote_ip)
18b5eda56753ca024aff52e6d78bf07cf28a3be3
humachine/AlgoLearning
/leetcode/Done/282_ExpressionAddOperators.py
2,796
3.953125
4
#https://leetcode.com/problems/expression-add-operators/ ''' Given a string that only contains digits 0-9 and a target, add any of the arithmetic operators (+-*) between digits so as to evaluate to the 'target'. Return all such possibilities. Inp: "123", 6 Out: ["1+2+3", "1*2*3"] Inp: '232', 8 Out: ["2*3+2", "2+3*2"] Inp: '105', 5 Out: ["1*0+5", "10-5"] Inp: "00", 0 Out: ["0+0", "0-0", "0*0"] Inp: "3456237490", 9191 Out: [] ''' class Solution(object): def findCombinations(self, startPos, currPath, currVal, multiplier, res): numStr, target = self.numStr, self.target if startPos == len(numStr): #If we have exhausted the entire input string if currVal == target: # If our current expression's evaluation = target, then we add it to our result res.append(''.join(currPath)) return for i in xrange(startPos, len(numStr)): if i!=startPos and numStr[startPos] == '0': #We can't including numbers which have trailing zeros (except 0). Hence we return return curr = int(numStr[startPos:i+1]) if startPos==0: # Check if we are starting first sequence currPath.append(str(curr)) self.findCombinations(i+1, currPath, curr, curr, res) #If this is the first sequence, then just add it to the sequence and begin the backtracking search currPath.pop() else: # We try to see if we can reach the target by adding/subtracting/multiplying curr to the previous sum (i.e currVal) currPath.extend(['+', str(curr)]) #Add + and the current Number to the path self.findCombinations(i+1, currPath, currVal+curr, curr, res) currPath[-2] = '-' #Change the operation to minus self.findCombinations(i+1, currPath, currVal-curr, -curr, res) currPath[-2] = '*' #Change the operation to multiplication self.findCombinations(i+1, currPath, currVal-multiplier+multiplier*curr, multiplier*curr, res) #The multiplier argument tells us what the previous multiplier was, so that we can multiply curr with that and add it to result currPath.pop() #Pop twice to remove the sign and the current number (Backtracking step) currPath.pop() def addOperators(self, num, target): if not num: return [] self.numStr, self.target = num, target res, currPath = [], [] self.findCombinations(0, currPath, 0, 0, res) return res s = Solution() print s.addOperators('123', 6) print s.addOperators('232', 8) print s.addOperators('105', 5) print s.addOperators('00', 0) print s.addOperators('2326738423', 91919)
f5345f97d514149ea5deb0d8abe4bacf4ee7d7a7
HoaiBach/LinearOEC
/ES.py
6,638
3.84375
4
''' This is an efficient implementation of Evolutionary Strategy (ES). Written by M.R.Bonyadi (rezabny@gmail.com) ''' import sys from random import normalvariate as random_normalvariate import numpy as np from random import normalvariate as random_normalvariate from math import log from AbstractEA import AbstractEA class ES(AbstractEA): def __init__(self, xstart, sigma, # mandatory max_eval='1e3*N**2', ftarget=None, popsize="4 + int(3 * log(N))", randn=random_normalvariate): """Initialize` ES` object instance, the first two arguments are mandatory. Parameters ---------- `xstart` ``list`` of numbers (like ``[3, 2, 1.2]``), initial solution vector `sigma` ``float``, initial step-size (standard deviation in each coordinate) `max_eval` ``int`` or ``str``, maximal number of function evaluations, a string is evaluated with ``N`` being the search space dimension `ftarget` `float`, target function value `randn` normal random number generator, by default ``random.normalvariate`` """ # process input parameters N = len(xstart) # number of objective variables/problem dimension self.dim = N self.xmean = xstart[:] # initial point, distribution mean, a copy self.ftarget = ftarget # stop if fitness < ftarget self.max_eval = eval(str(max_eval)) # eval a string self.randn = randn # Strategy parameter setting: Selection self.lam = eval(str(popsize)) # population size, offspring number self.sigma = np.ones(self.lam) * sigma self.mu = int(self.lam / 2) # number of parents/points for recombination self.counteval = 0 self.fitvals = [] # for bookkeeping output and termination self.tau = (1 / (np.sqrt(2 * self.dim))) self.best = BestSolution() def stop(self): """return satisfied termination conditions in a dictionary like {'termination reason':value, ...}, for example {'tolfun':1e-12}, or the empty dict {}""" res = {} if self.counteval > 0: if self.counteval >= self.max_eval: res['evals'] = self.max_eval if self.ftarget is not None and len(self.fitvals) > 0 \ and self.fitvals[0] <= self.ftarget: res['ftarget'] = self.ftarget if len(self.fitvals) > 1 \ and self.fitvals[-1] - self.fitvals[0] < 1e-12: res['tolfun'] = 1e-12 return res def ask(self): """return a list of lambda candidate solutions according to m + sig * Normal(0,C) = m + sig * B * D * Normal(0,I)""" arz = np.random.standard_normal((self.lam, self.dim)) arz = self.xmean + np.dot(np.diag(self.sigma), arz) arz = arz.T / np.sqrt(np.einsum('...i,...i', arz, arz)) res = arz.T return res def tell(self, arx, fitvals): """update the evolution paths and the distribution parameters m, sigma, and C within CMA-ES. Parameters ---------- `arx` a list of solutions, presumably from `ask()` `fitvals` the corresponding objective function values """ # bookkeeping, preparation self.counteval += len(fitvals) # slightly artificial to do here N = self.dim # convenience short cuts # Sort by fitness and compute weighted mean into xmean arindex = np.argsort(fitvals) self.fitvals = fitvals[arindex] self.sigma = self.sigma[arindex] # self.fitvals, arindex = np.sort(fitvals), np.argsort(fitvals) # min arx = [arx[arindex[k]] for k in range(self.mu)] # sorted arx del fitvals, arindex # to prevent misuse # self.fitvals is kept for termination and display only self.best.update([arx[0]], [self.fitvals[0]], self.counteval) recsigma = np.mean(self.sigma[0:self.mu]) self.sigma = recsigma * (np.exp(self.tau * np.random.standard_normal(self.lam))) self.xmean = np.mean(arx, axis=0) def result(self): """return (xbest, f(xbest), evaluations_xbest, evaluations, iterations, xmean) """ return self.best.get() + (self.counteval, int(self.counteval / self.lam), self.xmean) def disp(self, verb_modulo=1): """display some iteration info""" iteration = self.counteval / self.lam if iteration == 1 or iteration % (10 * verb_modulo) == 0: print('evals: ax-ratio max(std) f-value') if iteration <= 2 or iteration % verb_modulo == 0: print(repr(self.counteval).rjust(5) + ': ' + str(self.fitvals[0])) sys.stdout.flush() return None @staticmethod def dot(A, b, t=False): """ usual dot product of "matrix" A with "vector" b, where A[i] is the i-th row of A. With t=True, A transposed is used. :rtype : "vector" (list of float) """ n = len(b) if not t: m = len(A) # number of rows, like printed by pprint v = m * [0] for i in range(m): v[i] = sum(b[j] * A[i][j] for j in range(n)) else: m = len(A[0]) # number of columns v = m * [0] for i in range(m): v[i] = sum(b[j] * A[j][i] for j in range(n)) return v # ----------------------------------------------- class BestSolution(object): """container to keep track of the best solution seen""" def __init__(self, x=None, f=None, evals=None): """take `x`, `f`, and `evals` to initialize the best solution. The better solutions have smaller `f`-values. """ self.x, self.f, self.evals = x, f, evals def update(self, arx, arf, evals=None): """initialize the best solution with `x`, `f`, and `evals`. Better solutions have smaller `f`-values.""" if self.f is None or min(arf) < self.f: i = arf.index(min(arf)) self.x, self.f = arx[i], arf[i] self.evals = None if not evals else evals - len(arf) + i + 1 return self def get(self): """return ``(x, f, evals)`` """ return self.x, self.f, self.evals
e14357b795e9aa4f42b70607ecd2cb124e52b0c4
nickitaliano/matching-commonsense-twitter-sentiment-analysis
/source-code/parse-tweet/raw_to_plain.py
1,996
3.703125
4
# file name is slang.txt data = open("slang.txt","r") # file including all tweets tweets = open("tweets.txt","r") # output file with resultant plain text output = open("plaintext.txt","w") # making dictionary from slang.txt dict = {} for line in data: try: x = line.split(":") dict[x[0]]=x[1].replace("\n","") except: pass # read tweets from file and convert into list tweets_list = [] for line in tweets: try: tweets_list.append(line.replace("\n","")) except: pass for tweet in tweets_list: # covert into lower case tweet = tweet.lower() # remove all special charcters from the tweets tweet = tweet.replace("!"," ") tweet = tweet.replace("@"," ") tweet = tweet.replace("#"," ") tweet = tweet.replace("$"," ") tweet = tweet.replace("%"," ") tweet = tweet.replace("^"," ") tweet = tweet.replace("&"," ") tweet = tweet.replace("*"," ") tweet = tweet.replace("("," ") tweet = tweet.replace(")"," ") tweet = tweet.replace("-"," ") tweet = tweet.replace("_"," ") tweet = tweet.replace("="," ") tweet = tweet.replace("{"," ") tweet = tweet.replace("}"," ") tweet = tweet.replace("["," ") tweet = tweet.replace("]"," ") tweet = tweet.replace("|"," ") tweet = tweet.replace(":"," ") tweet = tweet.replace(";"," ") tweet = tweet.replace("'"," ") tweet = tweet.replace("."," ") tweet = tweet.replace("<"," ") tweet = tweet.replace(">"," ") tweet = tweet.replace("?"," ") tweet = tweet.replace("~"," ") tweet = tweet.replace("`"," ") raw = tweet.split(' ') # replace slang with actual meaning for idx, i in enumerate(raw): if dict.has_key(i): raw[idx]=dict[i] plaintext = " ".join(raw) plaintext = " ".join(plaintext.split()) output.write(plaintext+"\n") print "Converting Done!!!" # closing the files data.close() tweets.close() output.close()
68684f6face69c2dedd634f22bdaf3fc00ca1b8c
Alan-Flynn/Python-Labs
/prime.py
474
3.90625
4
# Name: Your Name # Student ID: 012345678 # File: prime.py ############################################################################ # ask for a number n = int(input("Please enter a positive integer: ")) i = 2 factorisable = False while not factorisable and i <= n**0.5: if(n % i) == 0: factorisable = True else: i = i + 1 if factorisable: print("value",n,"is not prime") else: print("value",n,"is prime")
44f72d83ac09b4ba3673f72528061eed5e5b8f73
m-attand/class-work
/ex5_1.py
333
3.703125
4
#ex5_1 score = [] while True: try: score = input('Enter a number: ') if score.strip() == 'done': break elif float(score): score.append(float(score)) else: print('error') except: print('error') if len(score) > 0: print('total: %d, Count: %d, Average: %f' % (sum(score), len(score),(sum(score/len(score))))
f698b64e13bfa3920d11937ca12f54338eda48fe
sangam92/https---github.com-sangam92-data_structure
/queue.py
566
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 21 11:41:51 2020 @author: sangam """ class Queue: def __init__(self): self.queue=[] def insert(self,dataval): self.queue.append(dataval) def remove(self): self.queue.pop(0) qu = Queue() print("Inserting the element in the queue") qu.insert(6) qu.insert(8) print("The elements in the queue are",qu.queue) print("remove function has been called") qu.remove() print("The queue after removing elemnts",qu.queue)
60638264f791d0971d7ff76a19f5c121606c7ac1
wajid-shaikh/Python-Examples
/2 conditions and loops/for_loop_exapmle1.py
223
3.984375
4
# sum fromo 1 to 10 # 1 + 2 + 3 + ... + 10 # total = 0 # for i in range(1, 11): # total = total + i # print(total) n = int(input("enter number = ")) total = 0 for i in range(1, n+1): total = total + i print(total)
d70120c6f76d4874364560d55e39872877ee9242
T882200/python_learning
/pythontutcs.py
171,693
4.375
4
#~~Learn to program 1 # Programming involves listing all the things that must happen to solve a problem # When writing a program first determine step-by-step what needs to happen # Then convert those steps into the language being Python in this situation # Every language has the following # 1. The ability to accept input and store it in many ways # 2. The ability to output information to the screen, files, etc. # 3. The ability to conditionally do one thing or another thing # 4. The ability to do something multiple times # 5. The ability to make mathematical calculations # 6. The ability to change data # 7. (Object Oriented Programming) Model real world objects using code # ---------- Hello World ---------- # Ask the user to input their name and assign it to the name variable # Variable names start with a letter or _ and then can contain numbers # Names are case sensitive so name is not the same as Name name = input('What is your name ') # Print out Hello followed by the name they entered print('Hello ', name) # You can't use the following for variable names # and, del, from, not, while, as, elif, global, # or, with, assert, else, if, pass, yield, break, # except, import, print, class, exec, in, raise, # continue, finally, is, return, def, for, lambda, # try # Single line comments are ignored by the interpreter ''' So are multiline comments ''' # ---------- MATH ON 2 VALUES ---------- # Ask the user to input 2 values and store them in variables num1 and num2 # split() splits input using whitespace num1, num2 = input('Enter 2 numbers : ').split() # Convert strings into regular numbers (integers) num1 = int(num1) num2 = int(num2) # Add the values entered and store in sum sum = num1 + num2 # Subtract the values and store in difference difference = num1 - num2 # Multiply the values and store in product product = num1 * num2 # Divide the values and store in quotient quotient = num1 / num2 # Use modulus on the values to find the remainder remainder = num1 % num2 # Print your results # format() loads the variable values in order into the {} placeholders print("{} + {} = {}".format(num1, num2, sum)) print("{} - {} = {}".format(num1, num2, difference)) print("{} * {} = {}".format(num1, num2, product)) print("{} / {} = {}".format(num1, num2, quotient)) print("{} % {} = {}".format(num1, num2, remainder)) # ---------- PROBLEM : MILES TO KILOMETERS ---------- # Sample knowing that kilometers = miles * 1.60934 # Enter Miles 5 # 5 miles equals 8.0467 kilometers # Ask the user to input miles and assign it to the miles variable miles = input('Enter Miles ') # Convert from string to integer miles = int(miles) # Perform calculation by multiplying 1.60934 times miles kilometers = miles * 1.60934 # Print results using format() print("{} miles equals {} kilometers".format(miles, kilometers)) # ---------- CALCULATOR ---------- # Receive 2 numbers separated by an operator and show a result # Sample # Enter Calculation: 5 * 6 # 5 * 6 = 30 # Store the user input of 2 numbers and an operator num1, operator, num2 = input('Enter Calculation: ').split() # Convert strings into integers num1 = int(num1) num2 = int(num2) # If, else if (elif) and else execute different code depending on a condition if operator == "+": print("{} + {} = {}".format(num1, num2, num1+num2)) # If the 1st condition wasn't true check if this one is elif operator == "-": print("{} - {} = {}".format(num1, num2, num1 - num2)) elif operator == "*": print("{} * {} = {}".format(num1, num2, num1 * num2)) elif operator == "/": print("{} / {} = {}".format(num1, num2, num1 / num2)) # If none of the above conditions were true then execute this by default else: print("Use either + - * or / next time") # Other conditional operators # > : Greater than # < : Less than # >= : Greater than or equal to # <= : Less than or equal to # != : Not equal to # ---------- IS BIRTHDAY IMPORTANT ---------- # We'll provide different output based on age # 1 - 18 -> Important # 21, 50, > 65 -> Important # All others -> Not Important # eval() converts a string into an integer if it meets the guidelines age = eval(input("Enter age: ")) # Logical operators can be used to combine conditions # and : If both are true it returns true # or : If either are true it returns true # not : Converts true into false and vice versa # If age is both greater than or equal to 1 and less than or equal to 18 it is true if (age >= 1) and (age <= 18): print("Important Birthday") # If age is either 21 or 50 then it is true elif (age == 21) or (age == 50): print("Important Birthday") # We check if age is less than 65 and then convert true to false or vice versa # This is the same as if we put age > 65 elif not(age < 65): print("Important Birthday") else: print("Sorry Not Important") # ---------- PROBLEM : DETERMINE GRADE ---------- # If age 5 go to kindergarten # Ages 6 through 17 goes to grades 1 through 12 # If age is greater then 17 then say go to college # Try to complete with 10 or less lines # Ask for the age age = eval(input("Enter age: ")) # Handle if age < 5 if age < 5: print("Too Young for School") # Special output just for age 5 elif age == 5: print("Go to Kindergarten") # Since a number is the result for ages 6 - 17 we can check them all # with 1 condition # Use calculation to limit the conditions checked elif (age > 5) and (age <= 17): grade = age - 5 print("Go to {} grade".format(grade)) # Handle everyone else else: print("Go to College") #~~Learn to program 2 # Every program has the ability to perform actions on a list of # values. The for loop can be used to do this. # Each time we go through the loop variable i's value will be # assigned the next value in our list for i in [2,4,6,8,10]: print("i = ", i) # We can also have range define our list for us. range(10) will # create a list starting at 0 and go up to but not include # the value passed to it. for i in range(10): print("i = ", i) # We can define the starting and ending value for range for i in range(2, 10): print("i = ", i) # You can use modulus to see if a number is odd or even # If we divide an even by 2 there will be no remainder # so if i % 2 == 0 we know it is true i = 2 print((i % 2) == 0) # ---------- PROBLEM : PRINT ODDS FROM 1 to 20 ---------- # Use a for loop, range, if and modulus to print out the odds # Use for to loop through the list from 1 to 21 for i in range(1, 21): # Use modulus to check that the result is NOT EQUAL to 0 # Print the odds if ((i % 2) != 0): print("i = ", i) # ---------- WORKING WITH FLOATS ---------- # Floating point numbers are numbers with decimal values your_float = input("Enter a float: ") # We can convert a string into a float like this your_float = float(your_float) # We can define how many decimals are printed being 2 # here by putting :.2 before f print("Rounded to 2 decimals : {:.2f}".format(your_float)) # ---------- PROBLEM : COMPOUNDING INTEREST ---------- # Have the user enter their investment amount and expected interest # Each year their investment will increase by their investment + # their investment * the interest rate # Print out their earnings after a 10 year period # Ask for money invested + the interest rate money = input("How much to invest: ") interest_rate = input("Interest Rate: ") # Convert value to a float money = float(money) # Convert value to a float and round the percentage rate by 2 digits interest_rate = float(interest_rate) * .01 # Cycle through 10 years using for and range from 0 to 9 for i in range(10): # Add the current money in the account + interest earned that year money = money + (money * interest_rate) # Output the results print("Investment after 10 years: {:.2f}".format(money)) # ---------- WORKING WITH FLOATS ---------- # When working with floats understand that they are not precise # This should print 0 but it doesn't i = 0.1 + 0.1 + 0.1 - 0.3 print(i) # Floats will print nonsense beyond 16 digits of precision i = .11111111111111111111111111111111 j = .00000000000000010000000000000001 print("Answer : {:.32}".format(i + j)) # ---------- ORDER OF OPERATIONS ---------- # When making calculations unless you use parentheses * and / # will supersede + and - print("3 + 4 * 5 = {}".format(3 + 4 * 5)) print("(3 + 4) * 5 = {}".format((3 + 4) * 5)) # ---------- THE WHILE LOOP ---------- # We can also continue looping as long as a condition is true # with a while loop # While loops are used when you don't know how many times # you will have to loop # We can use the random module to generate random numbers import random # Generate a random integer between 1 and 50 rand_num = random.randrange(1, 51) # The value we increment in the while loop is defined before the loop i = 1 # Define the condition that while true we will continue looping while (i != rand_num): # You must increment your iterator inside the while loop i += 1 # Outside of the while loop when we stop adding whitespace print("The random value is : ", rand_num) # ---------- BREAK AND CONTINUE ---------- # Continue stops executing the code that remains in the loop and # jumps back to the top # Break jumps completely out of the loop i = 1 while i <= 20: # If a number is even don't print it if (i % 2) == 0: i += 1 continue # If i equals 15 stop looping if i == 15: break # Print the odds print("Odd : ", i) # Increment i i += 1 # ---------- PROBLEM : DRAW A PINE TREE ---------- # For this problem I want you to draw a pine tree after asking the user # for the number of rows. Here is the sample program ''' How tall is the tree : 5 # ### ##### ####### ######### # ''' # You should use a while loop and 3 for loops # I know that this is the number of spaces and hashes for the tree # 4 - 1 # 3 - 3 # 2 - 5 # 1 - 7 # 0 - 9 # Spaces before stump = Spaces before top # So I need to # 1. Decrement spaces by one each time through the loop # 2. Increment the hashes by 2 each time through the loop # 3. Save spaces to the stump by calculating tree height - 1 # 4. Decrement from tree height until it equals 0 # 5. Print spaces and then hashes for each row # 6. Print stump spaces and then 1 hash # Get the number of rows for the tree tree_height = input("How tall is the tree : ") # Convert into an integer tree_height = int(tree_height) # Get the starting spaces for the top of the tree spaces = tree_height - 1 # There is one hash to start that will be incremented hashes = 1 # Save stump spaces til later stump_spaces = tree_height - 1 # Makes sure the right number of rows are printed while tree_height != 0: # Print the spaces # end="" means a newline won't be added for i in range(spaces): print(' ', end="") # Print the hashes for i in range(hashes): print('#', end="") # Newline after each row is printed print() # I know from research that spaces is decremented by 1 each time spaces -= 1 # I know from research that hashes is incremented by 2 each time hashes += 2 # Decrement tree height each time to jump out of loop tree_height -= 1 # Print the spaces before the stump and then a hash for i in range(stump_spaces): print(' ', end="") print("#") #~~Learn to Program 3 # ---------- FORCE USER TO ENTER A NUMBER ---------- # By giving the while a value of True it will cycle until a break is reached while True: # If we expect an error can occur surround potential error with try try: number = int(input("Please enter a number : ")) break # The code in the except block provides an error message to set things right # We can either target a specific error like ValueError except ValueError: print("You didn't enter a number") # We can target all other errors with a default except: print("An unknown error occurred") print("Thank you for entering a number") # ---------- Problem : Implement a Do While Loop ---------- # Now I want you to implement a Do While loop in Python # They always execute all of the code at least once and at # the end check if a condition is true that would warrant # running the code again. They have this format # do { # ... Bunch of code ... # } while(condition) # I'll create a guessing game in which the user must chose # a number between 1 and 10 of the following format ''' Guess a number between 1 and 10 : 1 Guess a number between 1 and 10 : 3 Guess a number between 1 and 10 : 5 Guess a number between 1 and 10 : 7 You guessed it ''' # Hint : You'll need a while and break secret_number = 7 while True: guess = int(input("Guess a number between 1 and 10 : ")) if guess == secret_number: print("You guessed it") break # ---------- MATH MODULE ---------- # Python provides many functions with its Math module import math # Because you used import you access methods by referencing the module print("ceil(4.4) = ", math.ceil(4.4)) print("floor(4.4) = ", math.floor(4.4)) print("fabs(-4.4) = ", math.fabs(-4.4)) # Factorial = 1 * 2 * 3 * 4 print("factorial(4) = ", math.factorial(4)) # Return remainder of division print("fmod(5,4) = ", math.fmod(5,4)) # Receive a float and return an int print("trunc(4.2) = ", math.trunc(4.2)) # Return x^y print("pow(2,2) = ", math.pow(2,2)) # Return the square root print("sqrt(4) = ", math.sqrt(4)) # Special values print("math.e = ", math.e) print("math.pi = ", math.pi) # Return e^x print("exp(4) = ", math.factorial(4)) # Return the natural logarithm e * e * e ~= 20 so log(20) tells # you that e^3 ~= 20 print("log(20) = ", math.log(20)) # You can define the base and 10^3 = 1000 print("log(1000,10) = ", math.log(1000,10)) # You can also use base 10 like this print("log10(1000) = ", math.log10(1000)) # We have the following trig functions # sin, cos, tan, asin, acos, atan, atan2, asinh, acosh, # atanh, sinh, cosh, tanh # Convert radians to degrees and vice versa print("degrees(1.5708) = ", math.degrees(1.5708)) print("radians(90) = ", math.radians(90)) # ---------- ACCURATE FLOATING POINT CALCULATIONS ---------- # The decimal module provides for more accurate floating point calculations # With from you can reference methods without the need to reference the module # like we had to do with math above # We create an alias being D here to avoid conflicts with methods with # the same name from decimal import Decimal as D sum = D(0) sum += D("0.01") sum += D("0.01") sum += D("0.01") sum -= D("0.03") print("Sum = ", sum) # ---------- STRINGS ---------- # Text is stored using the string data type # You can use type to see the data type of a value print(type(3)) print(type(3.14)) # Single quotes or double are both used for strings print(type("3")) print(type('3')) samp_string = "This is a very important string" # Each character is stored in a series of boxes labeled with index numbers # You can get a character by referencing an index print(samp_string[0]) # Get the last character print(samp_string[-1]) # Get the last character print(samp_string[3+5]) # Get the string length print("Length :", len(samp_string)) # Get a slice by saying where to start and end # The 4th index isn't returned print(samp_string[0:4]) # Get everything starting at an index print(samp_string[8:]) # Join or concatenate strings with + print("Green " + "Eggs") # Repeat strings with * print("Hello " * 5) # Convert an int into a string num_string = str(4) # Cycle through each character with for for char in samp_string: print(char) # Cycle through characters in pairs # Subtract 1 from the length because length is 1 more then the highest index # because strings are 0 indexed # Use range starting at index 0 through string length and increment by # 2 each time through for i in range(0, len(samp_string)-1, 2): print(samp_string[i] + samp_string[i+1]) # Computers assign characters with a number known as a Unicode # A-Z have the numbers 65-90 and a-z 97-122 # You can get the Unicode code with ord() print("A =", ord("A")) # You can convert from Unicode with chr print("65 =", chr(65)) # ---------- PROBLEM : SECRET STRING ---------- # Receive a uppercase string and then hide its meaning by turning # it into a string of unicodes # Then translate it from unicode back into its original meaning norm_string = input("Enter a string to hide in uppercase: ") secret_string = "" # Cycle through each character in the string for char in norm_string: # Store each character code in a new string secret_string += str(ord(char)) print("Secret Message :", secret_string) norm_string = "" # Cycle through each character code 2 at a time by incrementing by # 2 each time through since unicodes go from 65 to 90 for i in range(0, len(secret_string)-1, 2): # Get the 1st and 2nd for the 2 digit number char_code = secret_string[i] + secret_string[i+1] # Convert the codes into characters and add them to the new string norm_string += chr(int(char_code)) print("Original Message :", norm_string) # ---------- SUPER AWESOME MIND SCRAMBLING PROBLEM ---------- # Make the above work with upper and lowercase with 1 addition and # 1 subtraction # Add these 2 changes # secret_string += str(ord(char) - 23) # norm_string += chr(int(char_code) + 23) #~~Learn to program 4 # ---------- STRING METHODS ---------- # Strings have many methods we can use beyond what I covered last time rand_string = " this is an important string " # Delete whitespace on left rand_string = rand_string.lstrip() # Delete whitespace on right rand_string = rand_string.rstrip() # Delete whitespace on right and left rand_string = rand_string.strip() # Capitalize the 1st letter print(rand_string.capitalize()) # Capitalize every letter print(rand_string.upper()) # lowercase all letters print(rand_string.lower()) # Turn a list into a string and separate items with the defined # separator a_list = ["Bunch", "of", "random", "words"] print(" ".join(a_list)) # Convert a string into a list a_list_2 = rand_string.split() for i in a_list_2: print(i) # Count how many times a string occurs in a string print("How many is :", rand_string.count("is")) # Get index of matching string print("Where is string :", rand_string.find("string")) # Replace a substring print(rand_string.replace("an ", "a kind of ")) # ---------- PROBLEM : ACRONYM GENERATOR ---------- # You will enter a string and then convert it to an acronym # with uppercase letters like this ''' Convert to Acronym : Random Access Memory RAM ''' # Ask for a string orig_string = input("Convert to Acronym : ") # Convert the string to all uppercase orig_string = orig_string.upper() # Convert the string into a list list_of_words = orig_string.split() # Cycle through the list for word in list_of_words: # Get the 1st letter of the word and eliminate the newline print(word[0], end="") print() # ---------- MORE STRING METHODS ---------- # For our next problem some additional string methods are going to be # very useful letter_z = "z" num_3 = "3" a_space = " " # Returns True if characters are letters or numbers # Whitespace is false print("Is z a letter or number :", letter_z.isalnum()) # Returns True if characters are letters print("Is z a letter :", letter_z.isalpha()) # Returns True if characters are numbers (Floats are False) print("Is 3 a number :", num_3.isdigit()) # Returns True if all are lowercase print("Is z a lowercase :", letter_z.islower()) # Returns True if all are uppercase print("Is z a uppercase :", letter_z.isupper()) # Returns True if all are spaces print("Is space a space :", a_space.isspace()) # ---------- MAKE A isfloat FUNCTION ---------- # There is no way to check if a string contains a float # so let's make one by defining our own function # Functions allow use to avoid repeating code # They can receive values (attributes / parameters) # They can return values # You define your function name and the names for the values # it receives like this def isfloat(str_val): try: # If the string isn't a float float() will throw a # ValueError float(str_val) # If there is a value you want to return use return return True except ValueError: return False pi = 3.14 # We call our functions by name and pass in a value between # the parentheses print("Is Pi a Float :", isfloat(pi)) # ---------- PROBLEM : CAESAR'S CIPHER ---------- # Receive a message and then encrypt it by shifting the # characters by a requested amount to the right # A becomes D, B becomes E for example # Also decrypt the message back again # A-Z have the numbers 65-90 in unicode # a-z have the numbers 97-122 # You get the unicode of a character with ord(yourLetter) # You convert from unicode to character with chr(yourNumber) # You should check if a character is a letter and if not # leave it as its default # Hints # Use isupper() to decided which unicodes to work with # Add the key (number of characters to shift) and if # bigger or smaller then the unicode for A, Z, a, or z # increase or decrease by 26 # Receive the message to encrypt and the number of characters to shift message = input("Enter your message : ") key = int(input("How many characters should we shift (1 - 26)")) # Prepare your secret message secret_message = "" # Cycle through each character in the message for char in message: # If it isn't a letter then keep it as it is in the else below if char.isalpha(): # Get the character code and add the shift amount char_code = ord(char) char_code += key # If uppercase then compare to uppercase unicodes if char.isupper(): # If bigger than Z subtract 26 if char_code > ord('Z'): char_code -= 26 # If smaller than A add 26 elif char_code < ord('A'): char_code += 26 # Do the same for lowercase characters else: if char_code > ord('z'): char_code -= 26 elif char_code < ord('a'): char_code += 26 # Convert from code to letter and add to message secret_message += chr(char_code) # If not a letter leave the character as is else: secret_message += char print("Encrypted :", secret_message) # To decrypt the only thing that changes is the sign of the key key = -key orig_message = "" for char in secret_message: if char.isalpha(): char_code = ord(char) char_code += key if char.isupper(): if char_code > ord('Z'): char_code -= 26 elif char_code < ord('A'): char_code += 26 else: if char_code > ord('z'): char_code -= 26 elif char_code < ord('a'): char_code += 26 orig_message += chr(char_code) else: orig_message += char print("Decrypted :", orig_message) # ---------- EXTRA HOMEWORK ---------- # For homework put the duplicate code above in a function #~~Learn to program 5 # ---------- FUNCTION BASICS ---------- # Functions allow use to reuse code and make the code easier # to understand # To create a function type def (define) the function name # and then in parentheses a comma separated list of values # to pass if needed def add_numbers(num_1, num2): # Return returns a value if needed return num_1 + num2 # You call the function by name followed by passing comma # separated values if needed and a value may or may not be # returned print("5 + 4 =", add_numbers(5, 4)) # ---------- FUNCTION LOCAL VARIABLES ---------- # Any variable defined inside of a function is available only # in that function # ---------- EXAMPLE 1 ---------- # Variables created in a function can't be accessed outside # of it def assign_name(): name = "Doug" assign_name() # Throws a NameError # print(name) # ---------- EXAMPLE 2 ---------- # You can't change a global variable even if it is passed # into a function def change_name(name): # Trying to change the global name = "Mark" # A variable defined outside of a function can't be changed # in the function using the above way name = "Tom" # Try to change the value change_name(name) # Prints Tom even though the function tries to change it print(name) # ---------- EXAMPLE 3 ---------- # If you want to change the value pass it back def change_name_2(): return "Mark" name = change_name_2() print(name) # ---------- EXAMPLE 4 ---------- # You can also use the global statement to change it gbl_name = "Sally" def change_name_3(): global gbl_name gbl_name = "Sammy" change_name_3() print(gbl_name) # ---------- RETURNING NONE ---------- # If you don't return a value a function will return None def get_sum(num1, num2): sum = num1 + num2 print(get_sum(5, 4)) # ---------- PROBLEM : SOLVE FOR X ---------- # Make a function that receives an algebraic equation like # x + 4 = 9 and solve for x # x will always be the 1st value received and you only # will deal with addition # Receive the string and split the string into variables def solve_eq(equation): x, add, num1, equal, num2 = equation.split() # Convert the strings into ints num1, num2 = int(num1), int(num2) # Convert the result into a string and join (concatenate) # it to the string "x = " return "x = " + str(num2 - num1) print(solve_eq("x + 4 = 9")) # ---------- RETURN MULTIPLE VALUES ---------- # You can return multiple values with the return statement def mult_divide(num1, num2): return (num1 * num2), (num1 / num2) mult, divide = mult_divide(5, 4) print("5 * 4 =", mult) print("5 / 4 =", divide) # ---------- RETURN A LIST OF PRIMES ---------- # A prime can only be divided by 1 and itself # 5 is prime because 1 and 5 are its only positive factors # 6 is a composite because it is divisible by 1, 2, 3 and 6 # We'll receive a request for primes up to the input value # We'll then use a for loop and check if modulus == 0 for # every value up to the number to check # If modulus == 0 that means the number isn't prime def isprime(num): # This for loop cycles through primes from 2 to # the value to check for i in range(2, num): # If any division has no remainder we know it # isn't a prime number if (num % i) == 0: return False return True def getPrimes(max_number): # Create a list to hold primes list_of_primes = [] # This for loop cycles through primes from 2 to # the maximum value requested for num1 in range(2, max_number): if isprime(num1): list_of_primes.append(num1) return list_of_primes max_num_to_check = int(input("Search for Primes up to : ")) list_of_primes = getPrimes(max_num_to_check) for prime in list_of_primes: print(prime) # ---------- UNKNOWN NUMBER OF ARGUMENTS ---------- # We can receive an unknown number of arguments using # the splat (*) operator def sumAll(*args): sum = 0 for i in args: sum += i return sum print("Sum :", sumAll(1,2,3,4)) # ---------- pythontut2.py ---------- # We need this module for our program import math # Functions allow us to avoid duplicate code in our programs # Aside from having to type code twice duplicate code is bad # because it requires us to change multiple blocks of code # if we need to make a change # ---------- OUR FUNCTIONS ---------- # This routes to the correct area function # The name of the value passed doesn't have to match def get_area(shape): # Switch to lowercase for easy comparison shape = shape.lower() if shape == "rectangle": rectangle_area() elif shape == "circle": circle_area() else: print("Please enter rectangle or circle") # Create function that calculates the rectangle area def rectangle_area(): length = float(input("Enter the length : ")) width = float(input("Enter the width : ")) area = length * width print("The area of the rectangle is", area) # Create function that calculates the circle area def circle_area(): radius = float(input("Enter the radius : ")) area = math.pi * (math.pow(radius, 2)) # Format the output to 2 decimal places print("The area of the circle is {:.2f}".format(area)) # ---------- END OF OUR FUNCTIONS ---------- # We often place our main programming logic in a function called main # We create it this way def main(): # Our program will calculate the area for rectangles or circles # Without functions we'd have to create a giant list of ifs, elifs # Ask the user what shape they have shape_type = input("Get area for what shape : ") # Call a function that will route to the correct function get_area(shape_type) # Because of functions it is very easy to see what is happening # For more detail just refer to the very short specific functions # All of the function definitions are ignored and this calls for main() # to execute when the program starts main() # ---------- HOMEWORK ---------- # Add the ability to calculate the area for parallelograms, # rhombus, triangles, and trapezoids #~~Learn to program 6 # ---------- LEARN TO PROGRAM 6 ---------- import random import math # With lists we can refer to groups of data with 1 name # Each item in the list corresponds to a number (index) # just like how people have identification numbers. # By default the 1st item in a list has the index 0 # [0 : "string"] [1 : 1.234] [2 : 28] [3 : "c"] # Python lists can grow in size and can contain data # of any type randList = ["string", 1.234, 28] # Create a list with range oneToTen = list(range(10)) # An awesome thing about lists is that you can use many # of the same functions with them that you used with strings # Combine lists randList = randList + oneToTen # Get the 1st item with an index print(randList[0]) # Get the length print("List Length :", len(randList)) # Slice a list to get 1st 3 items first3 = randList[0:3] # Cycle through the list and print the index for i in first3: print("{} : {}".format(first3.index(i), i)) # You can repeat a list item with * print(first3[0] * 3) # You can see if a list contains an item print("string" in first3) # You can get the index of a matching item print("Index of string :", first3.index("string")) # Find out how many times an item is in the list print("How many strings :", first3.count("string")) # You can change a list item first3[0] = "New String" for i in first3: print("{} : {}".format(first3.index(i), i)) # Append a value to the end of a list first3.append("Another") # ---------- PROBLEM : CREATE A RANDOM LIST ---------- # Generate a random list of 5 values between 1 and 9 numList = [] for i in range(5): numList.append(random.randrange(1, 9)) # ---------- SORT A LIST : BUBBLE SORT ---------- # The Bubble sort is a way to sort a list # It works this way # 1. An outer loop decreases in size each time # 2. The goal is to have the largest number at the end of # the list when the outer loop completes 1 cycle # 3. The inner loop starts comparing indexes at the beginning # of the loop # 4. Check if list[Index] > list[Index + 1] # 5. If so swap the index values # 6. When the inner loop completes the largest number is at # the end of the list # 7. Decrement the outer loop by 1 # Create the value that will decrement for the outer loop # Its value is the last index in the list i = len(numList) - 1 while i > 1: j = 0 while j < i: # Tracks the comparison of index values print("\nIs {} > {}".format(numList[j], numList[j+1])) print() # If the value on the left is bigger switch values if numList[j] > numList[j+1]: print("Switch") temp = numList[j] numList[j] = numList[j + 1] numList[j + 1] = temp else: print("Don't Switch") j += 1 # Track changes to the list for k in numList: print(k, end=", ") print() print("END OF ROUND") i -= 1 for k in numList: print(k, end=", ") print() # ---------- MORE LIST FUNCTIONS ---------- numList = [] for i in range(5): numList.append(random.randrange(1, 9)) # Sort a list numList.sort() # Reverse a list numList.reverse() for k in numList: print(k, end=", ") print() # Insert value at index insert(index, value) numList.insert(5, 10) # Delete first occurrence of value numList.remove(10) for k in numList: print(k, end=", ") print() # Remove item at index numList.pop(2) for k in numList: print(k, end=", ") print() # ---------- LIST COMPREHENSIONS ---------- # You can construct lists in interesting ways using # list comprehensions # Perform an operation on each item in the list # Create a list of even values evenList = [i*2 for i in range(10)] for k in evenList: print(k, end=", ") print() # List of lists containing values to the power of # 2, 3, 4 numList = [1,2,3,4,5] listOfValues = [[math.pow(m, 2), math.pow(m, 3), math.pow(m, 4)] for m in numList] for k in listOfValues: print(k) print() # Create a 10 x 10 list multiDList = [[0] * 10 for i in range(10)] # Change a value in the multidimensional list multiDList[0][1] = 10 # Get the 2nd item in the 1st list # It may help to think of it as the 2nd item in the 1st row print(multiDList[0][1]) # Get the 2nd item in the 2nd list print(multiDList[1][1]) # ---------- MULTIDIMENSIONAL LIST ---------- # Show how indexes work with a multidimensional list listTable = [[0] * 10 for i in range(10)] for i in range(10): for j in range(10): listTable[i][j] = "{} : {}".format(i, j) for i in range(10): for j in range(10): print(listTable[i][j], end=" || ") print() # ---------- PROBLEM : CREATE MULTIPLICATION TABLE ---------- # With 2 for loops fill the cells in a multidimensional # list with a multiplication table using values 1 - 9 ''' 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8, 10, 12, 14, 16, 18, 3, 6, 9, 12, 15, 18, 21, 24, 27, 4, 8, 12, 16, 20, 24, 28, 32, 36, 5, 10, 15, 20, 25, 30, 35, 40, 45, 6, 12, 18, 24, 30, 36, 42, 48, 54, 7, 14, 21, 28, 35, 42, 49, 56, 63, 8, 16, 24, 32, 40, 48, 56, 64, 72, 9, 18, 27, 36, 45, 54, 63, 72, 81 ''' # Create the multidimensional list multTable = [[0] * 10 for i in range(10)] # This will increment for each row for i in range(1, 10): # This will increment for each item in the row for j in range(1, 10): # Assign the value to the cell multTable[i][j] = i * j # Output the data in the same way you assigned it for i in range(1, 10): for j in range(1, 10): print(multTable[i][j], end=", ") print() #~~Learn to program 7 # ---------- LEARN TO PROGRAM 7 ---------- # ---------- DICTIONARIES ---------- # While lists organize data based on sequential indexes # Dictionaries instead use key / value pairs. # A key / value pair could be # fName : "Derek" where fName is the key and "Derek" is # the value # Create a Dictionary about me derekDict = {"fName": "Derek", "lName": "Banas", "address": "123 Main St"} # Get a value with the key print("May name :", derekDict["fName"]) # Change a value with the key derekDict["address"] = "215 North St" # Dictionaries may not print out in the order created # since they are unordered print(derekDict) # Add a new key value derekDict['city'] = 'Pittsburgh' # Check if a key exists print("Is there a city :", "city" in derekDict) # Get the list of values print(derekDict.values()) # Get the list of keys print(derekDict.keys()) # Get the key and value with items() for k, v in derekDict.items(): print(k, v) # Get gets a value associated with a key or the default print(derekDict.get("mName", "Not Here")) # Delete a key value del derekDict["fName"] # Loop through the dictionary keys for i in derekDict: print(i) # Delete all entries derekDict.clear() # List for holding Dictionaries employees = [] # Input employee data fName, lName = input("Enter Employee Name : ").split() employees.append({'fName': fName, 'lName': lName}) print(employees) # ---------- PROBLEM : CREATE A CUSTOMER LIST ---------- # Create an array of customer dictionaries # Output should look like this ''' Enter Customer (Yes/No) : y Enter Customer Name : Derek Banas Enter Customer (Yes/No) : y Enter Customer Name : Sally Smith Enter Customer (Yes/No) : n Derek Banas Sally Smith ''' # Create customer array outside the for so it isn't local # to the while loop customers = [] while True: # Cut off the 1st letter to cover if the user # types a n or y createEntry = input("Enter Customer (Yes/No) : ") createEntry = createEntry[0].lower() if createEntry == "n": # Leave the while loop when n is entered break else: # Get the customer name by splitting at the space fName, lName = input("Enter Customer Name : ").split() # Add the dictionary to the array customers.append({'fName': fName, 'lName': lName}) # Print out customer list for cust in customers: print(cust['fName'], cust['lName']) # ---------- RECURSIVE FUNCTIONS ---------- # A function that refers to itself is a recursive function # Calculating factorials is commonly done with a recursive # function 3! = 3 * 2 * 1 def factorial(num): # Every recursive function must contain a condition # when it ceases to call itself if num <= 1: return 1 else: result = num * factorial(num - 1) return result print(factorial(4)) # 1st : result = 4 * factorial(3) = 4 * 6 = 24 # 2nd : result = 3 * factorial(2) = 3 * 2 = 6 # 3rd : result = 2 * factorial(1) = 2 * 1 = 2 # ---------- PROBLEM : CALCULATE FIBONACCI NUMBERS ---------- # To calculate Fibonacci numbers we sum the 2 previous # values to calculate the next item in the list like this # 1, 1, 2, 3, 5, 8 ... # The Fibonacci sequence is defined by: # Fn = Fn-1 + Fn-2 # Where F0 = 0 and F1 = 1 ''' Sample Run Though to Help print(fib(3)) # 1st : result = fib(2) + fib(1) : 2 + 1 # 2nd : result = (fib(1) + fib(0)) + (fib(0)) : 1 + 0 # 3rd : result = fib(2) + fib(1) print(fib(4)) # 1st : result = fib(3) + fib(2) : 3 + 2 # 2nd : result = (fib(2) + fib(1)) + (fib(1) + fib(0)) : 2 + 1 # 3rd : result = (fib(1) + fib(0)) + fib(0) : 1 + 0 ''' def fib(n): if n == 0: return 0 elif n == 1: return 1 else: result = fib(n-1) + fib(n-2) return result print(fib(3)) print(fib(4)) #~~Learn to program 8 # ---------- READING & WRITING TEXT ---------- # The os module provides methods for file processing import os # We are able to store data for later use in files # You can create or use an already created file with open # If you use w (write) for mode then the file is # overwritten. # If you use a (append) you add to the end of the file # Text is stored using unicode where numbers represent # all possible characters # We start the code with with which guarantees the file # will be closed if the program crashes with open("mydata.txt", mode="w", encoding="utf-8") as myFile: # You can write to the file with write # It doesn't add a newline myFile.write("Some random text\nMore random text\nAnd some more") # Open the file for reading # You don't have to provide a mode because it is # read by default with open("mydata.txt", encoding="utf-8") as myFile: # We can read data in a few ways # 1. read() reads everything into 1 string # 2. readline() reads everything including the first newline # 3. readlines() returns a list of every line which includes # each newline # Use read() to get everything at once print(myFile.read()) # Find out if the file is closed print(myFile.closed) # Get the file name print(myFile.name) # Get the access mode of the file print(myFile.mode) # Rename our file os.rename("mydata.txt", "mydata2.txt") # Delete a file # os.remove("mydata.dat") # Create a directory # os.mkdir("mydir") # Change directories # os.chdir("mydir") # Display current directory print("Current Directory :", os.getcwd()) # Remove a directory, but 1st move back 1 directory # os.chdir("..") # os.rmdir("mydir") # ---------- PROBLEM : Fibonacci sequence ---------- # Previously we generated 1 number in the # Fibonacci sequence. This time ask the user to define # how many numbers they want and display them # The formula for calculating the Fibonacci sequence is # Fn = Fn-1 + Fn-2 # Where F0 = 0 and F1 = 1 # Sample Output ''' How many Fibonacci values should be found : 30 1 1 2 3 5 All Done ''' def fib(num): if num == 0: return 0 elif num == 1: return 1 else: result = fib(num - 1) + fib(num - 2) return result numFibValues = int(input("How many Fibonacci values should be found : ")) i = 1 # While i is less then the number of values requested # continue to find more while i < numFibValues: # Call the fib() fibValue = fib(i) print(fibValue) i += 1 print("All Done") # ---------- READ ONE LINE AT A TIME ---------- # You can read 1 line at a time with readline() # Open the file with open("mydata2.txt", encoding="utf-8") as myFile: lineNum = 1 # We'll use a while loop that loops until the data # read is empty while True: line = myFile.readline() # line is empty so exit if not line: break print("Line", lineNum, " :", line, end="") lineNum += 1 # ---------- PROBLEM : ANALYZE THE FILE ---------- # As you cycle through each line output the number of # words and average word length ''' Line 1 Number of Words : 3 Avg Word Length : 4.7 Line 2 Number of Words : 3 Avg Word Length : 4.7 ''' with open("mydata2.txt", encoding="utf-8") as myFile: lineNum = 1 while True: line = myFile.readline() # line is empty so exit if not line: break print("Line", lineNum) # Put the words in a list using the space as # the boundary between words wordList = line.split() # Get the number of words with len() print("Number of Words :", len(wordList)) # Incremented for each character charCount = 0 for word in wordList: for char in word: charCount += 1 # Divide to find the answer avgNumChars = charCount/len(wordList) # Use format to limit to 2 decimals print("Avg Word Length : {:.2}".format(avgNumChars)) lineNum += 1 # ---------- TUPLES ---------- # A Tuple is like a list, but their values can't be changed # Tuples are surrounded with parentheses instead of # square brackets myTuple = (1, 2, 3, 5, 8) # Get a value with an index print("1st Value :", myTuple[0]) # Get a slice from the 1st index up to but not including # the 3rd print(myTuple[0:3]) # Get the number of items in a Tuple print("Tuple Length :", len(myTuple)) # Join or concatenate tuples moreFibs = myTuple + (13, 21, 34) # Check if a value is in a Tuple print("34 in Tuple :", 34 in moreFibs) # Iterate through a tuple for i in moreFibs: print(i) # Convert a List into a Tuple aList = [55, 89, 144] aTuple = tuple(aList) # Convert a Tuple into a List aList = list(aTuple) # Get max and minimum value print("Min :", min(aTuple)) print("Max :", max(aTuple)) #~~Learn to program 9 # ---------- LEARN TO PROGRAM 9 ---------- # Real world objects have attributes and capabilities # A dog for example has the attributes of height, weight # favorite food, etc. # It has the capability to run, bark, scratch, etc. # In object oriented programming we model real world objects # be defining the attributes (fields) and capabilities (methods) # that they have. # A class is the template used to model these objects # Here we will model a Dog object class Dog: # The init method is called to create an object # We give default values for the fields if none # are provided def __init__(self, name="", height=0, weight=0): # self allows an object to refer to itself # It is like how you refer to yourself with my # We will take the values passed in and assign # them to the new Dog objects fields (attributes) self.name = name self.height = height self.weight = weight # Define what happens when the Dog is asked to # demonstrate its capabilities def run(self): print("{} the dog runs".format(self.name)) def eat(self): print("{} the dog eats".format(self.name)) def bark(self): print("{} the dog barks".format(self.name)) def main(): # Create a new Dog object spot = Dog("Spot", 66, 26) spot.bark() bowser = Dog() main() # ---------- GETTERS & SETTERS ---------- # Getters and Setters are used to protect our objects # from assigning bad fields or for providing improved # output class Square: def __init__(self, height="0", width="0"): self.height = height self.width = width # This is the getter @property def height(self): print("Retrieving the height") # Put a __ before this private field return self.__height # This is the setter @height.setter def height(self, value): # We protect the height from receiving a bad value if value.isdigit(): # Put a __ before this private field self.__height = value else: print("Please only enter numbers for height") # This is the getter @property def width(self): print("Retrieving the width") return self.__width # This is the setter @width.setter def width(self, value): if value.isdigit(): self.__width = value else: print("Please only enter numbers for width") def getArea(self): return int(self.__width) * int(self.__height) def main(): aSquare = Square() height = input("Enter height : ") width = input("Enter width : ") aSquare.height = height aSquare.width = width print("Height :", aSquare.height) print("Width :", aSquare.width) print("The Area is :", aSquare.getArea()) main() # ---------- WARRIORS BATTLE ---------- # We will create a game with this sample output ''' Sam attacks Paul and deals 9 damage Paul is down to 10 health Paul attacks Sam and deals 7 damage Sam is down to 7 health Sam attacks Paul and deals 19 damage Paul is down to -9 health Paul has Died and Sam is Victorious Game Over ''' # We will create a Warrior & Battle class import random import math # Warriors will have names, health, and attack and block maximums # They will have the capabilities to attack and block random amounts class Warrior: def __init__(self, name="warrior", health=0, attkMax=0, blockMax=0): self.name = name self.health = health self.attkMax = attkMax self.blockMax = blockMax def attack(self): # Randomly calculate the attack amount # random() returns a value from 0.0 to 1.0 attkAmt = self.attkMax * (random.random() + .5) return attkAmt def block(self): # Randomly calculate how much of the attack was blocked blockAmt = self.blockMax * (random.random() + .5) return blockAmt # The Battle class will have the capability to loop until 1 Warrior dies # The Warriors will each get a turn to attack each turn class Battle: def startFight(self, warrior1, warrior2): # Continue looping until a Warrior dies switching back and # forth as the Warriors attack each other while True: if self.getAttackResult(warrior1, warrior2) == "Game Over": print("Game Over") break if self.getAttackResult(warrior2, warrior1) == "Game Over": print("Game Over") break # A function will receive each Warrior that will attack the other # Have the attack and block amounts be integers to make the results clean # Output the results of the fight as it goes # If a Warrior dies return that result to end the looping in the # above function # Make this method static because we don't need to use self @staticmethod def getAttackResult(warriorA, warriorB): warriorAAttkAmt = warriorA.attack() warriorBBlockAmt = warriorB.block() damage2WarriorB = math.ceil(warriorAAttkAmt - warriorBBlockAmt) warriorB.health = warriorB.health - damage2WarriorB print("{} attacks {} and deals {} damage".format(warriorA.name, warriorB.name, damage2WarriorB)) print("{} is down to {} health".format(warriorB.name, warriorB.health)) if warriorB.health <= 0: print("{} has Died and {} is Victorious".format(warriorB.name, warriorA.name)) return "Game Over" else: return "Fight Again" def main(): # Create 2 Warriors paul = Warrior("Paul", 50, 20, 10) sam = Warrior("Sam", 50, 20, 10) # Create Battle object battle = Battle() # Initiate Battle battle.startFight(paul, sam) main() #~~Learn to program 10 # When we create a class we can inherit all of the fields and methods # from another class. This is called inheritance. # The class that inherits is called the subclass and the class we # inherit from is the super class # This will be our super class class Animal: def __init__(self, birthType="Unknown", appearance="Unknown", blooded="Unknown"): self.__birthType = birthType self.__appearance = appearance self.__blooded = blooded # The getter method @property def birthType(self): # When using getters and setters don't forget the __ return self.__birthType @birthType.setter def birthType(self, birthType): self.__birthType = birthType @property def appearance(self): return self.__appearance @appearance.setter def appearance(self, appearance): self.__appearance = appearance @property def blooded(self): return self.__blooded @blooded.setter def blooded(self, blooded): self.__blooded = blooded # Can be used to cast our object as a string # type(self).__name__ returns the class name def __str__(self): return "A {} is {} it is {} it is " \ "{}".format(type(self).__name__, self.birthType, self.appearance, self.blooded) # Create a Mammal class that inherits from Animal # You can inherit from multiple classes by separating # the classes with a comma in the parentheses class Mammal(Animal): def __init__(self, birthType="born alive", appearance="hair or fur", blooded="warm blooded", nurseYoung=True): # Call for the super class to initialize fields Animal.__init__(self, birthType, appearance, blooded) self.__nurseYoung = nurseYoung # We can extend the subclasses @property def nurseYoung(self): return self.__nurseYoung @nurseYoung.setter def appearance(self, nurseYoung): self.__nurseYoung = nurseYoung # Overwrite __str__ # You can use super() to refer to the superclass def __str__(self): return super().__str__() + " and it is {} they nurse " \ "their young".format(self.nurseYoung) class Reptile(Animal): def __init__(self, birthType="born in an egg or born alive", appearance="dry scales", blooded="cold blooded"): # Call for the super class to initialize fields Animal.__init__(self, birthType, appearance, blooded) # Operator overloading isn't necessary in Python because # Python allows you to enter unknown numbers of values # Always make sure self is the first attribute in your # class methods def sumAll(self, *args): sum = 0 for i in args: sum += i return sum def main(): animal1 = Animal("born alive") print(animal1.birthType) # Call __str__() print(animal1) print() mammal1 = Mammal() print(mammal1) print(mammal1.birthType) print(mammal1.appearance) print(mammal1.blooded) print(mammal1.nurseYoung) print() reptile1 = Reptile() print(reptile1.birthType) print(reptile1.appearance) print(reptile1.blooded) print() # Operator overloading in Python print("Sum : {}".format(reptile1.sumAll(1,2,3,4,5))) # Polymorphism in Python works differently from other # languages in that functions accept any object # and expect that object to provide the needed method # This isn't something to dwell on. Just know that # if you call on a method for an object that the # method just needs to exist for that object to work. # Polymorphism is a big deal in other languages that # are statically typed (type is defined at declaration) # but because Python is dynamically typed (type defined # when a value is assigned) it doesn't matter as much. def getBirthType(theObject): print("The {} is {}".format(type(theObject).__name__, theObject.birthType)) getBirthType(mammal1) getBirthType(reptile1) main() # ---------- MAGIC METHODS ---------- # Magic methods are surrounded by double underscores # We can use magic methods to define how operators # like +, -, *, /, ==, >, <, etc. will work with our # custom objects # Magic methods are used for operator overloading # in Python # __eq__ : Equal # __ne__ : Not Equal # __lt__ : Less Than # __gt__ : Greater Than # __le__ : Less Than or Equal # __ge__ : Greater Than or Equal # __add__ : Addition # __sub__ : Subtraction # __mul__ : Multiplication # __div__ : Division # __mod__ : Modulus class Time: def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second # Magic method that defines the string format of the object def __str__(self): # :02d adds a leading zero to have a minimum of 2 digits return "{}:{:02d}:{:02d}".format(self.hour,self.minute, self.second) def __add__(self, other_time): new_time = Time() # ---------- PROBLEM ---------- # How would you go about adding 2 times together? # Add the seconds and correct if sum is >= 60 if (self.second + other_time.second) >= 60: self.minute += 1 new_time.second = (self.second + other_time.second) - 60 else: new_time.second = self.second + other_time.second # Add the minutes and correct if sum is >= 60 if (self.minute + other_time.minute) >= 60: self.hour += 1 new_time.minute = (self.minute + other_time.minute) - 60 else: new_time.minute = self.minute + other_time.minute # Add the minutes and correct if sum is > 60 if (self.hour + other_time.hour) > 24: new_time.hour = (self.hour + other_time.hour) - 24 else: new_time.hour = self.hour + other_time.hour return new_time def main(): time1 = Time(1, 20, 30) print(time1) time2 = Time(24, 41, 30) print(time1 + time2) # For homework get the Time objects to work for the other # mathematical and comparison operators main() #~~Learn to program 11 # ---------- STATIC METHODS ---------- # Static methods allow access without the need to initialize # a class. They should be used as utility methods, or when # a method is needed, but it doesn't make sense for the real # world object to be able to perform a task class Sum: # You use the static method decorator to define that a # method is static @staticmethod def getSum(*args): sum = 0 for i in args: sum += i return sum def main(): # Call a static method by proceeding it with its class # name print("Sum :", Sum.getSum(1,2,3,4,5)) main() # ---------- STATIC VARIABLES ---------- # Fields declared in a class, but outside of any method # are static variables. There value is shared by every # object of that class class Dog: # This is a static variable num_of_dogs = 0 def __init__(self, name="Unknown"): self.name = name # You reference the static variable by proceeding # it with the class name Dog.num_of_dogs += 1 @staticmethod def getNumOfDogs(): print("There are currently {} dogs".format(Dog.num_of_dogs)) def main(): spot = Dog("Spot") doug = Dog("Doug") spot.getNumOfDogs() main() # ---------- MODULES ---------- # Your Python programs will contain a main program that # includes your main function. Then you will create many # modules in separate files. Modules also end with .py # just like any other Python file # ————— sum.py ————— def getSum(*args): sum = 0 for i in args: sum += i return sum # ————— End of sum.py ————— # You can import by listing the file name minus the py import sum # Get access to functions by proceeding with the file # name and then the function you want print("Sum :", sum.getSum(1,2,3,4,5)) # ---------- FROM ---------- # You can use from to copy specific functions from a module # You can use from sum import * to import all functions # You can import multiple functions by listing them after # import separated by commas from sum import getSum # You don't have to reference the module name now print("Sum :", getSum(1,2,3,4,5)) # ---------- EXCEPTION HANDLING ---------- # Exceptions are triggered either when an error occurs # or when you want them to. # We use exceptions are used to handle errors, execute # specific code when code generates something out of # the ordinary, to always execute code when something # happens (close a file that was opened), # When an error occurs you stop executing code and jump # to execute other code that responds to that error # Let's handle an IndexError exception that is # triggered when you try to access an index in a list # that doesn't exist # Surround a potential exception with try try: aList = [1,2,3] print(aList[3]) # Catch the exception with except followed by the # exception you want to catch # You can catch multiple exceptions by separating them # with commas inside parentheses # except (IndexError, NameError): except IndexError: print("Sorry that index doesn't exist") # If the exception wasn't caught above this will # catch all others except: print("An unknown error occurred") # ---------- CUSTOM EXCEPTIONS ---------- # Lets trigger an exception if the user enters a # name that contains a number # Although you won't commonly create your own exceptions # this is how you do it # Create a class that inherits from Exception class DogNameError(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) try: dogName = input("What is your dogs name : ") if any(char.isdigit() for char in dogName): # Raise your own exception # You can raise the built in exceptions as well raise DogNameError except DogNameError: print("Your dogs name can't contain a number") # ---------- FINALLY & ELSE ---------- # finally is used when you always want certain code to # execute whether an exception is raised or not num1, num2 = input("Enter to values to divide : ").split() try: quotient = int(num1) / int(num2) print("{} / {} = {}".format(num1, num2, quotient)) except ZeroDivisionError: print("You can't divide by zero") # else is only executed if no exception was raised else: print("You didn't raise an exception") finally: print("I execute no matter what") # ---------- PROBLEM EXCEPTIONS & FILES ---------- # 1. Create a file named mydata2.txt and put data in it # 2. Using what you learned in part 8 and Google to find # out how to open a file without with try to open the # file in a try block # 3. Catch the FileNotFoundError exception # 4. In else print the file contents # 5. In finally close the file # 6. Try to open the nonexistent file mydata3.txt and # test to see if you caught the exception try: myFile = open("mydata2.txt", encoding="utf-8") # We can use as to access data and methods in the # exception class except FileNotFoundError as ex: print("That file was not found") # Print out further data on the exception print(ex.args) else: print("File :", myFile.read()) myFile.close() finally: print("Finished Working with File") #~~Learn to program 12 # ---------- ADVANCED FUNCTIONS ---------- # ---------- FUNCTIONS AS OBJECTS ---------- def mult_by_2(num): return num * 2 # A function can be # 1. Assigned to another name times_two = mult_by_2 print("4 * 2 =", times_two(4)) # 2. Passed into other functions def do_math(func, num): return func(num) print("8 * 2 =", do_math(mult_by_2, 8)) # 3. Returned from a function def get_func_mult_by_num(num): # Create a dynamic function that will receive a value # and then return that value times the value passed # into getFuncMultByNum() def mult_by(value): return num * value return mult_by generated_func = get_func_mult_by_num(5) print("5 * 10 =", generated_func(10)) # 4. Embedded in a data structure listOfFuncs = [times_two, generated_func] print("5 * 9 =", listOfFuncs[1](9)) # ---------- PROBLEM ---------- # Create a function that receives a list and a function # The function passed will return True or False if a list # value is odd. # The surrounding function will return a list of odd # numbers def is_it_odd(num): if num % 2 == 0: return False else: return True def change_list(list, func): oddList = [] for i in list: if func(i): oddList.append(i) return oddList aList = range(1, 21) print(change_list(aList, is_it_odd)) # ---------- FUNCTION ANNOTATIONS ---------- # It is possible to define the data types of attributes # and the returned value with annotations, but they have # no impact on how the function operates, but instead # are for documentation def random_func(name: str, age: int, weight: float) -> str: print("Name :", name) print("Age :", age) print("Weight :", weight) return "{} is {} years old and weighs {}".format(name, age, weight) print(random_func("Derek", 41, 165.5)) # You don't get an error if you pass bad data print(random_func(89, "Derek", "Turtle")) # You can print the annotations print(random_func.__annotations__) # ---------- ANONYMOUS FUNCTIONS : LAMBDA ---------- # lambda is like def, but rather then assign the function # to a name it just returns it. Because there is no name # that is why they are called anonymous functions. You # can however assign a lambda function to a name. # This is their format # lambda arg1, arg2,... : expression using the args # lambdas are used when you need a small function, but # don't want to junk up your code with temporary # function names that may cause conflicts # Add values sum = lambda x, y : x + y print("Sum :", sum(4, 5)) # Use a ternary operator to see if someone can vote can_vote = lambda age: True if age >= 18 else False print("Can Vote :", can_vote(16)) # Create a list of functions powerList = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4] # Run each function on a value for func in powerList: print(func(4)) # You can also store lambdas in dictionaires attack = {'quick': (lambda: print("Quick Attack")), 'power': (lambda: print("Power Attack")), 'miss': (lambda: print("The Attack Missed"))} attack['quick']() # You could get a random dictionary as well for say our # previous warrior objects import random # keys() returns an iterable so we convert it into a list # choice() picks a random value from that list attackKey = random.choice(list(attack.keys())) attack[attackKey]() # ---------- PROBLEM ---------- # Create a random list filled with the characters H and T # for heads and tails. Output the number of Hs and Ts # Example Output # Heads : 46 # Tails : 54 # Create the list flipList = [] # Populate the list with 100 Hs and Ts # Trick : random.choice() returns a random value from the list for i in range(1, 101): flipList += random.choice(['H', 'T']) # Output results print("Heads : ", flipList.count('H')) print("Tails : ", flipList.count('T')) # ---------- MAP ---------- # Map allows us to execute a function on each item in a list # Generate a list from 1 to 10 oneTo10 = range(1, 11) # The function to pass into map def dbl_num(num): return num * 2 # Pass in the function and the list to generate a new list print(list(map(dbl_num, oneTo10))) # You could do the same thing with a lambda print(list(map((lambda x: x * 3), oneTo10))) # You can perform calculations against multiple lists aList = list(map((lambda x, y: x + y), [1, 2, 3], [1, 2, 3])) print(aList) # ---------- FILTER ---------- # Filter selects items from a list based on a function # Print out the even values from a list print(list(filter((lambda x: x % 2 == 0), range(1, 11)))) # ---------- PROBLEM ---------- # Find the multiples of 9 from a random 100 value list with # values between 1 and 1000 # Generate a random list with randint between 1 and 1000 # Use range to generate 100 values randList = list(random.randint(1, 1001) for i in range(100)) # Use modulus to find multiples of 9 by passing the random # list to filter print(list(filter((lambda x: x % 9 == 0), randList))) # ---------- REDUCE ---------- # Reduce receives a list and returns a single result # You must import reduce from functools import reduce # Add up the values in a list print(reduce((lambda x, y: x + y), range(1, 6))) #~~Learn to program 13 # ---------- ITERABLES ---------- # An iterable is a stored sequence of values (list) or, # as we will see when we cover generators, an # object that produces one value at a time # Iterables differ from iterators in that an iterable # is an object with an __iter__ method which returns # an iterator. An iterator is an object with a # __next__ method which retrieves the next value from # sequence of values # Define a string and convert it into an iterator sampStr = iter("Sample") print("Char :", next(sampStr)) print("Char :", next(sampStr)) # You can add iterator behavior to your classes class Alphabet: def __init__(self): self.letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" self.index = -1 def __iter__(self): return self def __next__(self): if self.index >= len(self.letters) - 1: raise StopIteration self.index += 1 return self.letters[self.index] alpha = Alphabet() for letter in alpha: print(letter) # Iterate through a dictionary because it is an iterable derek = {"fName": "Derek", "lName": "Banas"} for key in derek: print(key, derek[key]) # ---------- PROBLEM ---------- # Create a class that returns values from the Fibonacci # sequence each time next is called # Sample Output # Fib : 1 # Fib : 2 # Fib : 3 # Fib : 5 class FibGenerator: def __init__(self): self.first = 0 self.second = 1 def __iter__(self): return self def __next__(self): fibNum = self.first + self.second self.first = self.second self.second = fibNum return fibNum fibSeq = FibGenerator() for i in range(10): print("Fib :", next(fibSeq)) # ---------- LIST COMPREHENSIONS ---------- # A list comprehension executes an expression against an iterable # Note: While they are super powerful, try not to make list # comprehensions that are hard to figure out for others # To multiply 2 times every value with a map we'd do print(list(map((lambda x: x * 2), range(1, 11)))) # With a list comprehension we'd do # Note that a list comprehension is surrounded by [] # because it returns a list print([2 * x for x in range(1, 11)]) # To construct a list of odds using filter we'd print(list(filter((lambda x: x % 2 != 0), range(1, 11)))) # To do the same with a list comprehension print([x for x in range(1, 11) if x % 2 != 0]) # A list comprehension can act as map and filter # on one line # Generate a list of 50 values and take them to the power # of 2 and return all that are multiples of 8 print([i ** 2 for i in range(50) if i % 8 == 0]) # You can have multiple for loops as well # Multiply all values in one list times all values in # another print([x * y for x in range(1, 3) for y in range(11, 16)]) # You can put list comprehensions in list comprehensions # Generate a list of 10 values, multiply them by 2 and # return multiples of 8 print([x for x in [i * 2 for i in range(10)] if x % 8 == 0]) # ---------- PROBLEM ---------- # Generate a list of 50 random values between 1 and 1000 # and return those that are multiples of 9 # You'll have to use a list comprehension in a list comprehension # This is a hard one! import random print([x for x in [random.randint(1, 1001) for i in range(50)] if x % 9 == 0]) # List comprehensions also make it easy to work with # multidimensional lists multiList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print([col[1] for col in multiList]) # Get the diagonal by incrementing 0, 0 -> 1, 1 -> 2, 2 print([multiList[i][i] for i in range(len(multiList))]) # ---------- GENERATOR FUNCTIONS ---------- # A generator function returns a result generator when called # They can be suspended and resumed during execution of # your program to create results over time rather then # all at once # We use generators when we want to big result set, but # we don't want to slow down the program by creating # it all at one time # Create a generator that calculates primes and returns # the next prime on command def isprime(num): # This for loop cycles through primes from 2 to # the value to check for i in range(2, num): # If any division has no remainder we know it # isn't a prime number if (num % i) == 0: return False return True # This is the generator def gen_primes(max_number): # This for loop cycles through primes from 2 to # the maximum value requested for num1 in range(2, max_number): if isprime(num1): # yield is what makes this a generator # When called by next it will return the # next result yield num1 # Create a reference to the generator prime = gen_primes(50) # Call next for each result print("Prime :", next(prime)) print("Prime :", next(prime)) print("Prime :", next(prime)) # ---------- GENERATOR EXPRESSIONS ---------- # Generator expressions look just like list comprehensions # but they return results one at a time # The are surrounded by parentheses instead of [ ] double = (x * 2 for x in range(10)) print("Double :", next(double)) print("Double :", next(double)) # You can iterate through all results as well for num in double: print(num) #~~Learn to program 14 # When you use threads it is like you are running # multiple programs at once. # Threads actually take turns executing. While one # executes the other sleeps until it is its turn # to execute. import threading import time import random def executeThread(i): # strftime or string formatted time allows you to # define how the time is displayed. # You could include the date with # strftime("%Y-%m-%d %H:%M:%S", gmtime()) # Print when the thread went to sleep print("Thread {} sleeps at {}".format(i, time.strftime("%H:%M:%S", time.gmtime()))) # Generate a random sleep period of between 1 and # 5 seconds randSleepTime = random.randint(1, 5) # Pauses execution of code in this function for # a few seconds time.sleep(randSleepTime) # Print out info after the sleep time print("Thread {} stops sleeping at {}".format(i, time.strftime("%H:%M:%S", time.gmtime()))) for i in range(10): # Each time through the loop a Thread object is created # You pass it the function to execute and any # arguments to pass to that method # The arguments passed must be a sequence which # is why we need the comma with 1 argument thread = threading.Thread(target=executeThread, args=(i,)) thread.start() # Display active threads # The extra 1 is this for loop executing in the main # thread print("Active Threads :", threading.activeCount()) # Returns a list of all active thread objects print("Thread Objects :", threading.enumerate()) # ---------- SUBCLASSING THREAD ---------- # You can subclass the Thread object and then define # what happens each time a new thread is executed # or run class CustThread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): getTime(self.name) print("Thread", self.name, "Execution Ends") def getTime(name): print("Thread {} sleeps at {}".format(name, time.strftime("%H:%M:%S", time.gmtime()))) randSleepTime = random.randint(1, 5) time.sleep(randSleepTime) # Create thread objects thread1 = CustThread("1") thread2 = CustThread("2") # Start thread execution of run() thread1.start() thread2.start() # Check if thread is alive print("Thread 1 Alive :", thread1.is_alive()) print("Thread 2 Alive :", thread2.is_alive()) # Get thread name # You can change it with setName() print("Thread 1 Name :", thread1.getName()) print("Thread 2 Name :", thread2.getName()) # Wait for threads to exit thread1.join() thread2.join() print("Execution Ends") # ---------- SYNCHRONIZING THREADS ---------- # You can lock other threads from executing # If we try to model a bank account we have to make sure # the account is locked down during a transaction so # that if more then 1 person tries to withdrawal money at # once we don't give out more money then is in the account class BankAccount (threading.Thread): acctBalance = 100 def __init__(self, name, moneyRequest): threading.Thread.__init__(self) self.name = name self.moneyRequest = moneyRequest def run(self): # Get lock to keep other threads from accessing the account threadLock.acquire() # Call the static method BankAccount.getMoney(self) # Release lock so other thread can access the account threadLock.release() @staticmethod def getMoney(customer): print("{} tries to withdrawal ${} at {}".format(customer.name, customer.moneyRequest, time.strftime("%H:%M:%S", time.gmtime()))) if BankAccount.acctBalance - customer.moneyRequest > 0: BankAccount.acctBalance -= customer.moneyRequest print("New account balance is : ${}".format(BankAccount.acctBalance)) else: print("Not enough money in the account") print("Current balance : ${}".format(BankAccount.acctBalance)) time.sleep(3) # Create a lock to be used by threads threadLock = threading.Lock() # Create new threads doug = BankAccount("Doug", 1) paul = BankAccount("Paul", 100) sally = BankAccount("Sally", 50) # Start new Threads doug.start() paul.start() sally.start() # Have threads wait for previous threads to terminate doug.join() paul.join() sally.join() print("Execution Ends") #~~Learn to program 15 # Regular expressions allow you to locate and change # strings in very powerful ways. # They work in almost exactly the same way in every # programming language as well. # Regular Expressions (Regex) are used to # 1. Search for a specific string in a large amount of data # 2. Verify that a string has the proper format (Email, Phone #) # 3. Find a string and replace it with another string # 4. Format data into the proper form for importing for example # import the Regex module import re # ---------- Was a Match Found ---------- # Search for ape in the string if re.search("ape", "The ape was at the apex"): print("There is an ape") # ---------- Get All Matches ---------- # findall() returns a list of matches # . is used to match any 1 character or space allApes = re.findall("ape.", "The ape was at the apex") for i in allApes: print(i) # finditer returns an iterator of matching objects # You can use span to get the location theStr = "The ape was at the apex" for i in re.finditer("ape.", theStr): # Span returns a tuple locTuple = i.span() print(locTuple) # Slice the match out using the tuple values print(theStr[locTuple[0]:locTuple[1]]) # ---------- Match 1 of Several Letters ---------- # Square brackets will match any one of the characters between # the brackets not including upper and lowercase varieties # unless they are listed animalStr = "Cat rat mat fat pat" allAnimals = re.findall("[crmfp]at", animalStr) for i in allAnimals: print(i) print() # We can also allow for characters in a range # Remember to include upper and lowercase letters someAnimals = re.findall("[c-mC-M]at", animalStr) for i in someAnimals: print(i) print() # Use ^ to denote any character but whatever characters are # between the brackets someAnimals = re.findall("[^Cr]at", animalStr) for i in someAnimals: print(i) print() # ---------- Replace All Matches ---------- # Replace matching items in a string owlFood = "rat cat mat pat" # You can compile a regex into pattern objects which # provide additional methods regex = re.compile("[cr]at") # sub() replaces items that match the regex in the string # with the 1st attribute string passed to sub owlFood = regex.sub("owl", owlFood) print(owlFood) # ---------- Solving Backslash Problems ---------- # Regex use the backslash to designate special characters # and Python does the same inside strings which causes # issues. # Let's try to get "\\stuff" out of a string randStr = "Here is \\stuff" # This won't find it print("Find \\stuff : ", re.search("\\stuff", randStr)) # This does, but we have to put in 4 slashes which is # messy print("Find \\stuff : ", re.search("\\\\stuff", randStr)) # You can get around this by using raw strings which # don't treat backslashes as special print("Find \\stuff : ", re.search(r"\\stuff", randStr)) # ---------- Matching Any Character ---------- # We saw that . matches any character, but what if we # want to match a period. Backslash the period # You do the same with [, ] and others randStr = "F.B.I. I.R.S. CIA" print("Matches :", len(re.findall(".\..\..", randStr))) # ---------- Matching Whitespace ---------- # We can match many whitespace characters randStr = """This is a long string that goes on for many lines""" print(randStr) # Remove newlines regex = re.compile("\n") randStr = regex.sub(" ", randStr) print(randStr) # You can also match # \b : Backspace # \f : Form Feed # \r : Carriage Return # \t : Tab # \v : Vertical Tab # You may need to remove \r\n on Windows # ---------- Matching Any Single Number ---------- # \d can be used instead of [0-9] # \D is the same as [^0-9] randStr = "12345" print("Matches :", len(re.findall("\d", randStr))) # ---------- Matching Multiple Numbers ---------- # You can match multiple digits by following the \d with {numOfValues} # Match 5 numbers only if re.search("\d{5}", "12345"): print("It is a zip code") # You can also match within a range # Match values that are between 5 and 7 digits numStr = "123 12345 123456 1234567" print("Matches :", len(re.findall("\d{5,7}", numStr))) # ---------- Matching Any Single Letter or Number ---------- # \w is the same as [a-zA-Z0-9_] # \W is the same as [^a-zA-Z0-9_] phNum = "412-555-1212" # Check if it is a phone number if re.search("\w{3}-\w{3}-\w{4}", phNum): print("It is a phone number") # Check for valid first name between 2 and 20 characters if re.search("\w{2,20}", "Ultraman"): print("It is a valid name") # ---------- Matching WhiteSpace ---------- # \s is the same as [\f\n\r\t\v] # \S is the same as [^\f\n\r\t\v] # Check for valid first and last name with a space if re.search("\w{2,20}\s\w{2,20}", "Toshio Muramatsu"): print("It is a valid full name") # ---------- Matching One or More ---------- # + matches 1 or more characters # Match a followed by 1 or more characters print("Matches :", len(re.findall("a+", "a as ape bug"))) # ---------- Problem ---------- # Create a Regex that matches email addresses from a list # 1. 1 to 20 lowercase and uppercase letters, numbers, plus ._%+- # 2. An @ symbol # 3. 2 to 20 lowercase and uppercase letters, numbers, plus .- # 4. A period # 5. 2 to 3 lowercase and uppercase letters emailList = "db@aol.com m@.com @apple.com db@.com" print("Email Matches :", len(re.findall("[\w._%+-]{1,20}@[\w.-]{2,20}.[A-Za-z]{2,3}", emailList))) #~~Learn to program 16 import re # Did you find a match # if re.search("REGEX", yourString) # Get list of matches # print("Matches :", len(re.findall("REGEX", yourString))) # Get a pattern object # regex = re.compile("REGEX") # Substitute the match # yourString = regex.sub("substitution", yourString) # [ ] : Match what is in the brackets # [^ ] : Match anything not in the brackets # . : Match any 1 character or space # + : Match 1 or more of what proceeds # \n : Newline # \d : Any 1 number # \D : Anything but a number # \w : Same as [a-zA-Z0-9_] # \W : Same as [^a-zA-Z0-9_] # \s : Same as [\f\n\r\t\v] # \S : Same as [^\f\n\r\t\v] # {5} : Match 5 of what proceeds the curly brackets # {5,7} : Match values that are between 5 and 7 in length # ---------- Matching Zero or One ---------- randStr = "cat cats" regex = re.compile("[cat]+s?") matches = re.findall(regex, randStr) # Match cat or cats print("Matches :", len(matches)) for i in matches: print(i) # ---------- Matching Zero or More ---------- # * matches zero or more of what proceeds it randStr = "doctor doctors doctor's" # Match doctor doctors or doctor's regex = re.compile("[doctor]+['s]*") matches = re.findall(regex, randStr) print("Matches :", len(matches)) # You can do the same by setting an interval match regex = re.compile("[doctor]+['s]{0,2}") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # ---------- PROBLEM ---------- # On Windows newlines are some times \n and other times \r\n # Create a regex that will grab each of the lines in this # string, print out the number of matches and each line longStr = '''Just some words and some more\r and more ''' print("Matches :", len(re.findall(r"[\w\s]+[\r]?\n", longStr))) matches = re.findall("[\w\s]+[\r]?\n", longStr) for i in matches: print(i) # ---------- Greedy & Lazy Matching ---------- randStr = "<name>Life On Mars</name><name>Freaks and Geeks</name>" # Let's try to grab everything between <name> tags # Because * is greedy (It grabs the biggest match possible) # we can't get what we want, which is each individual tag # match regex = re.compile(r"<name>.*</name>") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # We want to grab the smallest match we use *?, +?, or # {n,}? instead regex = re.compile(r"<name>.*?</name>") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # ---------- Word Boundaries ---------- # We use word boundaries to define where our matches start # and end # \b matches the start or end of a word # If we want ape it will match ape and the beginning of apex randStr = "ape at the apex" regex = re.compile(r"ape") # If we use the word boundary regex = re.compile(r"\bape\b") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # ---------- String Boundaries ---------- # ^ : Matches the beginning of a string if outside of # a [ ] # $ : Matches the end of a string # Grab everything from the start of the string to @ randStr = "Match everything up to @" regex = re.compile(r"^.*[^@]") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # Grab everything from @ to the end of the line randStr = "@ Get this string" regex = re.compile(r"[^@\s].*$") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # Grab the 1st word of each line using the the multiline # code which allows for the targeting of each line after # a line break with ^ randStr = '''Ape is big Turtle is slow Cheetah is fast''' regex = re.compile(r"(?m)^.*?\s") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # ---------- Subexpressions ---------- # Subexpressions are parts of a larger expression # If you want to match for a large block, but # only want to return part of it. To do that # surround what you want with ( ) # Get just the number minus the area code randStr = "My number is 412-555-1212" regex = re.compile(r"412-(.*)") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # ---------- Problem ---------- # Get just the numbers minus the area codes from # this string randStr = "412-555-1212 412-555-1213 412-555-1214" regex = re.compile(r"412-(.{8})") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # ---------- Multiple Subexpressions ---------- # You can have multiple subexpressions as well # Get both numbers that follow 412 separately randStr = "My number is 412-555-1212" regex = re.compile(r"412-(.*)-(.*)") matches = re.findall(regex, randStr) print("Matches :", len(matches)) print(matches[0][0]) print(matches[0][1]) #~~Learn to program 17 import re # Did you find a match # if re.search("REGEX", yourString) # Get list of matches # print("Matches :", len(re.findall("REGEX", yourString))) # Get a pattern object # regex = re.compile("REGEX") # Substitute the match # yourString = regex.sub("substitution", yourString) # [ ] : Match what is in the brackets # [^ ] : Match anything not in the brackets # ( ) : Return surrounded submatch # . : Match any 1 character or space # + : Match 1 or more of what proceeds # ? : Match 0 or 1 # * : Match 0 or More # *? : Lazy match the smallest match # \b : Word boundary # ^ : Beginning of String # $ : End of String # \n : Newline # \d : Any 1 number # \D : Anything but a number # \w : Same as [a-zA-Z0-9_] # \W : Same as [^a-zA-Z0-9_] # \s : Same as [\f\n\r\t\v] # \S : Same as [^\f\n\r\t\v] # {5} : Match 5 of what proceeds the curly brackets # {5,7} : Match values that are between 5 and 7 in length # ($m) : Allow ^ on multiline string # ---------- Back References ---------- # A back reference allows you to to reuse the expression # that proceeds it # Grab a double word randStr = "The cat cat fell out the window" # Match a word boundary, 1 or more characters followed # by a space if it is then followed by the same # match that is surrounded by the parentheses regex = re.compile(r"(\b\w+)\s+\1") matches = re.findall(regex, randStr) print("Matches :", len(matches)) for i in matches: print(i) # ---------- Back Reference Substitutions ---------- # Replace the bold tags in the link with no tags randStr = "<a href='#'><b>The Link</b></a>" # Regex matches bold tags and grabs the text between # them to be used by the back reference regex = re.compile(r"<b>(.*?)</b>") # Replace the tags with just the text between them randStr = re.sub(regex, r"\1", randStr) print(randStr) # ---------- Another Back Reference Substitution ---------- # Receive this string randStr = "412-555-1212" # Match the phone number using multiple subexpressions regex = re.compile(r"([\d]{3})-([\d]{3}-[\d]{4})") # Output (412)555-1212 randStr = re.sub(regex, r"(\1)\2", randStr) print(randStr) # ---------- PROBLEM ---------- # Receive a string like this randStr = "https://www.youtube.com http://www.google.com" # Grab the URL and then provide the following output # using a back reference substitution # <a href='https://www.youtube.com'>www.youtube.com</a> # <a href='https://www.google.com'>www.google.com</a> regex = re.compile(r"(https?://([\w.]+))") randStr = re.sub(regex, r"<a href='\1'>\2</a>\n", randStr) print(randStr) # ---------- Look Ahead ---------- # A look ahead defines a pattern to match but not return # You define the expression to look for but not return # like this (?=expression) randStr = "One two three four" # Grab all letters and numbers of 1 or more separated # by a word boundary but don't include it regex = re.compile(r"\w+(?=\b)") matches = re.findall(regex, randStr) for i in matches: print(i) # ---------- Look Behind ---------- # The look behind looks for what is before the text # to return, but doesn't return it # It is defined like (?<=expression) randStr = "1. Bread 2. Apples 3. Lettuce" # Find the number, period and space, but only return # the 1 or more letters or numbers that follow regex = re.compile(r"(?<=\d.\s)\w+") matches = re.findall(regex, randStr) for i in matches: print(i) # ---------- Look Ahead & Behind ---------- randStr = "<h1>I'm Important</h1> <h1>So am I</h1>" # Use the look behind, get 1 or more of anything, # and use the look ahead regex = re.compile(r"(?<=<h1>).+?(?=</h1>)") matches = re.findall(regex, randStr) for i in matches: print(i) import re # ---------- Negative Look Ahead & Behind ---------- # These are used to look for text that doesn't match # the pattern # (?!expression) : Negative Look Ahead # (?<!expression) : Negative Look Behind randStr = "8 Apples $3, 1 Bread $1, 1 Cereal $4" # Grab the total number of grocery items by ignoring the $ regex = re.compile(r"(?<!\$)\d+") matches = re.findall(regex, randStr) print(len(matches)) # Convert from a string list to an int list matches = [int(i) for i in matches] from functools import reduce # Sum the items in the list with reduce print("Total Items {}".format(reduce((lambda x, y: x + y), matches))) #~~Learn to program 20 TKinter # We are going to learn how to create Graphical User # Interfaces (GUIs) with Tk # Tk is a cross platform GUI toolkit that provides a # ton of Widgets (Buttons, Scrollbars, etc.) that are # used to build GUIs # TkInter (tee-kay-inter) is included since Python 3.1 on Macs, # Windows and Linux # TkInter is a Python interface for Tk from tkinter import * from tkinter import ttk # Test to see if TkInter is working # tkinter._test() # ---------- HELLO WORLD ---------- # root is the main window that surrounds your interface # This creates a Tk object root = Tk() # Give your app a title root.title("First GUI") # Put a button in the window # Components like button are called Widgets ttk.Button(root, text="Hello TkInter").grid() # This keeps the root window visible and your program # running root.mainloop() # ---------- MULTIPLE COMPONENTS ---------- # Some of the different Widgets : Button, Label, # Canvas, Menu, Text, Scale, OptionMenu, Frame, # CheckButton, LabelFrame, MenuButton, PanedWindow, # Entry, ListBox, Message, RadioButton, ScrollBar, # Bitmap, SpinBox, Image root = Tk() # Frame widgets surround other widgets frame = Frame(root) # We'll use a TkInter variable for our label text # so we can change it with set labelText = StringVar() # Create a label and button object # You can set attributes on creation or by calling # methods label = Label(frame, textvariable=labelText) button = Button(frame, text="Click Me") # Change the label text labelText.set("I am a label") # Pack positions the widgets in the window # It is a simple geometry manager label.pack() button.pack() frame.pack() root.mainloop() # ---------- PACK GEOMETRY MANAGER ---------- # Pack positions widgets by allowing them to define # their position (Top, Right, Bottom, Left) and # their fill direction (X, Y, BOTH, NONE) inside # of a box root = Tk() frame = Frame(root) # Define where the widgets should be placed and # how they should be stretched to fill the space Label(frame, text="A Bunch of Buttons").pack() Button(frame, text="B1").pack(side=LEFT, fill=Y) Button(frame, text="B2").pack(side=TOP, fill=X) Button(frame, text="B3").pack(side=RIGHT, fill=X) Button(frame, text="B4").pack(side=LEFT, fill=X) frame.pack() root.mainloop() # ---------- GRID GEOMETRY MANAGER ---------- # The Grid manager is the most useful using a series # of rows and columns for laying out widgets # Each cell can only hold 1 widget, but a widget # can cover multiple cells. root = Tk() # rows start at 0, 1, ... # columns start at 0, 1, ... # sticky defines how the widget expands (N, NE, E, SE, # S, SW, W, NW) # padx and pady provide padding around the widget above # and below it Label(root, text="First Name").grid(row=0, sticky=W, padx=4) Entry(root).grid(row=0, column=1, sticky=E, pady=4) Label(root, text="Last Name").grid(row=1, sticky=W, padx=4) Entry(root).grid(row=1, column=1, sticky=E, pady=4) Button(root, text="Submit").grid(row=3) root.mainloop() # ---------- GRID EXAMPLE 2 ---------- root = Tk() Label(root, text="Description").grid(row=0, column=0, sticky=W) Entry(root, width=50).grid(row=0, column=1) Button(root, text="Submit").grid(row=0, column=8) Label(root, text="Quality").grid(row=1, column=0, sticky=W) Radiobutton(root, text="New", value=1).grid(row=2, column=0, sticky=W) Radiobutton(root, text="Good", value=2).grid(row=3, column=0, sticky=W) Radiobutton(root, text="Poor", value=3).grid(row=4, column=0, sticky=W) Radiobutton(root, text="Damaged", value=4).grid(row=5, column=0, sticky=W) Label(root, text="Benefits").grid(row=1, column=1, sticky=W) Checkbutton(root, text="Free Shipping").grid(row=2, column=1, sticky=W) Checkbutton(root, text="Bonus Gift").grid(row=3, column=1, sticky=W) root.mainloop() # ---------- TKINTER EVENTS ---------- def get_sum(event): # Get the value stored in the entries num1 = int(num1Entry.get()) num2 = int(num2Entry.get()) sum = num1 + num2 # Delete the value in the entry sumEntry.delete(0, "end") # Insert the sum into the entry sumEntry.insert(0, sum) root = Tk() num1Entry = Entry(root) num1Entry.pack(side=LEFT) Label(root, text="+").pack(side=LEFT) num2Entry = Entry(root) num2Entry.pack(side=LEFT) equalButton = Button(root, text="=") # When the left mouse button is clicked call the # function get_sum equalButton.bind("<Button-1>", get_sum) equalButton.pack(side=LEFT) sumEntry = Entry(root) sumEntry.pack(side=LEFT) root.mainloop() #~~Learn to program 21 TKinter2 from tkinter import * from tkinter import messagebox # ---------- VARIABLES & UNBIND ---------- def get_data(event): # Output the values for the Widgets with get() print("String :", strVar.get()) print("Integer :", intVar.get()) print("Double :", dblVar.get()) print("Boolean :", boolVar.get()) # You can unbind and rebind an event to a function def bind_button(event): if boolVar.get(): getDataButton.unbind("<Button-1>") else: getDataButton.bind("<Button-1>", get_data) root = Tk() # As I showed previously there are TkInter variables # you can use with Widgets to set and get values strVar = StringVar() intVar = IntVar() dblVar = DoubleVar() boolVar = BooleanVar() # Set the default values with set() strVar.set("Enter String") intVar.set("Enter Integer") dblVar.set("Enter Double") boolVar.set(True) # Assign the variable to either textvariable or variable strEntry = Entry(root, textvariable=strVar) strEntry.pack(side=LEFT) intEntry = Entry(root, textvariable=intVar) intEntry.pack(side=LEFT) dblEntry = Entry(root, textvariable=dblVar) dblEntry.pack(side=LEFT) # Depending on if this check button is selected or not # will determine if we can get data on our Widgets theCheckBut = Checkbutton(root, text="Switch", variable=boolVar) theCheckBut.bind("<Button-1>", bind_button) theCheckBut.pack(side=LEFT) # Call the function get_data on click getDataButton = Button(root, text="Get Data") getDataButton.bind("<Button-1>", get_data) getDataButton.pack(side=LEFT) root.mainloop() # ---------- STYLING WIDGETS ---------- # There are many ways to custom style your widgets # You can open message boxes def open_msg_box(): messagebox.showwarning( "Event Triggered", "Button Clicked" ) root = Tk() # You can define the size of the window and the # position on the screen with # widthxheight+xoffset+yoffset root.geometry("400x400+300+300") # You can make it so the window isn't resizable root.resizable(width=False, height=False) frame = Frame(root) # Your can change a styling option like this # Color option names are here http://wiki.tcl.tk/37701 # For the font list the font family, px and font style style = ttk.Style() style.configure("TButton", foreground="midnight blue", font="Times 20 bold italic", padding=20) # Ttk widget names : TButton, TCheckbutton, TCombobox, # TEntry, TFrame, TLabel, TLabelframe, TMenubutton, # TNotebook, TProgressbar, TRadiobutton, TScale, # TScrollbar, TSpinbox, Treeview # You can change the theme style for your applications # This shows you all the themes for your OS print(ttk.Style().theme_names()) # You can see current style settings like this print(style.lookup('TButton', 'font')) print(style.lookup('TButton', 'foreground')) print(style.lookup('TButton', 'padding')) # Change the theme for every widget ttk.Style().theme_use('clam') # Have the button open a message box on click theButton = ttk.Button(frame, text="Important Button", command=open_msg_box) # You can also disable and enable buttons theButton['state'] = 'disabled' theButton['state'] = 'normal' theButton.pack() frame.pack() root.mainloop() # ---------- MENU BARS ---------- # Quits the TkInter app when called def quit_app(): root.quit() # Opens a message box when called def show_about(event=None): messagebox.showwarning( "About", "This Awesome Program was Made in 2016" ) root = Tk() # Create the menu object the_menu = Menu(root) # ----- FILE MENU ----- # Create a pull down menu that can't be removed file_menu = Menu(the_menu, tearoff=0) # Add items to the menu that show when clicked # compound allows you to add an image file_menu.add_command(label="Open") file_menu.add_command(label="Save") # Add a horizontal bar to group similar commands file_menu.add_separator() # Call for the function to execute when clicked file_menu.add_command(label="Quit", command=quit_app) # Add the pull down menu to the menu bar the_menu.add_cascade(label="File", menu=file_menu) # ----- FONT MENU FOR VIEW MENU ----- # Stores font chosen and will update based on menu # selection text_font = StringVar() text_font.set("Times") # Outputs font changes def change_font(event=None): print("Font Picked :", text_font.get()) # Define font drop down that will be attached to view font_menu = Menu(the_menu, tearoff=0) # Define radio button options for fonts font_menu.add_radiobutton(label="Times", variable=text_font, command=change_font) font_menu.add_radiobutton(label="Courier", variable=text_font, command=change_font) font_menu.add_radiobutton(label="Ariel", variable=text_font, command=change_font) # ----- VIEW MENU ----- view_menu = Menu(the_menu, tearoff=0) # Variable changes when line numbers is checked # or unchecked line_numbers = IntVar() line_numbers.set(1) # Bind the checking of the line number option # to variable line_numbers view_menu.add_checkbutton(label="Line Numbers", variable=line_numbers) view_menu.add_cascade(label="Fonts", menu=font_menu) # Add the pull down menu to the menu bar the_menu.add_cascade(label="View", menu=view_menu) # ----- HELP MENU ----- help_menu = Menu(the_menu, tearoff=0) # accelerator is used to show a shortcut # OSX, Windows and Linux use the following options # Command-O, Shift+Ctrl+S, Command-Option-Q with the # modifiers Control, Ctrl, Option, Opt, Alt, Shift, # and Command help_menu.add_command(label="About", accelerator="command-H", command=show_about) the_menu.add_cascade(label="Help", menu=help_menu) # Bind the shortcut to the function root.bind('<Command-A>', show_about) root.bind('<Command-a>', show_about) # Display the menu bar root.config(menu=the_menu) root.mainloop() #~~Learn to program 22 TKinter Calculator Use Case Description Describes Everything the App Does Step-By-Step I. User clicks a number button N3. With each number button press add the new value to the end of the first and update entry II. User clicks a math button N1. Make sure entry has a value N2. Switch boolean values representing math buttons to false on entry N2. Have Button pass in the math function pressed N4. Store the entry value on entry to this function (Class Field) N4. Clear the entry field? III. User clicks another number button IV. User clicks equal button and the result shows N1. Make sure a math function was clicked N2. Check which math function was clicked and provide the correct solution Note 1 : Since every button requires the previous button to have been clicked make sure the click occurred Note 2 : Make a way to track which math button was clicked last Note 3 : Think about a way to handle the user entering both single numbers and multiple numbers Note 4 : Track the first number in the entry box after a math button is clicked Note 5 : What about division problems caused by an integer division? a. Convert to float each time we retrieve, or store values in the entry from tkinter import * from tkinter import ttk class Calculator: # Stores the current value to display in the entry calc_value = 0.0 # Will define if this was the last math button clicked div_trigger = False mult_trigger = False add_trigger = False sub_trigger = False # Called anytime a number button is pressed def button_press(self, value): # Get the current value in the entry entry_val = self.number_entry.get() # Put the new value to the right of it # If it was 1 and 2 is pressed it is now 12 # Otherwise the new number goes on the left entry_val += value # Clear the entry box self.number_entry.delete(0, "end") # Insert the new value going from left to right self.number_entry.insert(0, entry_val) # Returns True or False if the string is a float def isfloat(self, str_val): try: # If the string isn't a float float() will throw a # ValueError float(str_val) # If there is a value you want to return use return return True except ValueError: return False # Handles logic when math buttons are pressed def math_button_press(self, value): # Only do anything if entry currently contains a number if self.isfloat(str(self.number_entry.get())): # make false to cancel out previous math button click self.add_trigger = False self.sub_trigger = False self.mult_trigger = False self.div_trigger = False # Get the value out of the entry box for the calculation self.calc_value = float(self.entry_value.get()) # Set the math button click so when equals is clicked # that function knows what calculation to use if value == "/": print("/ Pressed") self.div_trigger = True elif value == "*": print("* Pressed") self.mult_trigger = True elif value == "+": print("+ Pressed") self.add_trigger = True else: print("- Pressed") self.sub_trigger = True # Clear the entry box self.number_entry.delete(0, "end") # Performs a mathematical operation by taking the value before # the math button is clicked and the current value. Then perform # the right calculation by checking what math button was clicked # last def equal_button_press(self): # Make sure a math button was clicked if self.add_trigger or self.sub_trigger or self.mult_trigger or self.div_trigger: if self.add_trigger: solution = self.calc_value + float(self.entry_value.get()) elif self.sub_trigger: solution = self.calc_value - float(self.entry_value.get()) elif self.mult_trigger: solution = self.calc_value * float(self.entry_value.get()) else: solution = self.calc_value / float(self.entry_value.get()) print(self.calc_value, " ", float(self.entry_value.get()), " ", solution) # Clear the entry box self.number_entry.delete(0, "end") self.number_entry.insert(0, solution) def __init__(self, root): # Will hold the changing value stored in the entry self.entry_value = StringVar(root, value="") # Define title for the app root.title("Calculator") # Defines the width and height of the window root.geometry("430x220") # Block resizing of Window root.resizable(width=False, height=False) # Customize the styling for the buttons and entry style = ttk.Style() style.configure("TButton", font="Serif 15", padding=10) style.configure("TEntry", font="Serif 18", padding=10) # Create the text entry box self.number_entry = ttk.Entry(root, textvariable=self.entry_value, width=50) self.number_entry.grid(row=0, columnspan=4) # ----- 1st Row ----- self.button7 = ttk.Button(root, text="7", command=lambda: self.button_press('7')).grid(row=1, column=0) self.button8 = ttk.Button(root, text="8", command=lambda: self.button_press('8')).grid(row=1, column=1) self.button9 = ttk.Button(root, text="9", command=lambda: self.button_press('9')).grid(row=1, column=2) self.button_div = ttk.Button(root, text="/", command=lambda: self.math_button_press('/')).grid(row=1, column=3) # ----- 2nd Row ----- self.button4 = ttk.Button(root, text="4", command=lambda: self.button_press('4')).grid(row=2, column=0) self.button5 = ttk.Button(root, text="5", command=lambda: self.button_press('5')).grid(row=2, column=1) self.button6 = ttk.Button(root, text="6", command=lambda: self.button_press('6')).grid(row=2, column=2) self.button_mult = ttk.Button(root, text="*", command=lambda: self.math_button_press('*')).grid(row=2, column=3) # ----- 3rd Row ----- self.button1 = ttk.Button(root, text="1", command=lambda: self.button_press('1')).grid(row=3, column=0) self.button2 = ttk.Button(root, text="2", command=lambda: self.button_press('2')).grid(row=3, column=1) self.button3 = ttk.Button(root, text="3", command=lambda: self.button_press('3')).grid(row=3, column=2) self.button_add = ttk.Button(root, text="+", command=lambda: self.math_button_press('+')).grid(row=3, column=3) # ----- 4th Row ----- self.button_clear = ttk.Button(root, text="AC", command=lambda: self.button_press('AC')).grid(row=4, column=0) self.button0 = ttk.Button(root, text="0", command=lambda: self.button_press('0')).grid(row=4, column=1) self.button_equal = ttk.Button(root, text="=", command=lambda: self.equal_button_press()).grid(row=4, column=2) self.button_sub = ttk.Button(root, text="-", command=lambda: self.math_button_press('-')).grid(row=4, column=3) # Get the root window object root = Tk() # Create the calculator calc = Calculator(root) # Run the app until exited root.mainloop() #~~Learn to program 23 TKinter Text Editor from tkinter import * import tkinter.filedialog class TextEditor: # Quits the TkInter app when called @staticmethod def quit_app(event=None): root.quit() def open_file(self, event=None): txt_file = tkinter.filedialog.askopenfilename(parent=root, initialdir='/Users/derekbanas/PycharmProjects') if txt_file: self.text_area.delete(1.0, END) # Open file and put text in the text widget with open(txt_file) as _file: self.text_area.insert(1.0, _file.read()) # Update the text widget root.update_idletasks() def save_file(self, event=None): # Opens the save as dialog box file = tkinter.filedialog.asksaveasfile(mode='w') if file != None: # Get text in the text widget and delete the last newline data = self.text_area.get('1.0', END + '-1c') # Write the text and close file.write(data) file.close() def __init__(self, root): self.text_to_write = "" # Define title for the app root.title("Text Editor") # Defines the width and height of the window root.geometry("600x550") frame = Frame(root, width=600, height=550) # Create the scrollbar scrollbar = Scrollbar(frame) # yscrollcommand connects the scroll bar to the text # area self.text_area = Text(frame, width=600, height=550, yscrollcommand=scrollbar.set, padx=10, pady=10) # Call yview when the scrollbar is moved scrollbar.config(command=self.text_area.yview) # Put scroll bar on the right and fill in the Y direction scrollbar.pack(side="right", fill="y") # Pack on the left and fill available space self.text_area.pack(side="left", fill="both", expand=True) frame.pack() # Create the menu object the_menu = Menu(root) # Create a pull down menu that can't be removed file_menu = Menu(the_menu, tearoff=0) # Add items to the menu that show when clicked # compound allows you to add an image file_menu.add_command(label="Open", command=self.open_file) file_menu.add_command(label="Save", command=self.save_file) # Add a horizontal bar to group similar commands file_menu.add_separator() # Call for the function to execute when clicked file_menu.add_command(label="Quit", command=self.quit_app) # Add the pull down menu to the menu bar the_menu.add_cascade(label="File", menu=file_menu) # Display the menu bar root.config(menu=the_menu) root = Tk() text_editor = TextEditor(root) root.mainloop() #~~Learn to program 24 TKinter Tool Bars from tkinter import * from PIL import Image, ImageTk class TkInterEx: @staticmethod def quit_app(event=None): root.quit() # Handles events on list box def on_fav_food_select(self, event=None): lb_widget = event.widget # Get index selected index = int(lb_widget.curselection()[0]) # Get value selected in list box lb_value = lb_widget.get(index) self.fav_food_label['text'] = "I'll get you " + lb_value def __init__(self, root): root.title("Toolbar Example") # ---------- Create Menu Bar ---------- # Create menu object menubar = Menu(root) # Create drop down menu file_menu = Menu(root, tearoff=0) # Add menu drop down options file_menu.add_command(label="Open") file_menu.add_command(label="Save") file_menu.add_command(label="Exit", command=self.quit_app) # Add drop down options to File menubar.add_cascade(label="File", menu=file_menu) # ---------- Create Toolbar ---------- # RAISED draws a line under the tool bar and bd defines the border width toolbar = Frame(root, bd=1, relief=RAISED) # Get images for toolbar open_img = Image.open("open.png") save_img = Image.open("disk.png") exit_img = Image.open("exit.png") # Create a TkInter image to be used in the button open_icon = ImageTk.PhotoImage(open_img) save_icon = ImageTk.PhotoImage(save_img) exit_icon = ImageTk.PhotoImage(exit_img) # Create buttons for the toolbar open_button = Button(toolbar, image=open_icon) save_button = Button(toolbar, image=save_icon) exit_button = Button(toolbar, image=exit_icon, command=self.quit_app) open_button.image = open_icon save_button.image = save_icon exit_button.image = exit_icon # Place buttons in the interface open_button.pack(side=LEFT, padx=2, pady=2) save_button.pack(side=LEFT, padx=2, pady=2) exit_button.pack(side=LEFT, padx=2, pady=2) toolbar.pack(side=TOP, fill=X) root.config(menu=menubar) # ---------- Create a List Box ---------- # A listbox displays a list of items to select # A label frame is a frame with a label lb_frame = LabelFrame(root, text="Food Options", padx=5, pady=5) # This label changes based on list box selections self.fav_food_label = Label(lb_frame, text="What is your favorite food") self.fav_food_label.pack() list_box = Listbox(lb_frame) # Create list box options list_box.insert(1, "Spaghetti") list_box.insert(2, "Pizza") list_box.insert(3, "Burgers") list_box.insert(4, "Hot Dogs") # When a list box option is clicked execute the function list_box.bind('<<ListboxSelect>>', self.on_fav_food_select) list_box.pack() lb_frame.pack() # ---------- Create a Spin Box ---------- # Provides a fixed number of values as an option sb_frame = Frame(root) quantity_label = Label(sb_frame, text="How many do you want") quantity_label.pack() # Allow for the values 1 through 5 spin_box = Spinbox(sb_frame, from_=1, to=5) spin_box.pack() extras_label = Label(sb_frame, text="Add on Item") extras_label.pack() # Add a list of custom items extras_spin_box = Spinbox(sb_frame, values=('French Fries', 'Onion Rings', 'Tater Tots')) extras_spin_box.pack() sb_frame.pack() root = Tk() root.geometry("600x550") app = TkInterEx(root) root.mainloop() #~~Learn to program 25 TKinter Paint App from tkinter import * import tkinter.font class PaintApp: # Stores current drawing tool used drawing_tool = "line" # Tracks whether left mouse is down left_but = "up" # x and y positions for drawing with pencil x_pos, y_pos = None, None # Tracks x & y when the mouse is clicked and released x1_line_pt, y1_line_pt, x2_line_pt, y2_line_pt = None, None, None, None # ---------- CATCH MOUSE UP ---------- def left_but_down(self, event=None): self.left_but = "down" # Set x & y when mouse is clicked self.x1_line_pt = event.x self.y1_line_pt = event.y # ---------- CATCH MOUSE UP ---------- def left_but_up(self, event=None): self.left_but = "up" # Reset the line self.x_pos = None self.y_pos = None # Set x & y when mouse is released self.x2_line_pt = event.x self.y2_line_pt = event.y # If mouse is released and line tool is selected # draw the line if self.drawing_tool == "line": self.line_draw(event) elif self.drawing_tool == "arc": self.arc_draw(event) elif self.drawing_tool == "oval": self.oval_draw(event) elif self.drawing_tool == "rectangle": self.rectangle_draw(event) elif self.drawing_tool == "text": self.text_draw(event) # ---------- CATCH MOUSE MOVEMENT ---------- def motion(self, event=None): if self.drawing_tool == "pencil": self.pencil_draw(event) # ---------- DRAW PENCIL ---------- def pencil_draw(self, event=None): if self.left_but == "down": # Make sure x and y have a value if self.x_pos is not None and self.y_pos is not None: event.widget.create_line(self.x_pos, self.y_pos, event.x, event.y, smooth=TRUE) self.x_pos = event.x self.y_pos = event.y # ---------- DRAW LINE ---------- def line_draw(self, event=None): # Shortcut way to check if none of these values contain None if None not in (self.x1_line_pt, self.y1_line_pt, self.x2_line_pt, self.y2_line_pt): event.widget.create_line(self.x1_line_pt, self.y1_line_pt, self.x2_line_pt, self.y2_line_pt, smooth=TRUE, fill="green") # ---------- DRAW ARC ---------- def arc_draw(self, event=None): # Shortcut way to check if none of these values contain None if None not in (self.x1_line_pt, self.y1_line_pt, self.x2_line_pt, self.y2_line_pt): coords = self.x1_line_pt, self.y1_line_pt, self.x2_line_pt, self.y2_line_pt # start : starting angle for the slice in degrees # extent : width of the slice in degrees # fill : fill color if needed # style : can be ARC, PIESLICE, or CHORD event.widget.create_arc(coords, start=0, extent=150, style=ARC) # ---------- DRAW OVAL ---------- def oval_draw(self, event=None): if None not in (self.x1_line_pt, self.y1_line_pt, self.x2_line_pt, self.y2_line_pt): # fill : Color option names are here http://wiki.tcl.tk/37701 # outline : border color # width : width of border in pixels event.widget.create_oval(self.x1_line_pt, self.y1_line_pt, self.x2_line_pt, self.y2_line_pt, fill="midnight blue", outline="yellow", width=2) # ---------- DRAW RECTANGLE ---------- def rectangle_draw(self, event=None): if None not in (self.x1_line_pt, self.y1_line_pt, self.x2_line_pt, self.y2_line_pt): # fill : Color option names are here http://wiki.tcl.tk/37701 # outline : border color # width : width of border in pixels event.widget.create_rectangle(self.x1_line_pt, self.y1_line_pt, self.x2_line_pt, self.y2_line_pt, fill="midnight blue", outline="yellow", width=2) # ---------- DRAW TEXT ---------- def text_draw(self, event=None): if None not in (self.x1_line_pt, self.y1_line_pt): # Show all fonts available print(tkinter.font.families()) text_font = tkinter.font.Font(family='Helvetica', size=20, weight='bold', slant='italic') event.widget.create_text(self.x1_line_pt, self.y1_line_pt, fill="green", font=text_font, text="WOW") def __init__(self, root): drawing_area = Canvas(root) drawing_area.pack() drawing_area.bind("<Motion>", self.motion) drawing_area.bind("<ButtonPress-1>", self.left_but_down) drawing_area.bind("<ButtonRelease-1>", self.left_but_up) root = Tk() paint_app = PaintApp(root) root.mainloop() #~~Learn to program 26 TKinter Database from tkinter import * from tkinter import ttk import sqlite3 class StudentDB : # Will hold database connection db_conn = 0 # A cursor is used to traverse the records of a result theCursor = 0 # Will store the current student selected curr_student = 0 def setup_db(self): # Open or create database self.db_conn = sqlite3.connect('student.db') # The cursor traverses the records self.theCursor = self.db_conn.cursor() # Create the table if it doesn't exist try: self.db_conn.execute("CREATE TABLE if not exists Students(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, FName TEXT NOT NULL, LName TEXT NOT NULL);") self.db_conn.commit() except sqlite3.OperationalError: print("ERROR : Table not created") def stud_submit(self): # Insert students in the db self.db_conn.execute("INSERT INTO Students (FName, LName) " + "VALUES ('" + self.fn_entry_value.get() + "', '" + self.ln_entry_value.get() + "')") # Clear the entry boxes self.fn_entry.delete(0, "end") self.ln_entry.delete(0, "end") # Update list box with student list self.update_listbox() def update_listbox(self): # Delete items in the list box self.list_box.delete(0, END) # Get students from the db try: result = self.theCursor.execute("SELECT ID, FName, LName FROM Students") # You receive a list of lists that hold the result for row in result: stud_id = row[0] stud_fname = row[1] stud_lname = row[2] # Put the student in the list box self.list_box.insert(stud_id, stud_fname + " " + stud_lname) except sqlite3.OperationalError: print("The Table Doesn't Exist") except: print("1: Couldn't Retrieve Data From Database") # Load listbox selected student into entries def load_student(self, event=None): # Get index selected which is the student id lb_widget = event.widget index = str(lb_widget.curselection()[0] + 1) # Store the current student index self.curr_student = index # Retrieve student list from the db try: result = self.theCursor.execute("SELECT ID, FName, LName FROM Students WHERE ID=" + index) # You receive a list of lists that hold the result for row in result: stud_id = row[0] stud_fname = row[1] stud_lname = row[2] # Set values in the entries self.fn_entry_value.set(stud_fname) self.ln_entry_value.set(stud_lname) except sqlite3.OperationalError: print("The Table Doesn't Exist") except: print("2 : Couldn't Retrieve Data From Database") # Update student info def update_student(self, event=None): # Update student records with change made in entry try: self.db_conn.execute("UPDATE Students SET FName='" + self.fn_entry_value.get() + "', LName='" + self.ln_entry_value.get() + "' WHERE ID=" + self.curr_student) self.db_conn.commit() except sqlite3.OperationalError: print("Database couldn't be Updated") # Clear the entry boxes self.fn_entry.delete(0, "end") self.ln_entry.delete(0, "end") # Update list box with student list self.update_listbox() def __init__(self, root): root.title("Student Database") root.geometry("270x340") # ----- 1st Row ----- fn_label = Label(root, text="First Name") fn_label.grid(row=0, column=0, padx=10, pady=10, sticky=W) # Will hold the changing value stored first name self.fn_entry_value = StringVar(root, value="") self.fn_entry = ttk.Entry(root, textvariable=self.fn_entry_value) self.fn_entry.grid(row=0, column=1, padx=10, pady=10, sticky=W) # ----- 2nd Row ----- ln_label = Label(root, text="Last Name") ln_label.grid(row=1, column=0, padx=10, pady=10, sticky=W) # Will hold the changing value stored last name self.ln_entry_value = StringVar(root, value="") self.ln_entry = ttk.Entry(root, textvariable=self.ln_entry_value) self.ln_entry.grid(row=1, column=1, padx=10, pady=10, sticky=W) # ----- 3rd Row ----- self.submit_button = ttk.Button(root, text="Submit", command=lambda: self.stud_submit()) self.submit_button.grid(row=2, column=0, padx=10, pady=10, sticky=W) self.update_button = ttk.Button(root, text="Update", command=lambda: self.update_student()) self.update_button.grid(row=2, column=1, padx=10, pady=10) # ----- 4th Row ----- scrollbar = Scrollbar(root) self.list_box = Listbox(root) self.list_box.bind('<<ListboxSelect>>', self.load_student) self.list_box.insert(1, "Students Here") self.list_box.grid(row=3, column=0, columnspan=4, padx=10, pady=10, sticky=W+E) # Call for database to be created self.setup_db() # Update list box with student list self.update_listbox() # Get the root window object root = Tk() # Create the calculator studDB = StudentDB(root) # Run the app until exited root.mainloop() #~~Learn to program 27 Kivy 1 # ---------- Install Kivy on Mac ---------- 1. Install Python and PyCharm like I show here : https://youtu.be/nwjAHQERL08?t=37m 2. Download Kivy for Python 3 Kivy-1.9.1-osx-python3.7z here : https://kivy.org/#download 3. In terminal : cd <Directory you Downloaded Kivy> 4. In terminal : sudo mv Kivy2.app /Applications/Kivy.app 5. In terminal : ln -s /Applications/Kivy.app/Contents/Resources/script /usr/local/bin/kivy 6. Test it works in terminal type : kivy and then import kivy 7. Run application by typing in terminal : kivy yourapp.py # ---------- Install Kivy on Windows ---------- 1. Install Python and PyCharm like I show here : https://youtu.be/nwjAHQERL08?t=37m 2. In command prompt : python -m pip install --upgrade pip wheel setuptools 3. In command prompt : python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew 4. In command prompt : python -m pip install kivy.deps.gstreamer --extra-index-url https://kivy.org/downloads/packages/simple/ 5. In command prompt : python -m pip install kivy # ---------- kivytut.py ---------- import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.button import Label # Inherit Kivy's App class which represents the window # for our widgets # HelloKivy inherits all the fields and methods # from Kivy class HelloKivy(App): # This returns the content we want in the window def build(self): # Return a label widget with Hello Kivy return Label(text="Hello Kivy") helloKivy = HelloKivy() helloKivy.run() # ---------- kivytut2.py ---------- import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.button import Label # Inherit Kivy's App class which represents the window # for our widgets # HelloKivy inherits all the fields and methods # from Kivy class HelloKivyApp(App): # This returns the content we want in the window def build(self): # Return a label widget with Hello Kivy # The name of the kv file has to be hellokivy # minus the app part from this class to # match up properly return Label() hello_kivy = HelloKivyApp() hello_kivy.run() # ---------- hellokivy.kv ---------- # We can separate the logic from the presentation layer <Label>: text: "Hello Kivy" #~~Learn to program 28 Kivy 2 # ---------- KIVYTUT.PY ---------- # It is common practice to create your own custom # widgets so base widgets aren't effected import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.widget import Widget class CustomWidget(Widget): pass class CustomWidgetApp(App): def build(self): return CustomWidget() customWidget = CustomWidgetApp() customWidget.run() # ---------- CUSTOMWIDGET.KV ---------- # You can set default attributes that are shared by # other widgets # color is RGBA as a percent of 255 and alpha # Color is the text color # background_normal and background_down are either # white with '' or can be set to a png # background_color tints whatever the background is <CustButton@Button>: font_size: 32 color: 0, 0, 0, 1 size: 150, 50 background_normal: '' background_down: 'bkgrd-down-color.png' background_color: .88, .88, .88, 1 # Position is x and y from the bottom left hand corner # You can define the position based on the changing # window sizes with root.x being the left most side # and root.y being the bottom <CustomWidget>: CustButton: text: "Random" pos: root.x, 200 CustButton: text: "Buttons" pos: 200, root.y CustButton: text: "Buttons" pos: 200, 400 # ---------- KIVYTUT2.PY ---------- import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.floatlayout import FloatLayout # A Float layout positions and sizes objects as a percentage # of the window size class FloatingApp(App): def build(self): return FloatLayout() flApp = FloatingApp() flApp.run() # ---------- FLOATING.KV ---------- # size_hint defines the widget width (0-1) representing # a percentage of 100% and height of the window <CustButton@Button>: font_size: 32 color: 0, 0, 0, 1 size: 150, 50 background_normal: '' background_down: 'bkgrd-down-color.png' background_color: .88, .88, .88, 1 size_hint: .4, .3 # pos_hint represents the position using either x, y, left, # right, top, bottom, center_x, or center_y <FloatLayout>: CustButton: text: "Top Left" pos_hint: {"x": 0, "top": 1} CustButton: text: "Bottom Right" pos_hint: {"right": 1, "y": 0} CustButton: text: "Top Right" pos_hint: {"right": 1, "top": 1} CustButton: text: "Bottom Left" pos_hint: {"left": 1, "bottom": 0} CustButton: text: "Center" pos_hint: {"center_x": .5, "center_y": .5} # ---------- KIVYTUT3.PY ---------- import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.gridlayout import GridLayout # The Grid Layout organizes everything in a grid pattern class GridLayoutApp(App): def build(self): return GridLayout() glApp = GridLayoutApp() glApp.run() # ---------- GRIDLAYOUT.KV ---------- # Define the number of columns and rows # Define the spacing between children in pixels <GridLayout>: cols: 2 rows: 2 spacing: 10 # Set the size by passing None to size_hint_x # and then pass the width Button: text: "1st" size_hint_x: None width: 200 Button: text: "2nd" Button: text: "3rd" size_hint_x: None width: 200 Button: text: "4th" # ---------- KIVYTUT4.PY ---------- import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.boxlayout import BoxLayout # With a box layout we arrange widgets in a horizontal # or vertical box class BoxLayoutApp(App): def build(self): return BoxLayout() blApp = BoxLayoutApp() blApp.run() # ---------- BOXLAYOUT.KV ---------- # Orientation defines whether widgets are stacked (vertical) # or are placed side by side (horizontal) # padding is the space between the widgets and the # surrounding window <BoxLayout>: orientation: "vertical" spacing: 10 padding: 10 # size_hint defines the percentage of space taken on the # x access and the percentage of space left over by the # other widgets Button: text: "1st" size_hint: .7, .5 Button: text: "2nd" Button: text: "3rd" # ---------- KIVYTUT5.PY ---------- import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.stacklayout import StackLayout # A stack layout arranges widgets vertically or horizontally # as they best fit class StackLayoutApp(App): def build(self): return StackLayout() slApp = StackLayoutApp() slApp.run() # ---------- STACKLAYOUT.KV ---------- # orientation is lr-tb or left to right, top to bottom # Other options are tb-lr, rl-tb, tb-rl, lr-bt, bt-lr, # rl-bt, bt-rl <StackLayout>: orientation: "lr-tb" spacing: 10 padding: 10 # size_hint defines the percentage of space taken on the # x access and the percentage of space left over by the # other widgets Button: text: "Q" size_hint: None, .15 width: 100 Button: text: "W" size_hint: None, .15 width: 120 Button: text: "E" size_hint: None, .15 width: 140 Button: text: "R" size_hint: None, .15 width: 160 Button: text: "T" size_hint: None, .15 width: 180 Button: text: "Y" size_hint: None, .15 width: 200 # ---------- KIVYTUT6.PY ---------- import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.pagelayout import PageLayout # A page layout is used to create multi-page layouts # that you can flip through class PageLayoutApp(App): def build(self): return PageLayout() plApp = PageLayoutApp() plApp.run() # ---------- PAGELAYOUT.KV ---------- <PageLayout>: Button: text: "Page 1" Button: text: "Page 2" Button: text: "Page 3" #~~Learn to program 32 Django 1 # ---------- INSTALL DJANGO ON MAC ---------- 1. Check your Python version by typing in the terminal : python --version 2. You want Python 3.4 or higher. Type the following to see if you have Python 3 in the terminal : python3 --version 3. If you need Python 3.4 or above do this A. Download Python at https://www.python.org/downloads B. Click Download Python 3.5.1 or later C. Click Open D. Click continue a few times. Agree to the terms and install. You may have to enter your password. 4. Check to see if you have pip installed in the terminal type : pip --version 5. If you don't have pip 8 or above type in the terminal : sudo easy_install pip 6. Type in the terminal : sudo pip install Django 7. Test that Django is installed in the terminal A. python3 B. import django C. django.get_version() D. You should see '1.10.2' or higher 8. Create a sample site : django-admin startproject sampsite A. sampsite is were your project lives i. __init__.py tells Python that this is a Python package ii. settings.py has settings for the Django project iii. urls.py a sort of table of contents for your project iv. wsgi.py serves your project B. manage.py allows you to interact with your project 9. Start the server : python manage.py runserver # ---------- INSTALL DJANGO ON WINDOWS ---------- 1. Check your Python version by typing in the terminal : python --version (You want Python 3.4 or higher) 2. If Python 3.4 or higher isn't installed A. Go to https://www.python.org/getit/windows/ B. Click on Latest Python 3 Release C. Click on Windows x86 executable installer D. Click Run E. Check Install for all users and add Python 3 to path a. Open Control Panel -> System & Security -> System -> Advanced System Settings on the left b. Environment Variable button c. Select PATH and click edit d. Add c:\Pyhon34, or what ever your Python directory is 3. Install Pip in the command line type : python -m pip install -U pip 4. Create a Python Virtual Environment so we don't have to worry about changing dependencies that your system may not want edited. A. Type in Command Prompt : pip install virtualenv B. Create the virtual environment for your site in command prompt : virtualenv env_site1 C. Activate the environment in CP i. cd Scripts ii. activate 5. Install Django in CP : pip install django 6. Test that it works A. python B. import django C. django.get_version() D. You should see '1.10.2' or higher 7. Create a sample site : django-admin startproject sampsite A. sampsite is were your project lives i. __init__.py tells Python that this is a Python package ii. settings.py has settings for the Django project iii. urls.py a sort of table of contents for your project iv. wsgi.py serves your project B. manage.py allows you to interact with your project 8. Start the server : python manage.py runserver #~~Learn to program 33 Django 2 # ---------- sampsite/views.py ---------- from django.http import HttpResponse import random # This is our View function which receives info # on the request def hello_world(request): # Return a response object with the text Hello World return HttpResponse("Hello World") def root_page(request): return HttpResponse("Root Home Page") # Receives the number passed in the url and then returns # a random number def random_number(request, max_rand=100): # Calculate a random number between 0 and the number passed random_num = random.randrange(0, int(max_rand)) # Place the string and decimal in the output msg = "Random Number Between 0 and %s : %d" % (max_rand, random_num) return HttpResponse(msg) # ---------- NOW ON TO SETTINGS ---------- # ---------- settings.py ---------- """ Django settings for sampsite project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '1$(46qw^uc2q&c)gad(*4^y)a8g2^dbr$%)nlvyf3jygfbv70(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ # - The Django admin system 'django.contrib.admin', # - The authentication system 'django.contrib.auth', # - Framework for content types 'django.contrib.contenttypes', # - Session Framework 'django.contrib.sessions', # - Message Framework 'django.contrib.messages', # - Manages static files 'django.contrib.staticfiles', # 4 Include our polls app # 4 Run python3 manage.py makemigrations polls # 4 to notify Django that you have updated your Model # 4 Run python3 manage.py sqlmigrate polls 0001 to see # 4 the SQL used to create the DB # 4 Run python3 manage.py migrate to create the DB # 4 Create the models in polls/models.py 'polls.apps.PollsConfig', ] # 6 We can add data to the DB using the Python shell # - python3 manage.py shell # - Import Models : from polls.models import Question, Choice # - Display Questions : Question.objects.all() # - Create a Question # - from django.utils import timezone # - q = Question(question_text="What's New?", pub_date=timezone.now()) # - Save to the DB : q.save() # - Get the questions id : q.id # - Get the questions text : q.question_text # - Get the pub date : q.pub_date # - Change the question : q.question_text = "What's Up?" # - Save the change : q.save() # - Display Questions : Question.objects.all() # 6 Change polls/models.py to provide more info on question and choice MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'sampsite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'sampsite.wsgi.application' # 4 Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases # 4 We'll use the default database of SQLite3 # - You can use other DBs, but must add USER, PASSWORD and HOST # - django.db.backends.mysql # - django.db.backends.postgresql # - django.db.backends.oracle DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' # - Change the time zone to yours using # - https://en.wikipedia.org/wiki/List_of_tz_database_time_zones TIME_ZONE = 'America/New_York' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' # - Add a path for static files STATIC_ROOT = os.path.join(BASE_DIR, 'static') # ---------- sampsite/urls.py ---------- """sampsite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ # url matches the URL in the browser to a module # in your Django project from django.conf.urls import url # Loads URLs for Admin site from django.contrib import admin # Reference my hello_world function from sampsite.views import hello_world, root_page, random_number # 3 include allows you to reference other url files # in our project from django.conf.urls import include # Lists all URLs # Add the directory in the URL you want tied to # the hello_world function # The r means we want to treat this like a raw string # that ignored backslashes # Then we define a regular expression where ^ is the # beginning of a string, then we have the text to match # The $ signifies the end of a Regex string # We can pass data to a function by surrounding the part # of the Regex to send with parentheses # If they didn't enter a number I provide a default max urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^helloworld/$', hello_world), url(r'^$', root_page), url(r'^random/(\d+)/$', random_number), url(r'^random/$', random_number), # 3 Reference the root of the polls app url(r'^polls/', include('polls.urls')), ] # 3 Test that the polls URL works by running the server # python3 manage.py runserver # Go to localhost:8000/polls/ # 3 Setup the database in settings.py # ---------- polls/views.py ---------- # 1 Create the polls app inside our project # 1 python3 manage.py startapp polls # 1 You can have multiple apps in your project # 1 Now we will create a view from django.http import HttpResponse def index(request): return HttpResponse("You're in the polls index") # 1 Now attach the view to a url in urls.py # ---------- polls/urls.py ---------- from django.conf.urls import url from . import views # 2 Add a reference to the view and assign it to # the root URL for polls urlpatterns = [ url(r'^$', views.index, name='index'), ] # 2 Now point the root URL file to the polls app # ---------- polls/models.py ---------- # 5 Here you define the names and data types for # 5 the information you are storing in your database from django.db import models import datetime from django.utils import timezone # 5 Create your models here. # 5 Each model is a class with class variables that # 5 represent fields in your database # 5 After setting the column names an data types the DB # 5 can create the table class Question(models.Model): # 5 Define a DB column called question_text which # 5 contains text with a max size of 200 question_text = models.CharField(max_length=200) # 5 This contains a date and the text passed is an # 5 optional human readable name pub_date = models.DateTimeField('date published') # 7 Return the text for the question when the Question # 7 is called by editing __str__ def __str__(self): return self.question_text # 7 Here is a custom method for returning whether # 7 the question was published recently def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): # 5 Define that each choice is related to a single # 5 Question question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) # 7 Return the Choice text as well def __str__(self): return self.choice_text # 7 Let's test our changes : python3 manage.py shell # 7 from polls.models import Question, Choice # 7 Get a detailed list of questions # 7 Question.objects.all() # 7 Get the Question with the matching id # 7 Question.objects.filter(id=1) # 7 Get the question that starts with What # 7 Question.objects.filter(question_text__startswith='What') # 7 Get Question published this year # 7 from django.utils import timezone # 7 current_year = timezone.now().year # 7 Question.objects.get(pub_date__year=current_year) # 7 If you request something that doesn't exist you # 7 raise an exception # 7 Question.objects.get(id=2) # 7 Search for primary key # 7 Question.objects.get(pk=1) # 7 Test was_published_recently() # 7 q = Question.objects.get(pk=1) # 7 q.was_published_recently() # 7 Show choices for matching question # 7 q.choice_set.all() # 7 Add new choices # 7 q.choice_set.create(choice_text='Not Much', votes=0) # 7 q.choice_set.create(choice_text='The Sky', votes=0) # 7 q.choice_set.create(choice_text='The Clouds', votes=0) # 7 Display choices # 7 q.choice_set.all() # 7 Display number of choices # 7 q.choice_set.count() # 7 Show all choices for questions published this year # 7 Use __ to separate relationships # 7 Choice.objects.filter(question__pub_date__year=current_year) # 7 Delete a choice # 7 c = q.choice_set.filter(choice_text__startswith='The Clouds') # 5 After defining the model we include the app in our project # 5 under INSTALLED_APPS in settings.py #~~Learn to program 34 Django 3 # ---------- /polls/admin.py ---------- # 1 Django automates the interface used to add, change # and delete content # To create a user : python3 manage.py createsuperuser # Username: admin # Email address: db@compuserve.com # Enter passwords # 1 Run the server : python3 manage.py runserver # Open localhost:8000/admin # 1 Tell admin that our poll system has an admin interface # in polls/admin.py # 1 You can change any of the options and click History # to see a list of the changes # You can also add or delete questions # 1 Now add more views in polls/views.py from django.contrib import admin # Register your models here. # - Import Question from .models import Question # - Register Question for showing in admin admin.site.register(Question) # ---------- /polls/views.py ---------- from django.http import HttpResponse # 7 Opens a 404 page if get doesn't supply a result from django.shortcuts import get_object_or_404 # 2 Each view is represented by a function # We'll create : # index : Display the latest questions # detail : Display the question and the choices # results : Display question results # - Original index function ''' def index(request): return HttpResponse("You're in the polls index") ''' # 4 # Import Question and Choice from our models file from .models import Question, Choice ''' # 4 New index function def index(request): # 4 Receive a list of 5 questions ordered by date latest_question_list = Question.objects.order_by('-pub_date')[:5] # 4 Cycle through the questions to create a list output = ', '.join([q.question_text for q in latest_question_list]) # Return the text to display return HttpResponse(output) ''' # 4 This isn't the best solution because the results are # hard coded into the Python. Let's use a template to # separate the design from the code # Create a directory named templates in polls # Create a directory named polls in the templates directory # Create a file named index.html in that polls directory # and create the template # 6 Create a new index function that sends the question list # to the template # 6 Renders a page when it is passed a template and # any data required by the template from django.shortcuts import render def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] # 6 Define the name for the data to pass to the template context = { 'latest_question_list': latest_question_list, } # 6 Render the page in the browser using the template # and data required by the template return render(request, 'polls/index.html', context) # 2 add these 3 new views ''' def detail(request, question_id): return HttpResponse("You're looking at question %s" % question_id) ''' ''' def results(request, question_id): response = "You're looking at the results of question %s" return HttpResponse(response % question_id) ''' # 10 Let's update results() to show voting results def results(request, question_id): # 10 Get the question id passed or 404 question = get_object_or_404(Question, pk=question_id) # 10 Render the template return render(request, 'polls/results.html', {'question': question}) # 10 Now create /templates/polls/results.html template ''' def vote(request, question_id): return HttpResponse("You're voting on question %s" % question_id) # 7 Let's update detail to use a 404 page and template ''' # 9 Now we will update vote() to except the choice picked # 9 Used to avoid receiving data twice from a form if the user # clicks the back button from django.http import HttpResponseRedirect # 9 Used to return a url we can point to based on the # current question we are dealing with from django.urls import reverse def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) # 9 Try to get the selected radio button try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except(KeyError, Choice.DoesNotExist): # 9 Re-render the form return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice" }) else: # 9 If a choice was selected increment it in the DB selected_choice.votes += 1 selected_choice.save() # 9 Protect from data being sent twice if user clicks back return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) def detail(request, question_id): # 7 Check if the page exists, or display 404 page question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) # 7 Now create the detail.html template in templates/polls/ # 2 Add them to polls/urls.py # ---------- /polls/urls.py ---------- from django.conf.urls import url from . import views # 3 Add a namespace so Django knows what directory to load # if another app has views with the same name app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), # 3 Add the 3 views # The data surrounded by parentheses is sent to the function # ?P<question_id> defines the name for the data within # the parentheses # [0-9]+ says we will match 1 or more numbers url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] # 3 Now let's update polls/views.py # ---------- /polls/templates/polls/index.html ---------- <!-- 5 If a list of questions is available create an unordered list of the questions or print that none are available --> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li> <!-- 5 url defines directory to open based on using the namespace defined in polls/urls.py and the url defined in sampsite/urls.py --> <a href="{% url 'polls:detail' question.id %}">{{question.question_text}}</a> </li> {% endfor %} </ul> {% else %} <p>No polls are available</p> {% endif %} <!-- 5 Back to polls/views.py to update index --> # ---------- /polls/templates/polls/detail.html ---------- <!-- 8 Display the question passed and the choices available --> <h1>{{question.question_text}}</h1> <!-- 8 Display error message --> {% if error_message %} <p><strong>{{error_message}}</strong></p> {% endif %} <!-- 8 Create a form which allows users to pick a choice --> <!-- Point at the vote function in polls/views.py using the namespace and pass the question id --> <form action="{% url 'polls:vote' question.id %}" method="post"> <!-- 8 Protects your site from Cross Site Request Forgeries which occur when another site tries to target your form --> {% csrf_token %} <!-- 8 Cycle through all choices for this question and create a radio button for each --> {% for choice in question.choice_set.all %} <!-- 8 When submitted the choice id is sent --> <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br> {% endfor %} <input type="submit" value="Vote" /> </form> <!-- 8 Now update the vote function in polls/views.py --> # ---------- /polls/templates/polls/results.html ---------- <!-- 11 Displays choice results for the passed question --> <h1>{{question.question_text}}</h1> <!-- Cycle through all the choices for the question --> <ul> {% for choice in question.choice_set.all %} <li> <!-- Add a s to vote if not 1 --> {{choice.choice_text}} -- {{choice.votes}} vote{{choice.votes|pluralize}} </li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote Again</a> #~~Learn to program 35 Django 4 # ---------- /polls/urls.py ---------- # 1 Generic views are normally used from the beginning # and they help you avoid having to write a lot # of custom code from django.conf.urls import url from . import views app_name = 'polls' # 1 We'll change the urlpatterns urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] # 1 Now remove our index, detail and results views in polls/views.py ''' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] ''' # ---------- /polls/views.py ---------- from django.http import HttpResponse from .models import Question, Choice from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse # 2 Add the generic module from django.views import generic # 8 Import so we can get time information from django.utils import timezone # 2 The ListView displays your list of questions being # latest_question_list class IndexView(generic.ListView): template_name = 'polls/index.html' # 2 This defines the question list we want to use context_object_name = 'latest_question_list' # 8 Replace get_queryset and don't return questions # published in the future ''' def get_queryset(self): # 2 Return the last 5 questions entered return Question.objects.order_by('-pub_date')[:5] ''' def get_queryset(self): # 8 Return only questions with a pub_date less than # or equal to now return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] # 8 Add Choices to the Admin in admin.py # 2 The DetailView displays the details on your object # being the Question model # 2 The generic view expects the pk (Primary Key) value # from the URL to be called pk as we set in polls/urls.py class DetailView(generic.DetailView): model = Question # 2 Define the template to use with this data template_name = 'polls/detail.html' # 12 Exclude questions that are not published yet def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) # 12 Add tests in polls/tests.py # 2 class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' # 2 Remove these functions ''' def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list': latest_question_list, } return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) ''' # 2 Vote stays the same def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except(KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice" }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) # 3 Now we will explore automated testing. You can either # check your code by entering values randomly (and miss # a bunch of errors), or you can automate the process. # 3 We'll now explore a bug in the was_published_recently() function # in polls/models.py in the shell : python3 manage.py shell # 3 Create a Question with a pub_date in the future ''' import datetime from django.utils import timezone from polls.models import Question future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30)) future_question.was_published_recently() Returns true even though that doesn't make sense ''' # 3 Open the file called tests.py # ---------- /polls/tests.py ---------- from django.test import TestCase # 4 Import your needed modules import datetime from django.utils import timezone from django.test import TestCase from .models import Question # 4 TestCase runs tests without effecting your data # by creating a temporary database for testing class QuestionMethodTests(TestCase): # 4 Put the code used in the shell here # Start the method name with test def test_was_published_recently_with_future_question(self): # 4 Create a time 30 days in the future time = timezone.now() + datetime.timedelta(days=30) # 4 Create a question using the future time future_question = Question(pub_date=time) # 4 Check to see if the output is False like we expect self.assertIs(future_question.was_published_recently(), False) # 4 Run the test in the terminal # python3 manage.py test polls # You'll see that the test failed # 4 Fix the bug in models.py # 6 Return false if pub_date is older then 1 day def test_was_published_recently_with_old_question(self): # Should return false if pub_date is older then 1 day time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) # 6 Return True if published within the last day def test_was_published_recently_with_recent_question(self): time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) # 6 Test with : python3 manage.py test polls # 7 We can simulate user interaction at the view level in the shell # python3 manage.py shell ''' # This allows us access variable values in our templates # We will be using our real database here from django.test.utils import setup_test_environment setup_test_environment() # Create the client that we'll use to run our app from django.test import Client client = Client() # Get the status code from localhost:8000/ response = client.get('/') response.status_code # Get the status code for localhost:8000/polls/ from django.urls import reverse response = client.get(reverse('polls:index')) response.status_code # Get the HTML content response.content # Get the value of latest_question_list response.context['latest_question_list'] ''' # 7 Let's update polls/views.py so it doesn't show # questions published in the future # 10 Create a function that creates questions at # a specified date def create_question(question_text, days): time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) # 10 Add more question tests class QuestionViewTests(TestCase): # 10 Test to see what happens if there are no questions def test_index_view_with_no_questions(self): # Get the client response = self.client.get(reverse('polls:index')) # Check the status code self.assertEqual(response.status_code, 200) # Verify that response contains this string self.assertContains(response, "No polls are available.") # Check if latest_question_list is empty self.assertQuerysetEqual(response.context['latest_question_list'], []) # 10 Make sure questions with a pub_date in past are shown def test_index_view_with_a_past_question(self): # Create sample question create_question(question_text="Past question.", days=-30) # Get client response = self.client.get(reverse('polls:index')) # Verify that the question shows self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) # 10 Make sure questions with future pub_date don't show def test_index_view_with_a_future_question(self): # Create question create_question(question_text="Future question.", days=30) # Get client response = self.client.get(reverse('polls:index')) # Verify response contains text self.assertContains(response, "No polls are available.") # Verify that latest_question_list is empty self.assertQuerysetEqual(response.context['latest_question_list'], []) # 10 Verify that if past and future questions exist that only # past show def test_index_view_with_future_question_and_past_question(self): # Create questions create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) # Get client response = self.client.get(reverse('polls:index')) # Verify that question list only contains past questions self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) # 10 Make sure question list shows multiple questions def test_index_view_with_two_past_questions(self): # Create questions create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) # Create client response = self.client.get(reverse('polls:index')) # Verify that both questions show self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) # 11 Make sure future questions can't be accessed if the user # guess the URL in polls/views.py # 13 Add tests to make sure future posts aren't shown in detail class QuestionIndexDetailTests(TestCase): # 13 Make sure future question detail pages show 404 def test_detail_view_with_a_future_question(self): # Create question future_question = create_question(question_text='Future question.', days=5) # Open url using the future question in the url url = reverse('polls:detail', args=(future_question.id,)) # Get client response response = self.client.get(url) # Verify that it returns 404 self.assertEqual(response.status_code, 404) # 13 Verify that past questions show in detail def test_detail_view_with_a_past_question(self): # Create question past_question = create_question(question_text='Past Question.', days=-5) # Open url with past question url = reverse('polls:detail', args=(past_question.id,)) # Get response response = self.client.get(url) # Verify the question shows self.assertContains(response, past_question.question_text) # ---------- /polls/models.py ---------- from django.db import models import datetime from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): # 5 return self.pub_date >= timezone.now() - datetime.timedelta(days=1) # 5 Fix the code now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now # 5 Now the test will pass # 5 Add further tests to polls/tests.py class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text # ---------- /polls/admin.py ---------- from django.contrib import admin # 9 Add choice to imports from .models import Question, Choice admin.site.register(Question) # 9 Add Choice to the Admin page admin.site.register(Choice) # 9 Create some future questions # 9 Add some tests in polls/tests.py
0c9d884be92fc5be09579b9b6863de610dacbed9
saurabh190802/septocode
/Day 10/SaurabhSatapathy_day10.py
664
3.71875
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 30 10:53:09 2021 @author: saurabh satapathy """ def check_string(s): #defining the function check c=0 alphabet = "abcdefghijklmnopqrstuvwxyz" for char in alphabet: if char in s: c=c+1 if c == 26: print("Pass") if c < 26: print("Fail") n = int(input()) for i in range(0,n): #taking input of number of students s=str(input()) #taking input of string s check_string(s) #calling check function
2badb70ca36701549b24fdf84d14a0cb45a9317b
rimzimt/Hashing-2
/18_longest_palindrome_set.py
1,035
3.75
4
# S30 Big N Problem #18 {Easy} # Given a string consisting of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. #This is case sensitive, for example "Aa" is not considered a palindrome here. # Time Complexity : O(n) n= length of string # Space Complexity : O(n) n= length of string # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Maintain a set. Alternatively add or remove chars when they appear in the string. # When the char is removed, add the count by 2. # When a element is present in set, increment the final count by 1 class Solution: def longestPalindrome(self, s: str) -> int: dic=set() cnt=0 for a in s: if a in dic: dic.discard(a) cnt+=2 else: dic.add(a) if len(dic)!=0: cnt+=1 return cnt
0a7b343ad60867887813511935c5fbb174ef9d2b
mfalcirolli1/Python-Exercicios
/ex105.py
701
3.796875
4
# Analisando e gerando Dicionários def analise(*n, sit=False): """ -> Analisar notas de vários alunos :param n: Notas :param sit: Situação geral dos alunos :return: Dicionários com várias informações """ dic = {} dic['total'] = len(n) dic['maior'] = max(n) dic['menor'] = min(n) dic['média'] = sum(n) / len(n) if sit: if dic['média'] > 7: dic['Situação'] = 'Ótimo' elif 5 <= dic['média'] < 7: dic['Situação'] = 'Regular' elif dic['média'] < 5: dic['Situação'] = 'Péssimo' return dic resp = analise(5, 8, 7, 9, 7.5, 8.5, 9.5, sit=True) print(resp) help(analise)
32e4e71745daebd102617145cb0c49200d5cf9e7
DennisWanjeri/alx-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
463
4.40625
4
#!/usr/bin/python3 """Print square""" def print_square(size): """prints a square with character '#'""" if type(size) is not int: raise TypeError("size must be an integer") elif (size < 0) is True: raise ValueError("size must be >= 0") elif type(size) is float and (size < 0) is True: raise TypeError("size must be an integer") for i in range(size): [print("#", end="") for j in range(size)] print("")
4877e4cd7aced1842078ffabf1decc0ba16dfd21
arpitbhl/spoken-english-to-written-english
/spokenEng2WrittenEng/convertor.py
4,189
3.875
4
# Helper Functions # Function checkCommas: checks if word has comma at front or at last or at both if true then return front,word and last def checkCommas(word): start = "" last = "" if(len(word) > 1): if word[-1] == ',' or word[-1] == '.': last = word[-1] word = word[:-1] if word[0] == ',' or word[0] == '.': start = word[0] word = word[1:] return start, word, last # Function getRules: define all the rules of written english here def getRules(): rules = {"Numbers": { "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "forteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90, "hundred": 100, "thousand": 1000 }, "Tuples": { "single": 1, "double": 2, "triple": 3, "quadruple": 4, "quintuple": 5, "sextuple": 6, "septuple": 7, "octuple": 8, "nonuple": 9, "decuple": 10 }, "General": { "C M": "CM", "P M": "PM", "D M": "DM", "A M": "AM" } } return rules # MAIN CLASS for the logic: spEngtoWritEng class spEngtoWritEng: def __init__(self): self.rules = getRules() self.paragraph = "" self.convertedPara = "" # to get input from user in the form of paragraph def getInput(self): self.paragraph = input("\nEnter spoken english:\n\t") if not self.paragraph: raise ValueError("Error: You entered nothing.") # to print the output after converting to written english def printOutput(self): print("\nConverted Written English Paragraph: \n\n \"" + self.convertedPara+"\"") # main function to convert spoken to written english def convert(self): # splitting paragraph into individual words words_of_para = self.paragraph.split() numbers = self.rules['Numbers'] tuples = self.rules['Tuples'] general = self.rules['General'] i = 0 no_of_words = len(words_of_para) while i < no_of_words: start, word, last = checkCommas(words_of_para[i]) if i+1 != no_of_words: # when word is of the form e.g.: two front_n, next_word, last_n = checkCommas(words_of_para[i+1]) # checking dollar if word.lower() in numbers.keys() and (next_word.lower() == 'dollars' or next_word.lower() == 'dollar'): self.convertedPara = self.convertedPara+" " + \ start+"$"+str(numbers[word.lower()])+last i = i+2 elif word.lower() in tuples.keys() and len(next_word) == 1: # when word is of form Triple A self.convertedPara = self.convertedPara+" " + \ front_n+(next_word*tuples[word.lower()])+last_n i = i+2 elif (word+" "+next_word) in general.keys(): # if word is of form P M or C M self.convertedPara = self.convertedPara+" "+start+word+next_word+last_n i = i+2 else: self.convertedPara = self.convertedPara + \ " "+words_of_para[i] i = i+1 else: self.convertedPara = self.convertedPara+" "+words_of_para[i] i = i+1 # main function def convert_sp_to_wr(): # creating class object obj_spoken = spEngtoWritEng() # taking input obj_spoken.getInput() # conversion obj_spoken.convert() # showing output obj_spoken.printOutput()
b01acf242b0e4967aa93f384fb70207c49e138dc
ironboxer/leetcode
/python/9.py
1,141
3.859375
4
""" https://leetcode-cn.com/problems/palindrome-number/ 9. 回文数 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 示例 1: 输入: 121 输出: true 示例 2: 输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 示例 3: 输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。 进阶: 你能不将整数转为字符串来解决这个问题吗? """ class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False r = 0 t = x while t: r = r * 10 + t % 10 t //= 10 return r == x class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False buf = [] while x: buf.append(x % 10) x //= 10 l, r = 0, len(buf) - 1 while l < r: if buf[l] != buf[r]: return False l, r = l + 1, r - 1 return True
c3e32db548468917f51cc13c4d36e1b7438a6fce
rishika028/nq_ga
/nq_ga.py
8,475
3.953125
4
#!/usr/bin/env python3 """Solving the n-Queens problem using genetic algorithms.""" import datetime import math import random import sys import time class Queen: def __init__(self, row, col): self.row = row self.col = col def safe(self, other): if other.row == self.row and other.col == self.col: return True if other.row == self.row: return False if other.col == self.col: return False slope = abs((self.row - other.row) / (self.col - other.col)) if slope == 1: return False return True def __str__(self): return str(self.col + 1) class Board: def __init__(self, state): """Initialise the board from a state string.""" self._queens = [] self._size = len(state) tState = [int(c) for c in state] assert(max(tState) <= self._size) for i in range(0, self._size): self._queens.append(Queen(i, tState[i] - 1)) self.max_threats = math.factorial(self._size) / (math.factorial(self._size - 2) * 2) self._fitness = -1 def mutate(self, p): s = str(self) ms = '' for c in s: x = random.random() if x <= p: new_c = c while new_c == c: new_c = str(random.randint(1, len(s))) ms += new_c else: ms += c return Board(ms) def fitness(self): if self._fitness > -1: return self._fitness threats = 0 for q in self._queens: for o in self._queens: if not q.safe(o): threats += 1 self._fitness = self.max_threats - (threats / 2) return self._fitness def mate(self, other, i): sqs = ''.join(str(q) for q in self._queens[:i]) oqs = ''.join(str(q) for q in other._queens[i:]) return Board(sqs + oqs) def __str__(self): return ''.join([str(q) for q in self._queens]) def __len__(self): return self._size def goal_test(self): s = str(self) if len(s) != len(set(s)): return False if s.fitness() < self.max_threats: return False return True def random_board(n=8): return ''.join([str(random.randint(1, n)) for _ in range(n)]) def make_boards(*args): boards = [] for arg in args: boards.append(Board(arg)) return boards def crossover(a, b, i=-1): assert(a._size == b._size) if i == -1: i = random.randint(1, len(a) - 1) return a.mate(b, i), b.mate(a, i) class Population: def __init__(self, members, mutation_rate=0.2): self._members = members[:] self._mr = mutation_rate def select(self, n=4): assert(n % 2 == 0) scores = [parent.fitness() for parent in self._members] total = sum(scores) pcts = [round(score / total * 100) for score in scores] cutoff = 0 cutoffs = [] for pct in pcts: cutoff += pct cutoffs.append(cutoff) chosen = [] while len(chosen) < n: x = random.randint(1, 100) for i in range(len(cutoffs)): if x <= cutoffs[i]: chosen.append(self._members[i]) break return chosen def iterate(self, n=4, i=-1): chosen = self.select(n) assert(len(chosen) != 0) children = [] for j in range(0, len(chosen), 2): children.extend(crossover(chosen[j], chosen[j+1], i)) for j in range(0, len(children)): child = children[j] children[j] = child.mutate(self._mr) return Population(children) def display(self): s = '' for member in self._members: s += '{}: {}'.format(member, member.fitness()) return s def size(self): return len(self._members) def best(self): best = None best_score = -1 for member in self._members: score = member.fitness() if score > best_score: best_score = score best = member return best def max_fitness(self): return self.best().fitness() class Generation: def __init__(self, parents, i=4, p=0.2): self._parents = parents self._children = None self._best_parent = parents.best() self._best_child = None self.n = parents.size() self.i = i self.p = p def score(self): if self._best_child is None: self.run() return self._best_child.max_fitness() def run(self): if self._children is not None: return self._children self._children = self._parents.iterate(self.n, self.i) self._best_child = self._children.best() return self._children def __str__(self): if self._children is None: self.run() s = """ Parents:\t Children: """ for i in range(0, self.n): p = self._parents._members[i] c = self._children._members[i] s += "{} ({})\t| {} ({})\n".format(p, p.fitness(), c, c.fitness()) bpf = self._best_parent.fitness() bcf = self._best_child.fitness() s += """ Best: Parent: {} Child: {} """.format(bpf, bcf) s += "Generation has " if bpf < bcf: s += "improved" elif bpf == bcf: s += "stagnated" else: s += "regressed" return s + ".\n" def progress(self): bpf = self._best_parent.fitness() bcf = self._best_child.fitness() return bcf - bpf class Experiment: def __init__(self, starting=None, popsize=4): if starting is None: starting = Population([Board(random_board()) for _ in range(popsize)]) self.generations = [] self.latest = starting def completed(self): if self.latest is None: return False if self.latest.max_fitness() < self.latest._members[0].max_threats: return False return True def score(sef): return self.latest.max_fitness() def step(self): if self.completed(): return 0 g = Generation(self.latest) self.latest = g.run() self.generations.append(g) return g.progress() def run(self, max_steps=0, verbose=False, quiet=False): n = len(self.generations) stop_at = 0 stop_cond = lambda : False if max_steps > 0: stop_at = n + max_steps stop_cond = lambda : len(self.generations) >= stop_at cpr = 0 # chars printed while not stop_cond(): if self.completed(): break progress = self.step() if verbose: print(self.generations[:-1]) elif not quiet: if progress < 0: sys.stdout.write('<') elif progress == 0: sys.stdout.write('-') else: sys.stdout.write('>') sys.stdout.flush() cpr += 1 if cpr == 73: cpr = 0 sys.stdout.write('\n') if not verbose and not quiet: sys.stdout.write('\n') return self.completed() def __str__(self): if self.completed(): return 'Solution: {} in {} generations.'.format(self.best(), len(self.generations)) else: return 'No solution yet.' def best(self): return self.latest.best() def __len__(self): return len(self.generations) def random_experiment(): exp = Experiment() start = time.process_time() exp.run() stop = time.process_time() print(exp) print('Elapsed:', datetime.timedelta(seconds=stop-start)) if __name__ == '__main__': random_experiment()
f18acb55efa2f8c2846161cbad98eacbd51cb2a4
ReeceNich/Python-School
/181010 Image Editor/181010 Photo Editor.py
4,186
3.90625
4
from Image_Library import * menu_list = { 1: "Rotate 90 clockwise.", 2: "Rotate 90 anti-clockwise.", 3: "Custom rotation.", 4: "Print a histogram.", 5: "Quit" } def menu(options): print("--== Welcome to the Image Manipulator 3000! ==--") #prints the menu_list dictionary for x in options: print(str(x) + ":", str(options[x])) #tests to check the choice is a valid int. correct = False while not correct: try: choice = int(input("\nPlease enter your choice: ")) #checks if the int is in the menu_list dictionary. if choice in options: correct = True return choice else: print("***Enter a correct choice!***") except ValueError: print("***Enter a valid number!***") except: print("***Unexpected Error!!***") def selected(choice): print("\n*Selected: {}*".format(menu_list[choice])) def filename(): #check the filename is correct, turns the validated filename. filename = "" while filename == "": filename = input("Please enter a filename: ") return filename def main(): while True: #parameter menu_list. So it can use the dictionary inside the def. choice = menu(menu_list) if choice == 1: selected(choice) file = filename() try: rotate_90_clockwise(file) except FileNotFoundError: print("\n\n***** File specified not found! *****") print("Returning to main menu\n\n") except OSError: print("\n\n***** File error! *****") print("Returning to main menu\n\n") except: print("\n\n***** Unknown Error *****") print("Returning to main menu\n\n") elif choice == 2: selected(choice) file = filename() try: rotate_90_anticlockwise(file) except FileNotFoundError: print("\n\n***** File specified not found! *****") print("Returning to main menu\n\n") except OSError: print("\n\n***** File error! *****") print("Returning to main menu\n\n") except: print("\n\n***** Unknown Error *****") print("Returning to main menu\n\n") elif choice == 3: selected(choice) file = filename() try: custom_rotation(file) except FileNotFoundError: print("\n\n***** File specified not found! *****") print("Returning to main menu\n\n") except OSError: print("\n\n***** File error! *****") print("Returning to main menu\n\n") main() except: print("\n\n***** Unknown Error *****") print("Returning to main menu\n\n") elif choice == 4: selected(choice) file = filename() try: histogram(file) except FileNotFoundError: print("\n\n***** File specified not found! *****") print("Returning to main menu\n\n") except OSError: print("\n\n***** File error! *****") print("Returning to main menu\n\n") except: print("\n\n***** Unknown Error *****") print("Returning to main menu\n\n") elif choice == 5: return False exit print() print() ###MAIN PROGRAM STARTS HERE### main()
96eab88f7b126f6a7e7a8dd0122206060627a186
lim1017/Python
/functions.py
1,911
4.53125
5
def prints_hello_world(): print('Hello world from Python') prints_hello_world() def prints_something(something): return something + ' from Python' print(prints_something("passed in to python function")) # If you pass wrong number of arguments like two or three arguments to this function then Python will throw an error. # print(prints_something()) # Default parameter. I think its common in most languages now. def prints_default(something = 'default msg'): print(something + ' from Python') prints_default() # keyword arguments. You can pass explicitly which parameter should be matched. In this way, you don't have to send the arguments in order just explicitly mention the parameter name. def movie_info(title, director_name, ratings): print(title + " - " + director_name + " - " + ratings) movie_info(ratings='9/10', director_name='David Fincher', title='Fight Club') # Arbitrary number of arguments # Sometimes, you dont know how many arguments are passed. In that case, you have ask Python to accept as many arguments as possible. def languages(*names): print(names) # ('Python', 'Ruby', 'JavaScript', 'Go'). This is a tuple. return 'You have mentioned '+ str(len(names))+ ' languages' print(languages('Python', 'Ruby', 'JavaScript', 'Go', 'more names')) # You have mentioned 4 languages def languages2(fav_language, *names): print(names) # ('Ruby', 'JavaScript', 'Go') return 'My favorite language is ' + fav_language+ '. And Im planning to learn others ' + str(names) + 'thats ' + str(len(names))+ ' other languages!' print(languages2('Python', 'Ruby', 'JavaScript', 'Go')) # My favorite language is Python. And Im planning to learn other 3 languages too def user_info(id, name, **info): print(info) # {'fav_language': ['Python', 'Ruby'], 'twitter_handle': '@srebalaji'} user_info(1, 'Srebalaji', fav_language=['Python', 'Ruby'], twitter_handle=['Python', 'Ruby'])
cc1d8e5a6be6b3b185433e5e6a8021726032a3d2
Roc-J/python-3.5
/python3实验/d_1.py
2,285
4.09375
4
#3-4.py #本练习要求:定义一个类,完成指定功能。 class Student: #定义一个学生类 def __init__(self,name,num,chn,math,eng,phy,chem,bio): #定义构造函数 self.name=name self.number=num self.chn=chn self.math=math self.eng=eng self.phy=phy self.chem=chem self.bio=bio #计算平均分(请自行补充完整) def aver_score(self): total = self.chn + self.math + self.eng + self.phy + self.chem + self.bio total = float(total) score = total/6 return score #计算等级(请自行补充完整) def aver_grade(self): #若平均分在90~100,则为A if self.aver_score()>=90 and self.aver_score()<=100: grade="A" elif self.aver_score()>=80: grade = "B" elif self.aver_score()>=70: grade = "C" elif self.aver_score()>=60: grade = "D" else: grade = "F" return grade #按照格式输出学生信息(请自行补充完整) def print_student(self): print(self.name,"(学号:",self.number,") ","语",self.chn," 数",self.math," 英",self.eng," 物",self.phy," 化",self.chem," 生",self.bio,"平均分 %.2f " % self.aver_score()," 等级",self.aver_grade()) #测试开始(请自行补充完整) if __name__=="__main__": #采用列表保存类的实例 Stu_List=[] stu1=Student("A","201601",85,93,95,80,89,90) stu2=Student("B","201602",90,95,83,72,95,96) stu3=Student("C","201603",82,88,90,90,93,86) stu4=Student("D","201604",87,86,93,84,76,90) stu5=Student("E","201605",79,99,80,84,86,76) stu6=Student("F","201606",83,76,83,65,67,70) stu7=Student("G","201607",93,84,97,76,78,65) stu8=Student("H","201608",65,92,90,95,96,94) stu9=Student("I","201609",88,90,91,93,89,97) stu10=Student("J","201610",92,91,96,96,97,93) Stu_List.append(stu1) Stu_List.append(stu2) Stu_List.append(stu3) Stu_List.append(stu4) Stu_List.append(stu5) Stu_List.append(stu6) Stu_List.append(stu7) Stu_List.append(stu8) Stu_List.append(stu9) Stu_List.append(stu10) for item in Stu_List: item.print_student()
dee59e3dc215cffe0011872e34e751aa93cd3ae1
manoranjanmishra/Code
/MY_CODE/prime.py
18,560
4.34375
4
#computing a prime number findprime(). This function computes the n-th prime number, n is an argument of the function. #And a function isprime() , which checks if a number is prime. Added another pair of functions which generate the n-th prime number, and prime factor finds out the (smallest)prime factors of a number by itself. ##Function:: isprime() #returns 1 or True if it is prime. #returns 0 or False if it is not Prime, or is a Fractional or Irrational number,or 0 or is a Negative number. #returns 2 if the input is not a number. #The flags we return are changeable, and if one doesn't need an output, one can comment the print statements out. #This function uses only two variables, n & a. a is the argument to the function, n is an internal variable. There is no code outside the function. #What if you enter X?? THe function will determine that it is a string, and will exit with the flag for strings.. i.e return 2 def isprime(a): #we want to test if a is prime or not. The argument you pass to the function is stored in the variable called a. #this function assumes that a is a integer. #add-in functionality. #we'd normally expect not to get strings as input, but just in case we do, we'll include the possibility here.one way is to include a condition in the try block, and the rest of the function in it. The except block then contains an error, and a return false or 0 statement. Or else, include the checking condition in the try part, and if it is true, do nothing. The except part has a return zero, or someother number so that an error can be flagged if required. Plus it can say "You entered a string" try: a=float(a) #maybe this is a little odd, but if a is a string this statement would not execute. If it's anything else, it'll do fine. And anyway, we check for fractionals in the next if statement itself. except: print "You entered a string!" return 2 #here 2 is our flag for string input. if(a!=int(a)):#if a is a integer, a will be equal to int(a). If not, then a is a fraction. In that case, there is no point going ahead. You could try chopping off the decimal part, or rounding it. But we're not doing that here. print "Fractional Numbers are neither prime nor composite." return 0 #return False #the number is not prime so, we return False. if (a<0): print "Negative Numbers are neither prime nor composite." return 0 #return False #the number is not prime so, we return False. if(a==0): print "0 is neither prime nor composite." #for the case that someone calls the function with zero as argument. n=1 #we start checking with 1, since we cannot divide by 0 while (n<=a):#if you send a negative number, or zero to the function it will never be checked, because of the condition of the while loop. if (a%n==0): #i.e if a is divisible by n if (n==1)or(n==a): #if a is divisible by either 1 or a, then n can be either 1 or a if(n!=1): #this prevents the function from returning a value for n=1 print int(a),"is prime" #return True #whichever return statement you choose too include, note that only the first one gets executed. Any statement after that is simply ignored. return 1 else:#a is divisible by n, but n is not 1 or a, a is not prime print int(a),"is not prime" #we don't need to check further. So on the first occurrence, print this statement and exit. #return False return 0 #break the break statement is not needed here. Once a return statement is encountered, the value in it is returned, and the function stops executing. After the return 0 statement above, this break statement wont even be executed.. so no point including it at all. #the next few lines intend to reduce the number of computations, in order to make reaching the answer quicker. if (n>a/2)&(n!=a): #Even if n is equal to half of a, the first part of the if statement will be false, irrespective of whether a is odd or even. At that point when n is just more than half a, n!=a. So the if statement executes. n=a, the n=n+1 is skipped because of the continue statement. The next iteration is a%n being eval for n=a. When it reaches the if statement, n>a/2 is still true, so if not for the other n!=a, the n=n+1 would be skipped, and the loop would freeze endlessly evaluating at n=a. So, we include the n!=a condition, so as to tell that n has been set to a, dont do that again. Now n becomes a+1, which makes n<=a in the while loop false, and loop ends. This also takes care of the case when a=1 (where n=1 is greater than a/2=1/2, and n is assigned the value of a..1 again, making the loop freeze), so including a n!=1 is not necessary. n=a #Execute only if n is not equal to a already. If it is, break the loop. (MORAL) continue #this is to prevent the n=n+1 statement from being executed on the next line.. n=n+1 #if you put this statement before the previous if statement, you could save a loop-cycle. That is because, if n=n+1 comes after, the loop executes for a/2 + 1, and then n=a. If n=n+1 comes first, the loop executes for a/2, and since (a/2 + 1)>a/2, the next value in the loop is n=a #end of the checking loop. Since the loop has statements to return results, there are no more lines. Function ends. ##Function findprime() & findprime2() #This function takes an argument n, and finds the nth prime number. #The function findprime() is independent, and has all the code it needs to perform it's task. findprime2() however depends on the isprime() function above to work. #Features common to both functions: #if you send it a fractional number, it will print an error and quit/find the prime number corresponding to the integer part. #if you send it a negative number, it will print an error, and quit/find the prime number corresponding to the number part, ignoring sign. #if you send it zero, it will print an error, and quit. (optionally say that the first prime number is 2) #findprime(n) uses three variables: a,b,c.. a is the test number, b is constantly increased to check if a is div, and based on that, if a is prime, c counts which prime number that is. #findprime(n) is self sufficient, it doesn't depend on any external code. def findprime(n): try: #we want to avoid strings, and negative or fractional numbers. n=float(n) #this statements checks if the argument is a number, if not, it will cause an error, and the except loop to execute. if (n!=int(n)):#then the number is a fractional number print "You entered a fraction!" n=int(n)#however we don't print/return an error, and instead we compute the prime number corresponding to the integer part. if (n<0): print "You entered a negative value!" n=0-n#instead of an error, we simply flip the sign, and find the corresponding prime. if (n==0): print "We count from 1. There is no prime that corresponds to 0.\nThe first prime number is 2" return 0#exit the function except: print "You entered a string!" return 0 #this is the return value we use for strings in this function. #this function finds the nth prime number. a=0 #we start counting from zero, and for each number we test if it is prime. c=0 #c stores the count of how many prime numbers we have found. Once c reaches n, we return the prime & stop. while (c<n): #we didnt write c<=n because this condition would still hold even after the nth prime was found. Though c<=n is also fine, since we can always include a break in the if statement that checks if c==n. b=1 #b represents the number we divide a by, to test if a is prime. Since b has to start from 1 for every number b is outside the inner loop. b could have been after the loop too, but we have to initialise it first to use it. while (b<=a): #we also need b to be equal to a, since a prime number is divisible by 1 or the number itself. if (a%b==0): if(b==1)or(b==a): #then a is certainly prime. if (b!=1): #we don't want to increase the count if it is only divisible by 1. And, if we are counting from zero, this saves us. Because in that case, it wont count 0 as a prime number, neither will it count 1, since in both cases the condition of the outer if statement is fulfilled. c=c+1 #since we found a prime number we need to count it. #print "The",c,"\bth Prime number is",a else: #the number a is divisible by a number other than 1 or itself. So, it is not prime, no point checking further. Break the loop. break b=b+1 if (b>a/2)*(b!=(a+1)): #Quite simply we wait till b is equal to half of a, a%b s evaluated, and then b becomes a/2 + 1. We then immediately jump the value up to a. This value runs through the loop again, and again satisfies, b>a/2, but we don't want it getting assigned the value of a again, or else the loop will run infinitely (b is assigned a, runs, becomes a+1, a+1 is greater than a/2, b is assigned a again) to prevent it, we include the b!=(a+1) condition.. Since if b=a ran through the loop once, b is a+1 now, and we don't want a+1 passing the loop. [ If you're confused:: If the b=b+1 statement came after the if statement, and we set b=a, (we'd have to skip the b=b+1 statement), b=a would run through the loop and into the if statement, and we'd want to prevent b=a from passing the if statement, so we'd include a b!=a condition] b=a ##point to learn is that, the if centers around choosing between b=b+1 and b=a basing on if b is more than half of a or not. if (c==n): print "The",int(n),"\bth prime number is",a return a #we return the nth prime number break #this statement is optional. If you remove it, and the condition of the outer while loop is c<n, then the loop wont execute another time. If the condition is c<=n, the loop will execute again and again until it finds the next prime number i.e the n+1th prime and will then quit.. though it will not print the n+1th prime. a=a+1 #this is to check for the next number. def findprime2(n): #we use the isprime() function from above to find the nth prime number. try: n=float(n) #catches a string if (n!=int(n)): print "You entered a fraction!" n=int(n) #if n is a fraction, we assign it the integer part of the fraction. if (n<0): print "You entered a negative number" n=(0-n) #we flip the sign and assign it to n. except: print "You've entered a string!" #now that we have a numeric value of n, we proceed to find the nth prime number. a=1 #is prime doesn't like a zero. You could also start with a zero though. c=0 #to keep count of the number of primes we've calculated. while (c<n): #this means that the last value to go through will be the n-1, and when we find the nth prime, the loop prints the prime number and stops. If you put c<=n, the loop will still work, but it will keep going till it finds the n+1th number and stops. if (isprime(a)==1): #The print statements do not affect this. If you used return 0,1 or True,False , use the same here. But, if for a sequence of numbers you use isprime consider commenting out the print statements. c=c+1 if(c==n): print "The",int(n),"th prime number is",a break #not essential here, but if you write c<=n it is required, or else the loop will only stop when it finds the n+1th prime number. a=a+1 #Don't forget this! #that's it. #The next two functions go together. And generate prime numbers. def primefactor(n): while True: i=n/2 while (i>0): if(n%i==0): if(i!=1): return n/i n=i break if((n%(((n/2)-i)+1))==0): if ((((n/2)-i)+1)!=1): return (((n/2)-i)+1) n=n/(((n/2)-i)+1) break if(i<(((n/2)-i)+1)): i=1 break i=i-1 if(i==1):#then we have a prime number return n #since we have factored out every possible factor, this should be a prime number #one could use primefactor to find a prime number because if n is prime, it returns n. def primegen(n): #generates all prime numbers upto the n-th prime number c=0 #counter for primes i=1 while True: i=i+1 if(primefactor(i)==i): print "#",(c+1),": ",i c=c+1 if(c==n): return "Done" #The following skeleton functions are to illustrate the basic algorithm of generating primes. def prime_skeleton(n): #generate the n-th prime by brute force. Basic skeleton. #A prime is divisible by 1 and itself. Moreover, the largest factor of a number cannot be greater than half of itself. We use both facts to check if a number is prime, by starting with 1 & going upto i/2 to see if any number divides i. If it does, we stop looking further, and skip to the next number. If however there are no factors between 1 & i/2 we have a prime number. This generates the first 10K primes in ~127secs with the print statement, and in 106sec without it. c=0 #counter for primes. i=1 while (c<n): i=i+1 j=1 while(j<=i/2): if(i%j==0): if(j!=1): break if(j==i/2): c=c+1 print "#",c,":",i j=j+1 return "Done!"#%d:%d"%(c,i)#if you comment out the print statement, and only want the n-th prime, use this. def prime_faster_skeleton(n):#If a number is not prime, our method of checking from 1 upward till i/2 immediately skips the number. If, however a number is prime, a lot of time is spent checking from 1 till i/2. We try to eliminate this, by checking from 1->i/2 & from i/2->1 simultaneously. If we meet, and no factors have been found, we have a prime number & we stop. c=0 i=1 while(c<n): i=i+1 j=1 k=i/2 while(j<=i/2): if(((i%j)==0)&(j!=1)): break if(((i%k)==0)&(k!=1)): break if (k<j): j=i/2 if(j==i/2): c=c+1 print "#",c,":",i break j=j+1 k=k-1 return "Done!" #return "#%d:%d"%(c,i)#if you comment out the print statement, and only want the n-th prime, use this. #Without the print function it finds the 10,000th prime in 1:54s & with it in 3:15s. So, is it faster? #These functions now use stored & computed data to find primes. The following function computes primes, and stores them in a list to compute further primes. #using lists to find prime numbers. #every natural number is completely factorisable in terms of primes smaller than it-self. We are only checking for divisibility & not fatorising a number. So, once a number is divisible, we stop checking. #this program will create an integer list of primes. def prime_lists(n): primes=[] c=0 i=1 #first populate the list. & then use it to generate further primes. while (c<n): i=i+1 if(i<10): #this if statement uses the if statement, to activate a while loop to populate the first few elements of the list. j=1 while(j<=i/2): if(i%j==0)&(j!=1): break if(j==i/2): primes=primes+[i] c=c+1 j=j+1 if(i>=10): #This if statement contains a while loop which checks new numbers against those already in the list to find if they are prime. If they are, they are added to the list. j=0 while(j<len(primes)): if(primes[j]>(i/2)): break if(i%primes[j]==0): break j=j+1 if(primes[j]>(i/2)): primes=primes+[i] c=c+1 return primes[-1]#this returns only the last element of the list. If required, one can return any element or the entire list. One also has a stored list of primes after this function completes. #Finds 10K primes in ~17s. 100k primes in >20min. This is quicker than our previous algorithms because we are checking against lesser numbers. For example, in the previous case even if we checked against 2, we'd check with 4 & then 8 & so on. But, here we check only against a list of co-prime (and also absolutely prime) factors. So, no repetition occurs. #The function below leaves out checking even more numbers than the functions above. def primegenrtr(n): #this program generates the n-th prime. But, in this code, when we check for factors of a number i, we use the fat that if upto q, no factors have been found, none exist other than the number itself if q>n/q. c=0 #count the generated prime numbers i=1 #Start generating prime numbers from i #a=[] #this statement creates an empty list to store the generate the prime numbers. while (c<n): i=i+1 #one fault with this code is that if i starts with 1, 1 gets counted as a prime number. j=1 while True: if(i%j==0)&(j!=1): break if(j>(i/j)): #if no factors have been found yet, none will be found beyond now. This makes the function check for even lesser numbers. break j=j+1 if(j>(i/j)): a=i #a=a+[i] Change it to this if you need to keep all the generated prime numbers. Replace this statement with what you want to do with the prime numbers. You can add, print etc. c=c+1 return a #this will merely return the last prime number. #This function computes the first 1,000,000 primes in >25min & 100,000 primes in 1:05s. And, 10k primes in 5s. The 1 millionth prime is 15485863. The 100,000th prime is 1299709. The 10,000th prime is 104729. #Method fails miserably if you try to find very large prime numbers. Consider prime numbers above 1000000000000. This method takes over 4s to generate two successive primes. That is because this method checks M numbers for each number N, where M=sqrt(N). #this function generates a list of numbers first, and removes any numbers that have factors by successively combing the list toward the end. def primelists(n): #this function generates all the prime numbers upto the number n. i=2 a=[] #this stores the list of numbers, which we shall reduce to the list pf primes while(i<=n): a.append(i) i=i+1 #a=range(2,n+1) would also work instead of the loop above. This would initialise a, and also generate a list of integers from 2 to n. #this while loop will generate a list of numbers from 2 to n (inclusive) i=0 while(i<len(a)): j=i+a[i] while(j<len(a))&(a[i]!=0): a[j]=0 j=j+a[i] i=i+1 #we are left with a list of numbers where every number that is a multiple of a number lesser than it, has been zeroed out. #Since, pop & remove take too much time, we shift the non-zero elements toward the beginning of the list, and then slice off the end. i=0 c=0 #counter for primes (the non-zero elements now left in our list) while(i<len(a)): if(a[i]!=0): a[c]=a[i] c=c+1 #count the non-zero elements.. this also points to the index location we can store the next non zero element. i=i+1 #since the primes start at 0th position, the last prime is at c-1 th index.. i.e the cth index points beyond the last prime num. But a slice returns all numbers upto the last index excluding it. a=a[:c] #this slices the list to remove the rest of the elements, since we spanned the entire list & all non-zero elements are inside first c index positions. return a
796373948c0df9894307e91d845da13db3ee2201
shaon-data/Multivariate_Linear_Regression_scratch
/MVLR.py
16,845
3.75
4
# -*- -*- """ Author: Shaon Majumder This is multivariate linear regression implementation from scratch """ import matplotlib.pyplot as plt import numpy ## Statistical Function def list_multiplication(dm1,dm2): if length(dm1) == length(dm2): return [b*c for b,c in zip(dm1,dm2)] elif length(dm1) == 1 or length(dm2) == 1: if length(dm1) == 1: r = dm1[0] c = dm2 elif length(dm2) == 1: r = dm2[0] c = dm1 return [i*r for i in c] else: print("shape is not same for list multiplication") raise ValueError def ArithmeticMean(li=[],lower=[],upper=[],frequency=[]): if li == []: for i in range(length(lower)): midpoint =(lower[i]+upper[i])/2 li = appends(li,midpoint) else: del lower del upper del frequency frequency = [] if frequency == []: for i in range(length(li)): frequency = appends(frequency,1) sumn = 0 iteration = 0 for i in range(length(li)): sumn += (li[i]*frequency[i]) iteration += frequency[i] return float(sumn)/iteration def sample_standard_deviation(li): return (sum([(i - ArithmeticMean(li))**2 for i in li])/(length(li)-1))**(1/float(2)) ## Statistical Function ends ## String Function def length(li): iteration = 0 for c in li: iteration += 1 return iteration def split(string,spliting_char = ','): #Spliting Functions by comma, or character. Default spliting character is comma. word = "" li = [] iteration = 0 for c in string: if c != spliting_char: word += c #if c == '': # c = null_string else: li = appends(li,word) word = "" iteration += 1 #if word != "": li = appends(li, word) return li def strip(string,strip_chars = [" "]): iters = True iteration = 0 result = "" rstat = False for c in string: for d in strip_chars: if c != d: rstat = True else: rstat = False break if rstat == True: result += c rstat = False iteration += 1 return result def appends(lst, obj, index = -2): if index == -2:# -2 for accepting 0 value to be passed as it represents begining of the array index = length(lst) if type(obj) is list: return lst[:index] + obj + lst[index:] else: return lst[:index] + [obj] + lst[index:] def conv_type(obj,type_var): dts = ["int","float","str"] st = 0 for c in dts: if type_var == c: st = 1 break if st != 1: raise Exception('No avaiable conversion type passed') if type(obj) is list: #print("list") pass elif type(obj) is str: print("string") elif type(obj) is int: print("Integer") elif type(obj) is float: print("Float") else: print("else %s" % type(obj)) lists = [] callables = eval(type_var) for c in obj: try: lists = appends(lists,callables(c)) except ValueError: lists = appends(lists,c) return lists ## String Function ends ## Data Manipulation def getIndex(li,val): #indexes = [i for i,x in enumerate(li) if x == val] #indexes[-1] iteration = 0 for c in li: if(val == li[iteration]): return iteration iteration += 1 return False def reference_reverse_normalize(ypure,y_pred): y_PRED = [] ystd = sample_standard_deviation(ypure) ymean = ArithmeticMean(ypure) for c in range(length(y_pred)): y_reverse = y_pred[c]* ystd + ymean y_PRED.append(y_reverse) return y_PRED def df_size(df):#obs row = length(df[0]) column = length(df) return row, column def transpose(dm): n,m = df_size(dm) dm_n = create_dataframe(m,n) for c in range(m): it = 0 for b in dm[c]: #print("dm_n[%s][%s] = %s" % (it,c,b)) dm_n[it][c] = b it += 1 return dm_n def create_dataframe(m,n):#obs ''' df = [] df_r = [] for i in range(m): df_r = appends(df_r,0) for c in range(n): df = appends(df,[df_r]) ''' df=[] df = [[None]*m for _ in range(n)] return df class DataFrame(object): '''This is Onnorokom General Library''' def __init__(self, columns=[], dataframe = ['0']): #sequence checked self.dataframe = dataframe self.shape = self.framesize #self.T = self.trans self.columns = columns if self.dataframe != ['0']: self.shape = self.framesize self.T = self.trans if columns == []: self.columns = self.erase_col_names() def __del__(self): classname = self.__class__.__name__ #print ('%s class destroyed' % (classname)) def __str__(self): #return str(self.columns) + str(self.dataframe) #print(self.dataframe) #List representation strs = "Dataframe Representation\n" def str_sp(strs,space=10): for c in range(space - length(strs)): strs += " " return strs for c in self.columns: strs += str_sp(c) strs += "\n" for c in range( length(self.dataframe[0]) ): for d in self.dataframe: strs += str_sp( str(d[c]) ) strs += "\n" return strs def __getitem__(self,name): if type(name) == int: return self.dataframe[name] elif type(name) == str: if name.isdigit() == True: return self[int(name)] return self.dataframe[getIndex(self.columns,name)] elif isinstance(name, slice): return self.dataframe[name] def __iter__(self): return iter(self.columns) def normalize(self,change_self=False): #we need to normalize the features using mean normalization df = [] for c in self.dataframe: mean= ArithmeticMean(c) std = sample_standard_deviation(c) _ =[ (a - mean)/std for a in c] df = appends(df,[_]) if change_self == True: self.dataframe = df return df def conv_type(self,var_type,change_self=False): callables = eval(var_type) df = [] col = [] for c in self.dataframe: for i in c: col = appends(col,callables(i)) df = appends(df,[col]) col = [] if change_self == True: self.dataframe = df return df def ix(self): pass def iloc(self): pass def row(self,rowindex): row = [] for c in self.columns: row.append(self[c][rowindex]) return row def new(self,m,n,elm=''): if elm == '': elm = None df=[] df = [[elm]*m for _ in range(n)] #if change_self == True: return self.set_object(df) def concat(self,dm1,dm2,axis=0): #axis #[0 - row merge] #[1 - column merge] dm = [] m,n = dm1.framesize x,y = dm2.framesize b = dm1.tolist d = dm2.tolist if axis == 0: if n != y: print('ValueError: all the input array dimensions except for the concatenation axis must match exactly') raise ValueError for c,a in zip(b,d): dm = appends(dm,[c+a]) elif axis == 1: if m != x: print('ValueError: all the input array dimensions except for the concatenation axis must match exactly') raise ValueError for c in b:### dm = appends(dm,[c]) for c in d:### dm = appends(dm,[c]) return self.set_object(dm) def transpose(self,change_self=False): selfs = self.__class__() dm = self.dataframe n,m = self.size() dm_n = create_dataframe(m,n) for c in range(m): it = 0 for b in dm[c]: #print("dm_n[%s][%s] = %s" % (it,c,b)) dm_n[it][c] = b it += 1 if change_self == True: self.dataframe = dm_n self.erase_col_names() #self.T = dm_n #previous_code 5-4-18 #self.T = self.trans #previous_code 5-4-18 #sequence for returing self after dataframe calculation selfs.dataframe = dm_n selfs.shape = selfs.framesize selfs.columns = selfs.erase_col_names() return selfs #sequence for returing self after dataframe calculation def erase_col_names(self): self.columns = [str(c) for c in range(length(self.dataframe))] return self.columns def columns(self): return [ c for c in self.columns] def size(self,ob=[]): if ob == []: return length(self.dataframe[0]),length(self.dataframe) else: return length(ob[0]),length(ob) def read_csv(self,input_file,columns=[]): with open(input_file,'r') as file:#Taking file input as stream, handly for iterators and reading stream object saves memory losses data = file.readlines()#reading line by line first_line = split( strip(data[0],[' ','\n']) ,",") header = [c for c in range(0,length(first_line))] if first_line[0].isdigit() == False: self.columns = first_line del data[0] else: self.columns = conv_type(header,"str") df = [[] for d in header] for c in data: line = split( strip(c,[' ','\n']) ,',') for d in header: df[d] = appends(df[d],line[d]) if columns == []: columns = self.columns else: self.columns = columns #sequence for returing self after dataframe assigning self.dataframe = df self.shape = self.framesize self.T = self.trans #sequence for returing self after dataframe assigning return self def __sub__(self,dm2): dm1 = self selfs = self.__class__() m,n = dm1.shape x,y = dm2.shape dm=[] a = dm1.tolist b = dm2.tolist if m == x and n == y: j = 0 for c in range(n): i = 0 col = [] for r in range(m): si = a[j][i] - b[j][i] i+=1 col.append(si) j+=1 dm.append(col) return self.set_object(dm) else: print("Matrice Shape is not same for substract",dm1.shape,dm2.shape) raise ValueError def __add__(self,dm2): dm1 = self selfs = self.__class__() m,n = dm1.shape x,y = dm2.shape dm=[] a = dm1.tolist b = dm2.tolist if m == x and n == y: j = 0 for c in range(n): i = 0 col = [] for r in range(m): si = a[j][i] + b[j][i] i+=1 col.append(si) j+=1 dm.append(col) return self.set_object(dm) else: print("Matrice Shape is not same for substract",dm1.shape,dm2.shape) raise ValueError def __gt__(self, other): pass def __lt__(self, other): pass def __ge__(self, other): pass def __le__(self, other): pass def two2oneD(self): if self.shape[0] == 1: return self.T[0] elif self.shape[1] == 1: return self[0] else: print("Column/row != 1, can not converted to 1D list") def dot(self,dm1,dm2): a,b=dm1.shape m,n=dm2.shape if(b==m): dm_n = [] it = 0 for c in dm2.tolist: col = [] for i in (dm1.T).tolist: col = appends( col,sum( list_multiplication(i,c) ) ) dm_n = appends(dm_n,[col]) it+=1 return self.set_object(dm_n) else: print("Shape is not same for matrice multiplication -> ",dm1.shape,dm2.shape) raise ValueError def __mul__(self,dm2): dm1 = self #used inverse dataframe to convert numpy array representation #then used numpy broadcasting c1 = (dm1.shape[0]==dm2.shape[0]) and (dm1.shape[1] == 1 or dm2.shape[1] == 1) c2 = (dm1.shape[1]==dm2.shape[1]) and (dm1.shape[0] == 1 or dm2.shape[0] == 1) if dm1.shape == dm2.shape or c1: dm = [] dm1 = (dm1.T).tolist dm2 = (dm2.T).tolist for r1,r2 in zip(dm1,dm2): dm.append(list_multiplication(r1,r2)) #they are equal, or #one of them is 1 return self.set_object(transpose(dm)) elif c2: dm = [] dm1 = (dm1.T).tolist dm2 = (dm2.T).tolist for r1 in dm1: dm = [list_multiplication(r1,r2) for r2 in dm2] #they are equal, or #one of them is 1 return self.set_object(transpose(dm)) else: print("cross is not allowed") raise ValueError def sum(self,axis=0): if axis == 0: dm = [[sum(c)] for c in self.tolist] elif axis == 1: dm = [[sum(self.row(d)) for d in range(self.shape[0])]] return self.set_object(dm) def sum_np(self,axis=0): return self.sum(axis).two2oneD() def __float__(self): if self.shape == (1,1): return self[0][0] def __pow__(self,power): dm = [ [r**power for r in c] for c in self.tolist] return self.set_object(dm) def dftolist(self): return self.dataframe def dataA(self,dataframe): self.dataframe = dataframe return self def set_object(self,dm): selfs = self.__class__() #sequence for returing self after dataframe calculation selfs.dataframe = dm selfs.shape = selfs.framesize selfs.T = selfs.trans selfs.columns = selfs.erase_col_names() return selfs #sequence for returing self after dataframe calculation framesize = property(size) tolist = property(dftolist) trans = property(transpose) prop_var =property(set_object) ## ML Function def minResidual(pure , pred): """returns minimum error distance or residual""" E = [] for c in range(length(pure)): absolute_distance = abs(pure[c] - pred[c]) E.append(absolute_distance) return min(E) def meanResidual(pure , pred): """returns average error distance or residual""" E = [] for c in range(length(pure)): absolute_distance = abs(pure[c] - pred[c]) E.append(absolute_distance) import numpy as np return np.mean(E) def maxResidual(pure , pred): """returns maximum error distance or residual""" E = [] for c in range(length(pure)): absolute_distance = abs(pure[c] - pred[c]) E.append(absolute_distance) return max(E) def give_time_series(x,y): """Rearrange X,Y value pairs or points according to X's order""" xall = [] yall = [] for x1,y1 in sorted(zip(x,y)): xall.append(x1) yall.append(y1) return (xall,yall) def plot_error_distance(x,y_pred,y_actual): """Plot error distance or residual""" for [a,b,c] in [ [x,y_r,y_p] for x,y_r,y_p in zip(x,y_pred,y_actual) ]: plt.plot([a,a],[b,c],color='y',label='residual') def MLVR(XDATA,YDATA,xreference=0,residual=1,xlabel='',ylabel='',title='',alpha = 0.01,iters = 1000,plot=1): """Does Multivariant Linear Regression properties: XDATA = The Feature Dataframe YDATA = The Target Dataframe xreference = 1/0 -> The column index in XDATA for ploting graph xlabel = Label for X in Graph ylabel = Label for Y in Graph title = title for graph] alpha = Learning rate for model iters = the number of iteration to train the model """ XDATA.conv_type('float',change_self=True) xpure = XDATA[xreference] XDATA.normalize(change_self=True) YDATA.conv_type('float',change_self=True) ypure = YDATA.tolist[0] YDATA.normalize(change_self=True) X=XDATA y=YDATA df =DataFrame() ones = df.new(X.shape[0],1,elm=1.) X = df.concat(ones,X,axis=1) theta = DataFrame().new(1,length(X.columns),elm=0.) def computeCost(X,y,theta): dot_product = DataFrame().dot(X,theta.T) return float( ( (dot_product - y)**2 ).sum(axis=0) )/(2 * X.shape[0]) def gradientDescent(X,y,theta,iters,alpha): #cost = np.zeros(iters) cost = [] for i in range(iters): dot_product = DataFrame().dot(X,theta.T) derivative = DataFrame(dataframe = [[(alpha/X.shape[0])]]) * ( X*(dot_product - y) ).sum(axis = 0 ) theta = theta - derivative cost.append( computeCost(X, y, theta) ) #cost[i] = computeCost(X, y, theta) return theta,cost def print_equation(g): stra = "Estimated equation, y = %s"%g[0] g0 = g[0] del g[0] for c in range(length(g)): stra += " + %s*x%s"%(g[c],c+1) print(stra) def predict_li(XDATA,g): g0 = g[0] del g[0] y_pred = [] for row in range(XDATA.shape[0]): suma = 0 suma += sum(list_multiplication( g , XDATA.row(row) ) ) yres = g0 + suma y_pred.append(yres) return y_pred g,cost = gradientDescent(X,y,theta,iters,alpha) finalCost = computeCost(X,y,g) #g = g.T g = g.two2oneD() print("Thetas = %s"%g) #print("cost = ",cost) print("finalCost = %s" % finalCost) gN = g[:] print_equation(gN) gN = g[:] y_pred = predict_li(XDATA,gN) y_PRED = reference_reverse_normalize(ypure,y_pred) emin,emean,emax = minResidual(ypure , y_PRED),meanResidual(ypure , y_PRED),maxResidual(ypure , y_PRED) print("Min,Mean,Max residual = %s, %s, %s"%( emin,emean,emax ) ) print("Residual Min - Max Range = %s"%(emax-emin)) print("Residual range percentage = %s" %((emax-emin)/(max(ypure) - min(ypure))) ) print("Residual mean percentage = %s" %(emean/ArithmeticMean(ypure)) ) #-- If finalcost is lowest mean Residual or mean Error distance also will be lowest #y_pred = [g[0] + g[1]*my_data[0][c] + g[2]*my_data[1][c] for c in range(my_data.shape[0])] y_actual = YDATA.tolist[0] x = XDATA[xreference] if plot == 1: fig, ax = plt.subplots() ax.plot(numpy.arange(iters), cost, 'r') ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title('Error vs. Training Epoch') plt.show() x_a, y_a = give_time_series(xpure,y_PRED)#give_time_series(x,y_pred) plt.plot(x_a,y_a,color='r',marker='.',label='Prediction') x_a, y_a = give_time_series(xpure,ypure)#give_time_series(x,y_actual) plt.plot(x_a,y_a,color='g',marker='.',label='Real') if residual == 1: plot_error_distance(xpure,y_PRED,ypure) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.legend() plt.show() else: print('plot off') return finalCost def main(): my_data = DataFrame().read_csv('sample_inputs/home.txt',columns=["size","bedroom","price"]) XDATA = DataFrame(dataframe= my_data[0:2],columns=['size','bedroom']) YDATA = DataFrame(dataframe= [my_data[2]]) MLVR(XDATA,YDATA,xreference=0,residual=1,xlabel='serial,length',ylabel='views',title='Youtube View MLVR',alpha = 0.01,iters = 1000) if __name__ == "__main__": main()
28e9063c22c1c5bf38b35d26de2eabbb1903876a
nivedita81/LeetCode
/reorder_linked_list.py
2,145
4.1875
4
# Definition for singly-linked list. class ListNode: def __init__(self, val): self.val = val self.next = None class Solution: def __init__(self): self.head = None self.next = None def pushList(self, new_data): new_node = ListNode(new_data) new_node.next = self.head self.head = new_node def reverse_list(self, head: ListNode): if head is None or head.next is None: return previous, next_pointer = None, None current = head while current is not None: next_pointer = current.next current.next = previous previous = current current = next_pointer return previous def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ if head is None or head.next is None: return '''here we are getting the middle element to reverse and setting the next pointer of last ele of 1st half to be null''' slow = head fast = head.next # prev = None while fast is not None and fast.next is not None: # prev = slow slow = slow.next fast = fast.next.next second_half = slow.next slow.next = None '''reversing the 2nd half of the list''' second_half = self.reverse_list(second_half) first_node = head second_node = second_half '''combining both the halves''' while first_node is not None and second_node is not None: first_next = first_node.next second_next = second_node.next first_node.next = second_node second_node.next = first_next first_node = first_next second_node = second_next if __name__ == '__main__': list_node = Solution() list_node.pushList(3) list_node.pushList(7) list_node.pushList(4) list_node.pushList(2) list_node.pushList(8) list_node.pushList(12) list_node.pushList(11) s = Solution() s.reorderList(list_node)
15ddc8f902d022aee22747c3d27e0b957865c826
DamManc/workbook
/chapter_4/es96.py
460
4
4
# Exercise 96: Does a String Represent an Integer? def is_integer(a): new_int = a.strip() if ((a[0] == '+' or a[0] == '-') and a[1:].isdigit()) or a.isdigit(): return True else: return False def main(): int = input('Enter a integer: ') if is_integer(int): print('Your input is a valid integer!') else: print('Your input is not a integer!') if __name__ == '__main__': main() print(__name__)
b694e256a9a57e99bbe352dfd034c0c383500a0b
SnehaAS-12/Day-14
/day14.py
3,679
4.53125
5
#Design a simple calculator app with try and except for all use cases def calculate(): try: def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): return num1 / num2 print("Please select operation -\n" , "1. Add\n" , "2. Subtract\n" ,"3. Multiply\n", "4. Divide\n") select = int(input("Select operations form 1, 2, 3, 4 :")) number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) if select == 1: print(number_1, "+", number_2, "=", add(number_1, number_2)) elif select == 2: print(number_1, "-", number_2, "=", subtract(number_1, number_2)) elif select == 3: print(number_1, "*", number_2, "=", multiply(number_1, number_2)) elif select == 4: print(number_1, "/", number_2, "=", divide(number_1, number_2)) else: print("Invalid input") except Exception as e: print(e) calculate() #print one message if the try block raises a NameError and another for other errors try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") #When try-except scenario is not required? #A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example: except (RuntimeError, TypeError, NameError): pass #A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order: class B(Exception): pass class C(B): pass class D(C): pass for cls in [B, C, D]: try: raise cls() except D: print("D") except C: print("C") except B: print("B") #Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered. #The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well): import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error: {0}".format(err)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise #The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example: for arg in sys.argv[1:]: try: f = open(arg, 'r') except OSError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') f.close() #Try getting an input inside the try catch block try: roll_no=int(input('Enter your roll_no: ')) except: print ('You have entered an invalid value.')
860bf2201a2a6c027246817615d39f23680bca37
SaitoTsutomu/leetcode
/codes_/0706_Design_HashMap.py
339
3.578125
4
# %% [706. Design HashMap](https://leetcode.com/problems/design-hashmap/) class MyHashMap(dict): def put(self, key: int, value: int) -> None: self[key] = value def get(self, key: int) -> int: return dict.get(self, key, -1) def remove(self, key: int) -> None: if key in self: del self[key]
c249f55355a3d83bfc2020c93d33af3cbe229e28
x-jeff/Python_Code_Demo
/Demo2/Demo.py
575
3.625
4
a=[1,2,3,4,5,6,7,8] for i in a : print(i) for i in a : if i % 2 == 0 : print(i) for i in a: print(i) print("end") for i in a: print(i) print("end") b=15 if b==12: print("b=12") elif b<12: print("b<12") elif b>12 and b<20: print("12<b<20") else : print("b>=20") def addNum(a,b): return a+b print(addNum(2,3)) def square(x): return x*x print(square(3)) addNum1=lambda a,b:a+b print(addNum1(3,4)) square1=lambda x:x**3 print(square1(3)) a=3.2 import math b=math.ceil(a) print(b) import numpy numpy.random.normal(25,5,10)
b4fdb7c3f5a45aab78753d04dd6ecade9eb260f1
diegothuran/neural
/test-XOR.py
769
3.5
4
""" Obs: Este script é baseado na versão do livro http://neuralnetworksanddeeplearning.com/, com a devida autorização do autor. Código de teste para diferentes configurações de redes neurais.     Adaptado para o Python 3.6     Uso no shell:          python test.py     Parâmetros de rede:          2º param é contagem de épocas          O terceiro param é tamanho do lote          4º param é a taxa de aprendizado (eta) """ # Imports import mnist_loader import network2 import numpy as np X = np.array([[0, 0], [1, 0], [0, 1], [1, 1]]) y = np.array([1, 0, 0, 1]) training_data = list(zip(X, y)) net = network2.Network([2, 2, 1]) net.SGD(training_data, 1000, 10, 0.01) print(net.feedforward(X[0]))
b53574cc3fb4984ff5610e76aea3eca122cd3cc0
siverka/codewars
/ValidateCreditCardNumber/validate_credit_card_number.py
1,497
4.375
4
""" https://www.codewars.com/kata/validate-credit-card-number In this Kata, you will implement The Luhn Algorithm [https://en.wikipedia.org/wiki/Luhn_algorithm], which is used to help validate credit card numbers. Given a positive integer of up to 16 digits, return true if it is a valid credit card number, and false if it is not. Here is the algorithm: If there are an even number of digits, double every other digit starting with the first, and if there are an odd number of digits, double every other digit starting with the second. Another way to think about it is, from the right to left, double every other digit starting with the second to last digit. 1714 => [1*, 7, 1*, 4] => [2, 7, 2, 4] 12345 => [1, 2*, 3, 4*, 5] => [1, 4, 3, 8, 5] 891 => [8, 9*, 1] => [8, 18, 1] If a resulting doubled number is greater than 9, replace it with either the sum of its own digits, or 9 subtracted from it. [8, 18*, 1] => [8, (1+8), 1] => [8, 9, 1] (or) [8, 18*, 1] => [8, (18-9), 1] => [8, 9, 1] Sum all of the final digits [8, 9, 1] => 8+9+1 => 18 Finally, take that sum and divide it by 10. If the remainder equals zero, the original credit card number is valid. 18 (modulus) 10 => 8. 8 does not equal 0, so 891 is not a valid credit card number. """ def validate(number): digits = [int(d) for d in str(number)] i = 0 if len(digits) % 2 == 0 else 1 digits[i::2] = [d * 2 for d in digits[i::2]] digits = [d if d < 10 else d - 9 for d in digits] return sum(digits) % 10 == 0
271d4bd9e90ea83b897afbc00c16a7c78f2c12f9
williamfu24/CS372-AI-
/Project4/project4.py
11,683
4
4
#William Fu #AI Project 4 # #NOTES: #Takeing more then pile is just taking all #pile1 = 1 as opposed to your example where pile1 = 0 import random def main(): random.seed() print("pile1 = 1 not pile1 = 0 | pile2 = 2 not pile2 = 1 | pile3 = 3 not pile3 = 2\n") print("How many in pile 1?") x = int(input()) print("How many in pile 2?") y = int(input()) print("How many in pile 3?") z = int(input()) print("How many runs for q-learning?") trialNum = int(input()) print("Initial board is {}-{}-{}, simulating {} games".format(x,y,z,trialNum)) table = qlearning(trialNum, x, y, z) print("Final Q-Values:\n") for i in sorted(table): print("Q[{0}] = {1}".format(i, table[i])) gameOver = 0 print("Who starts first? (1) P1 or (2) CPU") startTurn = int(input()) turn = startTurn pile1 = x pile2 = y pile3 = z while gameOver==0: print("BOARD: [{}][{}][{}]".format(pile1,pile2,pile3)) if turn == 1: print("Player turn") choice = choiceFunc(pile1, pile2, pile3) if choice == 1: print("How many do you want to take?") takeNum = int(input()) if takeNum > pile1: pile1 = 0 else: pile1 -= takeNum elif choice == 2: print("How many do you want to take?") takeNum = int(input()) if takeNum > pile2: pile2 = 0 else: pile2 -= takeNum else: print("How many do you want to take?") takeNum = int(input()) if takeNum > pile3: pile3 = 0 else: pile3 -= takeNum if turn == 2: print("CPU turn") if startTurn == 1: tempTurn = 'B' alt = 2 else: tempTurn = 'A' alt = 1 moves = [] moves = findMoves(pile1,pile2,pile3,alt, table) print(moves) if tempTurn == 'A': maxval = -10000 maxkey = 0 for i in moves: tempval = table[i] if tempval >= maxval: maxkey = i maxval = tempval state, action = maxkey.split(',') CPUmove, CPUtake = action[:len(action)//2], action[len(action)//2:] CPUmove = int(CPUmove) CPUtake = int(CPUtake) print("Computer chooses pile {0} and removes {1}".format(CPUmove, CPUtake)) if CPUmove == 1: pile1 -= CPUtake elif CPUmove == 2: pile2 -= CPUtake else: #CPUmove == 3 pile3 -= CPUtake else: #tempTurn = 'B' minval = 10000 minkey = 0 for i in moves: tempval = table[i] if tempval <= minval: minkey = i minval = tempval state, action = minkey.split(',') CPUmove, CPUtake = action[:len(action)//2], action[len(action)//2:] CPUmove = int(CPUmove) CPUtake = int(CPUtake) print("Computer chooses pile {0} and removes {1}".format(CPUmove, CPUtake)) if CPUmove == 1: pile1 -= CPUtake elif CPUmove == 2: pile2 -= CPUtake else: #CPUmove == 3 pile3 -= CPUtake #checks for loser loser = endGoal(pile1, pile2, pile3, turn) if loser != 0: print(pile1,pile2,pile3) if loser == 2: print("CPU lost") else: print("P1 lost") print("Play agane? (1)yes or (2) no") ans = int(input()) if ans == 2: gameOver = 1 else: gameOver = 0 pile1 = x pile2 = y pile3 = z print("Who starts first? (1) P1 or (2) CPU") startTurn = int(input()) turn = startTurn turn = turnChange(turn) #just to counteract the turnchange at end of while #END OF TURN. CHANGE TURN turn = turnChange(turn) def qlearning(trialNum, x, y, z): table = {} turn = 1 #change to random later a = 0 while a < trialNum: #REPEAT FOR EACH EPISODE random.seed() turn = 1 #SET START STATE pile1=x pile2=y pile3=z gameOver = 0 while gameOver == 0: #REPEAT FOR EACH STEP OF THE EPISODE #CHOOSE ACTION (RANDOM) move = random.randrange(1, 4) #move from pile 1 - 3 #making sure pile is able to be taken from while 1: move = random.randrange(1,4) if move == 1: if pile1 == 0: pass else: #PILE ABLE TO BE TAKEN FRON SO TAKE X STICKS take = random.randrange(1, (pile1+1)) break elif move == 2: if pile2 == 0: pass else: take = random.randrange(1, (pile2+1)) break else: if pile3 == 0: pass else: take = random.randrange(1, (pile3+1)) break ##if turn == 1: if turn == 1: tempturn = "A" #turn id else: tempturn = "B" key = "{0}{1}{2}{3},{4}{5}".format(tempturn,pile1,pile2,pile3,move,take) if key not in table: #initalize Q[s,a] for all (s,a) pairs table[key] = 0 #make move if move == 1: pile1 -= take elif move == 2: pile2 -= take else: pile3 -= take #new state altturn = turnChange(turn) if turn == 1: tempturn = "A" else: tempturn = "B" #observe reward loser = endGoal(pile1,pile2,pile3,turn) if loser != 0: if loser == 1: r = -1000 if loser == 2: r = 1000 gameOver = 1 else: r = 0 #find all moves for all states moves = [] moves = findMoves(pile1,pile2,pile3,altturn, table) minval = 10000 minkey = 0 for i in moves: tempval = table[i] if tempval < minval: minkey = i minval = tempval maxval = -10000 maxkey = 0 for i in moves: tempval = table[i] if tempval > maxval: maxkey = i maxval = tempval #if r == 0 then not end state so find future value if r == 0: if turn == 1: #find the next state and its list of moves and all that jazz table[key] = 1*(r + .9*(table[minkey])) keyAlt = minkey else: table[key] = 1*(r + .9*(table[maxkey])) keyAlt = maxkey else: #if not 0 then an end state table[key] = r key = keyAlt #change turn turn = turnChange(turn) #end game. increase trial num a+=1 #when done with all runs return table def findMoves(pile1,pile2,pile3,turn, table): moves = [] for i in range(pile1, 0, -1): if turn == 1: if i != 0: ############ADDED IN EACH LOOP ################### Prevents taking 0 sticks moves.append("A{}{}{},{}{}".format(pile1,pile2,pile3,1,i)) if "A{}{}{},{}{}".format(pile1,pile2,pile3,1,i) not in table.keys(): table["A{}{}{},{}{}".format(pile1,pile2,pile3,1,i)] = 0 else: if i != 0: ############ADDED IN EACH LOOP ################### moves.append("B{}{}{},{}{}".format(pile1,pile2,pile3,1,i)) if "B{}{}{},{}{}".format(pile1,pile2,pile3,1,i) not in table.keys(): table["B{}{}{},{}{}".format(pile1,pile2,pile3,1,i)] = 0 for i in range(pile2, 0, -1): if turn == 1: if i != 0: ############ADDED IN EACH LOOP ################### moves.append("A{}{}{},{}{}".format(pile1,pile2,pile3,2,i)) if "A{}{}{},{}{}".format(pile1,pile2,pile3,2,i) not in table.keys(): table["A{}{}{},{}{}".format(pile1,pile2,pile3,2,i)] = 0 else: if i != 0: ############ADDED IN EACH LOOP ################### moves.append("B{}{}{},{}{}".format(pile1,pile2,pile3,2,i)) if "B{}{}{},{}{}".format(pile1,pile2,pile3,2,i) not in table.keys(): table["B{}{}{},{}{}".format(pile1,pile2,pile3,2,i)] = 0 for i in range(pile3, 0, -1): if turn == 1: if i != 0: ############ADDED IN EACH LOOP ################### moves.append("A{}{}{},{}{}".format(pile1,pile2,pile3,3,i)) if "A{}{}{},{}{}".format(pile1,pile2,pile3,3,i) not in table.keys(): table["A{}{}{},{}{}".format(pile1,pile2,pile3,3,i)] = 0 else: if i != 0: ############ADDED IN EACH LOOP ################### moves.append("B{}{}{},{}{}".format(pile1,pile2,pile3,3,i)) if "B{}{}{},{}{}".format(pile1,pile2,pile3,3,i) not in table.keys(): table["B{}{}{},{}{}".format(pile1,pile2,pile3,3,i)] = 0 return moves def choiceFunc(pile1, pile2, pile3): temp = 1 while temp == 1: print("What pile do you want to take from?") choice = int(input()) if choice == 1: if pile1==0: print("Pile 1 is empty. choose again") pass else: return choice if choice == 2: if pile2==0: print("Pile 2 is empty. choose again") pass else: return choice if choice == 3: if pile3==0: print("Pile 3 is empty. choose again") pass else: return choice def endGoal(pile1, pile2, pile3, turn): gameOver = 0 loser = 0 if (pile1 == 0 and pile2 == 0 and pile3 == 0): gameOver = 1 loser = turn return loser def turnChange(turn): if turn == 1: turn = 2 return turn else: turn = 1 return turn main()
704e2153c5bd51201388c971da0c063a9f9c6bdf
youhavethewrong/google-code-jam
/python/africa-2010/credit.py
852
3.703125
4
""" """ import sys def check_pair(tot, index, iteml): for i in range(len(iteml)): #print "Checking if %s + %s = %s" % (item, i, tot) if (index != i and int(iteml[index]) + int(iteml[i]) == int(tot)): return i return -1 def find_match(credit, itemc, iteml): for i in range(itemc): res = check_pair(credit, i, iteml) if res > 0: # 1-based indexing... really return i+1,res+1 return -1,-1 fh = open(sys.argv[1], 'r') case_count = int(fh.readline()) case_info = {} for i in range(case_count): case_info[i] = {'credit':int(fh.readline()), 'itemc':int(fh.readline()), 'iteml':fh.readline()[:-1]} for i in range(len(case_info)): case = case_info[i] print "Case #"+str(i+1)+": "+"%s %s" % find_match(case['credit'], case['itemc'], case['iteml'].split(' '))
c6ce40a0f8d135ebbe4b043eb5880c21e2474c52
iamanshika/Faulty-machine-Data-Analysis
/Exports/Faulty Machine Maintenance.py
6,235
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sb # ## Data Exploration # In[2]: #importing the csv file in dataframe df = pd.read_csv("maintenance_data.csv") df # In[3]: df.head() # In[4]: #Understanding data domain df.info() # The temperature and pressure columns have 3 and 4 missing values respectively. # In[5]: #To check if there are any outliers in the data df.describe() # There are signs that there might be outliers in lifetime column and moisture column. # ## Data Cleaning # In[6]: #To check if any other character other than NaN is used to depict Null values print(df['broken'].unique()) print(df['team'].unique()) print(df['provider'].unique()) # This shows that no special characters are used to depict NaN values. # In[7]: #To check the total number of missing values df.isnull().sum() # The 'pressureInd' column has 4 Null values and 'temperatureInd' column has 3 Null values # In[8]: #To check if there are any duplicted entries df.duplicated().sum() # There are no duplicated entries. # In[9]: #To decide if the NaN values sholud be replaced with the mean or the median. df.skew() # We can fill the missing values in pressure and temperature columns by their mean as the data in not much skewed # In[10]: #Replacing NaN values with the mean df.pressureInd.fillna(df.pressureInd.mean(), inplace = True ) df.temperatureInd.fillna(df.temperatureInd.mean(),inplace = True) df.info() # In[11]: #removing the outliers df.drop(df[df['moistureInd']>200].index,inplace = True) df.describe() # ## Data Analytics # #### Univariate Analysis # In[12]: #Categorising the columns into numeric or categorical numerics = ['lifetime', 'moistureInd', 'pressureInd', 'temperatureInd'] categorical = ['broken', 'team', 'provider'] # In[13]: #Using Matplotlib's Scatter plot to depict univariate analysis of numeric data for i in numerics: plt.figure(figsize = (12,5)) plt.scatter(np.arange(999),df[i]) plt.title(i) plt.show() # All graphs show uniform distribution except the mositure graph. Most of the machines are wroking at lower moisture level and a very few are working at high moisture levels. This might be a problem. # In[14]: #Using Seaborn's Countplot to depict univariate analysis of categorical data for i in categorical: plt.figure(figsize = (12,5)) sb.countplot(df[i]) plt.title(i) plt.show() # #### Bivariate Analysis # In[15]: #Using Matplotlib's Distribution Plot to depict Numeric v/s Categorical data #Moisture v/s Broken plt.figure(figsize = (12,5)) sb.distplot(df.moistureInd[df.broken==0]) sb.distplot(df.moistureInd[df.broken==1]) plt.legend(['0','1']) plt.show() # The distribution depicts that the machines wroking at moisture levels higher than 125 are more likely to be broken. # In[16]: #Temperature v/s Broken plt.figure(figsize = (12,5)) sb.distplot(df.temperatureInd[df.broken==0]) sb.distplot(df.temperatureInd[df.broken==1]) plt.legend(['0','1']) plt.show() # The distribution tends to depict that temperature as such does not affect the number of broken and not broken machines as both the broken and not broken machines operate at same temperature levels. # In[17]: #Pressure v/s Broken plt.figure(figsize = (12,5)) sb.distplot(df.pressureInd[df.broken==0]) sb.distplot(df.pressureInd[df.broken==1]) plt.legend(['0','1']) plt.show() # The distribution tends to depict that pressure as such does not affect the number of broken and not broken machines as both the broken and not broken machines operate at same pressure levels. # In[18]: #Lifetime v/s Broken plt.figure(figsize = (12,5)) sb.distplot(df.lifetime[df.broken==0]) sb.distplot(df.lifetime[df.broken==1]) plt.legend(['0','1']) plt.show() # The distribution plot is depicting that the machines which have a lifetime for 60 months or more are likely to be broken. # In[19]: #Using Matplotlib's Countplot to depict Categorical v/s Categorical data #Team v/s Broken plt.figure(figsize = (12,5)) sb.countplot(df.team) plt.show() plt.figure(figsize = (12,5)) sb.countplot(df.team[df.broken==1]) plt.show() # Team C maintains their machines slightly less. # In[20]: #Provider v/s Broken plt.figure(figsize = (12,5)) sb.countplot(df.provider) plt.show() plt.figure(figsize = (12,5)) sb.countplot(df.provider[df.broken==1]) plt.show() # The countplot depicts that Provider 4 is providing the best machines and Provider 1 and Provider 3, the worst. # ## Multivariate Analysis # In[21]: #Using Seaborn's point plot to depict Numeric v/s Categorical v/s Categorical Data plt.figure(figsize = (12,5)) sb.pointplot(x = 'provider', y = 'lifetime', hue = 'broken', data = df) plt.show() # The point plot is depicting that Provider 2 is providing the best machines and Provider 3 the worst. # In[22]: plt.figure(figsize = (12,5)) sb.pointplot(x = 'team', y = 'lifetime', hue = 'broken', data = df) plt.show() # The point plot is depicting that the Team C manages the machines slightly less. # In[23]: #Plotting Seaborn's Swarm plot to draw better conclusions for the above plotted graph plt.figure(figsize = (12,5)) sb.swarmplot(x = 'team',y = 'lifetime', hue = 'broken' , data = df) plt.show() # The point plot is depicting that the Team C has slightly less durable machines. # In[24]: #Using Seaborn's heatmap to depict the linear relationships between the features #Plotting the heatmap corr = df.corr() #Calculating the correlation matrix plt.figure(figsize = (12,8)) sb.heatmap( corr, annot = True, cmap = 'coolwarm') plt.show() # The heatmap is clearly depicting linear relationships between [Moisture, Lifetime] and [Moisture, Broken]. There is a non-linear relationship existing between [Moisture, Lifetime] which has already been shown # ### Ans1. The machines which have a lifetime for 60 months or more are likely to be broken. # ### Ans2. Provider 2 is providing the best machines and Provider 3 the worst. # ### Team C manages the machines slightly less. # ### Some machine providers are better than others and some teams are better at machine management than the rest. # In[ ]:
bf1968378635ebc25250c3d2032c67f25bbf5999
ParkerCS/ch00-variables-VladoVladVlaVlV
/ch00_problem_set_1.py
4,399
3.890625
4
#SECTION 1 - MATH OPERATORS AND VARIABLES (20PTS TOTAL) import math #PROBLEM 1 (From Math Class to Code - 2pts) # Print the answer to the math question: # 3(60x^2 + 3x/9) + 2x - 4/3(x) - sqrt(x) # where x = 12.83 x = 12.83 your_answer = 3*(60*x*x+(3*x/9))+2*x-((4/3)*x)-math.sqrt(x) print(your_answer, "") #LEE - use proper spacing in your code. Don't crunch everything together like this. (-1) #PROBLEM 2 (Set your alarm - 3pts) #You look at the clock and see that it is currently 1:00PM. # You set an alarm to go off 728 hours later. # At what time will the alarm go off? Write a program that prints the answer. # Hint: for the best solution, you will need the modulo operator. sat=1 vreme=1 alarm=728 vreme=vreme+alarm dzvoni=0 dzvoni=vreme-((vreme//24)*24) if (dzvoni+sat)>0 and (dzvoni+sat)<=12: print(dzvoni+sat,"PM") elif (dzvoni+sat)>12: print((dzvoni+sat)-12,"AM") #Lee - use English variables to help me out in grading for future projects. # You are off by one hour. I believe the floor got you on this one. Try a modulo as suggested in the problem (-1) #PROBLEM 3 (Wholesale Books - 3pts) #The cover price of a book is $27.95, but bookstores get a 50 percent discount. #Shipping costs $4 for the first copy and 75 cents for each additional copy. # Calculate the total wholesale costs for 68 copies to the nearest penny. #i know i know, variables. was too lazy to do that #im also not not sure of the numerical representation of a penny (0.1) (0.01) ? answer=((27.95*0.5)-4+67*((27.95*0.5)-0.75)) print(answer) # penny is 0.01, and you really should have variables. When I look at this, I don't know that we are discussing book sales at all. (-1) #PROBLEM 4 (Dining Room Chairs - 3pts) # You purchase eight chairs for your dining room. # You pay for the chairs plus sales tax at 9.5% # Make a program that prints the amount to the nearest penny using the variables below # Use the round(float, digits) function to get to nearest penny chair_price = 189.99 tax_percent = 0.095 units = 8 amount=chair_price*tax_percent*units print(round(amount,2)) # LEE - You calculated tax only and left out the chairs (-1) #PROBLEM 5 (Area of Circle - 3pts) # Write code that can compute the area of circle. # Create variables for radius and pi (3.14159) # The formula, in case you do not know, is radius times radius times pi. # Print the outcome of your program as follows: # “The surface area of a circle with radius ... is ...” radius=3 pi=math.pi rezultat=radius*radius*pi print("The surface area of a circle with radius",radius,"is",rezultat) #PROBLEM 6 (Coin counter - 4pts) # Write code that classifies a given amount of money (which you store in a variable named count), # as greater monetary units. Your code lists the monetary equivalent in dollars, quarters, # dimes, nickels, and pennies. # Your program should report the maximum number of dollars that fit in the amount, # then the maximum number of quarters that fit in the remainder after you subtract the dollars, # then the maximum number of dimes that fit in the remainder after you subtract the dollars and quarters, # and so on for nickels and pennies. # The result is that you express the amount as the minimum number of coins needed. #We shall assume 1 dollar=100 pennies, 4 quartets, 10 dimes and 20 nickels count=7.28 dolari=count//1 quarters=(count%dolari)//0.25 dimes=((count%dolari)-(quarters*0.25))//0.1 current_count=(count-dolari-(quarters*0.25)-(dimes*0.1)) nickels=(current_count//0.05) pennies=(current_count%0.05)//0.01 print(pennies,dimes,nickels,quarters) # Lee - This one did not work out properly. You are not tracking the current_amount properly. Calculate the number of dollars, then take them out of the running total, then calculate the quarters, then take them out of the running total, etc.. (-1) #PROBLEM 7 (Variable Swap - 2pts) # Can you think of a way to swap the values of two variables that does not # need a third variable as a temporary storage? # In the code below, try to implement the swapping of the values of 'a' and 'b' without using a third variable. # To help you out, the first step to do this is already given. # You just need to add two more lines of code. a = 17 b = 23 print( "a =", a, "and b =", b) a += b b=a-b a=a-b # this is the first line to help you out # add two more lines of code here to cause swapping of a and b print( "a =", a, "and b =", b)
b683c9897e4e056f63642d6558bb197030d6f15f
BalawalSultan/Mario-Mini-Game
/player.py
2,005
3.671875
4
class Player: def __init__(self): self.max_health = 15 self.health = self.max_health self.attack_power = 2 self.defense = 1 self.health_potion_ammount = 3 self.health_potion_power = 5 self.x = 0 self.y = 0 # increases the players stats def level_up(self): self.max_health += 15 self.health = self.max_health self.attack_power += 3 self.defense += 1 self.health_potion_ammount += 2 self.health_potion_power += 4 def attack(self, boss): boss.health -= self.attack_power def drink_potion(self): if self.health_potion_ammount > 0: self.health_potion_ammount -= 1 missing_health = self.max_health - self.health recovered_health = self.health_potion_power # makes sure that the players health doesn't go above his max health if self.health + self.health_potion_power > self.max_health: self.health += missing_health recovered_health = missing_health else: self.health += self.health_potion_power print("You recovered ", recovered_health, " HP.") print(self.health_potion_ammount, " health potions remaining.") else: print("You ran out of healing potions.") def isAlive(self): if self.health > 0: return True else: return False # returns a list that will act as health bar def getHealth(self): health_color = (255, 0, 0) # RED black = (0, 0, 0) health = [health_color if i < self.health else black for i in range(64)] return health # player chooses what to do on the terminal def playerTurn(self): print("[1] Attack \n[2] Heal") option = int(input("What will you do?")) return option
7003167d2036b1d79093b16ee0d9a6ac288d993a
C109156209/midterm
/25.py
247
3.78125
4
while True: s=input("檢測的字串(end結束):") if(s=="end"): print("檢測結束") break s=list(s) c=input("檢測的單一字元:") print("字元%s出現的次數為:%s" %(c,str(s.count(c))))
9d976ac0721bd261907fafaba93414d1ee023ac7
sijapu17/Advent-of-Code
/2021/2021-22.py
12,135
3.5625
4
#Advent of Code 2021 Day 22 import re f = open('C:/Users/Simon/OneDrive/Home Stuff/Python/Advent of Code/2021/2021-22.txt') contents = f.read() inp = contents.splitlines() class Cuboid(): def __init__(self,x0,x1,y0,y1,z0,z1): self.x0=min(x0,x1) self.x1=max(x0,x1) self.y0=min(y0,y1) self.y1=max(y0,y1) self.z0=min(z0,z1) self.z1=max(z0,z1) def area(self): #Return area of cuboid return((self.x1-self.x0+1)*(self.y1-self.y0+1)*(self.z1-self.z0+1)) def any_overlap(self,other): #Boolean determining if two cubes overlap at all return(self.x1>=other.x0 and other.x1>=self.x0) and (self.y1>=other.y0 and other.y1>=self.y0) and (self.z1>=other.z0 and other.z1>=self.z0) def __str__(self) -> str: return(self.__repr__()) def __repr__(self) -> str: return(f'x=({self.x0},{self.x1}),y=({self.y0},{self.y1}),z=({self.z0},{self.z1})') def __eq__(self, other) -> bool: return(self.x0==other.x0 and self.y0==other.y0 and self.z0==other.z0 and self.x1==other.x1 and self.y1==other.y1 and self.z1==other.z1) def __hash__(self) -> int: return(hash((self.x0,self.y0,self.z0,self.x1,self.y1,self.z1))) class Reactor(): def __init__(self,inp): self.cuboids=[] #List of cuboids that are currently switched on self.steps=[] p=re.compile('(^\w+) x=(\-?\d+)\.\.(\-?\d+),y=(\-?\d+)\.\.(\-?\d+),z=(\-?\d+)\.\.(\-?\d+)$') #Regex pattern to read in instructions for line in inp: m=p.match(line) step=m.group(1),int(m.group(2)),int(m.group(3)),int(m.group(4)),int(m.group(5)),int(m.group(6)),int(m.group(7)) self.steps.append(step) def run_reboot(self,part): for s in self.steps: #print(f'Step {s}') type,x0,x1,y0,y1,z0,z1=s #Assign each element of step to correct meaning if part==1: #Bounding for part 1 only if max(x0,y0,z0)>50 or min(x1,y1,z1)<-50: #If cuboid is fully outside (-50,50) range, skip entirely continue else: #If cuboid is partly outside range, only consider section within (-50,50) x0=max(-50,x0) y0=max(-50,y0) z0=max(-50,z0) x1=min(50,x1) y1=min(50,y1) z1=min(50,z1) new=Cuboid(x0,x1,y0,y1,z0,z1) new_cuboids=[] #At the end of the step, overwrite the old list of cuboids with this for cub in self.cuboids: #print(f'Cub={str(cub)}') #print(f'New={str(new)}') if new.any_overlap(cub): #If there is any overlap, partition existing cuboid into smaller cuboids and keep those that do not intersect the new one x_ranges=[] y_ranges=[] z_ranges=[] #Case where both starts and ends match if cub.x0==new.x0 and cub.x1==new.x1: x_ranges.append((new.x0,new.x1)) #Cases where starts match elif cub.x0==new.x0 and cub.x1<new.x1: x_ranges.append((new.x0,cub.x1)) x_ranges.append((cub.x1+1,new.x1)) elif cub.x0==new.x0 and new.x1<cub.x1: x_ranges.append((new.x0,new.x1)) x_ranges.append((new.x1+1,cub.x1)) #Cases where ends match elif cub.x1==new.x1 and cub.x0<new.x0: x_ranges.append((cub.x0,new.x0-1)) x_ranges.append((new.x0,new.x1)) elif cub.x1==new.x1 and new.x0<cub.x0: x_ranges.append((new.x0,cub.x0-1)) x_ranges.append((cub.x0,new.x1)) #n1=c0 case elif new.x0<new.x1==cub.x0<cub.x1: x_ranges.append((new.x0,new.x1-1)) x_ranges.append((new.x1,cub.x0)) x_ranges.append((new.x1+1,cub.x1)) #n0=c1 case elif cub.x0<new.x0==cub.x1<new.x1: x_ranges.append((cub.x0,cub.x1-1)) x_ranges.append((cub.x1,new.x0)) x_ranges.append((new.x0+1,new.x1)) #cncn case elif cub.x0<new.x0<cub.x1<new.x1: x_ranges.append((cub.x0,new.x0-1)) x_ranges.append((new.x0,cub.x1)) x_ranges.append((cub.x1+1,new.x1)) #cnnc case elif cub.x0<new.x0<=new.x1<cub.x1: x_ranges.append((cub.x0,new.x0-1)) x_ranges.append((new.x0,new.x1)) x_ranges.append((new.x1+1,cub.x1)) #ncnc case elif new.x0<cub.x0<new.x1<cub.x1: x_ranges.append((new.x0,cub.x0-1)) x_ranges.append((cub.x0,new.x1)) x_ranges.append((new.x1+1,cub.x1)) #nccn case elif new.x0<cub.x0<=cub.x1<new.x1: x_ranges.append((new.x0,cub.x0-1)) x_ranges.append((cub.x0,cub.x1)) x_ranges.append((cub.x1+1,new.x1)) else: print('Error, x ranges not found') #Case where both starts and ends match if cub.y0==new.y0 and cub.y1==new.y1: y_ranges.append((new.y0,new.y1)) #Cases where starts match elif cub.y0==new.y0 and cub.y1<new.y1: y_ranges.append((new.y0,cub.y1)) y_ranges.append((cub.y1+1,new.y1)) elif cub.y0==new.y0 and new.y1<cub.y1: y_ranges.append((new.y0,new.y1)) y_ranges.append((new.y1+1,cub.y1)) #Cases where ends match elif cub.y1==new.y1 and cub.y0<new.y0: y_ranges.append((cub.y0,new.y0-1)) y_ranges.append((new.y0,new.y1)) elif cub.y1==new.y1 and new.y0<cub.y0: y_ranges.append((new.y0,cub.y0-1)) y_ranges.append((cub.y0,new.y1)) #n1=c0 case elif new.y0<new.y1==cub.y0<cub.y1: y_ranges.append((new.y0,new.y1-1)) y_ranges.append((new.y1,cub.y0)) y_ranges.append((new.y1+1,cub.y1)) #n0=c1 case elif cub.y0<new.y0==cub.y1<new.y1: y_ranges.append((cub.y0,cub.y1-1)) y_ranges.append((cub.y1,new.y0)) y_ranges.append((new.y0+1,new.y1)) #cncn case elif cub.y0<new.y0<cub.y1<new.y1: y_ranges.append((cub.y0,new.y0-1)) y_ranges.append((new.y0,cub.y1)) y_ranges.append((cub.y1+1,new.y1)) #cnnc case elif cub.y0<new.y0<=new.y1<cub.y1: y_ranges.append((cub.y0,new.y0-1)) y_ranges.append((new.y0,new.y1)) y_ranges.append((new.y1+1,cub.y1)) #ncnc case elif new.y0<cub.y0<new.y1<cub.y1: y_ranges.append((new.y0,cub.y0-1)) y_ranges.append((cub.y0,new.y1)) y_ranges.append((new.y1+1,cub.y1)) #nccn case elif new.y0<cub.y0<=cub.y1<new.y1: y_ranges.append((new.y0,cub.y0-1)) y_ranges.append((cub.y0,cub.y1)) y_ranges.append((cub.y1+1,new.y1)) else: print('Error, y ranges not found') #Case where both starts and ends match if cub.z0==new.z0 and cub.z1==new.z1: z_ranges.append((new.z0,new.z1)) #Cases where starts match elif cub.z0==new.z0 and cub.z1<new.z1: z_ranges.append((new.z0,cub.z1)) z_ranges.append((cub.z1+1,new.z1)) elif cub.z0==new.z0 and new.z1<cub.z1: z_ranges.append((new.z0,new.z1)) z_ranges.append((new.z1+1,cub.z1)) #Cases where ends match elif cub.z1==new.z1 and cub.z0<new.z0: z_ranges.append((cub.z0,new.z0-1)) z_ranges.append((new.z0,new.z1)) elif cub.z1==new.z1 and new.z0<cub.z0: z_ranges.append((new.z0,cub.z0-1)) z_ranges.append((cub.z0,new.z1)) #n1=c0 case elif new.z0<new.z1==cub.z0<cub.z1: z_ranges.append((new.z0,new.z1-1)) z_ranges.append((new.z1,cub.z0)) z_ranges.append((new.z1+1,cub.z1)) #n0=c1 case elif cub.z0<new.z0==cub.z1<new.z1: z_ranges.append((cub.z0,cub.z1-1)) z_ranges.append((cub.z1,new.z0)) z_ranges.append((new.z0+1,new.z1)) #cncn case elif cub.z0<new.z0<cub.z1<new.z1: z_ranges.append((cub.z0,new.z0-1)) z_ranges.append((new.z0,cub.z1)) z_ranges.append((cub.z1+1,new.z1)) #cnnc case elif cub.z0<new.z0<=new.z1<cub.z1: z_ranges.append((cub.z0,new.z0-1)) z_ranges.append((new.z0,new.z1)) z_ranges.append((new.z1+1,cub.z1)) #ncnc case elif new.z0<cub.z0<new.z1<cub.z1: z_ranges.append((new.z0,cub.z0-1)) z_ranges.append((cub.z0,new.z1)) z_ranges.append((new.z1+1,cub.z1)) #nccn case elif new.z0<cub.z0<=cub.z1<new.z1: z_ranges.append((new.z0,cub.z0-1)) z_ranges.append((cub.z0,cub.z1)) z_ranges.append((cub.z1+1,new.z1)) else: print('Error, z ranges not found') #print(x_ranges) #print(y_ranges) #print(z_ranges) for a in x_ranges: for b in y_ranges: for c in z_ranges: sub=Cuboid(a[0],a[1],b[0],b[1],c[0],c[1]) #print(sub) if cub.any_overlap(sub) and not new.any_overlap(sub): #Append sub-cuboids if they are part of cub that doesn't overlap new #print('^Part of cub, not new') new_cuboids.append(sub) else: #If new cuboid doesn't overlap existing cuboid, keep existing cuboid as is new_cuboids.append(cub) if type=='on': #If new cuboid is an addition ('on') then add it to the list - existing cuboids have had their overlaps removed so there is no double-counting new_cuboids.append(new) self.cuboids=new_cuboids #Overwrite self.cuboids with new list #print(sum([x.area() for x in self.cuboids])) return(sum([x.area() for x in self.cuboids])) reactor=Reactor(inp) print(reactor.run_reboot(1)) print(reactor.run_reboot(2))
3d074d9899f0af54a5f8786f2d6a38d5fbe6b0f0
ethunk/python_challenges
/ex4.py
561
3.71875
4
cars = 100 space_in_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capactiy = cars_driven*space_in_car average_passenger_per_car = passengers/cars_driven print ("There are,", cars, "cars available.") print ("There are only", drivers, "drivers available") print ("There will be", cars_not_driven, "empty cars today.") print ("We can transport", carpool_capactiy, "people today.") print ("We have", passengers, "to carpool today.") print ("We need to put about", average_passenger_per_car, "in each car.")
72e08ca09ec3eb848d1cf7ab9042c8f8c8cf36ab
namnamgit/pythonProjects
/fibonacci.py
114
3.609375
4
#sequência de fibonacci a, b, c = 0, 1, 0 while a < 100: print(a, end=', ') c = a a = a + b b = c input()
3d28ca7d0a8e5b6b5872a4155700439be7090d93
Sundarmax/assignment
/workspace/test.py
836
3.8125
4
def create_dict(): a = [1,2,3] b = [4,5,6] c = {} i = 0 while i < len(a) and i < len(b): c[a[i]] = b[i] i+=1 print("dict",c) def remove_duplicates(): a = [1,2,3,4,1,2] temp = [] for item in a: if item not in temp: temp.append(item) #print("unique list",temp) c = [i for index,i in enumerate(a) if i not in a[:index] ] print(c) def find_balance_of_paranthesis(): pass def func(xyz=[]): xyz.append(4) print(xyz) xyz = [5,6,7] return class Staff: name = None count = 0 def __init__(self,name): self.name = name Staff.count+=1 obj1 = Staff("A") obj2 = Staff("B") print("No .of objects have been created is ",Staff.count) #create_dict() #remove_duplicates() #find_balance_of_paranthesis()
4a1f845b0e129be3a66b5a029854f0134647161c
SergioKronemberg/CursoBlueMod1
/aula9/ex2.py
81
3.734375
4
n = input("digite um numero positivo:") print("o numero tem", len(n), "digitos")
f8f8f016b1c5e9ce71b416ca0acb157aa4612695
matsmartens/coma-hex
/hex/PlayerController.py
1,517
3.59375
4
from random import * class PlayerController: def __init__(self): self._currentPlayer = 1 self._currentPlayerType = "human" self._playerIdentity = 0 self.mode = "human" # generate random player number def chooseFirst(self): self._currentPlayer = round(random.random()) + 1 def setPlayerIdentity(self, player): self._playerIdentity = player def getPlayerIdentity(self): return self._playerIdentity def setCurrentPlayer(self, player): self._currentPlayer = player # is the getter for the private variable def currentPlayer(self): return self._currentPlayer def currentEnemy(self): if self._currentPlayer == 1: return 2 else: return 1 # is the current Player human? def isPlayerHuman(self): return self._currentPlayerType == "human" # alter the players def changePlayer(self): if self._currentPlayer == 1: self._currentPlayer = 2 else: self._currentPlayer = 1 if self.mode == "ki": if self._currentPlayerType == "human": self._currentPlayerType = "ki" else: self._currentPlayerType = "human" if self.mode in ["inter", "machine"]: self._currentPlayerType = "ki"
058018bfad650c880a4d38df359580bdd12a6bf8
przemo1694/wd
/zad12.py
239
3.859375
4
for y in range(1,11,1): for x in range(1,11,1): if(y*x)>= 10: print (y*x , " ",end='') elif(y*x)== 100: print (y*x , " ",end='') else: print (y*x , " ",end='') print("")
ec5509918dc172b9a4e3cd0350f82ac52679d15b
udaypandey/BubblyCode
/Python/RevereNumber.py
240
3.96875
4
# Read a number from the keyboard # Print reverse number # For eg for 1234567, 7654321 num = int(input("Enter a number: ")) sum = 0 while num > 0: remain = num % 10 sum = sum * 10 + remain num = num // 10 print(sum)
33869fa1bb72093a4a7154a10fde8c7543632b67
Ahn-seongjun/How-to-Python
/multi for.py
178
3.765625
4
for y in range(3): for x in range(5): print(x,end='') print() a=0 for i in range(3): for j in range(4): a+=1 print(a, end="\t") print()
67915c237f3b6632cb53c70ae92c040056b83dd0
Sourabh-Kishore-Sharma/Megahack-DualSpecs
/visualize.py
5,343
3.5
4
#!/usr/bin/env python3 import pandas as pd import matplotlib.pyplot as plt from pandasql import sqldf sql=lambda q: sqldf(q,globals()) import re from PIL import Image import os from PyPDF2 import PdfFileReader, PdfFileWriter bank = input("Enter Bank: ").lower() df = pd.read_csv(str(bank)+".csv") c = input("Would you like to give a date range? Y/N: ").lower() if c == "y": start = str(input("Start Date (dd/mm/yyyy) : ")) end = str(input("End Date (dd/mm/yyyy) : ")) try: start_index = df[df["Transaction_Date"]==start].index.values[0] end_index = df[df["Transaction_Date"]==end].index.values[-1] if start_index<end_index: df = df[start_index:end_index] else: df = df[end_index:start_index] except: start_index = df[df["Transaction_Date"]==start].index.values end_index = df[df["Transaction_Date"]==end].index.values if start_index<end_index: df = df[start_index:end_index] else: df = df[end_index:start_index] """ print("Inside except") print(start_index) print(end_index) """ #Pie Chart Visualization of Payment Area df_pay_area = sql(""" SELECT `Payment_Area`,COUNT(*) as Total FROM df where `Transaction_Date` group by `Payment_Area` order by Total desc limit 6 """) df_pay_area.set_index("Payment_Area",inplace=True) colors_list = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'lightgreen', 'pink'] explode_list = [0.1, 0,0.1, 0,0.1, 0] # ratio for each continent with which to offset each wedge. plt.rcParams.update({'font.size': 13}) try: df_pay_area['Total'].plot(kind='pie', figsize=(15, 6), autopct='%1.1f%%', startangle=90, shadow=True, labels=None, # turn off labels on pie chart pctdistance=1.12, # the ratio between the center of each pie slice and the start of the text generated by autopct colors=colors_list, # add custom colors explode=explode_list # 'explode' lowest 3 payment types ) except: df_pay_area['Total'].plot(kind='pie', figsize=(15, 6), autopct='%1.1f%%', startangle=90, shadow=True, labels=None, # turn off labels on pie chart pctdistance=1.12 # the ratio between the center of each pie slice and the start of the text generated by autopct # add custom colors # 'explode' lowest 3 payment types ) # scale the title up by 12% to match pctdistance plt.title('Distribution by Payment Area', y=1.05) plt.axis('equal') # add legend plt.legend(labels=df_pay_area.index, loc='upper left') plt.savefig("pay_area.png") print("1/4 Analysis Done!!") image1 = Image.open("pay_area.png") im1 = image1.convert("RGB") plt.close() #Bar graph for Top 6 Debits df_from_debit = sql(""" SELECT `From`,SUM(`Debit`) as Total FROM df group by `From` order by Total desc limit 6 """) df_from_debit.set_index("From",inplace=True) df_from_debit.plot(kind='bar') plt.rcParams.update({'font.size': 17}) plt.ylabel("Total Amount Debited") plt.xlabel("Entity") plt.savefig("Debit.png",bbox_inches = 'tight') print("2/4 Analysis Done!!") image2 = Image.open("Debit.png") im2 = image2.convert("RGB") plt.close() #Bar graph for Top 6 Credits df_from_credit = sql(""" SELECT `Class`,SUM(`Credit`) as Total FROM df group by `Class` order by Total desc limit 6 """) df_from_credit.set_index("Class",inplace=True) df_from_credit.plot(kind='bar') plt.rcParams.update({'font.size': 17}) plt.ylabel("Total Amount Credited") plt.xlabel("Entity") plt.savefig("Credit.png",bbox_inches = 'tight') print("3/4 Analysis Done!!") image3 = Image.open("Credit.png") im3 = image3.convert("RGB") plt.close() #Bar graph for each month expenses df_month = sql(""" select substr(`Transaction_Date`,4,6) as Month,sum(`Debit`) as Debit,sum(`Credit`) as Credit from df group by Month order by `Transaction_Date` limit 15 """) df_month.set_index("Month",inplace=True) df_month.plot(kind='bar') plt.rcParams.update({'font.size': 17}) plt.rcParams["figure.figsize"] = (10,10) plt.ylabel("Total Amount") plt.xlabel("Entity") plt.savefig("Expenses by Month.png",bbox_inches = 'tight') print("4/4 Analysis Done!!") image4 = Image.open("Expenses by Month.png") im4 = image4.convert("RGB") plt.close() img_list = [im2,im3,im4] im1.save("Analysis.pdf",save_all=True, append_images=img_list) os.remove("pay_area.png") os.remove("Debit.png") os.remove("Credit.png") os.remove("Expenses by Month.png") password = input("Enter password for Report: ") out = PdfFileWriter() file = PdfFileReader("Analysis.pdf") num = file.numPages for idx in range(num): page = file.getPage(idx) out.addPage(page) out.encrypt(password) # Open a new file "myfile_encrypted.pdf" with open("Analysis-encrypted.pdf", "wb") as f: out.write(f) os.remove("Analysis.pdf") print("Visualization was done successfully!!")
691ab566c15b9f6e58c16e90d4f884acb235ad45
albertisfu/devz-community
/linked-list/linked-list.py
3,214
4.1875
4
# Alberto Islas # Linked List and remove duplicates of a linked list #Node Class class Node: def __init__(self, data): self.data = data self.next_node = None #LinkedList Class class LinkedList: def __init__(self): self.head = None #append new elements to linked list method def append(self, data): new_node = Node(data) if self.head == None: self.head = new_node return new_node else: current_node =self.head while current_node.next_node != None: current_node = current_node.next_node current_node.next_node = new_node return new_node #print elements of linked list def print_list(self): if self.head != None: current_node = self.head while current_node != None: print(current_node.data) current_node = current_node.next_node #delete a node from linked list def delete(self, node_to_delete): prev_node = None current_node =self.head while current_node !=None: if current_node == node_to_delete: if prev_node == None: #if is head node, change linked list head self.head = current_node.next_node else: #if is not head node, change prev node reference to current.next_node prev_node.next_node = current_node.next_node prev_node = current_node current_node = current_node.next_node #remove duplicates elements form the linked list def delete_duplicates(self): uniq_values = {} if self.head != None: current_node = self.head while current_node != None: #check if current.data is inside uniq_values dict (duplicate) exist = uniq_values.get(current_node.data, True) if exist != True: #delete node if is duplicate self.delete(current_node) else: #add current data to uniq_values dict uniq_values[current_node.data] = None #change reference to next Node(data) current_node = current_node.next_node #test 1 new_list = LinkedList() n1 = new_list.append(4) n2 = new_list.append(5) n3 = new_list.append(9) n4 = new_list.append(0) n5 = new_list.append(5) n5 = new_list.append(1) n6 = new_list.append(2) print("-------- TEST 1 ------------") print('Original Linked List') new_list.print_list() print('After remove Duplicates:') new_list.delete_duplicates() new_list.print_list() new_list2 = LinkedList() n12 = new_list2.append(1) n22 = new_list2.append(2) n32 = new_list2.append(3) n42 = new_list2.append(3) n52 = new_list2.append(2) n52 = new_list2.append(1) print("-------- TEST 2 ------------") print('Original Linked List') new_list2.print_list() print('After remove Duplicates:') new_list2.delete_duplicates() new_list2.print_list()
f2e70f0c150d1b47a33317b2df430b5aaa752da3
i150251/Python-tkinter-GUI-basic-example
/main.py
15,352
3.546875
4
import tkinter as tk from tkinter import * from tkinter import messagebox from matplotlib import pylab from pylab import plot, show, xlabel, ylabel from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from collections import defaultdict from pprint import pprint import matplotlib.pyplot as plt from moneymanager import MoneyManager win = tk.Tk() #Set window size here to '540 x 640' win.geometry('%sx%s' % (540, 640)) #Set the window title to 'FedUni Money Manager' win.winfo_toplevel().title("FedUni Money Manager") #The user number and associated variable user_number_var = tk.StringVar() #This is set as a default for ease of testing user_number_var.set('') user_number_entry = tk.Entry(win, textvariable=user_number_var,font="Calibri 16") user_number_entry.focus_set() #The pin number entry and associated variables pin_number_var = tk.StringVar() #This is set as a default for ease of testing pin_number_var.set('') #Modify the following to display a series of * rather than the pin ie **** not 1234 user_pin_entry = tk.Entry(win, text='PIN Number', textvariable=pin_number_var, font="Calibri 16",show='*') #set the user file by default to an empty string user_file = '' # The balance label and associated variable balance_var = tk.StringVar() balance_var.set('Balance: $0.00') balance_label = tk.Label(win, textvariable=balance_var) # The Entry widget to accept a numerical value to deposit or withdraw #amount_var = tk.StringVar() tkVar=StringVar(win) amount_entry = tk.Entry(win) entry_type=tk.Entry(win) entryType = tk.StringVar() # The transaction text widget holds text of the transactions transaction_text_widget = tk.Text(win, height=10, width=48) # The money manager object we will work with user = MoneyManager() # ---------- Button Handlers for Login Screen ---------- def clear_pin_entry(event): # Clearing the pin number entry here pin_number_var.set('') def handle_pin_button(event): # Limiting to 4 chars in length & Set the new pin number on the pin_number_var NewPinAdded=event.widget['text'] if( len ( pin_number_var.get() )<4): pin_number_var.set(pin_number_var.get()+NewPinAdded) def log_in(event): '''Function to log in to the banking system using a known user number and PIN.''' global user global pin_number_var global user_file global user_num_entry # Creating the filename from the entered account number with '.txt' on the end FileName=user_number_var.get()+".txt" # Try to open the account file for reading try: # Open the account file for reading user_file = open(FileName,'r');user_file.seek(0, 0) # First line is account number user.UserNumber = read_line_from_user_file() if(user.UserNumber!=user_number_var.get()): raise Exception("Inavlid account number") # Second line is PIN number, raise exceptionk if the PIN entered doesn't match account PIN read user.PinNumber = read_line_from_user_file() if(user.PinNumber!=pin_number_var.get()): raise Exception("Invalid pin number") # Reading third line for BALANCE user.Balance = float(read_line_from_user_file()) # Section to read account transactions from file - start an infinite 'do-while' loop here while True: LineRead = read_line_from_user_file() LineRead.upper() if (LineRead=="Deposit" or LineRead=="Entertainment" or LineRead=="Food" or LineRead=="Rent" or LineRead=="Other" or LineRead=="Bills"): AmountLine = read_line_from_user_file() user.TransactionList.append((LineRead,AmountLine)) else: break # Close the file now we're finished with it user_file.close() balance_var.set('Balance: '+str(user.Balance)) # Catch exception for erros except Exception as exception_error: # Show error messagebox and & reset BankAccount object to default... messagebox.showerror(" Invalid Error ",exception_error) user = MoneyManager() # ...also clear PIN entry and change focus to account number entry pin_number_var.set('') user_number_entry.focus_set() return remove_all_widgets() create_user_screen() # ---------- Button Handlers for User Screen ---------- def remove_all_widgets(): global win for widget in win.winfo_children(): widget.grid_remove() def read_line_from_user_file(): global user_file return user_file.readline()[0:-1] def plot_spending_graph(): # YOUR CODE to generate the x and y lists here which will be plotted X=["Entertainment","Other","Rent","Food","Bills"] Y = [0,0,0,0,0] #Figure variable to be updated figure = Figure(figsize=(3,2), dpi=70);figure.suptitle('Spendings') a = figure.add_subplot(111) #For creating relative X and Y data for T in user.TransactionList: if(T[0]=="Entertainment"): Y[0]=Y[0]+float(T[1]) if(T[0]=="Other"): Y[1]=Y[1]+float(T[1]) if(T[0]=="Rent"): Y[2]=Y[2]+float(T[1]) if T[0]=="Food": Y[3]=Y[3]+float(T[1]) if(T[0]=="Bills"): Y[4]=Y[4]+float(T[1]) #Your code to display the graph on the screen here - do this last a.plot(X, Y, marker='o') a.grid() canvas = FigureCanvasTkAgg(figure, master=win) canvas.draw() graph_widget = canvas.get_tk_widget() graph_widget.grid(row=5, column=0, columnspan=5, sticky='nsew') def save_and_log_out(): global user # Save the account with any new transactions user.save_to_file() # Reset the bank acount object user = MoneyManager() # Reset the account number and pin to blank pin_number_var.set('');user_number_var.set('');user_number_entry.focus_set() # Remove all widgets and display the login screen again remove_all_widgets();create_login_screen() def perform_deposit(): global user global amount_entry global balance_label global balance_var #Increasing the account balance and append the deposit to the account file try: # Getting the cash amount to deposit & Depositing funds AmountT = amount_entry.get() TryD = user.deposit_funds(AmountT) if(TryD!="OK"): raise Exception(" Invalidation raised ") #Update the transaction widget with the new transaction by calling account.get_transaction_string() transaction_text_widget['state']='normal';transaction_text_widget.delete(0.0,tk.END) #contents, and finally configure back to state='disabled' so it cannot be user edited. transaction_text_widget.insert(tk.END,user.get_transaction_string());transaction_text_widget['state']='disabled' # Change the balance label to reflect the new balance balance_var.set('Balance($): ' + str(user.Balance)) # Clear the amount entry amount_entry.delete(0,'end') # Update the interest graph with our new balance plot_spending_graph() except Exception as exception: #exception Handling return messagebox.showerror("ALERT! ",exception) def perform_transaction(): '''Function to add the entry the amount in the amount entry from the user balance and add an entry to the transaction list.''' global user global amount_entry global balance_label global balance_var global entry_type #Decreasing the account balance and append the deposit to the account file try: # Get the cash amount to use & Get the type of entry that will be added ie rent etc Check = user.add_entry(amount_entry.get(),entryType.get()) if(Check!="OK"): raise Exception(Check) # Update the transaction widget with the new transaction by calling user.get_transaction_string() transaction_text_widget['state']='normal';transaction_text_widget.delete(0.0,tk.END) # contents, and finally configure back to state='disabled' so it cannot be user edited. transaction_text_widget.insert(tk.END,user.get_transaction_string());transaction_text_widget['state']='disabled' # Change the balance label to reflect the new balance balance_var.set('Balance : ' + str(user.Balance)) # Clear the amount entry amount_entry.delete(0,'end') # Update the graph plot_spending_graph() except Exception as exception: #exception handling return messagebox.showerror("ALERT! ",exception) # ---------- UI Drawing Functions ---------- def create_login_screen(): # ----- Row 0 ----- # 'FedUni Money Manager' label here. Font size is 28. tk.Label(win,text="FedUni Money Manager",font="None 28").grid(row=0,column=0,columnspan=5,sticky="nsew") # ----- Row 1 ----- # Acount Number / Pin label here tk.Label(win,text="Account Number / Pin",font="None 10").grid(row=1,column=0,sticky="nsew") # Account number entry here user_number_entry.grid(row=1,column=1) # Account pin entry here user_pin_entry.grid(row=1,column=2) # ----- Row 2 ----- # Buttons 1, 2 and 3 here. Buttons are bound to 'handle_pin_button' function via '<Button-1>' event. B1 = tk.Button(win,text='1');B1.bind('<Button-1>',handle_pin_button);B1.grid(row=2,column=0,sticky='nsew') B2 = tk.Button(win,text='2');B2.bind('<Button-1>',handle_pin_button);B2.grid(row=2,column=1,sticky='nsew') B3 = tk.Button(win,text='3');B3.bind('<Button-1>',handle_pin_button);B3.grid(row=2,column=2,sticky='nsew') # ----- Row 3 ----- # Buttons 4, 5 and 6 here. Buttons are bound to 'handle_pin_button' function via '<Button-1>' event. B4 = tk.Button(win,text='4');B4.bind('<Button-1>',handle_pin_button);B4.grid(row=3,column=0,sticky='nsew') B5 = tk.Button(win,text='5');B5.bind('<Button-1>',handle_pin_button);B5.grid(row=3,column=1,sticky='nsew') B6 = tk.Button(win,text='6');B6.bind('<Button-1>',handle_pin_button);B6.grid(row=3,column=2,sticky='nsew') # ----- Row 4 ----- # Buttons 7, 8 and 9 here. Buttons are bound to 'handle_pin_button' function via '<Button-1>' event. B7 = tk.Button(win,text='7');B7.bind('<Button-1>',handle_pin_button);B7.grid(row=4,column=0,sticky='nsew') B8 = tk.Button(win,text='8');B8.bind('<Button-1>',handle_pin_button);B8.grid(row=4,column=1,sticky='nsew') B9 = tk.Button(win,text='9');B9.bind('<Button-1>',handle_pin_button);B9.grid(row=4,column=2,sticky='nsew') # ----- Row 5 ----- # Cancel/Clear button here. 'bg' and 'activebackground' should be 'red'. But calls 'clear_pin_entry' function. BC = tk.Button(win,text='Clear',activebackground='red',bg='red');BC.bind('<Button-1>',clear_pin_entry);BC.grid(row=5,column=0,sticky='nsew') # Button 0 here B0 = tk.Button(win,text='0');B0.bind('<Button-1>',handle_pin_button);B0.grid(row=5,column=1,sticky='nsew') # Login button here. 'bg' and 'activebackground' should be 'green'). Button calls 'log_in' function. BL = tk.Button(win,text='Login',activebackground='green',bg='green');BL.bind('<Button-1>',log_in);BL.grid(row=5,column=2,sticky='nsew') # ----- Set column & row weights ----- # Set column and row weights. There are 5 columns and 6 rows (0..4 and 0..5 respectively) win.rowconfigure(0,weight=1);win.columnconfigure(0,weight=1) win.rowconfigure(1,weight=1);win.columnconfigure(1,weight=1) win.rowconfigure(2,weight=1);win.columnconfigure(2,weight=2) win.rowconfigure(3,weight=1);win.columnconfigure(3,weight=2) win.rowconfigure(4,weight=1);win.columnconfigure(4,weight=2) win.rowconfigure(5,weight=1);win.columnconfigure(5,weight=2) def create_user_screen(): global amount_text global amount_label global transaction_text_widget global balance_var # ----- Row 0 ----- # FedUni Banking label here. Font size should be 24. tk.Label(win,text="FedUni Banking",font="None 24").grid(row=0,column=0,columnspan=5,sticky="nsew") # ----- Row 1 ----- # Account number label here tk.Label(win,text="Account Number: "+user_number_var.get()).grid(row=1,column=0,sticky="nsew") # Balance label here balance_label.grid(row=1,column=1,sticky="nsew") # Log out button here tk.Button(win,text = "Log Out" ,command=save_and_log_out).grid(row=1,column=2,columnspan=2,sticky="nsew") # ----- Row 2 ----- # Amount label here tk.Label( win,text = "Amount :" ).grid( row=2 , column=0,sticky = "nsew" ) # Amount entry here amount_entry.grid( row=2 , column=1,sticky="nsew") # Deposit button here tk.Button(win,text="Deposit", command = perform_deposit ,width=11).grid(row=2, column=2,sticky="nsew") # ----- Row 3 ----- # Entry type label here tk.Label(win,text="Entry Type : ").grid(row=3,column=0,sticky="nsew") # Entry drop list here DD = OptionMenu(win,entryType, "Food", "Rent", "Bills","Entertainment","Other") DD.grid(row=3,column=1,sticky="nsew") # Add entry button here tk.Button(win,text="Entry Add", command = perform_transaction ,width=11).grid(row=3, column=2,sticky="nsew") # ----- Row 4 ----- # Declare scrollbar (text_scrollbar) here (BEFORE transaction text widget) ScrollBar=tk.Scrollbar(win) ScrollBar.grid(sticky="ns",columnspan=8,row=4,column=4) # Add transaction Text widget and configure to be in 'disabled' mode so it cannot be edited. transaction_text_widget['wrap']=tk.NONE;transaction_text_widget['bd']=0;transaction_text_widget['state']='disabled' # Note: Set the yscrollcommand to be 'text_scrollbar.set' here so that it actually scrolls the Text widget transaction_text_widget['yscrollcommand']=ScrollBar.set;transaction_text_widget.grid(row=4,column=0,columnspan=8,sticky="nsew") # Note: When updating the transaction text widget it must be set back to 'normal mode' (i.e. state='normal') for it to be edited ScrollBar.config(command=transaction_text_widget.yview)#in Y directions transaction_text_widget['state']='normal';transaction_text_widget.delete(0.0,tk.END) transaction_text_widget.insert(tk.END,user.get_transaction_string());transaction_text_widget['state']='disabled' # ----- Row 5 - Graph ----- # Call plot_spending_graph() here to display the graph plot_spending_graph() # ----- Set column & row weights ----- # Set column and row weights here - there are 6 rows and 5 columns (numbered 0 through 4 not 1 through 5!) #configuring all rows in 1 line win.rowconfigure(0,weight=0);win.rowconfigure(1,weight=0);win.rowconfigure(2,weight=0);win.rowconfigure(3,weight=0);win.rowconfigure(4,weight=0);win.rowconfigure(5,weight=1); #configuring all columns in 1 line win.columnconfigure(0,weight=0);win.columnconfigure(1,weight=0);win.columnconfigure(2,weight=1) # ---------- Display Login Screen & Start Main loop ---------- create_login_screen() win.mainloop()
d9efba93e5ae91967d45061d4a281af3fea3e0ee
cpita/TicTacToeAI
/core/policies.py
6,060
3.515625
4
import numpy as np import random from core.models import NeuralNetwork class Policy: def __init__(self, env): """Initialize Policy by saving the environment as an instance variable and assigning it a turn""" self.environment = env self.turn = None self.model = None def sample(self, state): """Samples an action given a state""" def collect(self, state, action, reward): """Stores in memory a state, an action and a reward""" pass def update(self): """Performs any updates needed""" pass class NeuralNetPolicy(Policy): def __init__(self, env, hidden_layers, alpha=.01, gamma=.95, alpha_decay_factor=None, eps_decay_factor=None, trainable=True): """Initializes the Policy :param env: Environment the policy acts on :type env: TicTacToe :param hidden_layers: List of the number of neurons per hidden layer :type hidden_layers: list[int] :param alpha: Learning rate of the neural net :type alpha: float :param gamma: Discount factor the policy uses :type gamma: float :param alpha_decay_factor: Multiplicative decay factor to apply to alpha after a gradient descent update. No decay applied by default :type alpha_decay_factor: float or None :param eps_decay_factor: Multiplicative decay factor to apply to epsilon after a policy update. No eps-greedy applied by default :type eps_decay_factor: float or None :param trainable: Weather we want to train this net or not :type trainable: bool """ super().__init__(env) self.afterstate_values = {} self.afterstate_visits = {} self.states_actions_rewards = [] self.gamma = gamma self.model = NeuralNetwork(self.environment.state_dimension, *hidden_layers, 1, alpha=alpha, decay_factor=alpha_decay_factor) if eps_decay_factor: self.epsilon = .9 self.eps_decay_factor = eps_decay_factor else: self.epsilon = None self.trainable = trainable def sample(self, state): """Samples an action given a state :param state: Tuple of 9 integers representing the state of the game :type state: tuple[int] :return: The desired action to perform, ranging from 0 to 8 :rtype: int """ if self.epsilon: if np.random.rand() < self.epsilon: return np.random.choice(self.environment.get_action_space(state)) actions = self.environment.get_action_space(state) random.shuffle(actions) best_afterstate_value = float('-inf') for action in actions: afterstate = self.environment.get_afterstate(state, action, self.turn) afterstate_value = self.model.predict(np.array(afterstate, dtype=np.float64).reshape([self.environment.state_dimension, 1])) if afterstate_value > best_afterstate_value: best_action = action best_afterstate_value = afterstate_value return best_action def collect(self, state, action, reward): """Stores in memory a state, an action and a reward obtained in one timestep""" self.states_actions_rewards.append((state, action, reward)) def update(self): """Performs a Monte Carlo update of the afterstate estimates once the episode has finished""" G = 0 for state, action, reward in reversed(self.states_actions_rewards): G = reward + self.gamma * G afterstate = self.environment.get_afterstate(state, action, self.turn) old_value = self.afterstate_values.get(afterstate, 0) no_visits = self.afterstate_visits.get(afterstate, 0) + 1 self.afterstate_visits[afterstate] = no_visits new_value = old_value + (1/no_visits) * (G - old_value) self.afterstate_values[afterstate] = new_value self.states_actions_rewards = [] def update_gradient(self): """Updates the gradient using the encountered afterstates so far and their corresponding Monte Carlo estimates of their values. It then clears these estimates, as the policy has changed and so has the value function. It also decays epsilon if using eps-greedy""" X = np.array(list(self.afterstate_values.keys()), dtype=np.float64) Y = np.array(list(self.afterstate_values.values())) if self.trainable: self.model.gd_step(X.T, Y) self.afterstate_visits = {} self.afterstate_values = {} if self.epsilon: self.epsilon *= self.eps_decay_factor class RandomPolicy(Policy): def sample(self, state): """Samples a random action from a given state""" return np.random.choice(self.environment.get_action_space(state)) class OneStepPolicy(Policy): def sample(self, state): """Samples the action that yields the best immediate reward from a given state. It only considers afterstates, not the moves the opponent might make afterwards""" actions = self.environment.get_action_space(state) random.shuffle(actions) best_afterstate_value = float('-inf') for action in actions: afterstate = self.environment.get_afterstate(state, action, self.turn) afterstate_value = (self.environment.get_reward_player1( grid=np.array(afterstate)) or 0) * self.environment.turn if afterstate_value > best_afterstate_value: best_action = action best_afterstate_value = afterstate_value return best_action class HumanPolicy(Policy): def sample(self, state): """Samples an action from a state with User input""" actions = self.environment.get_action_space(state) print('Possible actions: ', actions) return int(input('Input your action'))
7c940724f574a955fe8d85b60d7a84e7c4b45a74
ramyasutraye/Guvi_Python
/set3/21.py
175
3.953125
4
n=int(input("Enter the n value:")) a=int(input("Enter the a value:")) d=int(input("Enter the d value:")) sum = 0 for i in range(0,n): sum+= a a+= d i = i + 1 print(sum)
81daa8cb68d4a32340825345c86d011fee09b239
hyuhyu2001/Python_oldBoy
/src/Day001/variable.py
1,975
3.640625
4
#-*- coding: UTF-8 -*- #变量variable与常量constant PAI = 3.1415926 x=2 y=3 z=x+2 print id(x) x=5 print x+y print 'z:',z print id(z) print 'x:',x print id(x) #运算 优先级(先乘除,再加减) print 1+1*3/2 print 3/2 #只能等于1,如果想运算准确,需要把3改为浮点数3.0 print 1+1*3.0/2 print (1+1)*3.0/2 print (1+1)*3/2 print 2**32 #求多少次方 print 9.0/2.0 print 9.0//2.0 #双引号里面嵌套单引号 print "hello,my name's alex li" '''1、变量就是可变的,常量就是不变的量; 2、写代码时大写的一般就代表常量,小写的就代表变量 3、第一次是定义X,第二次的X重新修改值" 4、为什么打印时z=2,而不是等于5?每次更改前会有一个内存机制,所以后面更改时会针对原先的内存 通过id指向内存地址,看是否指向相同的内存地址,是完全独立的数据 变量命名规则 1、标识符的第一个字符必须是字母表中的字母(大写或者小写)或者一个下划线(“_”) 2、标识符名称的其他部分可以由字母(大写或者小写)、下划线(“_”)或者数字(0-9)组成 3、标识符是对大小写敏感的,例如myname和myName不是同一个标识符 4、有效标识符名称的例子:_my_name、name_23和alb2_c3 无效标识符的例子有2things(数字开头)、this is spaced out(空格) 和 my-name(横杠代表是减号) 5、起变量的风格:定义变量为了以后来调用,变量存储什么东西能明确出来,尽量用名词,尽量分开,比如task_detail,TaskDetail,taskDetail 二进制十进制十六进制的转换 计算机中0表示False假 ,1表示为True 6、单行注释 一个# ;多行注释 前后个 三个单引号,只要前后有3个单引号就行,中间的不用关心 7、单引号与双引号的区别:没区别,但是单引号外面嵌套时,需要用双引号 '''
3c5b6c7f8dfb18069c0c9dc4542270a047110d0d
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/shrdan007/question4.py
1,110
3.65625
4
# histogram output of marks # Danielle Sher from collections import Counter marks = input("Enter a space-separated list of marks:\n") marklist = marks.split() symbol_list = [] for i in marklist: if int(i) < 50: symbol_list.append('F') elif 50 <= int(i) < 60: symbol_list.append('3') elif 60 <= int(i) < 70: symbol_list.append('2-') elif 70 <= int(i) < 75: symbol_list.append('2+') elif 75 <= int(i) <= 100: symbol_list.append('1') counts = Counter(symbol_list) keys = counts.keys() values = counts.values() if '1' in counts == False: print ("1" + " " + "|") else: print("1" + " " + "|" + "X"*counts['1']) if '2+' in counts == False: print("2+" + "|") else: print("2+" + "|" + "X"*counts['2+']) if '2-' in counts == False: print("2-" + "|") else: print("2-" + "|" + "X"*counts['2-']) if '3' in counts == False: print("3" + " " + "|") else: print("3" + " " + "|" + "X"*counts['3']) if 'F' in counts == False: print("F" + " " + "|") else: print("F" + " " + "|" + "X"*counts['F'])
8939eb5fbec2b210d7f7a4bde004f8fc5ba12a6c
singto4/Building-a-recommender-system
/Program.py
5,220
4.03125
4
#Dataframe manipulation library. import pandas as pd #Reading The Data: movies_data = 'movies.csv' #Setting max-row display option to 20 rows. pd.set_option('display.max_rows', 20) #Defining additional NaN identifiers. missing_values = ['na','--','?','-','None','none','non'] #Then we read the data into pandas data frames. movies_df = pd.read_csv(movies_data, na_values=missing_values) print(movies_df) #Data Cleaning and Pre-processing: #movies_df data set: #Using regular expressions to find a year stored between parentheses #We specify the parentheses so we don't conflict with movies that have years in their titles. movies_df['year'] = movies_df.title.str.extract('(\(\d\d\d\d\))',expand=False) #Removing the parentheses. movies_df['year'] = movies_df.year.str.extract('(\d\d\d\d)',expand=False) #Note that expand=False simply means do not add this adjustment as an additional column to the data frame. #Removing the years from the 'title' column. movies_df['title'] = movies_df.title.str.replace('(\(\d\d\d\d\))', '') #Applying the strip function to get rid of any ending white space characters that may have appeared, using lambda function. movies_df['title'] = movies_df['title'].apply(lambda x: x.strip()) #Every genre is separated by a | so we simply have to call the split function on |. movies_df['genres'] = movies_df.genres.str.split('|') #Filling year NaN values with zeros. movies_df.year.fillna(0, inplace=True) #Converting columns year from obj to int16 and movieId from int64 to int32 to save memory. movies_df.year = movies_df.year.astype('int16') movies_df.movieId = movies_df.movieId.astype('int32') #First let's make a copy of the movies_df. movies_with_genres = movies_df.copy(deep=True) #Let's iterate through movies_df, then append the movie genres as columns of 1s or 0s. #1 if that column contains movies in the genre at the present index and 0 if not. x = [] for index, row in movies_df.iterrows(): x.append(index) for genre in row['genres']: movies_with_genres.at[index, genre] = 1 #Filling in the NaN values with 0 to show that a movie doesn't have that column's genre. movies_with_genres = movies_with_genres.fillna(0) #Content-Based Recommender System: #Creating User’s Profile #So on a scale of 0 to 5, with 0 min and 5 max, see User’s movie ratings below. User_movie_ratings = [ {'title':'Predator', 'rating':4.9}, {'title':'Final Destination', 'rating':4.9}, {'title':'Heat', 'rating':4}, {'title':"Beverly Hills Cop", 'rating':3}, {'title':'Exorcist, The', 'rating':4.8}, {'title':'Waiting to Exhale', 'rating':3.9}, {'title':'Jumanji', 'rating':4.5}, {'title':'Toy Story', 'rating':5.0} ] User_movie_ratings = pd.DataFrame(User_movie_ratings) #Let’s add movie Id to User_movie_ratings by extracting the movie IDs from the movies_df data frame above. #Extracting movie Ids from movies_df and updating User_movie_ratings with movie Ids. User_movie_Id = movies_df[movies_df['title'].isin(User_movie_ratings['title'])] #Merging User movie Id and ratings into the User_movie_ratings data frame. #This action implicitly merges both data frames by the title column. User_movie_ratings = pd.merge(User_movie_Id, User_movie_ratings, on='title') #Dropping information we don't need such as genres User_movie_ratings = User_movie_ratings.drop(['genres'], 1) #Learning User’s Profile #filter the selection by outputing movies that exist in both User_movie_ratings and movies_with_genres. User_genres_df = movies_with_genres[movies_with_genres.movieId.isin(User_movie_ratings.movieId)] #Clean User_genres_df #First, let's reset index to default and drop the existing index. User_genres_df.reset_index(drop=True, inplace=True) #Next, let's drop redundant columns(1) User_genres_df.drop(['movieId', 'title', 'genres', 'year'], axis=1, inplace=True) #Building User’s Profile #Let's find the dot product of transpose of User_genres_df by User rating column. User_profile = User_genres_df.T.dot(User_movie_ratings.rating) #Deploying The Content-Based Recommender System. #let's set the index to the movieId. movies_with_genres = movies_with_genres.set_index(movies_with_genres.movieId) #Deleting four unnecessary columns. movies_with_genres.drop(['movieId','title','genres','year'], axis=1, inplace=True) #Multiply the genres by the weights and then take the weighted average. recommendation_table_df = (movies_with_genres.dot(User_profile)) / User_profile.sum() #Let's sort values from great to small recommendation_table_df.sort_values(ascending=False, inplace=True) #first we make a copy of the original movies_df copy = movies_df.copy(deep=True) #Then we set its index to movieId copy = copy.set_index('movieId', drop=True) #Next we enlist the top 20 recommended movieIds we defined above top_20_index = recommendation_table_df.index[:20].tolist() #finally we slice these indices from the copied movies df and save in a variable recommended_movies = copy.loc[top_20_index, :] print(recommended_movies)
4b473d85c85f8398a6fe1ddf9467a0b9e9da954a
burman05/Square-Collector
/main.py
3,030
3.921875
4
import pygame # Keyboard Constants from pygame.locals import * # Import Coin from getcoin import Coin # Create Screen pygame.display.init() # Set Dimensions of the display # Get "Surface Object" to Draw on screen = pygame.display.set_mode((800, 600)) # Pygame works based on these Surface Objects # Rendered sprites are placed on Surface in rectangular areas # Create Rectangle For Player player = pygame.Rect(400, 300, 30, 30) # define speed variables for Player speed_x = 0 speed_y = 0 # define Colors WHITE = pygame.Color(255, 255, 255) BLACK = pygame.Color(0, 0, 0) BLUE = pygame.Color(0,255,255) RED = pygame.Color(255, 0, 0) # Clock for FPS clock = pygame.time.Clock() # Add Movement Functions def move_up(): global speed_y speed_y = 10 def move_right(): global speed_x speed_x = 10 def move_down(): global speed_y speed_y = -10 def move_left(): global speed_x speed_x = -10 # Funciton called every loop to move player def movement_loop(): global speed_x, speed_y, player player.centerx += speed_x # Remember that Y is reversed! player.centery -= speed_y speed_x = 0 speed_y = 0 ## Add Coins # add a Score score = 0 # add a list to keep track of the coins list_of_coins = [] # Spawn 100 coins for i in range(100): list_of_coins.append(Coin()) # Check Collision For Each Coin def collision_loop(): global list_of_coins global player global score # For each coin in game for coin in list_of_coins: # If collided rectangles and is not already hidden if player.colliderect(coin.rect) and coin.isHidden == False: # Hide and add 1 to score coin.isHidden = True score += 1 def render_coin_loop(screen): global list_of_coins global YELLOW for coin in list_of_coins: if coin.isHidden == False: screen.fill(BLACK, coin.rect) ## SHOW TEXT ON SCREEN pygame.font.init() FONT = pygame.font.SysFont("freeserif", 36) # Loop Forever! In Main def main(): global FONT, score while True: # detect events for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) # Another Way to Get Keyboard Input # Pump Events (Prepare "key" structure) pygame.event.pump() key = pygame.key.get_pressed() # Defined by pygame.locals if key[K_UP]: move_up() if key[K_RIGHT]: move_right() if key[K_DOWN]: move_down() if key[K_LEFT]: move_left() # call movement function movement_loop() # call collision function collision_loop() # Tick Clock (60 FPS) clock.tick(60) # Fill screen with blue screen.fill(BLUE) screen.fill(RED, player) # render coins render_coin_loop(screen) # Render Score screen.blit( FONT.render("Score: " + str(score), True, BLACK), (20, 80) ) # Get Time seconds = int(pygame.time.get_ticks() / 1000) screen.blit( FONT.render("Time: " + str(seconds), True, BLACK), (640, 80) ) pygame.display.flip() main()
7ef470027cc0c7e9a7f9001b020346793cb606ba
captainmoha/MITx-6.00.1x
/Week 4/exceptions.py
250
3.734375
4
def divide(x, y): try: result = x / y except ZeroDivisionError,e: print "Division by zero! " + str(e) except TypeError: divide(int(x), int(y)) else: print "result is " + str(result) finally: print "Excuting finally clause"
4ecf0f0372429ba70ca2e16c5961c353eb47ad75
hikoyoshi/hello_python
/example_3.py
367
3.953125
4
#!-*- coding:utf-8 -*- print "算算看你有沒有過重" w = input("請輸入體重:\n") h = input("請輸入身高(cm):\n") bmi = w /((h/100.0)**2) print "你的bmi是",bmi if bmi<18.5: print ("過輕") elif bmi>=18.5 and bmi <24: print ("正常體重") elif bmi>24 and bmi <27: print ("有點過重") else: print ("小胖該減肥了......")
2fac602b7f7cda44ac5446f422095c77e57e0f01
hejackson/46-simple-python
/simple.py
16,379
3.59375
4
#!/usr/local/bin/python3 import re import functools import os import time import random import requests import itertools import sys import bs4 def max_new(a, b): if a > b: return a elif b > a: return b else: return a def max_of_three(a, b, c): """ Either a, b or c is max, or they're all equal """ if a > b and a > c: return a elif b > a and b > c: return b elif c > a and c > b: return c else: return a def length_of_thing(thing): x = 0 for item in thing: x += 1 return x def is_a_vowel(character): if character.lower() in 'aeiouy': return True else: return False def translate(string): new_string = '' for c in string: if is_a_vowel(c): new_string += c elif c.isalpha(): new_string += c + 'o' + c else: new_string += c return new_string def sum(list): x = 0 for item in list: x += item return x def multiply(list): x = 1 for item in list: x *= item return x def reverse(string): return string[::-1] def is_palindrome(string): if string == reverse(string): return True else: return False def is_member(x, a): for item in a: if x == item: return True return False def overlapping(a, b): for item in a: for other in b: if other == item: return True return False def generate_n_chars(n, c): string = '' for x in range(n): string += c return string def historgram(list): for x in list: print(generate_n_chars(x, '*')) def max_in_list(list): if len(list) > 0: max = list[0] else: return None if len(list) > 1: for item in list[1:]: if item > max: max = item return max def map_words_to_len(words): result = {} for item in words: try: result[len(item)].append(item) except KeyError: result[len(item)] = [item] return result def find_longest_word(list): if len(list) > 0: max = len(list[0]) else: return None if len(list) > 1: for word in list: if len(word) > max: max = len(word) return max def filter_long_words(words, n): result = [] for item in words: if len(item) > n: result.append(item) return result def palindrome2(phrase): alpha_string = '' for c in phrase: if c.lower().isalpha(): alpha_string += c.lower() return is_palindrome(alpha_string) def pangram(phrase): # define list of lower case characters, taken from comment on # https://stackoverflow.com/questions/16060899/alphabet-range-python alphabet = set(map(chr, range(ord('a'), ord('z') + 1))) newset = set() for c in phrase: if c.isalpha(): newset.add(c.lower()) return alphabet == newset def bottles_of_beer(): for x in range(99, 0, -1): print('{} bottles of beer on the wall, {} bottles of beer.' .format(x, x)) print('Take one down, pass it around, {} bottles of beer on the wall' .format(x - 1)) print() def translate2(phrase): """ doesn't yet handle phrases like 'christmas!' """ result_list = [] eng_to_swed = { 'merry': 'god', 'christmas': 'jul', 'and': 'och', 'happy': 'gott', 'new': 'nytt', 'year': 'år' } for word in phrase.split(): if word.lower() in eng_to_swed: result_list.append(eng_to_swed[word.lower()]) else: result_list.append(word.lower()) return ' '.join(result_list) def char_freq(string): freq = {} for c in string: try: freq[c] += 1 except KeyError: freq[c] = 1 return freq def rot13(phrase): cipher = { 'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q', 'e': 'r', 'f': 's', 'g': 't', 'h': 'u', 'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y', 'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c', 'q': 'd', 'r': 'e', 's': 'f', 't': 'g', 'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k', 'y': 'l', 'z': 'm', 'A': 'N', 'B': 'O', 'C': 'P', 'D': 'Q', 'E': 'R', 'F': 'S', 'G': 'T', 'H': 'U', 'I': 'V', 'J': 'W', 'K': 'X', 'L': 'Y', 'M': 'Z', 'N': 'A', 'O': 'B', 'P': 'C', 'Q': 'D', 'R': 'E', 'S': 'F', 'T': 'G', 'U': 'H', 'V': 'I', 'W': 'J', 'X': 'K', 'Y': 'L', 'Z': 'M' } decode = '' for c in phrase: if c.isalpha(): decode += cipher[c] else: decode += c return decode def correct(phrase): a = re.sub('\.', ' ', phrase) b = re.sub(' +', ' ', a) return b def endswitch(word): if word[-1].lower() == 'y': return word[:-1] + 'ies' elif word[-1].lower() in ['o', 's', 'x', 'z']: return word + 'es' elif word[-2:].lower() in ['ch', 'sh']: return word + 'es' else: return word + 's' def make_ing_form(word): if word.lower()[-2:] == 'ie': return word[:-2] + 'ying' elif word.lower()[-1] == 'e': if word.lower() != 'be' and word.lower()[-2:] != 'ee': return word[:-1] + 'ing' else: return word + 'ing' elif word.lower()[-3] not in 'aeiouy': if word.lower()[-2] in 'aeiouy': if word.lower()[-1] not in 'aeiouy': return word + word[-1] + 'ing' else: return word + 'ing' def max_in_list2(list): # stolen from http://www.python-course.eu/python3_lambda.php result = functools.reduce(lambda a, b: a if (a > b) else b, list) return result def mapit1(words): list = {} for word in words: try: list[len(word)].append(word) except KeyError: list[len(word)] = [word] return list def mapit2(words): return list(map(len, words)) def mapit3(words): return [len(x) for x in words] def find_longest_word2(words): return max([len(x) for x in words]) def filter_long_words2(words, n): return [x for x in words if len(x) > n] def palindrome3(file): with open(file, 'r') as infile: for text in infile: text = text.strip() if palindrome2(text): print(text) print() def semordnilap(file): # create set to keep first word of all semos found # create and populate set for all words in file # walk through each word and add first word of all semos to semos list semos = set() words = set() with open(file, 'r') as infile: for text in infile: text = text.strip() words.add(text) for word in words: # is this word already in semos set? if word not in semos and word[::-1] not in semos: # is this word and it's reverse in the list of words? if word[::-1] in words: semos.add(word) for word in semos: print('{} {}'.format(word, word[::-1])) def char_freq_table(file): letters = {} with open(file, 'r') as infile: for line in infile: line = line.strip() for c in line: if c.isalpha(): try: letters[c] += 1 except KeyError: letters[c] = 1 return letters def speak_ICAO(phrase): d = {'a': 'alfa', 'b': 'bravo', 'c': 'charlie', 'd': 'delta', 'e': 'echo', 'f': 'foxtrot', 'g': 'golf', 'h': 'hotel', 'i': 'india', 'j': 'juliett', 'k': 'kilo', 'l': 'lima', 'm': 'mike', 'n': 'november', 'o': 'oscar', 'p': 'papa', 'q': 'quebec', 'r': 'romeo', 's': 'sierra', 't': 'tango', 'u': 'uniform', 'v': 'victor', 'w': 'whiskey', 'x': 'x-ray', 'y': 'yankee', 'z': 'zulu'} a = .2 b = .5 for c in phrase: if c.isalpha(): c = c.lower() os.system('say ' + d[c]) time.sleep(a) else: time.sleep(b) def hapax(file): words = {} with open(file, 'r') as infile: for line in infile: line = line.strip() for word in line.split(): word = re.sub('[\W_]', '', word) try: words[word.lower()] += 1 except KeyError: words[word.lower()] = 1 for word in sorted(words): if words[word] == 1: print(word) def number_lines(file, file2): line_number = 1 with open(file, 'r') as infile: with open(file2, 'w') as outfile: for line in infile: outfile.write('{}: {}'.format(line_number, line)) line_number += 1 def average_word_length(file): number_of_words = 0 length_of_all_words = 0 with open(file, 'r') as infile: for line in infile: line = line.strip() for word in line.split(): word = re.sub('[\W_]', '', word) number_of_words += 1 length_of_all_words += len(word) return length_of_all_words / number_of_words def guess_number(): name = input('Hello! What is your name? ') print('Well, {}, I am thinking of a number between 1 and 20.'.format(name)) number = random.randint(1, 20) guess = 999 number_of_guesses = 0 while guess != number and number_of_guesses < 10: print('Take a guess.') guess = int(input()) number_of_guesses += 1 if guess > number: print('Your guess is too high.') elif guess < number: print('Your guess is too low.') else: print('Good job, {}! You guessed my number in {} guesses!'. format(name, number_of_guesses)) break def anagram(words): word = words[random.randint(0, len(words) - 1)] scramble = ''.join(random.sample(word, len(word))) print('Word anagram: {}'.format(scramble)) guess = '' number_of_guesses = 0 while guess != word and number_of_guesses < 10: print('Guess the word!') guess = input() number_of_guesses += 1 if guess == word: print('Correct!') break def lingo(word): guess = '' while guess != word: guess = input('Please enter your {} character guess: ' .format(len(word))) result = '' for x in range(len(guess)): if guess[x].lower() == word[x].lower(): result += '[' + guess[x] + ']' elif guess[x].lower() in word.lower(): result += '(' + guess[x] + ')' else: result += guess[x] print('Clue: {}'.format(result)) def sentence_splitter(text): # taken from: # https://github.com/R4meau/46-simple-python-exercises/blob/master/exercises/ex42.py # Add newline to sentences ending in period, but not if Mr., Mrs., Dr. # new = re.sub(r'(?<!Mr)(?<!Mrs)(?<!Dr)\.\s([A-Z])', r'.\n\1', text) pattern = re.compile(r""" (?<!Mr) # ignore Mr. (?<!Mrs) # ignore Mrs. (?<!Dr) # ignore Dr. \. # match a period, follwed by \s+ # one or more spaces, followed by ([A-Z]) # A CAPITAL letter, saving letter """, re.VERBOSE) new = re.sub(pattern, r'.\n\1', text) # replace ! or ? with same, followed by newline # -- this next line didn't work, it didn't put the ! or ? back # new = re.sub(r'([!\?])\s+', '\1\n', new) new = re.sub(r'!\s+', '!\n', new) new = re.sub(r'\?\s+', '?\n', new) return new def anagram2(): url = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' response = requests.get(url) spinner = itertools.cycle(['-', '/', '|', '\\']) results = set() for word in response.text.split(): if len(word) < 7: print('{}...'.format(word)) for x in itertools.permutations(word, len(word)): sys.stdout.write(next(spinner)) sys.stdout.flush() y = ''.join(x) # add newlines to either end of sample 'word' to match # word boundaries present in the response.text output from # the URL. For example: '\nzombie\n' z = '\n' + y + '\n' if y != word and z in response.text: results.add(word + ' : ' + y) sys.stdout.write('\b') print('\n\nDone...\n\n') return results def nested(): text = '' length = 2 * random.randint(1, 5) for x in range(length): r = random.randint(0, 1) if r: text += '[' else: text += ']' open = 0 for c in text: if open >= 0: if c == '[': open += 1 else: open -= 1 if open < 0: break if open != 0: print('{} NOT OK'.format(text)) else: print('{} OK'.format(text)) def spinit(x): spinner = itertools.cycle(['-', '/', '|', '\\']) for i in range(x): sys.stdout.write(next(spinner)) sys.stdout.flush() sys.stdout.write('\b') def pokemon(): url = "https://en.wikipedia.org/wiki/List_of_Pok%C3%A9mon#List" response = requests.get(url) soup = bs4.BeautifulSoup(response.text, 'html.parser') table = soup.findChildren('table') rows = table[0].findChildren('tr') names = [] for row in rows[1:]: names.append(row.find('a', href=True, title=True).string) names = """audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask""".split() # names = ['dog', 'goldfish', 'gecko', 'hipster', 'ostritch'] # names = 'goldfish dog hippopotamus snake elephant tick gecko \ # kangaroo ocelot'.split() print(names) perms = itertools.permutations(names, len(names)) total = len(names) ** len(names) print('There are {0:,} permutations of names.' .format(total)) input('Press [enter | return] to begin...') longest = [] def invalid_word(word, names): for name in names: if name[0].lower() == word[-1].lower(): return True return False def check_last_and_next(current_word, next_word): if current_word[-1].lower() == next_word[0].lower(): return True else: return False def longest_set(permutation): current_list = [] current_word = permutation[0] current_list.append(current_word) if current_word in bad_words: return current_list for word in permutation[1:]: if current_word in bad_words: return current_list if check_last_and_next(current_word, word): current_list.append(word) current_word = word else: return current_list return current_list bad_words = [] for name in names: if invalid_word(name, names) is False: bad_words.append(name) for p in perms: if p[0] in bad_words: pass else: print(longest) current_set = longest_set(p) if len(current_set) > len(longest): longest = current_set print('LONGEST: {} {}'.format(len(longest),longest)) if __name__ == '__main__': pass
f9bf7663c3321f1d6e774b96c99b219f081bdade
wanggalex/leetcode
/LinkedList/141_LinkedListCycle.py
790
3.765625
4
# coding: utf8 """ 题目链接: https://leetcode.com/problems/linked-list-cycle/description. 题目描述: Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if not head or not head.next: return False pre = head ptr = head.next while ptr and ptr.next: if pre == ptr: return True pre = pre.next ptr = ptr.next.next return False
f95f8f312f9f606854955b9dd7ab94640e7574c6
mcbunkus/scripts
/sym
3,595
4.375
4
#!/usr/bin/env python3 """ sym v0.1 A small utility for integrating or differentiating functions. sym uses 'operators' to decide what to do with an expression. For example: sym 't => 2t' will integrate '2 * t' sym 't -> 2t' will differentiate '2 * t' The arrows in the expression are the operators. The variable on the left of an operator is the variable you wish to integrate with respect to, and on the right is the equation itself. Usage: integ EXPR [RANGE...] [-n] Arguments: EXPR sym 't -> t^2' = t^3 / 3 RANGE (x₀ x) sym 't -> t^2' 0 1 = 1 / 3 Options: --help Display this help message -n Normal equation output Operators: => Integrate the given expression -> Differentiate the expression """ EXPR = "EXPR" VALUES = "RANGE" import re from sys import stderr from docopt import docopt from sympy import integrate, diff, Symbol, pprint from sympy.core import sympify def unpackage_expression(arg_list): """ Extract the variable the user is performing an operation on and the expression itself, strip them of whitespace, and convert them to appropriate types. In this, var is a sympy symbol and expr is returned as a sympy function. """ if len(arg_list) != 2: raise ValueError("Expression has more than one operator") vars = [Symbol(x.strip()) for x in arg_list[0].split(",")] # x, y => ... expr = expand_expression(arg_list[1].strip()) return (vars, sympify(expr)) def expand_expression(expr): """ Take user input and convert it to something sympy can use, for example, 2x * x^2 becomes 2*x * x**2 """ # expand_mult is a function that re.sub uses to convert values like # 2t to 2 * t, etc expand_mult = lambda group: group[1] + "*" + group[2] expr = re.sub("([\d.]+)(\w)", expand_mult, expr).replace("^", "**") return expr def run_differentiation(expr, vars, norm): for i, var in enumerate(vars): result = diff(expr, var) if not norm: print(f"df({var}):") pprint(result) else: print(f"df({var}):\t{result}") if i != len(vars) - 1: print() def run_integration(func, vars, values, norm): for i, var in enumerate(vars): if values: result = integrate(func, (var, values[0], values[1])) print(f"∫ f({values[0]}, {values[1]}) d{var}:") pprint(result) else: result = integrate(func, var) if not norm: print(f"∫ f({var}) d{var}:") pprint(result) else: print(f"∫ f({var}) d{var}:\t{result}") if i != len(vars) - 1: print() def main(**kwargs): """ Parse the input string from the user and decide what operation to do based on the given operator, and catch any exceptions along the way. """ normal_output = kwargs["-n"] expression = kwargs[EXPR] values = kwargs[VALUES] try: operator = re.search("[-=]>", expression).group(0) vars, expr = unpackage_expression(expression.split(operator)) if operator == "->": run_differentiation(expr, vars, normal_output) elif operator == "=>": run_integration(expr, vars, values, normal_output) except ValueError as e: stderr.write(f"{e}: '{expression}'\n") except AttributeError: stderr.write(f"Invalid operator in {expression}\n") if __name__ == "__main__": args = docopt(__doc__) main(**args)
0860c50def3055383f6f1443979a85b632a17f53
sean578/advent_of_code
/2020/day_22.py
3,537
3.703125
4
from collections import deque import copy import sys def load_input(filename): deck1, deck2 = [], [] on_deck_2 = False for line in open(filename).readlines(): if len(line.strip()) == 0: on_deck_2 = True elif line.strip()[0] == 'P': pass else: if on_deck_2: deck2.append(int(line.strip())) else: deck1.append(int(line.strip())) return deque(deck1), deque(deck2) def play_game(deck1, deck2): while deck1 and deck2: c1 = deck1.popleft() c2 = deck2.popleft() if c1 > c2: deck1.append(c1) deck1.append(c2) elif c2 > c1: deck2.append(c2) deck2.append(c1) else: print('We have a match - what to do?') return deck1, deck2 def play_hand(deck1, deck2, winner): """ If winner then use this instead of checking cards """ c1 = deck1.popleft() c2 = deck2.popleft() if winner == '1': deck1.append(c1) deck1.append(c2) elif winner == '2': deck2.append(c2) deck2.append(c1) elif c1 > c2: deck1.append(c1) deck1.append(c2) elif c2 > c1: deck2.append(c2) deck2.append(c1) else: print('We have a match - what to do?') return deck1, deck2 def answer(w): mults = list(range(len(list(w)), 0, -1)) answer = 0 for a, b in zip(w, mults): answer += a*b return answer def play_recursive_ok(deck1, deck2): """ Determine whether to play a recursive game """ if len(deck1) > deck1[0] and len(deck2) > deck2[0]: return True else: return False def in_infinite_loop(deck1, deck2, states): """ Check if stuck in an infinite loop """ for s in states: if tuple(deck1) == s[0] and tuple(deck2) == s[1]: return True return False def copy_cards_for_subgame(deck1, deck2): d1 = copy.deepcopy(deck1) d2 = copy.deepcopy(deck2) num_cards_d1 = d1.popleft() num_cards_d2 = d2.popleft() d1 = deque(list(d1)[:num_cards_d1]) d2 = deque(list(d2)[:num_cards_d2]) return d1, d2 def play_recursive_game(deck1, deck2, states, num_games): num_games += 1 # print(num_games) # if a deck is empty - finish if len(list(deck1)) == 0: winner = '2' return deck1, deck2, winner, num_games elif len(list(deck2)) == 0: winner = '1' return deck1, deck2, winner, num_games if in_infinite_loop(deck1, deck2, states): winner = '1' return deck1, deck2, winner, num_games else: states.add((tuple(deck1), tuple(deck2))) # Check if enough cards left to play recursive game if play_recursive_ok(deck1, deck2): d1, d2 = copy_cards_for_subgame(deck1, deck2) d1, d2, winner, num_games = play_recursive_game(d1, d2, set(), num_games) deck1, deck2 = play_hand(deck1, deck2, winner) else: deck1, deck2 = play_hand(deck1, deck2, False) return play_recursive_game(deck1, deck2, states, num_games) if __name__ == '__main__': sys.setrecursionlimit(22000) filename = 'day_22.txt' states = set() deck1, deck2 = load_input(filename) deck1, deck2, w, num_games = play_recursive_game(deck1, deck2, states, 0) if w == '1': answer_part2 = answer(deck1) else: answer_part2 = answer(deck2) print('Answer part 2', answer_part2) print('It took', num_games, 'calls')
b8d716b39ec8ebeffbc2bde487b28b7087d4f793
DanMayhem/project_euler
/003.py
560
3.734375
4
#!python """ The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ class PrimeFactors(): def __init__(self, x): self.x = x self.pfp = 1 def __iter__(self): return self def __next__(self): y = self.x / self.pfp if y == 1: raise StopIteration() #find the next factor of y. the least factor of a composite must be prime i = 2 while(i<=y): if y%i == 0: self.pfp = self.pfp * i return i i = i+1 if __name__=='__main__': print(max(PrimeFactors(600851475143)))
51e8275f23404b234cd369541a4a20b07c3a9c25
moxiaoyu007/only_path_in_a_DAG
/Monlypath.py
4,385
3.515625
4
from collections import defaultdict from heapq import * import sys import numpy from numpy import * def dijkstra_raw(edges, from_node, to_node): # edges : ( from_node, to_node, weight of links (j,i)) g = defaultdict(list) #build a dict whose values are lists as a default value. for l,r,c in edges: g[l].append((c,r)) # g = {l: (c1, r1), (c2, r2) }, g contains all the edges . q, seen = [(0,from_node,())], set() # () is a set. while q: (cost,v1,path) = heappop(q) # heappop(q) : delete the smallest one in heap q, and return it # v1 is the from_node now and path is the path now if v1 not in seen: seen.add(v1) path = (v1, path) if v1 == to_node: Only_path = True # if reach the to_node, return the cost and the path. #print (list(q)) for wanted_path in list(q): ###print (wanted_path) ###print (wanted_path[1]) if wanted_path[1] == to_node: Only_path = False print ('there is more than one path from node %s to node %s\n' % (from_node, to_node)) #wanted_path[2] = (v1, wanted_path[2]) print ('one of other pathes is :', wanted_path[2]) else: pass if Only_path: print ('there is ONLY ONE PATH from node %s to node %s\n' % (from_node, to_node)) return cost, path for c, v2 in g.get(v1, ()): # dict.get(key, defalut) : return the value of key, if key is not here , return default # get all the target_nodes of source_node now, v1. # c is the cost of path(v1->v2), if v2 not in seen: # if v2 have not been seen ,in the seen set, push (cost+c, v2, path) to the heap. # this loop push all target_nodes that have not been seen of source_node v1 to he heap q. heappush(q, (cost+c, v2, path)) print ('there is - NO PATH - from node %s to node %s !!!\n' % (from_node, to_node)) return float("inf"),[] # if there is no path between from_node and to_node, the cost is infinite and past is null. def dijkstra(edges, from_node, to_node): len_shortest_path = -1 ret_path=[] length, path_queue = dijkstra_raw(edges, from_node, to_node) ###print (path_queue) if len(path_queue)>0: len_shortest_path = length ## 1. Get the length firstly; ## 2. Decompose the path_queue, to get the passing nodes in the shortest path. left = path_queue[0] ret_path.append(left) ## 2.1 Record the destination node firstly; right = path_queue[1] while len(right)>0: left = right[0] ret_path.append(left) ## 2.2 Record other nodes, till the source-node. right = right[1] ret_path.reverse() ## 3. Reverse the list finally, to make it be normal sequence. return len_shortest_path,ret_path ### ==================== Given a list of nodes in the topology shown in Fig. 1. list_nodes_id = range(51); ### ==================== Given constants matrix of topology. ### M_topo is the 2-dimensional adjacent matrix used to represent a topology. M_topo = mat(numpy.loadtxt('L1023.txt')) M_topo[10, 1] = -1 #print (M_topo) row, col = M_topo.shape print (row, col) ### --- Read the topology, and generate all edges in the given topology. edges = [] for i in range(row): for j in range(col): if i!=j and int(M_topo[i, j]) == -1 : edges.append((j, i, -int(M_topo[i, j])))### (i,j) is a link; M_topo[i][j] here is -1, the length of link (j,i). ###print ((-int(M_topo[1, 0]) == 1 )) ### === MAIN === ### print ("=== Monlypath ===") src_node = 3 target_node = 1022 print ("Let's figure out if there is A Only_path from node \033[1;35;47m%s\033[0m to node \033[1;35;47m%s\033[0m :\n" % (src_node, target_node)) length,Shortest_path = dijkstra(edges, src_node, target_node) print ('length = ',length) print ('The path is ',Shortest_path) # Print with color #print ("\033[1;35;47m%s\033[0m" % " RED") # #***************************************
dc618dd665ad06dc8e97ec003b3c2d7b8f5f28a1
brunozupp/TreinamentoPython
/exercicios/exercicio075.py
512
4.0625
4
if __name__ == '__main__': tupla = () for i in range(0,4): valor = int(input("Digite um número inteiro = ")) tupla += (valor,) # A) print(f"Apareceu o número 9 um total de {tupla.count(9)} vezes") # B) print(f"O número 3 foi digitado inicialmente na posição {tupla.index(3)}") # C) tuplaNumerosPares = () for numero in tupla: if numero % 2 == 0: tuplaNumerosPares += (numero,) print(f"Números pares = {tuplaNumerosPares}")
46dc064a1e708ccda5e29c3e8ad7e13d25236de4
ConorODonovan/online-courses
/Udemy/Python/Data Structures and Algorithms/LinkedList/class_SingleLinkedList.py
8,876
3.96875
4
class SingleLinkedList: def __init__(self): self.start = None def display_list(self): if self.start is None: print("List is empty") return else: print("List is: ") p = self.start while p is not None: print(p.info, " ", end="") p = p.link print() def count_nodes(self): p = self.start n = 0 while p is not None: n += 1 p = p.link print("Number of nodes in the list = {}".format(n)) def search(self, x): position = 1 p = self.start while p is not None: if p.info == x: print(x, " is at position ", position) return True position += 1 p = p.link else: print(x, " not found in list") return False def insert_in_beginning(self, data): from class_Node import Node temp = Node(data) temp.link = self.start self.start = temp def insert_at_end(self, data): from class_Node import Node temp = Node(data) if self.start is None: self.start = temp return p = self.start while p.link is not None: p = p.link p.link = temp def create_list(self): n = int(input("Enter the number of nodes: ")) if n == 0: return for i in range(n): data = int(input("Enter the element to be inserted: ")) self.insert_at_end(data) def insert_after(self, data, x): from class_Node import Node p = self.start while p is not None: if p.info == x: break p = p.link if p is None: print(x, "not present in the list") else: temp = Node(data) temp.link = p.link p.link = temp def insert_before(self, data, x): from class_Node import Node # If list is empty if self.start is None: print("List is empty") return # x is in first node, new node is to be inserted before first node if x == self.start.info: temp = Node(data) temp.link = self.start self.start = temp return # Find reference to predecessor of node containing x p = self.start while p.link is not None: if p.link.info == x: break p = p.link if p.link is None: print(x, " not present in the list") else: temp = Node(data) temp.link = p.link p.link = temp def insert_at_position(self, data, k): from class_Node import Node if k == 1: temp = Node(data) temp.link = self.start self.start = temp return p = self.start i = 1 while i < k - 1 and p is not None: # find a reference to k-1 node p = p.link i += 1 if p is None: print("You can insert only upto position", i) else: temp = Node(data) temp.link = p.link p.link = temp def delete_node(self, x): if self.start is None: print("List is empty") return # Deletion of first node if self.start.info == x: self.start = self.start.link return # Deletion in between or at the end p = self.start while p.link is not None: if p.link.info == x: break p = p.link if p.link is None: print("Element ", x, "not in list") else: p.link = p.link.link def delete_first_node(self): if self.start is None: return self.start = self.start.link def delete_last_node(self): if self.start is None: return if self.start.link is None: self.start = None return p = self.start while p.link.link is not None: p = p.link p.link = None def reverse_list(self): prev = None p = self.start while p is not None: next = p.link p.link = prev prev = p p = next self.start = prev def bubble_sort_exdata(self): end = None while end != self.start.link: p = self.start while p.link != end: q = p.link if p.info > q.info: p.info, q.info = q.info, p.info p = p.link end = p def bubble_sort_exlinks(self): end = None while end != self.start.link: r = p = self.start while p.link != end: q = p.link if p.info > q.info: p.link = q.link q.link = p if p != self.start: r.link = q else: self.start = q p, q = q, p r = p p = p.link end = p def has_cycle(self): if self.find_cycle() is None: return False else: return True def find_cycle(self): if self.start is None or self.start.link is None: return None slowR = self.start fastR = self.start while fastR is not None and fastR.link is not None: slowR = slowR.link fastR = fastR.link.link if slowR == fastR: return slowR return None def remove_cycle(self): c = self.find_cycle() if c is None: return print("Node at which the cycle was detected is ", c.info) p = c q = c len_cycle = 0 while True: len_cycle += 1 q = q.link if p == q: break print("Length of cycle is: ", len_cycle) len_rem_list = 0 p = self.start while p != q: len_rem_list += 1 p = p.link q = q.link print("Number of nodes not included in the cycle are: ", len_rem_list) length_list = len_cycle + len_rem_list print("Length of the list is: ", length_list) p = self.start for i in range(length_list - 1): p = p.link p.link = None def insert_cycle(self, x): if self.start is None: return p = self.start px = None prev = None while p is not None: if p.info == x: px = p prev = p p = p.link if px is not None: prev.link = px else: print(x, " not present in list") def merge2(self, list2): merge_list = SingleLinkedList() merge_list.start = self._merge2(self.start, list2.start) return merge_list def _merge2(self, p1, p2): if p1.info <= p2.info: startM = p1 p1 = p1.link else: startM = p2 p2 = p2.link pM = startM while p1 is not None and p2 is not None: if p1.info <= p2.info: pM.link = p1 pM = pM.link p1 = p1.link else: pM.link = p2 pM = pM.link p2 = p2.link if p1 is None: pM.link = p2 else: pM.link = p1 return startM def merge_sort(self): self.start = self._merge_sort_rec(self.start) def _merge_sort_rec(self, list_start): # if list empty or has one element if list_start is None or list_start.link is None: return list_start # if more than one element start1 = list_start start2 = self._divide_list(list_start) start1 = self._merge_sort_rec(start1) start2 = self._merge_sort_rec(start2) startM = self._merge2(start1, start2) return startM def _divide_list(self, p): q = p.link.link while q is not None and q.link is not None: p = p.link q = q.link.link start2 = p.link p.link = None return start2
811c339cca06d7413cb70f755c8bcbe676579227
hayabalasmeh/data-structures-and-algorithms.
/data_structures_algorth/challenge_linked_list_insertion/linked_list_insertion.py
3,300
3.96875
4
# Building the class # class Node: # def __init__(self,value = ''): # self.value = value # self.next = None # def __str__(self): # return str(self.value) # class LinkedListInsertion: # def __init__(self): # self.head = None # def append(self,value): # node = Node(value) # if self.head == None: # self.head = node # return #in order to stop here in first time # current = self.head # to tranverse through the list # while current.next: # current = current.next #to tranverse through the nex until reach the null # current.next = node # when the current.next equal to none assign the new obj to it # def add_after(self,value,new_value): # node = Node(new_value) # # if self.head == None: # # self.head = node # current = self.head # while current.next: # #to tranverse through the nex until reach the value # if (current.value == value): # #first you need to keep the refrence for the next node # node.next = current.next # current.next = node # # when the current.next equal to none assign the new obj to it # break # current = current.next # def add_before(self,value,new_value): # node = Node(new_value) # case = False # current = self.head # prev = self.head # if(self.head == None): # next_node = Node(value) # self.head = node # node.next = next_node # while current: # #to tranverse through the nex until reach the value # if(current.value == value): # prev.next = node # node.next = current # case = True # break # # when the current.next equal to none assign the new obj to it # # return # prev = current # current = current.next # # if (current != None): # # node.next = holder.next # # holder.next = node # def __iter__(self): # current = self.head # while current : #as to stop traversing when the node is null # yield current.value #will stop the function and send the node to the caller then make the function complete from where it stopped # current = current.next # def __str__(self): # nodes = self.__iter__() # string = "" # for value in nodes: # string = string + f"{ {value} } -> " # string = string + " Null" # return string # if __name__ == '__main__' : # num = LinkedListInsertion() # num.append(1) # num.append(2) # num.append(3) # num.append(5) # num.add_before(7,6) # # num.add_before(3,4) # ll = LinkedListInsertion() # ll.append(1) # ll.add_after(1,4) # print(ll) # # print(num) # # print(num)
77722a2b2a66358bc2a2284a8ba0e8cb209d3c79
Yang-Jianlin/python-learn
/python数据结构与算法/sixth_chapter/P-6.34.py
775
3.765625
4
from sixth_chapter.stack import ArrayStack def comp(num1, num2, e): if e == '+': return num1 + num2 if e == '-': return num1 - num2 if e == '*': return num1 * num2 if e == '/': return num1 / num2 # 后缀表达式已经将计算的优先顺序排好, # 只需要将后缀表达式的数字逐个入栈,直到遇到符号, # 将前栈顶两个元素运算放回栈顶即可 def comp_postfix(expr): stack = ArrayStack() for e in expr: if e.isnumeric(): stack.push(e) else: num = comp(num2=int(stack.pop()), num1=int(stack.pop()), e=e) stack.push(num) return stack.pop() if __name__ == '__main__': expr = '52+83-*4/5-' print(comp_postfix(expr))
eebbc5dd0eed26afeb039df5dbfd474fb2df66c7
curiosaurus/CTL
/Assignment 2/adivbytwo.py
210
3.828125
4
st=input("Enter the String of As And Bs with no. of As divisible by 2 : ") counta=sum(map(lambda x : 1 if 'a' in x else 0, st)) if (counta%2==0): print("Valid String") else: print("Invalid String")
b6faaebf5e26709b93edc84ff87231eb8388771b
jinaur/codeup
/1901.py
104
3.53125
4
N = int(input()) def myfunc(n) : print(n) if n == N : return myfunc(n-1) myfunc(1)
55deb2bc11f2ed6161f2f3ec58e542096081d8c1
NathanialNewman/ProjectEuler
/problems/1-9/9.py
952
4.21875
4
# Author: Nate Newman # Source: Project Euler Problem 9 # Title: Special Pythagorean Triplet # Description: There exists exactly 1 Pythagorean triplet for which # a + b + c = 1000 # Find the product a*b*c import time # Determines if set of 3 values form a Pythagorean Triple def pythagTriplet(a, b, c): triplets = [a,b,c] triplets.sort() return ((triplets[0]*triplets[0]) + (triplets[1]*triplets[1]) == (triplets[2]*triplets[2])) # Finds 3 numbers that add to 'target' which are a pythagorean triplet def find3SumTarget(target): for i in range(1,target): for j in range(1,target): if pythagTriplet(i,j,(1000-i-j)): return[i,j,(1000-i-j)] if __name__ == "__main__": start = time.time() # Execute code here foundSet = find3SumTarget(1000) print (foundSet[0]*foundSet[1]*foundSet[2]) end = time.time() print "Time to complete: " + str(end-start)
e8757510f01e318dba95862d835874c69e97286d
Jiezhi/myleetcode
/src/11-ContainerWithMostWater.py
1,828
3.875
4
#!/usr/bin/env python """ https://leetcode.com/problems/container-with-most-water/ https://leetcode.com/explore/interview/card/top-interview-questions-hard/116/array-and-strings/830/ Created on 2018-12-13 Updated at 2022/01/04 @author: 'Jiezhi.G@gmail.com' Reference: https://leetcode.com/problems/container-with-most-water/solution/ Difficulty: Medium """ from typing import List class Solution: def maxArea(self, height: List[int]) -> int: """ Updated at 2022/01/04 Runtime: 1491 ms, faster than 5.01% Memory Usage: 27.6 MB, less than 22.34% n == height.length 2 <= n <= 10^5 0 <= height[i] <= 10^4 :param height: :return: """ low, high = 0, len(height) - 1 ret = 0 while low < high: ret = max(min(height[low], height[high]) * (high - low), ret) if height[low] <= height[high]: low += 1 else: high -= 1 return ret def maxArea2(self, height): """ Updated at 2018-12-13 :type height: List[int] :rtype: int """ i = 0 j = len(height) - 1 max_value = 0 top = max(height) while i < j: if top * (j - i) < max_value: break max_value = max(max_value, min(height[i], height[j]) * (j - i)) if height[i] > height[j]: j -= 1 else: i += 1 return max_value def test(): assert Solution().maxArea(height=list(range(1000))) == 249500 assert Solution().maxArea(height=[1, 2, 3, 4, 5, 4, 3, 2, 1]) == 12 assert Solution().maxArea(height=[1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49 assert Solution().maxArea(height=[1, 2]) == 1 if __name__ == '__main__': test()
604526bdbb537df949e8bfac65ed59cd7c263041
codingstudy-pushup/python
/top/Sort_Searching/MeetingRoom2.py
1,363
3.515625
4
import heapq from typing import List class Solution: def solve_1(self, intervals): intervals.sort(key=lambda x: x[0]) heap = [] for i in intervals: if heap and heap[0] <= i[0]: # pop, push heapq.heapreplace(heap, i[1]) else: # push heapq.heappush(heap, i[1]) return len(heap) def solve_2(self, intervals: List[List[int]]) -> int: h = [] sort = sorted(intervals) for i in sort: # need a new meeting room if h == [] or h[0] > i[0]: heapq.heappush(h, i[1]) # don't need a new meeting room, just update the end time else: heapq.heapreplace(h, i[1]) return len(h) def solve_3(self, intervals: List[List[int]]) -> int: if not intervals: return 0 intervals.sort(key=lambda x: x[0]) meeting_room = [intervals[0][1]] for i in range(1, len(intervals)): if intervals[i][0] >= meeting_room[-1]: meeting_room.pop() meeting_room.append(intervals[i][1]) meeting_room.sort(reverse=True) return len(meeting_room) print(Solution().solve_1([[0, 30], [5, 10], [15, 20]])) print(Solution().solve_2([[0, 30], [5, 10], [15, 20]]))
7f96569b515fc1a70a68a2caa626e3f0811a3a9b
monique-tukaj/curso-em-video-py
/Exercises/ex050_soma_pares.py
343
3.921875
4
'''Desenvolva um programa que leia seis numeros inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for impar , desconsidere-o. ''' s = 0 for a in range(1, 7): num = int(input('Digite o {} numero inteiro: '.format(a))) if num % 2 == 0: s += num print('O somatorio dos numeros pares é {}.'.format(s))
0b572774c376a7c215b7024501110c45747c3589
Anton-Naumov/Programming-101-with-Python
/week10/Money_In_The_Bank/client_test.py
2,358
3.671875
4
import unittest from client import Client from exceptions import InvalidPassword class ClientTests(unittest.TestCase): def setUp(self): self.test_client = Client(1, "Ivo", 200000.00, 'Bitcoin mining makes me rich', "ivo@abv.bg") def test_client_id(self): self.assertEqual(self.test_client.get_id(), 1) def test_client_name(self): self.assertEqual(self.test_client.get_username(), "Ivo") def test_client_balance(self): self.assertEqual(self.test_client.get_balance(), 200000.00) def test_client_message(self): self.assertEqual(self.test_client.get_message(), "Bitcoin mining makes me rich") def test_validate_password_returns_False(self): with self.subTest('username is substring of the password!'): with self.assertRaisesRegex(InvalidPassword, 'The password should\'t contain the username!'): Client.validate_password('#Antonski1', 'tons') with self.subTest('password is shorter than 8 symbols'): with self.assertRaisesRegex(InvalidPassword, 'The password should be longer then 8 symbols!'): Client.validate_password('#Aa1arg', 'Z') with self.subTest('passwort does\'t contain any digits'): with self.assertRaisesRegex(InvalidPassword, 'The password must contain a digit!'): Client.validate_password('#Aaargqwe', 'Z') with self.subTest('passwort does\'t contain any capital letters'): with self.assertRaisesRegex(InvalidPassword, 'The password must contain a capital letter!'): Client.validate_password('#aargqwe1', 'Z') with self.subTest('passwort does\'t contain any special symbol'): with self.assertRaisesRegex(InvalidPassword, 'The password must contain a special symbol!'): Client.validate_password('Aaargqwe1', 'Z') def test_validate_password_returns_True(self): try: Client.validate_password('#anton1Naumov', 'Toni') except InvalidPassword as e: self.fail(e) if __name__ == '__main__': unittest.main()
c814f25b53bea705dc854d37b9fbd7f156bd4190
othienoJoe/Weekly-Blog
/tests/test_article.py
861
3.5
4
import unittest from app.models import Articles class ArticlesTest(unittest.TestCase): def setUp(self): self.new_article = Articles('CNN', 'A West Virginia city is taking a Tesla patrol car for a test drive', 'Emma Raducanu defeats Leylah Fernandez in all-teen US Open final', 'The strangers who fell in love when 9/11 diverted their flight', 'https://twitter.com/cnnbrk/status/1436882485170802688','2019-09-04T14:00:00Z', "SLIDELL, La. -- A man was attacked by a large alligator while walking through floodwaters from Hurricane Ida and is now missing, a Louisiana sheriff said.\r\nThe 71-year-old mans wife told sheriffs dep… [+1041 chars]" ) def test_instance(self): self.assertTrue(isinstance(self.new_article, Articles))
26119cb51ff5ea445c75344e9812935be35776b5
verdastelo/wgc
/gglPy/minutes.py
132
3.609375
4
minutes = 42 seconds = 42 seconds_in_a_minute = 60 total_seconds = (minutes * seconds_in_a_minute) + seconds print(total_seconds)
3c515bbc6f41270aefd40b85f24c2aa8e153c9c9
OlliePoole/FYP
/Python/Assignment-1/CreditCardProblem.py
2,091
3.875
4
''' Created on 16 Oct 2012 @author: Ollie Poole ''' def getValidInput(): num = str(input("Enter the eight digit credit card number: ")) while len(num) != 8: num = str(input("Incorrect input, please try again: ")) return num #This function returns valid input only and will keep asking the user for input until correct input is given def S1function(num): S1total = 0 for count in range(7,0,-2): S1total += int(num[count]) return S1total #This function adds the total of the numbers starting from the right hand side of the string with the step of 2 def S2function(num): S2total = "" for count2 in range(0,7,2): S2total += str((int(num[count2])*2)) #Converts the credit card numbers into integers to multiply them by 2 then turns them back to generate the string i.e. 10+2 = 102 return S2total #This generates a string of all the numbers multiplied by 2 def S3function(S2total): S3total =0#Variable for adding the individual digits from section 2 for count3 in range(0,len(S2total)): S3total += int(S2total[count3]) return S3total #Adds all the digits of the string created in S2function num = getValidInput() S1total = S1function(num) S2total = S2function(num) S3total = S3function(S2total) Gtotal = S1total + S3total Gtotal = str(Gtotal) #A grand total variable for finding the sum of the totals from Section 1 and Section 3 def checkDigitCheck(Gtotal): if Gtotal[-1:] == "0": return True else: return False #Function to check whether the Gtotal variable shows that the card is valid or not if checkDigitCheck(Gtotal) == True: print("Your card is valid") #If the function returns the value 'True' it will output a suitable message else: print("Your card is not valid") check = str(int(num[-1:])-int(Gtotal[-1:])+10) #Takes the total end digit away from the check digit and adds 10 to avoid negative numbers print("To be correct the check digit would be: ", check[-1:]) #Takes the end digit so the check bit is only one digit long
cbbf316aa63fdc9825c50185fd345a053cc9010e
Sunshine-Queen/Test
/day17/私有属性.py
806
3.84375
4
class People(object): def __init__(self, name): self.__name = name def getName(self): return self.__name def setName(self, newName): if len(newName) >= 5: self.__name = newName else: print("error:名字长度需要大于或者等于5") xiaoming = People("dongGe") xiaoming.setName("wanger") print(xiaoming.getName()) xiaoming.setName("lisi") print(xiaoming.getName()) # Python中没有像C++中public和private这些关键字来区别公有属性和私有属性 # 它是以属性命名方式来区分,如果在属性名前面加了2个下划线'__',则表明该属性是私有属性, # 否则为公有属性(方法也是一样,方法名前面加了2个下划线的话表示该方法是私有的,否则为公有的)。
faf09587c4362ec77b55ceb8a41feed7016d20d0
chipjacks/presidents-and-assholes
/common.py
8,125
3.5625
4
"""Deck, Player, and Table classes used by client and server to play Warlords and Scumbags card game. """ from random import shuffle import logging # Constants HOST = 'localhost' PORT = 36716 TABLESIZE = 7 LOBBYSIZE = 35 def setup_logging(to_file=False): FORMAT = '%(filename)s: %(message)s' # To log to file, use filename='log.log' argument if to_file: logging.basicConfig(level=logging.DEBUG, format=FORMAT, filename='log.log') else: logging.basicConfig(level=logging.DEBUG, format=FORMAT) logging.info('Logging started') class Deck: """A deck of cards, which can be shuffled and dealt. """ DECK_SIZE = 52 def __init__(self): self.cards = [x for x in range(self.DECK_SIZE)] def shuffle(self): shuffle(self.cards) def deal(self, numplayers): self.shuffle() handsize = self.DECK_SIZE // numplayers hands = [self.cards[i*handsize:(i+1)*handsize] for i in range(numplayers)] for i in range(self.DECK_SIZE - handsize * numplayers): hands[i].append(self.cards[-1-i]) return hands class Player: """A player who has a hand of cards. """ def __init__(self, name): self.hand = [] self.name = name self.status = 'l' self.strikes = 0 def pickup_hand(self, cards): self.clear_hand() self.add_to_hand(cards) def add_to_hand(self, cards): assert(isinstance(cards, list)) for i in cards: assert(i >= 0 and i <= 51) self.hand += cards hand_set = set(self.hand) assert(len(self.hand) == len(hand_set)) def clear_hand(self): self.hand = [] def remove_from_hand(self, cards): if not cards: return assert(isinstance(cards, list)) cards = set(cards) hand_set = set(self.hand) if (not cards <= hand_set): raise PlayerError(self, "tried to remove cards they don't have from hand") for card in cards: self.hand.remove(card) class Table: """A table that holds players and tracks gameplay. """ def __init__(self): self.players = [] self.winners = [] self.played_cards = [] self.turn = 0 self.starting_round = True self.deck = Deck() def add_player(self, player): assert(isinstance(player, Player)) if self.full(): return False else: self.players.append(player) return True def active_players(self): active_players = [] for player in self.players: if player.status in ('a','w','p') and len(player.hand) > 0: active_players.append(player) return active_players def last_play(self): if not self.played_cards: return None else: return self.played_cards[-1] def deal(self): hands = self.deck.deal(len(self.players)) assert(len(self.players) == len(hands)) for i, player in enumerate(self.players): player.pickup_hand(hands[i]) return hands def remove_player(self, player): assert(isinstance(player, Player)) self.players.remove(player) def play_cards(self, player, cards): assert(isinstance(cards, list)) # assert(len(self.players) > 1) # make sure the game should still be going if (len(self.players) < 2): pass # validate play self.validate_play(player, cards) # did they pass or play? if not cards: player.status = 'p' else: self.played_cards.append(cards) player.remove_from_hand(cards) player.status = 'w' if len(player.hand) == 0: # they won! logging.info('%s won!', player.name) self.winners.append(player) active_players = self.active_players() if len(active_players) <= 1: # the game is over return # who is next? if cards and cards[0] >= 48: # the player played a 2 and gets to go again, unless he is out if player in self.winners: # he is out, it's next players turn player.status = 'w' self.turn += 1 self.turn %= len(active_players) active_players[self.turn].status = 'a' else: # he is still playing, it's his turn player.status = 'a' self.played_cards.append([]) else: # see if anyone got skipped if (player.status == 'w' and len(self.played_cards) >= 2 and [c // 4 for c in self.played_cards[-2]] == [c // 4 for c in cards]): # someone did get skipped self.turn += 1 self.turn %= len(active_players) active_players[self.turn].status = 'p' logging.info('skipping %s', active_players[self.turn].name) # it's next players turn self.turn += 1 self.turn %= len(active_players) active_players[self.turn].status = 'a' # see if everyone has passed for player in active_players: assert(player.status not in ('e', 'd')) if player.status == 'w': # they have played this round break else: # everyone has passed, new round self.played_cards.append([]) def full(self): return (len(self.players) >= TABLESIZE) def ready(self): return (len(self.players) > 2) def validate_play(self, player, cards): assert(isinstance(cards, list)) # make sure no duplicate cards in list cards_set = set(cards) if len(cards_set) != len(cards): raise PlayerError(player, "played duplicates of a card", '17') # check the player is in turn and has the cards if player not in self.players: raise PlayerError(player, "tried to play cards when not at table", '31') for card in cards: if card not in player.hand: raise PlayerError(player, "tried to play cards they don't have: {}, {}".format(str(card), repr(player.hand)), '14') if player.status != 'a': raise PlayerError(player, "tried to play when not his turn", '15') if len(cards) == 0: # they passed return if len(cards) > 1: # check that they are all the same number for card in cards: if card // 4 != cards[0] // 4: raise PlayerError(player, "sent cards that don't have matching face value", '11') # check that it beats last play if self.played_cards == [] or self.played_cards[-1] == []: # last play is empty, this play is valid return elif cards[0] // 4 == 12: # they played a 2 return else: last_play = self.played_cards[-1] if cards[0] // 4 < last_play[0] // 4: raise PlayerError(player, "sent cards with too low of a face value", '12') elif len(cards) < len(last_play): raise PlayerError(player, "played cards without too low of a quantity", '13') return class GameError(Exception): pass class PlayerError(GameError): """ Exception raised when players perform invalid actions Attributes: player -- player who caused exception msg -- what the player did wrong e.g. "Player JohnD: invalid cards played" """ def __init__(self, player, msg, strike_code='00'): self.player = player self.msg = msg self.strike_code = strike_code def __str__(self): return "Player {}: {}".format(self.player.name, self.msg) if __name__ == '__main__': d = Deck()