text
stringlengths
37
1.41M
## https://leetcode.com/problems/valid-palindrome class Solution: def isPalindrome(self, s: str) -> bool: S = "" for i in s: if i.isalnum(): S += i return S.lower() == S[::-1].lower()
# https://leetcode.com/problems/sort-colors/submissions/ # Given an array nums with n objects colored red, white, or blue, sort them in-place # so that objects of the same color are adjacent, with the colors in the order red, # white, and blue. # We will use the integers 0, 1, and 2 to represent the color red, white, and blue, # respectively. # You must solve this problem without using the library's sort function. # Example 1: # Input: nums = [2,0,2,1,1,0] # Output: [0,0,1,1,2,2] def sortColors(nums): """ Do not return anything, modify nums in-place instead. """ n = len(nums) for i in range(n): for j in range(0, n-1): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] return nums if __name__ == "__main__" : nums = [2,0,2,1,1,0] ans = sortColors(nums) print(ans)
#User function Template for python3 ## https://practice.geeksforgeeks.org/problems/middle-of-three2926/1# class Solution: def middle(self,A,B,C): # R = sorted([A,B,C]) # return R[1] if((A-B)*(A-C)<0) : return A elif((B-A)*(B-C)<0): return B else: return C #{ # Driver Code Starts #Initial Template for Python 3 if __name__=='__main__': t=int(input()) for _ in range(t): A,B,C=map(int,input().strip().split()) ob=Solution() print(ob.middle(A,B,C)) # } Driver Code Ends
## Practice of Tree Traversals class TreeNode(object): def __init__(self,val = None,left = None, right = None): self.val = val self.left = left self.right = right class BinaryTree(object): def __init__ (self,root = None): self.root = TreeNode(root) def TreeVisualizer(self,root): ## Works only upto 3 level with perfect Tree print(f""" {root.val} {root.left.val} {root.right.val} {root.left.left.val} {root.left.right.val} {root.right.left.val} {root.right.right.val} """) def StackPreorder(self,root): stack = [] if root is None: return stack.append(root) while stack: temp = stack.pop() print(temp.val,end = " - ") if temp.right: stack.append(temp.right) if temp.left: stack.append(temp.left) def StackPostorder(self,root): ## Using 1 stack stack = [] if root is None: return while True: while root: if root.right: stack.append(root.right) stack.append(root) root = root.left root = stack.pop() if root.right and stack and root.right == stack[-1]: stack.pop() stack.append(root) root = root.right else: print(root.val,end = " - ") root = None if len(stack) <= 0: break def Stack_Inorder(self,root): if root is None: return stack = [] while True: if root: stack.append(root) root = root.left else: if not stack: break temp = stack.pop() print(temp.val, end = " - ") root = temp.right T = BinaryTree(5) T.root.left = TreeNode(3) T.root.right = TreeNode(6) T.root.left.left = TreeNode(31) T.root.right.left = TreeNode(1) T.root.left.right = TreeNode(13) T.root.right.right = TreeNode(16) T.TreeVisualizer(T.root) T.StackPreorder(T.root) print() T.StackPostorder(T.root) print() T.Stack_Inorder(T.root)
## Fibonacci numbers using Bottom up DP def Fib(n): fib = [0]*10000 fib[0] = 1 fib[1] = 1 for i in range(2,n+1): fib[i] = fib[i-1]+fib[i-2] return fib[n] if __name__ == "__main__": print(Fib(250))
## https://leetcode.com/problems/number-of-1-bits/ class Solution: def hammingWeight(self, n: int) -> int: return bin(n).count("1") ####### Another approach ######## class Solution: def hammingWeight(self, n: int) -> int: bitcount = 0 while n > 0: if n % 2 == 1: bitcount += 1 n >>= 1 return bitcount ### One More approach ### class Solution: def hammingWeight(self, n: int) -> int: res = 0 while n: res += n & 1 n >>= 1 return res
#!/bin/python3 import math import os import random import re import sys # 3 # 11 2 4 # 4 5 6 # 10 8 -12 # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as parameter. # def diagonalDifference(arr): # Write your code here d = 0 ad = 0 n = len(arr) # for i in range(len(arr)): # for j in range(len(arr[0])): # if i == j: # d += arr[i][j] # elif # ad = arr[] for i in range(n): d += arr[i][i] ad += arr[i][n-i-1] # print(d,ad) return abs(d-ad) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(arr) fptr.write(str(result) + '\n') fptr.close()
# Calculator print( """ Hey, this is an Awesome calculator... These are the operations supported by it. 1 for addition 2 for Multiplication 3 for Division 4 for Substraction 5 for power(x,y) 6 for exit """ ) while True: X = float(input("Please enter the value of X: ")) Y = float(input("Please enter the value of Y: ")) Opr = int(input("Kindly enter the operation code - - - ")) if Opr == 6: print("Thank you for using CalC, Come again tomorrow!") break Result = 0 if Opr == 1: Result = (X+Y) elif Opr == 2: Result =(X*Y) elif Opr == 3: Result =(X/Y) elif Opr == 4: Result =(X-Y) elif Opr == 5: Result =(X**Y) else: print("This is not a valid operation!") continue print("Your result is : ", Result)
## https://leetcode.com/problems/can-place-flowers/ class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: if n == 0: return True for i in range(len(flowerbed)): left = (i == 0 or flowerbed[i - 1] == 0) right = (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0) # If we're clear from the left and right and current value is 0, we can plant a flower if left and right and flowerbed[i] == 0: n -= 1 flowerbed[i] = 1 # We can skip the next element since it would be invalid i += 1 if n == 0: return True return False
# Enter your code here. Read input from STDIN. Print output to STDOUT ## https://www.hackerrank.com/challenges/input/problem x,k = map(int,input().split()) print(k==eval(input()))
###### INSERTION SORT -- Practice ###### def InsertionSort(arr): for i in range(1,len(arr)): key = arr[i] j = i-1 while j >= 0 and key < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = key if __name__ == "__main__": arr = list(map(int,input("Enter the array elements separated by space: \n").split())) # arr = [2,5,1,33,4,23,9] print("The given array is: ",arr) InsertionSort(arr) print("Sorted Array is: ",arr)
## https://leetcode.com/problems/shuffle-the-array/ class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: # nums1 = nums[:n] # nums2 = nums[n:] # res= [] # for i in range(len(nums1)): # res.append(nums1[i]) # res.append(nums2[i]) # return res res = [] for i in range(len(nums)//2): res.append(nums[i]) res.append(nums[i+n]) return res
### Q: Write a program to insert, delete at beginning, end, middle of a linked list. class node: def __init__(self,data = None): self.data = data self.next = None class Linked_list: def __init__(self): self.head = node() def insert_at_end(self,data): new_node = node(data) cur = self.head while cur.next != None: cur = cur.next print(f"Element {new_node.data} is added at the end") cur.next = new_node def insert_at_start(self,data): cur = self.head temp = cur.next new_node = node(data) cur.next = new_node new_node.next = temp print(f"Element {new_node.data} is added at the start") def insert_at_index(self,index,data): if self.length() < index: print("ERROR! List index out of range!") return None cur = self.head new_node = node(data) i = 0 while True: temp = cur.next if i == index: cur.next = new_node new_node.next = temp print(f"Element {new_node.data} is added at the index position {index}") return cur = cur.next i += 1 def delete_from_index(self,index): if self.length() == 0: print("ERROR! List is Already Empty") return None elif index >= self.length(): print("ERROR! List index out of range!") return None else: cur = self.head # cur = cur.next i = 0 while True: lst_node = cur cur = cur.next if i == index: print(f"Element {cur.data} is removed from index {index}") lst_node.next = cur.next return i +=1 def delete_from_start(self): cur = self.head print(f"Element {cur.next.data} is removed from start.") cur.next = cur.next.next return def delete_from_last(self): cur = self.head if cur.next is None: print("List is Empty, cannot delete!") return while cur.next.next != None: cur = cur.next print(f"Element {cur.next.data} is removed from end") cur.next = None return def length(self): total = 0 cur = self.head while cur.next != None: total+=1 cur = cur.next # print(f"Length of the current list is {total}") return total def display(self): res= [] cur = self.head while cur.next != None: cur = cur.next res.append(cur.data) print(f"Current linked list is {res}") if __name__ == "__main__": my_list = Linked_list() print(" Welcome! Please try you hands on the linked list program: ") def Menu(): print(""" -------------- M E N U -------------- Press 1 to Add an element at start Press 2 to Add an element at last Press 3 to Add an element at an index position Press 4 to Delete an element from Head Press 5 to Delete an element from an index Press 6 to Delete an element from Tail Type Len to check the length of the List Type Display to see the current list Type MENU to see the Menu at any point of time Type Exit or Quit to end the program! """) Menu() while True: Op = input("====>") if Op == "1": my_list.insert_at_start(int(input("Enter the Number to be added: "))) elif Op == "2": my_list.insert_at_end(int(input("Enter the Number to be added: "))) elif Op == "3": my_list.insert_at_index(int(input("Enter the index value: ")), int(input("Enter the Number to be added: "))) elif Op == "4": my_list.delete_from_start() elif Op == "5": my_list.delete_from_index((int(input("Enter the index value: ")))) elif Op == "6": my_list.delete_from_last() elif Op.lower() == "len": print("The length of current list is: ",my_list.length()) elif Op.lower() == "display": my_list.display() elif Op.lower() == "menu": Menu() elif Op.lower() == "exit" or Op.lower() == "quit": print("Thank you for checking this program. Bye!") break else: print("Invalid Operation! Please check the MENU and enter an appropriate input/command.")
''' Q. Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Notice that the solution set must not contain duplicate quadruplets. ''' def fourSum(nums, target): if len(nums)<4: return [] two_sum_matrix = [ [ 0 for _ in range(len(nums))] for _ in range(len(nums))] two_sum_dict = dict() for i in range(len(nums)): for j in range(i+1, len(nums)): two_sum = nums[i]+nums[j] two_sum_list = two_sum_dict.get(two_sum,[]) two_sum_list.append((i,j)) two_sum_dict[two_sum] = two_sum_list two_sum_matrix[i][j] = two_sum ret_set = set() for i in range(len(nums)): for j in range(i+1, len(nums)): need_num = target - two_sum_matrix[i][j] if need_num in two_sum_dict: for _i, _j in two_sum_dict.get(need_num): if len(set([i,j,_i,_j]))==4: ret_set.add(tuple(sorted([nums[i], nums[j], nums[_i], nums[_j]]))) ret_list = [list(t) for t in list(ret_set)] return ret_list if __name__ == "__main__": nums = list(map(int,input("Enter the elements of nums sepeareted by comma: ").strip().split(","))) target = int(input("Enter the target value: ")) ans = fourSum(nums, target) print(ans)
### https://leetcode.com/problems/contains-duplicate/submissions/ ### class Solution: def containsDuplicate(self, nums: List[int]) -> bool: ##### Method 1 ##### # return not len(nums) == len(list(set(nums))) ##### Method 2 ##### d = {} for i in nums: if i in d: return True else: d[i] = True ## Can take anything as a value here return False
# Enter your code here. Read input from STDIN. Print output to STDOUT ## https://www.hackerrank.com/challenges/30-review-loop if __name__ == "__main__": n = int(input()) for i in range(n): odd = "" even = "" strng = input() for j in range(len(strng)): if j%2 == 1: odd += strng[j] else: even += strng[j] print(f"{even} {odd}")
### https://leetcode.com/problems/sort-array-by-parity-ii/submissions/ class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: # """ # Dictionaries are a convenient way to store data for later retrieval by name (key). # A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) # f that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. ########Refer : https://www.geeksforgeeks.org/defaultdict-in-python/ ############ d = defaultdict(list) for i in A: if i%2 == 0: d["Even"].append(i) else: d["odd"].append(i) for i in range(len(A)): if i%2 == 0: A[i] = d["Even"].pop() else: A[i] = d["odd"].pop() return A
#!/usr/bin/python # -*- coding: utf-8 -*- def person(name,age,**kw): if 'city' in kw: pass if 'job' in kw: pass print ('name:',name,'age:',age,'other:',kw) person('Michael',30) person('Bob',35,city='Beijing') person('Jack',24,city='Beijing',addr='Chaoyang') def f1(a,b,c=0,*args,**kw): print ('a=',a,'b=',b,'c=',c,'args=',args,'kw=',kw) def f2(a,b,c=0,*,d,**kw): print ('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw) #位置参数(必选参数、默认参数),可变参数,关键字参数和命名关键字参数 f1(1,2) f1(1,2,c=3) f1(1,2,3,'a','b') f1(1,2,3,'a','b',x=99) f2(1,2,d=99,ext=None) args=(1,2,3,4) kw={'d':99,'x':'#'} f1(*args,**kw) args=(1,2,3) kw={'d':88,'x':'#'} #f2(*args,**kw)
#!/usr/bin/python # -*- coding: utf-8 -*- import functools def int2(x,base=2): return int(x,base) #functools中partial function 偏函数,把一个函数的某些参数固定住,返回一个新函数 if __name__=="__main__": print (int2('120',8)) print (int2('10101')) int8 = functools.partial(int,base=8) print (int8('120')) kw = {'base':8} print (int('120',**kw)) max2 = functools.partial(max,10) print (max2(5,6,7))
#!/usr/bin/python # -*- coding: utf-8 -*- dict1 = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"} print ("initial dict1: %s"%dict1) dict2 = sorted(dict1.items(),key=lambda d:d[0]) print ("order by key: %s"%dict2) dict3 = sorted(dict1.items(),key=lambda d:d[1]) print ("order by value: %s"%dict3) ks = list(dict1.keys()) ks.sort() for k in ks: print (k,dict1[k]) dict4 = {value:key for key,value in dict1.items()} print (dict4) def sortedDictValue1(adict): keys = adict.keys() sorted(keys) return [adict[key] for key in keys] print (sortedDictValue1(dict1))
#!/usr/bin/python # -*- coding: utf-8 -*- names = ["Michael","Bob","Tracy"] scores = [95,75,85] d = {} for i in range(3): d[names[i]] = scores[i] print ("Initial Dict: ",d) c = d.copy() if 'Bob' in d: print ("Scores of Bob",d['Bob']) d['Ray'] = 100 print ("Updated Dict: ",d) del(d["Tracy"]) print ("Updated Dict: ",d) d.pop("Michael") print ("Updated Dict: ",d) d.clear() print ("Cleard Dict: ",d) for k in c: print ("d[%s] = %s"%(k,c[k])) print (c) for key, value in c.items(): print ("c[%s]="%key,value) print (c) for key, value in c.iteritems(): print ("c[%s]="%key,value)
import sqlite3 as sqlite def connect_db(filename='app/db.sqlite'): conn = sqlite.connect(database=filename) init_tables(conn) conn.row_factory = dict_factory # allows to call sql rows by their field name instead of by index return conn def init_tables(conn): cur = conn.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS ftdb ( id INTEGER PRIMARY KEY, datetime DATETIME, text TEXT ) """) conn.commit() pass def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
""" The file that writes everything to a java file. This is the main file which is going to be run. Author: Utkarsh Dayal """ from docParser import * from javaclass import * def getMethodStub(methodName): """ Takes in a method name, and based on what the return type of the method is, it returns a return statement as a string :param methodName: name of the method :return: the return statement for the method stub """ if " void " in methodName: return "" elif " int " in methodName or " double " in methodName: return " return 0; " elif " float " in methodName: return " return 0.0; " elif " String " in methodName: return " return "" " elif " boolean " in methodName: return " return false; " else: return " return null; " def writeMethods(file,dict): """ Takes a .java file and a dictionary containing the methods for a java class, and then stubs out the methods in the file :param file: the java file :param dict: the dictionary of methods """ for name in dict.keys(): docString = dict[name][1] methodName = dict[name][0] params = dict[name][2] returns = dict[name][3] override = dict[name][4] for parameter in params.keys(): docString += "\n\t* @param " + parameter + params[parameter] if returns != None: docString += "\n\t* @return " + returns file.write( "\t/*\n") file.write("\t* " + docString + "\n") file.write("\t*/\n") if override: file.write("\t@Override\n") file.write("\t" + methodName + "{" + getMethodStub(methodName) + "}\n") file.write("\n") def writeFields(file,dict): for name in dict.keys(): docString = dict[name][1] infoName = dict[name][0] file.write("\t/*\n") file.write("\t* " + docString + "\n") file.write("\t*/\n") file.write("\t" + infoName + "\n") file.write("\n") def main(): page = "https://www.cs.rit.edu/~csci142/Labs/07/doc/bee/Bee.html" response = requests.get(page) data = response.text className = findBetweenTag(data, "<title>", "</title>") classAccess = findBetweenTag(data, "<pre>", "<span") #java = JavaClass(className[0],classAccess[0]) methods = findAllMethods(data) fields = findAllFields(data) #for method in methods.keys(): #java.addToClass("method",method,methods[method]) #for field in fields.keys(): #java.addToClass("field",field,fields[field]) file = open("ParseTree.java","w") file.write(classAccess[0] + className[0] + "{\n") writeFields(file,fields) writeMethods(file,methods) file.write("}") if __name__ == '__main__': main()
# Crear un programa con tres clases Universidad, con atributos nombre # (Donde se almacena el nombre de la Universidad). Otra llamada Carerra, # con los atributos especialidad (En donde me guarda la especialidad de # un estudiante). Una ultima llamada Estudiante, que tenga como atributos # su nombre y edad. El programa debe imprimir la especialidad, edad, nombre # y universidad de dicho estudiante con un objeto llamado persona. class Universidad(): def __init__(self,nombreU): self.nombreU = nombreU class Carrera(): def carrera(self,especialidad): self.especialidad = especialidad class Estudiante(Universidad,Carrera): def datos(self,nombre,edad): self.nombre = nombre self.edad = edad print("Mi nombre es {}, tengo {} años, mi especialidad es {} y estudio en {}".format(self.nombre,self.edad,self.especialidad,self.nombre)) persona = Estudiante("UES") persona.carrera("Sistema") persona.datos("Juan",20)
class Animales(): def __init__(self,descripcion,especie,hablar): self.descripcion = descripcion self.especie = especie self.hablar = hablar def habla(self): print("Yo hago ",self.hablar) def describir(self): print("Soy de la especie ",self.especie) class Perro(Animales): # HERENCIA EN PYTHON pass class Abeja(Animales): #HERENCIA def sonido(self,sonido): self.sonido = sonido print(self.sonido) ############## perro = Perro("Perro","Mamífero","Guau!") perro.habla() perro.describir() abeja = Abeja("Abeja","Insecto","brr") abeja.habla() abeja.describir() abeja.sonido("brr")
#escriba un script que sea capaz de calcular el índice de masa corporal de una persona en base a los datos ingresados por el usuario. import math from tabulate import tabulate peso = float(input("Ingrese su peso en Kilogramos: ")) estatura = float(input("Ingrese su estatura en metros: ")) IMC = round(peso/math.pow(estatura,2),1) print("Su IMC es de "+str(IMC)) lista = [["Composición corporal","Índice de masa corporal (IMC)"],["Peso inferior al normal","Menos de 18.5"],["Normal","18.5 – 24.9"],["Peso superior al normal","25.0 – 29.9"],["Obesidad","Más de 30.0"]] print(tabulate(lista))
# clase class Persona(): # atributos nombre = "Carlos" apellido = "Vergara" sexo = "Masculino" edad = 30 # metodos def hablar(self, mensaje): return mensaje ########################### # objeto persona = Persona() print(persona.hablar("Hola soy"), "{} y mi apellido es {}, tengo {} y de sexo {}".format( persona.nombre, persona.apellido, persona.edad, persona.sexo))
variable_uno = 5 variable_dos = 20 menor = variable_uno < variable_dos mayor_igual = variable_uno >= variable_dos menor_igual = variable_uno <= variable_dos igual = variable_uno == variable_dos diferente = variable_uno != variable_dos mayor = variable_uno > variable_dos print(mayor) print(menor) print(mayor_igual) print(menor_igual) print(igual) print(diferente)
import sqlite3 conexion=sqlite3.connect("AdministracionAlumnos3") cursor = conexion.cursor() elcodigo = int(input("Digite el código del curso que desea consultar: ")), cursor.execute("SELECT * FROM CURSOS WHERE id_curso = ?",elcodigo) loscursos=cursor.fetchall() print(loscursos) conexion.commit() conexion.close()
variable_uno = 5 variable_dos = 20 mayor = variable_uno > variable_dos menor = variable_uno < variable_dos mayor_igual = variable_uno >= variable_dos menor_igual = variable_uno <= variable_dos igual = variable_uno == variable_dos diferente = variable_uno != variable_dos resultado = True and True and diferente resultado2 = True and True and mayor resultado3 = True or True or mayor print(resultado) print(resultado2) print(resultado3)
""" f=open("data.txt","r") print(f.read(1)) # 한바이트만 읽어옴 print("") f=open("data.txt","r") print(f.read()) print("") f=open("data.txt","r") print(f.readlines()) print("") f=open("data.txt","r") r=f.readlines() print(r[2]) f=open("data.txt","r") r=f.readlines() for x in range (0,4): print(r[x]) f=open("data.txt","r") r=f.readlines() for line in r: words=line.split() print(words) """ import collections as c f=open("data.txt","r") r1=f.read() word = r1.split() """ for i in range(0, 20): print(i+1, word[i]) d={} # 딕셔너리 선언 for i in range(0, 20): print(i+1,word[i]) d[word[i]] = 1 #모든 key값을 1로 지정 print(d) """ d={} for i in word: if i in d.keys(): d[i] += 1 else: d[i] =1 print(d)
#Linked list #including the function: #insertAtFront(); #insertAtBack() #removeFromFront() #removeFromBack() class Node(object): def __init__(self,data): self.data=data self.nextNode=None def __str__(self): return self.data class linkedList(object): def __init__(self): self._firstNode=None self._lastNode=None def insertAtFront(self,value): node=Node(value) if(self.isEmpty()): node.nextNode=None self._firstNode=node self._lastNode=node else: node.nextNode=self._firstNode self._firstNode=node def insertAtBack(self,value): node=Node(value) if self.isEmpty(): self._firstNode=node self._lastNode=node else: self._lastNode.nextNode=node self._lastNode=node def removeFromFront(self): tempNode=self._firstNode if self.isEmpty(): raise IndexError,"remove from empty list" elif(self._firstNode is self._lastNode): self._firstNode=None self._lastNode=None else: self._firstNode=self._firstNode.nextNode return tempNode def removeFromBack(self): tempNode=self._lastNode if self.isEmpty(): raise IndexError,"remove from empty list" elif self._firstNode is self._lastNode: self._firstNode=self._lastNode=None else: currentNode=self._firstNode while currentNode.nextNode is not self._lastNode: currentNode=currentNode.nextNode currentNode.nextNode=None self._lastNode=currentNode return tempNode def isEmpty(self): return self._firstNode is None def __str__(self): currentNode=self._firstNode while currentNode is not None: print currentNode.data print '\n' currentNode=currentNode.nextNode
from abc import ABCMeta class Vuelo(metaclass=ABCMeta): '''Abstracción que representa a un vuelo''' def __init__(self, codigo, avion, fecha_partida, horario_partida): self.aeropuerto_origen = "Silvio Pettirossi" self.pais_origen = "Paraguay" self.codigo = codigo self.avion = avion self.fecha_partida = fecha_partida self.horario_partida = horario_partida self.estado = "" self.habilitado = "" def __str__(self): return self.codigo + 2*'\t' + str(self.avion) + '\t'\ + str(self.horario_partida) + 2*'\t' \ + str(self.fecha_partida) + '\t' + self.estado def cambiar_estado(self, estado): '''Cambia el estado del vuelo''' self.estado = estado def cambiar_habilitacion(self, habilitacion_vuelo): '''Cambia la habilitación del vuelo''' self.habilitado = habilitacion_vuelo class Reserva(metaclass=ABCMeta): '''Abstracción que representa a una reserva''' def __init__(self, pasajero, lugar, cabina, vuelo, cantidad_pasajero): self.pasajero = pasajero self.lugar = lugar self.cabina = cabina self.vuelo = vuelo self.cantidad_pasajero = cantidad_pasajero def obtener_cantidad_pasajero(self): total = str(self.cantidad_pasajero[0] + self.cantidad_pasajero[1] + self.cantidad_pasajero[2]) return total def __str__(self): return str(self.pasajero) + '\n' + str(self.lugar) + '\n' + str(self.cabina) \ + '\n' + 'Aeropuerto de partida: ' + self.vuelo.aeropuerto_origen + '\n'\ + 'Cantidad de pasajeros: ' + self.obtener_cantidad_pasajero()\ + '\n'+ 'Código de Avión: ' + self.vuelo.codigo + '\n' + 'Tipo de Avión: ' \ + str(self.vuelo.avion) + '\n' + 'Horario de partida: ' + str(self.vuelo.horario_partida) \ + '\n' + 'Fecha de partida: ' + str(self.vuelo.fecha_partida) + '\n' \ + 'Estado del vuelo: ' + self.vuelo.estado def __del__(self): return 'Ha cancelado su reserva.' def eliminar_reserva(self, reserva): del(reserva) class Precio(metaclass=ABCMeta): '''Abstracción que representa a un precio''' def __init__(self, precio_economico, precio_intermedio, precio_especial): self.precio_economico = precio_economico self.precio_intermedio = precio_intermedio self.precio_especial = precio_especial def __str__(self): return 'Precio Especial en US$: ' + str(self.precio_especial) + '\n' \ 'Precio Intermedio en US$: ' + str(self.precio_intermedio) + '\n' \ 'Precio Económico en US$: ' + str(self.precio_economico) class Lugar(metaclass=ABCMeta): '''Abstracción que representa a un lugar''' def __init__(self, nombre, aeropuerto, precio): self.nombre = nombre self.aeropuerto = aeropuerto self.precio = precio self.descripcion = "" self.cant_vuelos = [] def __str__(self): return 'Lugar: ' + self.nombre + '\n' + 'Aeropuerto destino: ' + self.aeropuerto def descripcion_bsas(self): '''Descripción buenos aires''' self.descripcion = "¡LTAM te invita a conocer las ciudades más bellas de Argentina!\n" \ "¿Qué tal una noche de tango con una parrillada o una escapada a\n" \ "la Patagonia?\n" \ "Aprovecha los vuelos a Buenos Aires, compra tus pasajes ahora mismo\n" \ "y disfruta de esta hermosa ciudad." return self.descripcion def descripcion_cancun(self): '''Descripción Cancún''' self.descripcion = "¡No te quedes sin volar! Si estás pensando en viajar, " \ "te recomendamos\nconocer las playas caribeñas de Cancún y " \ "todas sus atracciones.\nAprovecha los vuelos a Cancún, " \ "compra ahora tus pasajes y comienza\na disfrutar desde " \ "ahora tu próxima aventura." return self.descripcion def descripcion_rio(self): '''Descripción Rio de Janeiro''' self.descripcion = "No te puedes perder los increíbles destinos que Brasil te ofrece." \ "\nLTAM te invita a recorrer sus playas paradisíacas, ciudades y pueblos" \ "\nllenos de alegría. Aprovecha los vuelos a Río de Janeiro, compra ahora\n" \ "tus pasajes y disfruta de esta ciudad." return self.descripcion def descripcion_bogota(self): '''Descripción Bogotá''' self.descripcion = "LTAM quiere que viajes a los increíbles destinos que Colombia\nte ofrece." \ " Con playas hermosas, el país del café te invita a descansar y\ndivertirte." \ " Aprovecha los vuelos a Bogotá, compra ahora tus pasajes y \ndisfruta de esta ciudad." return self.descripcion def descripcion_lima(self): '''Descripción Lima''' self.descripcion = "LTAM te invita a conocer los increíbles destinos que Perú ofrece." \ "\nAprovecha los vuelos a Lima, compra ahora tus pasajes y comienza\na disfrutar " \ "de todas las atracciones que esta hermosa ciudad\ntiene para ti." return self.descripcion def descripcion_montevideo(self): '''Descripción Montevideo''' self.descripcion = "¿Qué tal disfrutar de un recorrido por Pocitos o encantarte\ncon su " \ "exquisita gastronomía? Todo eso y más te lo ofrece Uruguay." \ "\nAprovecha los vuelos a Montevideo, compra ahora tus pasajes " \ "y disfruta\nde esta ciudad." return self.descripcion def descripcion_guayaquil(self): '''Descripción Punta Cana''' self.descripcion = "LTAM te invita a recorrer los increíbles destinos que Ecuador te ofrece. " \ "\nVisita la mitad del mundo o las Islas Galápagos y sus especies únicas\n" \ "en el planeta. Aprovecha los vuelos a Guayaquil, compra ahora tus\npasajes " \ "y disfruta de esta ciudad." return self.descripcion def descripcion_lapaz(self): '''Descripción La Paz''' self.descripcion = "LTAM te invita a volar a los increíbles destinos que Bolivia te ofrece." \ "\nCulturas únicas incrustadas en paisajes rústicos, llenos de belleza y\n encanto." \ "Aprovecha los vuelos a La Paz, compra ahora tus pasajes y\n disfruta de esta ciudad." return self.descripcion def descripcion_miami(self): '''Descripción Miami''' self.descripcion = "LTAM te invita a conocer los increíbles destinos que Estados Unidos ofrece." \ "\nAprovecha los vuelos a Miami, compra ahora tus pasajes y comienza\n" \ "a disfrutar de todas las atracciones que esta hermosa ciudad tiene para ti." return self.descripcion def descripcion_madrid(self): '''Descripción Madrid''' self.descripcion = "LTAM te invita a conocer los increíbles destinos que España ofrece." \ "\nAprovecha los vuelos a Madrid, compra ahora tus pasajes y comienza a\n " \ "disfrutar de todas las atracciones que esta hermosa ciudad tiene para ti." return self.descripcion def descripcion_paris(self): '''Descripción París''' self.descripcion = "LTAM te invita a conocer los increíbles destinos que Francia ofrece." \ "\nAprovecha los vuelos a París, compra ahora tus pasajes y comienza a\n" \ "disfrutar de todas las atracciones que esta hermosa ciudad tiene\npara ti." return self.descripcion def descripcion_puntacana(self): self.descripcion = "¡No te quedes sin volar! Si estás pensando en viajar, te recomendamos\n" \ "conocer las playas caribeñas de República Dominicana y todas sus\natracciones." \ "Aprovecha los vuelos a Punta Cana, compra ahora tus pasajes y\ncomienza a disfrutar." return self.descripcion class Avion(metaclass=ABCMeta): '''Abstracción que representa a un avión''' def __init__(self, nombre): self.nombre = nombre def __str__(self): return self.nombre
from abc import ABCMeta, abstractmethod class Cabina(metaclass=ABCMeta): '''Abstracción que representa a una cabina''' def __init__(self, precio, nombre): self.precio = precio self.nombre = nombre def __str__(self): return 'Precio: ' + str(self.precio) + ' US$' + '\n' + 'Cabina: ' + self.nombre def max_pasajeros(self, pasajero): self.cant_pasajeros = pasajero.bebes + pasajero.niños + pasajero.adultos return self.cant_pasajeros @abstractmethod def descripcion_cabina(self): pass class CabinaEspecial(Cabina, metaclass=ABCMeta): #Clase Premium Business, el mejor servicio para el pasajero '''Abstracción que representa a una cabina especial''' def __init__(self, precio, nombre): Cabina.__init__(self, precio, nombre) self.bienvenida = "" self.desc_1 = "" self.desc_2 = "" self.desc_3 = "" self.ficha_tecnica1 = "" self.ficha_tecnica2 = "" self.ficha_tecnica3 = "" @classmethod def descripcion_cabina(self): self.bienvenida = "Relájate en asientos de última generación que se convierten en cama." \ " Disfruta el más cálido servicio a bordo y deléitate con una carta\nde alta cocina diseñada" \ " por destacados chefs y vinos escogidos por el sommelier más premiado de Sudamérica." \ "\n¡Prepárate a vivir la experiencia Premium Business!" #Descripcion 1 self.desc_1= "Esta clase ha sido especialmente diseñada para que tu vuelo se transforme " \ "en un verdadero descanso. El rediseño de la cabina y los asientos\n-cama harán " \ "que disfrutes de un sueño perfecto y placentero." self.ficha_tecnica1 = "Los asientos bajan a una posición 100% horizontal, transformándose en una cama" \ " de 23 pulgadas de ancho por 73 de largo.\nLa distancia entre asientos se aumentó" \ " a 74 pulgadas, un 32% más por pasajero, muy por encima de lo ofrecido\n" \ " por otras líneas aéreas." #descripcion 2 self.desc_2 = "Déjate cautivar con el sistema de entretenimiento de última\n generación y disfruta del placer" \ " de una buena película o\npieza de música el que sumado a una atención personalizada\nhacen de esta"\ "clase una experiencia inolvidable." self.ficha_tecnica2 = "Cada asiento cuenta con una pantalla de alta resolución de 15,4\npulgadas y un sistema de" \ " audio-video que se puede usar libremente.\nÉste cuenta con un repertorio de 110 películas" \ "- 12 estrenos\n8 hits recientes, 10 latinas, 10 infantiles y 70 clásicos" \ "\nde todos los tiempos" \ "-, 42 programas de TV, 3 series con temporada\ncompleta, más de 1000 CD’s de música" \ " y 25 juegos." #descripcion 3 self.desc_3 = "En Premium Business recibirás un nivel de servicio que muy pocas\naerolíneas en el mundo" \ " pueden entregar.Se trata de un nuevo concepto de viaje\nbasado en lo que los pasajeros" \ " más valoran en sus vuelos: el cuidado del descanso\ny un servicio de excelencia." \ "Encántate con la calidez de los tripulantes y\nsorpréndete con el exquisito menú" \ " y fantástica carta de vinos." self.ficha_tecnica3 = "Contamos con un menú especialmente elaborado por reconocido chefs, que incorpora" \ "\nproductos naturales característicos de esta región sudamericana." \ "\nAdemás, tenemos una selección de los más nobles vinos de esta zona del mundo\n" \ "elaborada por el único Master Sommelier en Latinoamérica, Héctor Vergara." class CabinaIntermedia(Cabina, metaclass=ABCMeta): #Clase Premium Economy, exclusivo para viaje de negocios '''Abstracción que representa a una cabina tipo intermedia''' def __init__(self, precio, nombre): Cabina.__init__(self, precio, nombre) self.desc_1 = "" self.desc_2 = "" self.desc_3 = "" self.ficha_tecnica = "" @classmethod def descripcion_cabina(self): #Descripcion 1 self.desc_1 = "Descubre nuestra Premium Economy, la clase que responde a lo más valorado por los pasajeros" \ " que viajan por negocios: aprovechar al máximo su tiempo.\nEn esta cabina exclusiva" \ " y de atención preferente, encontrarás todo el espacio y comodidad que necesitas para tu viaje." self.ficha_tecnica = "Es una cabina exclusiva y con atención preferente para sólo 12 personas. Posee butacas" \ " de cuero y\nun asiento central cuyo respaldo se convierte en mesa" \ " para que obtengas un mayor espacio y\ncomodidad especial para un computador portátil." \ " Además, posee mayor reclinación y espacio entre\nasientos para máxima comodidad." # Descripcion 2 self.desc_2 = "Para una mayor comodidad, algunos de nuestros aviones que cuentan con esta cabina" \ "\ntienen una conexión universal para cargar la batería de computadores, iPod, reproductor de DVD" \ "\no juegos electrónicos. Además del moderno sistema de entretenimiento a bordo con" \ "\npantallas generales y canales individuales de audio, está disponible una amplia" \ "\nselección de revistas y diarios." # Descripcion 3 self.desc_3 = "Esta clase fue especialmente diseñada para responder a lo que los\npasajeros de negocios" \ " más valoran en los vuelos de corta duración:\nel cuidado de su tiempo y un servicio de excelencia." \ "En esta clase podrás\naprovechar todas las ventajas de un servicio Premium," \ " volando en Economy:\nacceso a salones VIP asiento en primeras filas con el asiento" \ "\ncentral bloqueado, Check-in y embarque preferente, desembarque y salida\nde equipaje preferente" \ "servicio a bordo de Premium Business, acumulación\nde kms." \ " Mayor franquicia de equipaje (3 piezas de 23 kgs. cada una)." class CabinaEconomica(Cabina, metaclass=ABCMeta): '''Abstracción que representa a una cabina tipo económica''' def __init__(self, precio, nombre): Cabina.__init__(self, precio, nombre) self.desc_1 = "" self.desc_2 = "" self.desc_3 = "" self.ficha_tecnica = "" @classmethod def descripcion_cabina(self): #Descripción 1 self.desc_1 = "Descubre nuestra clase Economy, que con sus tapices renovados, mayor entretenimiento" \ " y la más cálida atención, creará toda una experiencia\nde vuelo para recordar. " \ "Disfruta de los asientos con diseño ergonómico, reclinables y con apoya-cabeza\najustable," \ " pensados únicamente en tu comodidad." # Descripción 2 self.desc_2 = "A veces son muchas horas de viaje que te separan de tu destino, pero cuando todo el vuelo" \ " ha sido pensado para ti, el tiempo y la distancia desaparecen.\n" \ "Sorpréndete y disfruta del sistema de entretenimiento individual con música, videos y juegos" \ " para todos los gustos." # Descripción 3 self.desc_3 = "Desde los simples detalles de nuestra atención, como una sonrisa, queremos transmitirte" \ " nuestro propósito permanente de ofrecerte el mejor servicio a bordo.\n" \ "Además disfruta de los sabores, olores y colores que fueron especialmente elegidos en las comidas" \ " y snacks de la clase Economy." self.ficha_tecnica = "El sistema de entretenimiento a bordo está disponible en nuestros aviones " \ "Alitalia 222, Boeing 777 y Airbus 330." return '\n\n3. BIENVENIDO A LA EXPERIENCIA ECONOMY' + '\n\n>>AMBIENTE Y COMODIDAD<<'\ + self.desc_1 + '\n\n>>VUELOS MÁS CORTOS GRACIAS A NUESTRO ENTRETENIMIENTO A BORDO<<' + self.desc_2 \ +'\n\n' + '>>CALIDAD EN SERVICIO<<' + self.desc_3 + '\n' + 'FICHA TÉCNICA' + self.ficha_tecnica
threes = [value * 3 for value in range(3, 31)] for three in threes: print(three)
seats = input('How many people: ') seats = int(seats) if seats > 8: print("You have to wait for table") else: print("Your table is ready")
guests = ['Katya', 'Kambar', 'Tanya'] print("I would like to invite you", guests[0], "for dinner") print("I would like to invite you", guests[1], "for dinner") print("I would like to invite you", guests[2], "for dinner")
def make_albums(artist, title, songs = None): album = {'artist': '', 'title': ''} album['artist'] = artist album['title'] = title if songs: album['songs'] = songs return album fallout_boy_albums = make_albums('Fallout Boy', 'Centuries', 10) for key, value in fallout_boy_albums.items(): print(key.title(), "and their album", value)
#! /usr/bin/env python3 #2020-07-22(Wes.) Note """ a.py 로 저장 class C: # c = a.C() : class C 의 인스턴스가 생성 def __init__(self): print("class C 의 인스턴스가 생성됨") self.name = "ccc" # print(c.name) ## ccc self.age = 0 # print(c.age) ##출력: 0 def say_hi(self): print("hi") # c.say_hi() ##출력: hi def add_age(self, n:int): self.age += n # c.add_age(5) # print(c.age) ##출력: 5 def __str__(self): return "__str__ 호출됨" # print(c) ##출력: __str__ 호출됨 def __repr__(self): return "__repr__ 호출됨" def __abs__(self): print("__abs__ 호출됨") def __len__(self): print("__len__ 호출됨") def __add__(self, other): return self.age + other.age """ """ 저장 후, 프롬프트 창에서 python 실행 후 입력 """ # 200722(화) 복습 """ 텍스트 파일 1 txt 2 csv: , 3 tsv: tab 4 xml: / 5 json: key value로 구성됨 google: python document json 입력 후 공부 FASTA vs. FASTQ vs. BAM vs. VCF """ print() print('<1. FASTA - 059.fasta 파일의 염기 A,T,C,G 의 갯수 세기>' ) from Bio import SeqIO record = SeqIO.read("059.fasta", "fasta") A = record.seq.count("A") T = record.seq.count("T") C = record.seq.count("C") G = record.seq.count("G") print(f"A: {A}") # A: 497 print(f"T: {T}") # T: 514 print(f"C: {C}") # C: 444 print(f"C: {G}") # G: 585
#!/usr/bin/env python """Convert font PNGs from renderpng.sh into a header with an array of font bitmap data. """ import os from PIL import Image def main(): print('#ifndef FONT_H') print('#define FONT_H') chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZdhms" # Pixel data is in VFD format - column-major order, each byte is 8 consecutive # vertical pixels. print('const uint8_t font[' + str(len(chars)) + '][5] = {') for char in chars: with open(char + '.png', 'rb') as imagefile: print('\t{', end='') image = Image.open(imagefile) pixels = image.load() for x in range(5): pix = 0 for y in range(8): if pixels[x, y+1] == 0: pix |= 1 << (7 - y) print('0x{:02x},'.format(pix), end='') print('},') print('};') print('#endif') if __name__ == '__main__': main()
# This is patterned after the [TensorFlow custom training tutorial] # (https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough#define_the_loss_and_gradient_function). import matplotlib.pyplot as plt def plot_training_experiment(train_loss_results, train_accuracy_results): fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8)) fig.suptitle('Training Metrics') axes[0].set_ylabel("Loss", fontsize=14) axes[0].plot(train_loss_results) axes[1].set_ylabel("Accuracy", fontsize=14) axes[1].set_xlabel("Epoch", fontsize=14) axes[1].plot(train_accuracy_results) plt.show()
class Calculator: def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def add(self): return (self.num2 + self.num1) def subtract(self): if num1 > num2: return (self.num1 - self.num2) else: return (self.num2 - self.num1) def multiply(self): return (self.num2 * self.num1) def divide(self): if self.num2 > self.num1: return (self.num2 / self.num1) demo1 = Calculator(10, 94) print("Addition:", demo1.add()) print("Subtraction:", demo1.subtract()) print("Mutliplication:", demo1.multiply()) print("Division:", demo1.divide())
import unittest from hero import Hero from spell import Spell from weapon import Weapon class TestHero(unittest.TestCase): def setUp(self): self.hero = Hero("Martin", "Manqk", 200, 300, 3) def test_hero_init_(self): self.assertEqual(self.hero.health, 200) self.assertEqual(self.hero.mana, 300) self.assertEqual(self.hero.damage, 0) self.assertEqual(self.hero.name, "Martin") self.assertEqual(self.hero.title, "Manqk") self.assertEqual(self.hero.mana_regen, 3) def test_hero_known_as(self): self.assertEqual(self.hero.known_as(), "Martin the Manqk") def test_hero_equip(self): w = Weapon('noj', 20) self.hero.equip(w) self.assertEqual(self.hero.damage, self.hero.phisical_damage + w.damage) self.assertEqual(self.hero.max_equiped_weapons, 1) self.assertFalse(self.hero.equip(w)) def test_hero_learn(self): s = Spell("BatkaAttack", 30, 50, 2) self.hero.learn(s) self.assertEqual(self.hero.magic_damage, s.damage) self.assertEqual(self.hero.max_learned_spells, 1) self.assertFalse(self.hero.learn(s)) def test_hero_attack(self): w = Weapon('noj', 20) self.hero.equip(w) self.hero.attack(by='weapon') self.assertTrue(self.hero.can_attack()) self.assertEqual(self.hero.damage, self.hero.phisical_damage + self.hero.damage) s = Spell("BatkaAttack", 30, 50, 2) self.hero.learn(s) self.hero.attack(by='magic') self.assertEqual(self.hero.damage, self.hero.magic_damage) self.hero.attack(by='RKO') self.assertRaises(Exception) if __name__ == '__main__': unittest.main()
import unittest from bank_account import BankAccount class TestBankAccount(unittest.TestCase): def setUp(self): self.acc = BankAccount("Sasho", 100, "dollars") self.acc2 = BankAccount("Misho", 200, "dollars") def test_init(self): self.assertEqual(self.acc.get_name(), "Sasho") self.assertEqual(self.acc.get_balance(), 100) self.assertEqual(self.acc.get_currency(), "dollars") def test_deposits(self): self.acc.deposit(200) self.assertEqual(self.acc.get_balance(), 300) def test_withdraw(self): self.acc.withdraw(100) self.assertEqual(self.acc.get_balance(), 0) def test_transfer(self): self.acc.transfer_to(self.acc2, 100) self.assertEqual(self.acc2.get_balance(), 300) def test_history(self): arr2 = self.acc.history(self.acc2, 50) arr = ["Account was created", "Balance : "+str(self.acc.get_balance()), "Sasho transfered 50 dollars to Misho", "Balance : 100"] self.assertEqual(arr, arr2) if __name__ == '__main__': unittest.main()
from unit import Unit class Hero(Unit): def __init__(self, name, title, health, mana, mana_regen): self.name = name self.title = title self.mana_regen = mana_regen Unit.__init__(self, health, mana, name) self.phisical_damage = 0 self.magic_damage = 0 self.max_equiped_weapons = 0 self.max_learned_spells = 0 def __str__(self): return 'Hero(health = ' + str(self.curr_health) + ', mana = ' + str(self.curr_mana) + ')' def known_as(self): return "{} the {}".format(self.name, self.title) def can_equip(self): return self.max_equiped_weapons == 0 def can_learn_spell(self): return self.max_learned_spells == 0 def equip(self, weapon): if self.can_equip(): self.phisical_damage = weapon.damage self.max_equiped_weapons = 1 return True else: print("{} cannot carry anymore weapons.".format(self.known_as())) return False def take_mana(self, mana_points): if map.move_hero(): if (self.get_mana() + self.mana_regen) < self.mana: self.curr_mana = self.get_mana() + self.mana_regen else: if (self.get_mana() + mana_points) < self.mana: self.curr_mana = self.get_mana() + mana_points return self.get_mana() def learn(self, spell): if self.can_learn_spell(): self.magic_damage = spell.damage self.max_learned_spells = 1 return True else: print("{} cannot learn anymore magics.".format(self.known_as())) return False def can_attack(self): if self.max_equiped_weapons == 1 or self.max_learned_spells == 1: return True else: return False def attack(self, **kwargs): for key in kwargs: try: if key == 'by' and kwargs[key] == 'weapon': if self.can_attack() == True and self.phisical_damage != 0: self.damage += self.phisical_damage else: self.damage = self.damage elif key == 'by' and kwargs[key] == 'magic': if self.can_attack() == True and self.magic_damage != 0: self.damage = self.magic_damage else: self.damage = self.damage return self.damage except: raise Exception('for key use {} and for keyworld use {} or {}, please.'.format( 'by', 'weapon', 'magic'))
def getFactorOf(number): for i in range(2, int(number // 2)): if number % i == 0: return i return None def check(number): factor = getFactorOf(number) if factor: print(number, 'has factor', factor) else: print(number, 'is prime') if __name__ == '__main__': check(13) check(13.0) check(15) check(15.0)
s = 'abcdefghjiklmnopqrstuvxyz' # a for char in s: print(ord(char)) # b codesSum = 0 for char in s: codesSum += ord(char) print('The sum is: {0}'.format(codesSum)) # c charCodes = [] for char in s: charCodes.append(ord(char)) print('Char codes are: {0}'.format(charCodes)) # c1 print('Char codes are: {0}'.format(list(map(ord, s))))
def addDict(*dicts): result = {} for d in dicts: for k in d: result[k] = d[k] return result if __name__ == '__main__': d1 = {1: 2, 3: 4, 'c': 'e'} d2 = {'a': 'b', 'c': 'd'} print(d1, d2, addDict(d1, d2))
#fizzbuzz for i in range(1,21): if i%15==0: print("Fizz Buzz") continue if i%3==0: print("Fizz") continue if i%5==0: print("Buzz") continue print(i)
# Use for, .split(), and if to create a Statement that will print out words that start with 's': st = 'Print only the words that start with s in this sentence' words = st.split() for word in words: if word[0] == 's' and len(word) > 1: print(word) # Use range() to print all the even numbers from 0 to 10. range_array = range(1, 11) for r in range_array: if r % 2 == 0: print(r) # Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3. comprehension_array = [three_divided for three_divided in range(1, 51) if three_divided % 3 == 0] print(comprehension_array) # Go through the string below and if the length of a word is even print "even!" even_string = 'Print every word in this sentence that has an even number of letters' for even_word in even_string.split(): if len(even_word) % 2 == 0: print(even_word + " even!") # Write a program that prints the integers from 1 to 100. # But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". # For numbers which are multiples of both three and five print "FizzBuzz". fizz = "Fizz" buzz = "Buzz" for int_num in range(1, 101): if int_num % 15 == 0: print(fizz + buzz) elif int_num % 3 == 0: print(fizz) elif int_num % 5 == 0: print(buzz) else: print(int_num) # Use List Comprehension to create a list of the first letters of every word in the string below: comprehension_string = 'Create a list of the first letters of every word in this string' for letter in [word for word in comprehension_string.split()]: print(letter[0])
import math import constants def calc_alpha_probabilities(alpha): """ Calculate the normalized probabilities for each weight in the alpha distribution :param: alpha: A float between (-2) to 3 :return: A dictionary with the probability for each weight """ constants.print_debug("\ncalculating alpha probabilities") sum_weights = 0 for weight in [constants.WEIGHT_1, constants.WEIGHT_2, constants.WEIGHT_4, constants.WEIGHT_8, constants.WEIGHT_16]: sum_weights += weight ** ((-1) * alpha) # constants.print_debug("{} ** ((-1) * {}) = {}".format(weight, alpha, (weight ** ((-1) * alpha)))) prob_dict = {} for weight in [constants.WEIGHT_1, constants.WEIGHT_2, constants.WEIGHT_4, constants.WEIGHT_8, constants.WEIGHT_16]: prob_dict[weight] = (weight ** ((-1) * alpha)) / sum_weights constants.print_debug("probabilities dictionary:") constants.print_dict(prob_dict) constants.print_debug("sum of all probabilities is: {}\n".format(sum(prob_dict.values()))) return prob_dict def calculate_expected_weight(alpha, alpha_prob_dict=None): """ Calculates the expected weights and store into a dictionary with the keys: UNIFORM/ALPHA_<> :param: alpha: A float between (-2) to 3 for an alpha distribution or None for uniform distribution :param: prob_dict: A dictionary representing the probabilities for each weight :return: The expected weight - 2 * sqrt(the second moment of the distribution) """ if alpha: constants.print_debug("calculating expected weight for alpha= {}:".format(alpha)) sec_moment = 0 for weight in [constants.WEIGHT_1, constants.WEIGHT_2, constants.WEIGHT_4, constants.WEIGHT_8, constants.WEIGHT_16]: sec_moment += (weight ** 2) * alpha_prob_dict[weight] constants.print_debug("weight is: {}".format(sec_moment)) return sec_moment else: constants.print_debug("calculating expected weight for uniform distribution") # the second moment (=E[x^2]) of the uniform[0,1] distribution is 1/3 constants.print_debug("weight is: {}".format(2 * math.sqrt(1/3))) return 2 * math.sqrt(1/3)
class Bullet(): _instances = [] ''' Bullet class should have only 1 instance ''' def __init__(self,Img): self.Img = Img self.bullet_state = False if len(self._instances) == 0: self._instances.append(self) else: raise Exception("This class is Singleton") def fire(self,screen,x,y): self.bullet_state = True screen.blit(self.Img , (x+16,y+16)) def display(self,screen,x,y): return screen.blit(self.Img , (x,y))
## 1. Execute Method Placeholders ## row_values = { 'identifier': 1, 'mail': '[email protected]', 'name': 'Adam Smith', 'address': '42 Fake Street' } import psycopg2 conn = psycopg2.connect("dbname=dq user=dq") cur = conn.cursor() cur.execute("INSERT INTO users VALUES( %(identifier)s, %(mail)s, %(name)s, %(address)s);", row_values) conn.commit() conn.close() ## 2. SQL Injections ## def get_email(name): import psycopg2 conn = psycopg2.connect("dbname=dq user=dq") cur = conn.cursor() # create the query string using the format function query_string = "SELECT email FROM users WHERE name = '" + name + "';" # execute the query cur.execute(query_string) res = cur.fetchall() conn.close() return res all_emails = get_email("Elena' OR 1=1; --") ## 3. Getting the Address ## def get_email(name): import psycopg2 conn = psycopg2.connect("dbname=dq user=dq") cur = conn.cursor() # create the query string using the format function query_string = "SELECT email FROM users WHERE name = '" + name + "';" # execute the query cur.execute(query_string) res = cur.fetchall() conn.close() return res print( get_email("Larry Cain' UNION SELECT address FROM users WHERE name = 'Larry Cain") ) ## 4. Avoiding SQL Injections ## def get_email_fixed(name): import psycopg2 conn = psycopg2.connect("dbname=dq user=dq") cur = conn.cursor() # fix the line below cur.execute("SELECT email FROM users WHERE name= %s;", (name,)) res = cur.fetchall() conn.close() return res ## 5. Prepared Statements ## import psycopg2 user = (10003, '[email protected]', 'Alice', '102, Fake Street') conn = psycopg2.connect("dbname=dq user=dq") cur = conn.cursor() cur.execute(""" PREPARE insert_user AS INSERT INTO users VALUES ($1, $2, $3, $4); """) cur.execute(""" EXECUTE insert_user(%s, %s, %s, %s); """, user) ## 6. Prepared Statements Table ## import psycopg2 conn = psycopg2.connect("dbname=dq user=dq") cur = conn.cursor() cur.execute(""" PREPARE get_email AS SELECT email FROM users WHERE name = $1; """) cur.execute(""" EXECUTE get_email(%s); """, ("Anna Carter",)) anna_email = cur.fetchone() print(anna_email) cur.execute("SELECT * FROM pg_prepared_statements;") print(cur.fetchall()) ## 7. Runtime Gain ## import timeit import psycopg2 import csv # function that inserts all users using a prepared statement def prepared_insert(): conn = psycopg2.connect("dbname=dq user=dq") cur = conn.cursor() cur.execute(""" PREPARE insert_user(integer, text, text, text) AS INSERT INTO users VALUES ($1, $2, $3, $4) """) for user in users: cur.execute("EXECUTE insert_user(%s, %s, %s, %s)", user) conn.close() # function that insert all users using a new INSERT query for each user def regular_insert(): conn = psycopg2.connect("dbname=dq user=dq") cur = conn.cursor() for user in users: cur.execute(""" INSERT INTO users VALUES (%s, %s, %s, %s) """, user) conn.close() # read the users into a list users = [ ] with open('user_accounts.csv', 'r') as file: next(file) # skip csv header reader = csv.reader(file) for row in reader: users.append(row) time_prepared = timeit.timeit(prepared_insert, number=1) time_regular = timeit.timeit(regular_insert, number=1) print(time_prepared) print(time_regular)
## 1. Introduction ## import pandas as pd ## 2. Read a CSV with Pandas ## import pandas as pd cars = pd.read_csv("cars.csv") ## 3. Dataframes ## cars_shape = cars.shape first_six_rows = cars.head(6) last_four_rows = cars.tail(4) ## 4. Accessing Data With Indexes ## cars_odd = cars.iloc[1::2, 0:3 ] fifth_odd_car_name = cars_odd.iat[4,0] last_four = cars_odd.tail(4) print(last_four) ## 5. Accessing Data With Names ## cars.set_index("Name", inplace=True) weight_torino = cars.loc["Ford Torino", "Weight"] ## 6. Dataframe Indexes ## honda_civic_hp = cars.loc["Honda Civic","Horsepower"] print(honda_civic_hp) cars.reset_index(inplace=True) ## 7. Delving Deeper Into Loc ## numeric_data = cars.loc[:, "MPG":"Acceleration"] numeric_data.head() ## 8. Selecting Columns ## weights = cars["Weight"] name_origin_0_and_3 = cars.loc[[0,3],["Name", "Origin"]] ## 9. Selecting Rows ## car_100 = cars.iloc[99, :] cars_2_to_10 = cars.iloc[1:10, :] ## 10. Index Locations and Label Locations ## num_rows = cars.shape[0] one_index = pd.Index([i for i in range(1, num_rows+1)]) cars.set_index(one_index, inplace=True) car_100 =cars.loc[100] cars_2_to_10 = cars.loc[2:10, :]
class Node: def __init__(self, letter): self.childleft = None self.childright = None self.Nodedata = letter # create the nodes for the tree root = Node('A') root.childleft = Node('B') root.childright = Node('C') root.childleft.childleft = Node('D') root.childleft.childright = Node('E')
import RPi.GPIO as GPIO import sys import time from datetime import datetime from lib.relay import Relay from lib.temp_sensor import TempSensor relay_pin = 16 # After turning the relay on or maintaining current status, sleep this period before checking the temperature again period = 30 # Set the GPIO mode to use the board numbers GPIO.setmode(GPIO.BOARD) # Initialize the AC relay pin in the off state GPIO.setup(relay_pin, GPIO.OUT, initial=0) upper_threshold = 80.00 lower_threshold = 79.00 def execute(relay, temp_sensor): while True: temp = temp_sensor.get_temp() print('Temperature at {now} is {temp} degrees Fahrenheit.'.format(now=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),temp=temp)) if temp >= upper_threshold and relay.is_on == False: print("Turning unit on...") relay.turn_on() time.sleep(period) elif temp < lower_threshold and relay.is_on == True: print('Turning unit off...') relay.turn_off() # In this case, sleep for a manufacturer-specified reset period for the AC unit. Not all units may have such a recommendation. time.sleep(relay.reset_period) else: print('Maintaining current status...') time.sleep(period) if __name__ == '__main__': try: relay = Relay(relay_pin) temp_sensor = TempSensor() execute(relay, temp_sensor) except KeyboardInterrupt: print('Exiting...') GPIO.cleanup() sys.exit(0)
import unittest import shoppingCart as sc class TestShoppingCart(unittest.TestCase): def test_addToCart(self): tsc=sc.ShoppingCart() #If any invalid Item is added to Cart which is not present in PriceList self.assertRaises(KeyError,tsc.addToCart,['T-Shirt','Mukesh','Jacket']) #Empty Input self.assertRaises(ValueError,tsc.addToCart,[]) def test_getTaxApplied(self): tsc=sc.ShoppingCart() self.assertEqual(tsc.getTaxApplied(8500),1530) #Zero or Negative Tax Values for Discount Rates tsc.taxprct=0 self.assertRaises(ValueError,tsc.getTaxApplied,100) tsc.taxprct=-1 self.assertRaises(ValueError,tsc.getTaxApplied,100) def test_getSubTotal(self): tsc=sc.ShoppingCart() tsc.loadpricelist() inputlis1=['T-Shirt','T-Shirt','Shoes','Jacket'] tsc.addToCart(inputlis1) self.assertEqual(tsc.getSubTotal(tsc.cart),8500) tsc1=sc.ShoppingCart() tsc1.loadpricelist() inputlis2=['T-Shirt','Trousers'] tsc1.addToCart(inputlis2) self.assertEqual(tsc1.getSubTotal(tsc1.cart),2000) #To Check the eligibility for Discount Offers def test_checkOffers(self): inputlis1=['T-Shirt','T-Shirt','Shoes','Jacket'] tsc=sc.ShoppingCart() tsc.loadpricelist() #2 TShirts 1 Shoes 1 Jacket Discount to be applied on Shoes & Jacket tsc.addToCart(inputlis1) discounts=tsc.CheckOffers() if 'Shoes' in discounts: self.assertEqual(discounts['Shoes'],500) if 'Jacket' in discounts: self.assertEqual(discounts['Jacket'],1250) # TShirts 1 Shoes 1 Jacket Discount to be applied only on Shoe tsc1=sc.ShoppingCart() tsc1.loadpricelist() inputlis2=['T-Shirt','Shoes','Jacket'] tsc1.addToCart(inputlis2) discounts2=tsc1.CheckOffers() if 'Shoes' in discounts: self.assertEqual(discounts2['Shoes'],500) #3 TShirts 1 Shoes 2 Jacket Discount to be applied on Shoes & only 1 Jacket tsc2=sc.ShoppingCart() tsc2.loadpricelist() inputlis3=['T-Shirt','Shoes','Jacket','T-Shirt','T-Shirt','Jacket'] tsc2.addToCart(inputlis3) discounts3=tsc2.CheckOffers() if 'Jacket' in discounts: self.assertEqual(discounts3['Jacket'],1250) if __name__=='main': unittest.main()
import json from difflib import get_close_matches data=json.load(open("dat.json")) def word_meaning(w): w=w.upper() if w in data: return data[w] elif len(get_close_matches(w,data.keys())) > 0: print("Did you mean %s instead ?" %get_close_matches(w,data.keys())[0]) new_word=input("Enter the word ") return word_meaning(new_word) else: return "The word does not exist in dictionary" word=input("Enter the word You want the meaning for :") meaning=word_meaning(word) print(meaning)
import tkinter as tk # 第1步,实例化object,建立窗口window window = tk.Tk() window.title("番茄time") window.geometry('400x400') # 长x宽 var = tk.StringVar() e1 =tk.Entry(window,textvariable=var,font=("Microsoft Yahei",14)) e1.place(x=100,y=100) # e1.focus_set() a = e1.get() #放置标签 #test.place() window.mainloop() # print(e1.get()) for i in range(10): print(a)
def car(s,many): #排序 int_sort =sorted(many,reverse=True) #计算车辆数量 count=0 #转化为文本列表 str_sort =[str(i) for i in int_sort] while len(str_sort)>0:#str sort 列表未清空时: all=[]#创建 all 并每次清空all 列表 m=len(str_sort)#判断当前 str sort 长度 # i=0 for l in range(1,m): #每次从当前 str sort第一个元素为开始(一直在变),从第二个加 检查和是否等于s lin=[str_sort[0]]#记录0 num(也就是第一个元素)到 lin中 sum=int(str_sort[0]) sum+=int(str_sort[l])#sum为 l num 与0 num 之和 #根据上面的sum与s的比较 分情况判断 if sum==s:#等于 lin.append(str_sort[l])#记录l num到 lin中 all.append([sum,lin])#记录lin到 all中 sum=0#sum清0 break #推出当前for 循环 elif sum>s:#大于 continue #退出本次l 循环,进入下次l+1 for循环 elif sum<s:#小于 lin.append(str_sort[l]) #记录l num到 lin中 j=l+1 while j<m: sum+=int(str_sort[j])# sum 为 :j num 与 l num 与0 num 之和 if sum>s: sum-=int(str_sort[j])#sum去掉上一步操作,为 l num 与0 num 之和 j+=1 continue#退出本次j 循环,进入下次j+1 for循环 else:#sum<=s的时候 lin.append(str_sort[j]) #记录j num到 lin中 j+=1 else:#当j >= m的时候,j为最后一个元素 all.append([sum,lin]) if len(all)>=1: all.sort(reverse=True)#根据all列表里面的列表的数字部分(也就是sum)按降序排序, print("第",count+1,"车,装载:",",".join(all[0][1]))#取第一个元素,为列表(即sum最大的)的第二个元素(即要求的组合), for item in all[0][1]: str_sort.remove(item) #删除已用求和的数据 else:#未给all赋值,表明第一个num 等于或者很接近于 目的值 加上其他任何一个值 都大于S print("第",count+1,"车,装载:",str_sort[0])#取第一个元素 str_sort.remove(str_sort[0]) count+=1 #str_sort 元素清空,结束while循环, print('最少需要使用',count,'个平面面积为',s,'的物流车') input_s=int(input("请输入物流车的平面面积:\n")) input_m=input("请输入每个箱子平面面积的大小,用英文逗号间隔箱子平面面积:\n").split(",") new=[int(i) for i in input_m] car(input_s,new) '''思路总结:复制输入列表 降序 当列表长度大于0: '''
import heapq from collections import OrderedDict from collections import deque import math # 平均值函数 def avg(data): a = 0 for i in data: a = a+i return round(a/len(data), 1) # 去头尾 求平均值 def dropFL(data): _discard, *medi, _discard2 = data return avg(medi) ''' data = [1,4,3,8,10,9] data.reverse() print(dropFL(data)) # 星号解压语法 records =[('foo', 1, 2), ('bar', 'hello'), ('foo', 3, 4)] for arg, *args in records: # print(arg,"===",*arg) if arg == 'foo': print(*args)#智能用args表示多个数据, record = ('ACME', 50, 123.45, (12, 18, 2012)) name, *_, (*_, year) = record# _表示要丢弃的变量 print(name,year) ''' def sum(items): head, *tail = items print("head is ", head) return head + sum(tail) if tail else head # items = [1, 10, 7, 4, 5, 9] # print(sum(items)) def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for li in lines: if pattern in li: yield li, previous_lines previous_lines.append(li) # Example use on a file # if __name__ == '__main__': # with open(r'D:\github\pythonFile\每日一题\text.txt',encoding="utf-8") as f: # for line, prevlines in search(f, '第三方', 5): # for pline in prevlines: # print(pline, end='') # print(line, end='') # print('-' * 20) nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23] print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2] portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) # print(cheap,expensive) a = {"a": [1, 2, 3], "b": [2]} # 有序字典 # def ordered_dict(): d = OrderedDict() d['foo'] = 1 d['bar'] = 2 d['spam'] = 3 d['grok'] = 4 # Outputs "foo 1", "bar 2", "spam 3", "grok 4" # for key in d: # print(key, d[key]) # 字典排序 最大最小 prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } # zip() 函数创建的是一个只能访问一次的迭代器 tt = zip(prices.values(), prices.keys()) # print(min(tt),max(tt)) #会报错 min_price = min(zip(prices.values(), prices.keys())) max_price = max(zip(prices.values(), prices.keys())) # prices_sorted = sorted(zip(prices.values(), prices.keys())) # print(min_price,max_price) # print(prices_sorted) #取最小值或最大值对应的键的信息 如果恰巧最小或最大值有重复的,那么拥有最小或最大键的实体会返回 print(min(prices, key=lambda k: prices[k]) ) max(prices, key=lambda k: prices[k])
#创建text文件 并逐行写入 import os # ls =os.linesep#行的切换符号 适用于任何平台 Windows Unix # print(ls) class TextFlie: def __init__(self): self.fileName =input("please enter your file name:") def makeTextFlie(self): #检查filename 是否已存在 #os.path.exists 处理异常 # while True: # if os.path.exists(self.fileName): # print("Error: {} already exists".format(self.fileName)) # else: # break #输入文本 print("输入 quit 结束") allStrList =[] while True: entryStr = input("please enter your content:") if entryStr == "quit": break else: allStrList.append(entryStr) # print(["{}{}".format(x,ls) for x in allStrList]) #写入text fileObj = open(self.fileName,"w") fileObj.writelines(["{}{}".format(x,"\n") for x in allStrList]) fileObj.close() print("done......") def readTextFlie(self): fileObj = open(self.fileName,"r") for l in fileObj: print(l) fileObj.close() if __name__ == '__main__': textf = TextFlie() textf.makeTextFlie() textf.readTextFlie()
import io from nltk.corpus import stopwords from nltk.tokenize import word_tokenize #word_tokenize accepts a string as an input, not a file. stop_words = set(stopwords.words('english')) file1 = open("2015b.txt") line = file1.read()# Use this to read file content as a stream: words = line.split() for r in words: if not r in stop_words: appendFile = open('filteredtext.txt','a') appendFile.write(" "+r) appendFile.close()
celsius = 37 fahrenheit = (celsius * 1.8) + 32 print ("%.2f celsius = %.2f Fahrenheit" %(celsius,fahrenheit))
''' Figuring out how to work with zip files in memory ''' import io from tempfile import TemporaryFile from zipfile import ZipFile import requests import pandas as pd # Typical CSV file content df = pd.DataFrame({'a': (1, 2), 'b': (3, 4)}) fname = 'stata_out.dta' # write file to disk df.to_stata(fname) # Write to zipfile with open(fname, 'rb') as source, ZipFile('stata.zip', mode='w') as target: target.writestr(fname, source.read()) # Read out the bytes with ZipFile('stata.zip').open(fname) as z: fb = io.BytesIO(z.read()) df2 = pd.read_stata(fb) # Try it on the web: url = 'http://download.geonames.org/export/zip/BD.zip' response = requests.get(url) archive = ZipFile(io.BytesIO(response.content)) df = pd.read_csv(archive.open('BD.txt'))
''' iterable_cards.py This script demonstrates core data structures and iterables in Python 3 using basic statistical concepts. Pay attention to what lazy evaluation does for the program's memory usage. In this simple card game each card has a value. A player draws several cards without replacement and sums their values to determine their final score. Task: Understand the probability distribution for scores from this card game. Approach 1: Convert directly to DataFrame dist = pd.Series(list(allhands())) dist.hist(bins=100) Approach 2: Reduce operation This has the advantage of being able to run an arbitrarily large data. For example, the line below produces and scores 750 million hands. score_counts = collections.Counter(allhands(handsize=8)) ''' import itertools suits = {'clubs', 'spades', 'hearts', 'diamonds'} # Face cards have these values: cards = {'jack': 13, 'queen': 17, 'king': 18, 'ace': 50} # Numbered cards are worth twice their face value nums = range(2, 11) numbered_cards = zip(nums, (2 * x for x in nums)) cards.update(numbered_cards) def score(hand): ''' Random variables are functions from the sample space to the real line. This one sums the values of the cards in the hand by looking up the value of cards in the module namespace. >>> hand = ((5, 'C'), (5, 'S'), (5, 'H'), (5, 'D'), (2, 'C')) >>> score(hand) 44 ''' return sum(cards[x[0]] for x in hand) def allhands(handsize=5, random_variable=score): ''' Returns an iterator that applies a random variable to each possible hand of size `handsize`. >>> small = list(allhands(handsize=2)) >>> max(small) 100 >>> len(small) 1326 >>> from scipy.misc import comb >>> comb(N=52, k=2, exact=True) 1326 Use `scipy.misc.comb` to verify expectations. Here 52 choose 2 hands are generated and scored. ''' # The cartesian product of cards and suits produces a deck of cards. deck = itertools.product(cards.keys(), suits) # This iterator produces all possible combinations of 5 card hands. sample_space = itertools.combinations(deck, handsize) # Apply the random variable to every element in the sample space. return map(random_variable, sample_space) if __name__ == '__main__': import doctest doctest.testmod()
''' Chapter 9, Exercise 2 on page 146 of Wasserman's All of Statistics Maximum likelihood estimators for parameters of uniform distribution. Solving numerically as a constrained optimization problem. Amazing what a difference it makes to use the log of the objective function rather than the actual objective function. ''' import numpy as np from scipy import stats from scipy.optimize import minimize, root np.random.seed(89) # True parameters a, b = -10, 10 # Simulated data n = 20 X = stats.uniform(a, b - a).rvs(n) minX, maxX = min(X), max(X) meanX, sdX = np.mean(X), np.std(X) def obj(x): ''' objective function to minimize, taking array as input ''' a, b = x return -(b - a) ** (-n) def log_obj(x): ''' logarithm of objective function with constants dropped ''' a, b = x return -np.log(1 / (b - a)) # Initializing with actual values min_out = minimize(log_obj, (a, b), #tol=1e-100, #method='L-BFGS-B', #method='SLSQP', bounds=((None, minX), (maxX, None))) if all(min_out.x == (minX, maxX)): print('Numerical optimization of MLE matched theoretical result exactly.') ############################################################ # # Method of moments # Numerically solve a system of nonlinear equations # # This doesn't work well at all here. Why do this over MLE? # ############################################################ # Theoretical results mm_a = meanX - np.sqrt(meanX ** 2 + 3 * sdX - meanX) mm_b = 2 * meanX - mm_a def f(x): ''' Defines nonlinear system of equations ''' a, b = x return [(a + b) / 2 - meanX, (b - a) ** 2 - 12 * sdX] root_out = root(f, [a, b]) message = ''' True a and b values: {}, {} Theoretical a, b from method of moments: {}, {} Numerical a, b from method of moments: {}, {} The theoretical and numerical should be very close. If they aren't it's because my math is wrong. '''.format(a, b, mm_a, mm_b, *root_out.x) print(message)
import enum class Direction(enum.Enum): UP = 1 DOWN = -1 RIGHT = 2 LEFT = -2 def is_opposite(self, direction): return self.value == -direction.value if __name__ == "__main__": """should be TRUE""" print(Direction.UP.is_opposite(Direction.DOWN)) """should be FALSE""" print(Direction.UP.is_opposite(Direction.RIGHT))
# coding:utf-8 __author__ = 'sinlov' # python 中含有一个类型是列表类型,列表是可变的序列,可以保存任何类型 book = ['python', 'Development', 8, 2008] book.insert(1, 'web') print("print book list", book) print("print book list slicing ", book[:2]) # check object is in list print("is python in book?", 'python' in book) # remove object my_list = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'] print("from my_list full", my_list) my_list.remove('w') print("from my_list remove item 'w'", my_list) my_list.pop(2) print("from my_list remove item by index", my_list) # copy list by '*' copy_list = ['a', 's', 'd'] print("this is one list to copy begin", copy_list) print("this is one list to copy after", copy_list * 2) # extend this list copy_list.extend(['f', 'g']) print("list copy list can extend", copy_list) # can sort this list for_sort = ['python', 'Development', 8, 2008, 'web'] print("list for sort before", for_sort) for_sort.sort() print("list for sort before", for_sort) # python 对于未指定的混合序列,排序是不定的,默认顺序是,先对所有数字进行排序,然后对于字符串按照字典排序, # 如果是对象类型,则非常混乱 # 列表中,内置函数, sort() append() insert 都是直接对对象进行修改,没有返回值。所以,直接打印 list.soft() 会返回none。 # 而字符串的操作函数,如 upper() 是返回一个字符串(其实是包含一个全部是大写的字符串拷贝,所以未对原有字符串对象进行修改, # 新增了一个字符串)如果是希望得到一个排好序的拷贝, # 使用 sorted() 或者 reversed # 分别意思为接受一个列表作为参数并返回一个排好序的或者倒序的拷贝 # list comprehension 是一个由逻辑代码组成的结构, 包含一段逻辑代码生成的值或者对象 # list comperhension 列推导 data = [x + 1 for x in range(10)] print("list comperhension", data) even_numbers = [x for x in range(10) if x % 2 == 0] print("list comperhenison by double", even_numbers) # 这种写法常用于过滤表达式 其中 x 本身就是一个表达式值 # generator expression generator_number = (x for x in range(10000) if x % 2 == 0) print("generator numbers print", generator_number)
#Initial conditions: choose v0 = 0, p = -1, timestep = choose #d2s/dt2 = -Ps(t) #s(tn) ~~ s(t0) + ds/dt * DeltaT #v(tn) ~~ v(t0) + dv/dt * DeltaT import numpy as np import matplotlib.pyplot as plt #P, t0, delta_t, s0, a0, v0, delta_v, delta_s def acceleration(p,s,damp=0, v=0): """an expression for the acceleration of a harmonic oscillator s is the position value, Q is a damping coefficient p is the spring coefficient v is velocity""" return -p * s - damp*v def updater(c0, u, delta_t): """provided an initial value and the corresponding value to update by, it will update using Euler's forward method""" c1 = c0 + u * delta_t return c1 def eulers_spring(dt=.05,p=1,s0=1,v0=0,t0=0,damp=0,plotit = True,trials = 1000): """dt is time step, p is the spring coefficient, s0 is the initial position value (extension), v0 is initial velocity, t0 is initial time damp provides a damp coefficient to the spring system set the damp value to 0.05 to counteract euler's algorithm's instability, plotit allows you to choose to plot both velocity and position in time, or simply one.""" delta_t = dt s = np.zeros([trials+1]) v = np.zeros([trials+1]) t = np.zeros([trials+1]) s[0] = s0 v[0] = v0 t[0] = t0 for i in range(trials): s[i + 1] = updater(s[i],v[i], delta_t) v[i + 1] = updater(v[i],acceleration(p,s[i],v=v[i],damp=damp),delta_t) t[i + 1] = updater(t[i],1,delta_t) #s[i + 1] = s[i] + v[i] *delta_t #non functional implementation I saw online #v[i + 1] = v[i] + -p*s[i] * delta_t #t[i + 1] = t[i] + delta_t if plotit == True: plt.plot(t,s) plt.plot(t,v) plt.show() print(eulers_spring(damp = 0.05))
""" Project Euler Problem 5 ======================= 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest number that is evenly divisible by all of the numbers from 1 to 20? """ def smallest_common_multiple(limit): num = 1 i = 1 step = 0 while i <= limit: if num % i == 0: i += 1 step = num else: num += step return num def main(): limit = 20 print(smallest_common_multiple(limit)) if __name__ == '__main__': main()
# friends1 = ["Jim", 2, false] friends = ["Jim", "Bob", "Fred", "Mary", "John", "Shaun"] friends[1] = "changed from Bob" print(friends[-1]) print(friends[1:]) print(friends[2:4]) print(friends[1])
class Vehicle(object): def Move(self): print ("Vehicle is moving") def Transpot(self): print ("Vehicle is transpoting") class Car(Vehicle): def __init__(self,weight,height): self.weight = weight self.height = height def SpeedUp(self): print ("Car is speeding up") def SpeedDown(self): print("Car is speeding down") def ShowInfo(self): print ("weight is %d,height is %d"%(self.weight,self.height)) Benz = Car(2000,1100) Benz.SpeedUp() Benz.ShowInfo() Benz.Move() Benz.Transpot()
from sys import exit from random import randint class Scene(object): def enter(self): print "You have found an unfinished scene. Woops." exit(1) class Engine(object): def __init__(self, scene_map): self.scene_map=scene_map def play(self): #Get player name, boon, and bane stats = { "name":"Aerith", "HEALTH":10, "STRENGTH":10, "SMARTS":10, "SPEED":10, "DEFENSE":10, "SLOT_ONE":"NA", "SLOT_TWO":"NA" } print "Hero, you alone have the courage to save this land. What is your name?" name = raw_input(">>") stats["name"]=name print "Your mother was in the ROYAL GUARD, and she always said heroes had five main traits, HEALTH, STRENGTH, SMARTS, SPEED, and DEFENSE." print "Which of these are you best at?" boon = raw_input(">>").upper() while boon!="HEALTH" and boon!="STRENGTH" and boon!="SMARTS" and boon!= "SPEED" and boon !="DEFENSE": print "Take this seriously, young hero." boon = raw_input(">>") stats[boon]=18 print "Which of them did you really suck at?" bane = raw_input(">>") while bane!="HEALTH" and bane!="STRENGTH" and bane!="SMARTS" and bane!="SPEED" and bane!="DEFENSE": print "Take this seriously, young hero." bane = raw_input(">>") if bane=="YOUAREABIGGUY": print "FOR YOU" #set health and strength to 20 stats["HEALTH"]=20 stats["STRENGTH"]=20 stats[bane]=5 print "Well then, let us begin." #Run first scene current_scene=self.scene_map.opening_scene() last_scene=self.scene_map.next_scene('fin') while current_scene!=last_scene: #current_scene.enter() needs to return (name of the next scene,stats) print stats print current_scene next_scene_name,new_stats=current_scene.enter(stats) stats=new_stats current_scene=self.scene_map.next_scene(next_scene_name) current_scene.enter(stats) def drop(item,ply_sts): if item==1: ply_sts["SLOT_ONE"]=="NA" return ply_sts else: ply_sts["SLOT_TWO"]=="NA" return ply_sts #Adds an item to the inventory, possibly calling drop to prompt player to drop an item def take(item,ply_sts): if ply_sts.get("SLOT_ONE")=="NA": ply_sts["SLOT_ONE"]=item print "You pick up "+item return ply_sts elif ply_sts.get("SLOT_TWO")=="NA": ply_sts["SLOT_TWO"]=item print "You pick up "+item return ply_sts else: print "Your backpack is full! Which Slot would you like to drop from?" print "Slot one contains "+ply_sts.get("SLOT_ONE") print "Slot two contains "+ply_sts.get("SLOT_TWO") print "Enter 1, 2, or NA." act=raw_input(">>") if act==1: return drop(1,ply_sts) elif act==2: return drop(2,ply_sts) elif act.upper()==NA: print "Ah well, you leave "+item+" behind." return ply_sts else: print "WHAT ARE YOU SAYING. I CAN NOT UNDERSTAND YOU. PLEASE." return ply_sts #Checks if a player has an item(for solving puzzles), returns True if they do, False otherwise def check(item,ply_sts): if ply_sts.get("SLOT_ONE")==item: return True else: return False def statCheck(DC,stat,ply_sts): if ply_sts[stat]>=DC: return True else: return False class Death(Scene): def enter(self,ply_sts): print "You have died an ignoble death, the land shall be terrorized forevermore." exit(1) class Drawbridge(Scene): def __init__(self):#, ply_sts): print "Enter Drawbridge." def enter(self,ply_sts): print "The rain batters down on your mother's armor(Unfortunately she left no sword) as you are confronted with the sprawling home of the LICH KING, known only as ALDER KEEP." print "The drawbridge is raised, and the moat churns with dark shapes in the water. Lurid light pours from several small windows about the walls of the keep. A small boat lies wrecked against the trees, tossed by some great power. It is completely destroyed, but a rope is strewn amongst it." print "The grass is slick with mud underfoot, and the road you came in on is but a dirt path. A number of trees line the edges of the moat." print "What dost thou do?" ropeTaken=False while True: act=raw_input(">>") if act.upper()=="LOOK" or act.upper()=="EXAMINE" or act.upper()=="SEARCH": print "While looking around, you find a set of tracks leading from the edge of the moat. It looks like they have come from a sewer grate on the side of the castle, which has been busted open. You could fit inside, but it's quite a distance to jump, way more than most people can." print "What do you doest?" elif act.upper()=="TAKE ROPE" and ropeTaken==False: print "You pick up the rope." ropeTaken==True if ply_sts.get("SLOT_ONE")=="NA": ply_sts["SLOT_ONE"]="ROPE" elif act.upper()=="JUMP TO WINDOW" and (ply_sts.get("SLOT_ONE")=="ROPE" or ply_sts.get("SLOT_TWO")=="ROPE"): print "You take your rope and throw it to the window, using it to swing over easily and clamber up!" return ("Pantry",ply_sts) elif act.upper()=="JUMP TO WINDOW" and ply_sts.get("SLOT_ONE")!="ROPE" and ply_sts.get("SLOT_TWO")!="ROPE": print "The window is very far to jump to, unless you had something to bridge the gap, or if you're very strong." print "Do you want to try and jump?" act2=raw_input(">>") if act2.upper()=="YES" or act2.upper()=="Y": if ply_sts.get("STRENGTH")<12 and ply_sts.get("SLOT_ONE")!="ROPE" and ply_sts.get("SLOT_TWO")!="ROPE": print "You leap, and you fail. Sucks to be you, hero. The shark bears infesting the waters devour you." else: if (ply_sts.get("SLOT_ONE")=="ROPE" or ply_sts.get("SLOT_TWO")=="ROPE"): print "You swing the rope up onto a branch, and use it to swing towards the window!" if ply_sts.get("SLOT_ONE")=="ROPE": ply_sts["SLOT_ONE"]="NA" elif ply_sts.get("SLOT_TWO")=="ROPE": pl_sts["SLOT_TWO"]="NA" print "You fly like an eagle, and roll straight through the window!" #enter pantry return ("Pantry",ply_sts) elif act2.upper()=="NO" or act2.upper()=="N": print "probably a smart choice." else: print "Well, I'll take that as a no." elif act.upper()=="JUMP TO HOLE" or act.upper()=="JUMP IN HOLE": print "You brace yourself, take a few steps back, and then take a running jump towards the grate!" if ply_sts.get("STRENGTH")<12: print "Well damn young hero, I guess you shouldn't have skipped leg day so many times." print "You leap forwards with all your strength, but unfortunately all your strength isn't enough strength." print "You plummet into the water, and are eaten by horrendously large shark-bears." return("Death") else: print "Grass and mud tears up beneath your feet as you leap forwards with great power!" print "You slam into the wall, and scrabbling for a handhold, you manage to grasp it, and climb in." #enter dungeon return ("Dungeon",ply_sts) else: print "Sorry, I don't understand." class Grand_Hall(Scene): def enter(self,ply_sts): pass class Pantry(Scene): def enter(self,ply_sts): pass class Armory(Scene): def enter(self,ply_sts): pass class Dungeon(Scene): def enter(self,ply_sts): print "You stumble through the darkness, slipping on wet cobblestones strewn with brittle bones and moist fungus." print "Soon, you enter a pool of lurid light, cast by a single roughshod lantern hanging from a crude hook on the wall." print "There is a small table stained dark red with some substance, one you don't care to investigate." print "Three cells sit in a row along the north wall, two opened. One door sits to your east, made of wood and shut." print "The cells are labeled A, B, and C. The one labelled C is still closed." print "What do you do?" LanternTaken=False HookTaken=False while True: act=raw_input(">>").upper() if act=="TAKE LANTERN" or act=="GET LANTERN": print "You grab the lantern off the hook." if ply_sts.get("SLOT_ONE")=="NA" and ply_sts.get("SLOT_TWO")=="NA": ply_sts["SLOT_ONE"]="LANTERN" LanternTaken=True elif ply_sts.get("SLOT_ONE")!="NA" and ply_sts.get("SLOT_TWO")=="NA": ply_sts["SLOT_TWO"]="LANTERN" LanternTaken=True else: print "Your hands are full, so you put it back." elif act=="TAKE HOOK" or act=="GET HOOK": if ply_sts.get("STRENGTH")>=18: print "You rip that hook right outta the stone. You're strong as hell." if ply_sts.get("SLOT_ONE")=="NA" and ply_sts.get("SLOT_TWO")=="NA": ply_sts["SLOT_ONE"]="HOOK" HookTaken=True elif ply_sts.get("SLOT_ONE")!="NA" and ply_sts.get("SLOT_TWO")=="NA": ply_sts["SLOT_TWO"]="HOOK" HookTaken=True else: print "Your hands are full, do you want to drop something? If yes, tell me 1 or 2." act2=raw_input(">>").upper() if act2=="1": print "Cool, you throw that thing away and take the new thing instead." ply_sts["SLOT_ONE"]="HOOK" HookTaken=True elif act2=="2": print "Cool, you throw that thing away and take the new thing instead." ply_sts["SLOT_TWO"]="HOOK" HookTaken=True else: print "You put it back though, your hands are full." else: print "You tug on it, but it doesn't come out." else: print "Sorry, I don't understand." class Throne_Room(Scene): def enter(self,ply_sts): pass def battle(self): pass class fin(Scene): def enter(self,ply_sts): pass class Map(object): sceneList={ 'Drawbridge':Drawbridge(), 'Death':Death(), 'Grand Hall':Grand_Hall(), 'Pantry':Pantry(), 'Armory':Armory(), 'Dungeon':Dungeon(), 'Throne_Room':Throne_Room(), 'fin':fin() } def __init__(self, start_scene): #Sets the first scene to the parameter which Map is called with self.start_scene=start_scene def next_scene(self, scene_name): #Retrieve and return the function(or result of said function?) based off the scene name returned by #the ending of the current scene return Map.sceneList.get(scene_name) def opening_scene(self): #return the starting scene that was given to the map as a parameter return self.next_scene(self.start_scene) a_map=Map('Drawbridge') a_game=Engine(a_map) a_game.play()
#!/usr/bin/env python # coding: utf-8 # In[4]: import json import pandas as pd import requests # In[1]: #Part III: Steam API #In order to search for specific info about each game, we need to maintain a list of games and their corresponding steam app id #to do so, we use the steam_app_id() which returns a list of ids of the desired games from the input dataframe def steam_appid(df): url1='http://api.steampowered.com/ISteamApps/GetAppList/v0001/' url2='http://api.steampowered.com/ISteamApps/GetAppList/v0002/' response = requests.get(url1) game_lst1 = response.json()['applist']['apps']['app'] response = requests.get(url2) game_lst2 = response.json()['applist']['apps'] game_lst = game_lst1 + game_lst2 appid_table = pd.DataFrame(game_lst) appid_table = appid_table.rename(columns = {"name":"Name"}) appid_table = pd.merge(appid_table, df, on = "Name") return appid_table # In[2]: #use steam_reviews() to return a table of steam game reviews def steam_reviews(appid_table): steam_reviews=[] for ID in list(appid_table['appid']): appid=ID url=f'https://store.steampowered.com/appreviews/{appid}?json=1' response = requests.get(url) review = response.json() steam_reviews.append(review['query_summary']) steam_review_table = pd.DataFrame(steam_reviews) return steam_review_table # In[ ]:
""" The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ square = 0 sum = 0 for num in range(1, 101): square = square+num**2 sum = sum+num # print(square) sum_square = (sum**2) # print(sum_square) print(sum_square-square)
#Find the sum of all the multiples of 3 or 5 below a limit defined by user # % is the modulus operator def sum_3_5(limit): sum = 0 for x in range(1, limit): if x % 3 == 0: sum += x elif x % 5 == 0: sum += x return sum limit = input('What is the limit? ') limit = int(limit) sum = sum_3_5(limit) print('\n\n{}\n\n\n'.format(sum)) assert sum == 233168
import math def is_square(n): if n< 0: return False else: if int(math.sqrt(n) + 0.5) ** 2 == n: return True else: return False ''' import math def is_square(n): if n < 0: return False sqrt = math.sqrt(n) return sqrt.is_integer() '''
def parseData(self, data_s, numberOfArraySlots, separationChar = "."): s_len = len(data_s) # Number of characters in the string l = 0 # Index for the data array entry = "" # The entry that we are pushing into the array if numberOfArraySlots == 2: data_arr = ["a", "b"] # Array with 2 placeholders elif numberOfArraySlots == 3: data_arr = ["a", "b", "c"] # Array with 3 placeholders elif numberOfArraySlots == 4: data_arr = ["a", "b", "c", "d"] # Array with 4 placeholders elif numberOfArraySlots == 5: data_arr = ["a", "b", "c", "d", "e"] # Array with 5 placeholders elif numberOfArraySlots == 6: data_arr = ["a", "b", "c", "d", "e", "f"] # Array with 6 placeholders elif numberOfArraySlots == 7: data_arr = ["a", "b", "c", "d", "e", "f", "g"] # Array with 7 placeholders elif numberOfArraySlots == 8: data_arr = ["a", "b", "c", "d", "e", "f", "g", "h"] # Array with 8 placeholders else: print("Ungültige Anzahl an Array Slots angegeben!") return "Error" for i in range(0, s_len): if data_s[i] != separationChar: # Check for separation character entry += data_s[i] # Push character into entry string else: data_arr[l] = entry # Push string into array entry = "" # Reset entry variable l += 1 # Increment "word"-counter data_arr[l] = entry # Final push to include last element return data_arr
import random, math, cards from cards import Color class Board(): def __init__(self, num_players): """ Constructs a new board :param num_players: The number of players (Currently can only be 2-4) :type num_players: int """ num_victory_cards = 4 + math.ceil(float(num_players) / 2) * 4 self.num_cards = { 'estate': num_victory_cards, 'dutchy': num_victory_cards, 'province': num_victory_cards, 'curse': (num_players - 1) * 10, 'copper': 60 - 7 * num_players, 'silver': 40, 'gold': 30, 'action': [10 for x in range(10)] } self.action_cards = [] self.num_empty_piles = 0 # Get 10 random action cards for the board and sort them by price action_list = random.sample(range(0, len(cards.action)), 10) for x in action_list: self.action_cards.append(cards.action[list(cards.action)[x]]) self.action_cards.sort(reverse=True, key=lambda e : e['cost']) def take_card(self, to_take): """ Takes a card off the board :param to_take: Card to be removed :type to_take: String """ if to_take in self.num_cards: # We don't have an action card if self.num_cards[to_take] < 1: print("No card to take!") return self.num_cards[to_take] -= 1 if self.num_cards[to_take] <= 0: self.num_empty_piles += 1 def available_cards(self): """ Returns set of available cards :returns: set of available cards :rtype: Set: {'estate', 'dutchy', 'province', ...} """ available = set() if self.num_cards['estate'] > 0: available.add('estate') if self.num_cards['dutchy'] > 0: available.add('dutchy') if self.num_cards['province'] > 0: available.add('province') if self.num_cards['curse'] > 0: available.add('curse') if self.num_cards['copper'] > 0: available.add('copper') if self.num_cards['silver'] > 0: available.add('silver') if self.num_cards['gold'] > 0: available.add('gold') for i in range(len(self.num_cards['action'])): if self.num_cards['action'][i] > 0: available.add(self.action_cards[i]['name'].lower()) return(available) def display(self): """ Displays the board """ # Action Cards print(Color.BOLD + Color.CYAN + 'Action Cards:' + Color.END) print(Color.BOLD + Color.BLUE + "Cost | Card | Left" + Color.END) i = 0 for card in self.action_cards: print("{:^5}| {:^13} | {:^5}".format(card['cost'], card['name'], self.num_cards['action'][i])) i += 1 print() # Treasure Cards print(Color.BOLD + Color.YELLOW + 'Treasure Cards:' + Color.END) print(Color.BOLD + Color.BLUE + "Cost | Card | Value | Left" + Color.END) print("{:^5}| {:^6} | {:^5} | {:^5}".format(6, 'Gold', 3, self.num_cards['gold'])) print("{:^5}| {:^6} | {:^5} | {:^5}".format(3, 'Silver', 2, self.num_cards['silver'])) print("{:^5}| {:^6} | {:^5} | {:^5}".format(1, 'Copper', 0, self.num_cards['copper'])) print() # Victory Cards print(Color.BOLD + Color.GREEN + 'Victory Cards:' + Color.END) print(Color.BOLD + Color.BLUE + "Cost | Card | VP | Left" + Color.END) print("{:^5}| {:^13} | {:>2} | {:^5}".format(6, 'Province', 6, self.num_cards['province'])) print("{:^5}| {:^13} | {:>2} | {:^5}".format(6, 'Dutchy', 3, self.num_cards['dutchy'])) print("{:^5}| {:^13} | {:>2} | {:^5}".format(6, 'Estate', 1, self.num_cards['estate'])) print("{:^5}| {:^13} | {:^2} | {:^5}".format(6, 'Curse', -1, self.num_cards['curse'])) print()
num_1 = int(input()) num_2 = int(input()) print(num_1 + num_2) print(num_1 - num_2) print(num_1 * num_2)
#%% import necessary modules import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model import pdb ##Q1a x_year= np.array([2005,2006,2007,2008,2009]) y_sales= np.array([12,19,29,37,45]) model = linear_model.LinearRegression() model.fit(x_year.reshape(-1,1),y_sales.reshape(-1,1)) print('Slope β =', model.coef_[0][0]) print('Intercept α =', model.intercept_[0]) # the plot is not required yPrediction = (model.coef_ * x_year) + model.intercept_ print('Y =', yPrediction[0]) plt.scatter(x_year, y_sales) plt.plot(x_year,yPrediction.reshape(-1,1), color = 'r') plt.show() #%%Q1b estimate = model.coef_ * 2012 + model.intercept_ print('Estimated sales in 2012 is ', estimate[0][0]) #%% Q2 #Q2a, just output the formula directly print( "2*( binom.pmf(12, 15, 0.5) + binom.pmf(13, 15, 0.5)+ binom.pmf(14, 15, 0.5)+ binom.pmf(15,15, 0.5))") #Q2b, just output either 'accept' or 'reject' print("If it is smaller than the p-value, then reject H0") #%% Q3 setup, 70pts import scipy.stats as stats import numpy.random as rn #%% Q3a, 15pts rn.seed(0) N = 16; m = 10**5; # 10**5 by 16 = 16 + 16 + ... + 16 # use the uniform or binomial functions to generate the data nHeads = (rn.uniform(size=(m, N))>0.5).sum(1) plt.hist(nHeads, bins=range(18)) plt.xlabel('nHeads') plt.ylabel('Number of coins') plt.title('Q3a: Histogram') plt.show() #%% Q3b, 15pts counts=plt.hist(nHeads, bins=range(18), density=True) plt.xlabel('k') plt.ylabel('P(nHeads = k)') plt.title('Q3b: Probability Mass Function') plt.show() #%% Q3c, 15pts ecdf = np.cumsum(counts[0]) #or you can calculate it by yourself plt.plot(counts[1][:-1], ecdf) plt.xlabel('k') plt.ylabel('P(nHeads <= k)') plt.title('Q3c: Cumulative Distribution Function') plt.show() #%% Q3d, 25pts # Use the binomial distribution CDF (use scipy.stats.binom.cdf) tcdf = stats.binom.cdf(range(17), 16, 0.5) plt.scatter(ecdf, tcdf) plt.xlabel('Empirical CDF') plt.ylabel('Theoretical CDF') plt.title('Q3d: scatter plot') plt.show() plt.plot(range(17), ecdf, '-o', range(17), tcdf, ':d') plt.legend(('Empirical CDF', 'Theoretical CDF')) plt.xlabel('k') plt.ylabel('CDF') plt.title('Q3d: line plot') plt.show() plt.loglog(ecdf, tcdf, 'o') plt.xlabel('Empirical CDF') plt.ylabel('Theoretical CDF') plt.title('Q3d: loglog plot') plt.show()
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm #%% Q1 Matrix multiplication print("Question 1 **************************************") A = np.array([ [2, 8, 4], [5, 4, 2]]) B = np.array([ [4, 1], [6, 4], [5, 3]]) C = np.array([ [4, 1, 2], [6, 4, 3], [5, 3, 4]]) D = np.array([ [4, 1, 2], [6, 4, 3]]) try: AB = A.dot(B) print("AB=", AB) except ValueError: print("A can not multiplicate with B.") try: AC = A.dot(C) print("AC=", AC) except ValueError: print("A can not multiplicate with C.") try: AD = A.dot(D) except ValueError: print("A can not multiplicate with D.") print("The multiplication requires the columns of first matrix is equal to the rows of second matrix.") #%% Q2 print("Question 2 **************************************") def zscore(arr): return (arr - np.mean(arr))/np.std(arr) x = np.array([ 50, 68, 74, 70, 65, 61, 63, 74, 62]) y = np.array([170, 193, 209, 185, 195, 188, 188, 202, 183]) plt.scatter(x, y) plt.show() xScores = zscore(x) yScores = zscore(y) plt.scatter(xScores, yScores) plt.show() coeff = (xScores.dot(yScores))/len(xScores) print("Pearsons Corr Coefficient: ", coeff) print("Coefficient calculated by NumPy: ", np.corrcoef(x, y)[0,1]) print("The results are the same.") #%% Q3 print("Question 3 **************************************") x = np.array([ 50, 68, 74, 70, 65, 61, 63, 74, 62, 80]) y = np.array([170, 193, 209, 185, 195, 188, 188, 202, 183, 1000]) plt.scatter(x, y) plt.show() print("3b. Coefficient calculated by NumPy: ", np.corrcoef(x, y)[0,1]) xRank = np.argsort(np.argsort(x)) yRank = np.argsort(np.argsort(y)) spearmanCoeff = np.corrcoef(xRank, yRank) print("3c. Spearman rank correlation coefficient: ", spearmanCoeff[0, 1]) print("3d. They are not the same. Comparing to the x and y in Question 2, there is an outlier (80, 1000). We expect the correlation coefficient is much closer to the coefficient in Question 2. Therefore, the Spearman correlation coefficient is better. The Spearman rank correlation works better with outliers.") print("3e. 1: incidates a positive linear relationship between data points") print("0: no or non-linear correlation") print("-1: indicates a negative/inverse relationship") #%% Q4 print("Question 4 **************************************") print("norm.cdf(0.5) - norm.cdf(-0.5)\n") print("2*(norm.cdf(0) - norm.cdf(-0.5)) or 2*(norm.cdf(0.5) - norm.cdf(0))\n") #%% Q5 print("Question 5 **************************************") print("5a. X' ~ ( aμ+b, (aσ)^2)\n") print("5b. Z = (X- \u03BC)/σ\n") print("5c. P(2<=X<=7) = norm.cdf(7, 5, 3) - norm.cdf(2, 5, 3) = ", norm.cdf(7, 5, 3) - norm.cdf(2, 5, 3)) print("5d. P(-1.5 <= X <= 1.5) = norm.cdf(1.5) - norm.cdf(-1.5) = ", norm.cdf(1.5) - norm.cdf(-1.5)) #%% Q6 print("Question 6 **************************************") print("a: P(A ∪ B) = P(A) + P(B) – P(A ∩ B)") print("b: P(A | B) = P(A ∩ B) / P(B)") print("c: P(A ∩ B) = P(B) * P(A | B)") print("d: If A and B are independent, P(A ∩ B) = P(A) * P(B)") #%% Q7 print("Question 7 **************************************") print("P(d = even) = 1/2") print("P(d < 5) = 1/2") print("P(d = even) * P(d < 5) = 1/4") print("P(d = even ∩ d < 5) = 2/8 = 1/4") print("P(d = even) * P(d < 5) = P(d = even ∩ d < 5)") print("Therefore, P(d = even) and P(d < 5) are independent.") #%% Q8 print("Question 8 **************************************") print("P( loaded | 6666) = P(6666 | loaded)*P(loaded)/P(6666)") print("= P(6666 | loaded)*P(loaded)/(P(6666 | loaded)*P(loaded) + P(6666 | fair)*P(fiar))" ) print("= (0.5**4) * 0.05 / ((0.5**4) * 0.05 + ((1/6)**4)*0.95)") print("=0.81") #%% Q9 print("Question 9 **************************************") print("A: have the disease, P(A) = 0.0001;") print("B: test positive;") print("P(A)+P(neg(A)) =1") print("P(B)+P(neg(B)) =1") print("9a") print("P(B | A) = 0.999; P(B | neg(A)) = 0.0002;") print("By Bayes Theorem, P(A | B) = P(B | A) * P(A) / P(B)") print("=P(B|A)*P(A)/(P(B|A)*P(A) + P(B|neg(A))*P(neg(A)))") print("= 33.3%") print("9b") print("P(neg(A)| neg(B)) = P(neg(B)|neg(A))*P(neg(A))/P(neg(B))") print("= (1-P(B|neg(A)))*(1-P(A))/(1-P(B))") print("=0.99999") # close all figures plt.close('all') print("Question 10 **************************************") #%% load data import pandas as pd measles=pd.read_csv('Measles.csv',header=None).values mumps=pd.read_csv('Mumps.csv',header=None).values chickenPox=pd.read_csv('chickenPox.csv',header=None).values #a. plot annual total measles cases in each year plt.figure() plt.title('a. NYC measles cases') plt.plot(measles[:,0], measles[:, 1:].sum(1), '-*') plt.xlabel('Year') plt.ylabel('Number of cases') plt.show() #%% b. bar plot average mumps cases for each month of the year plt.figure() plt.title('b. Average monthly mumps cases') plt.bar(range(1,13), mumps[:, 1:].mean(0)) plt.xlabel('Month') plt.ylabel('Average number of cases') plt.show() #%% c. scatter plot monthly mumps cases against measles cases mumpsCases = mumps[:, 1:].reshape(41*12) measlesCases = measles[:, 1:].reshape(41*12) plt.figure() plt.title('c. Monthly mumps vs measles cases') plt.scatter(mumpsCases, measlesCases) plt.xlabel('Number of Mumps cases') plt.ylabel('Number of Measels cases') plt.show() #%% d. plot monthly mumps cases against measles cases in log scale plt.figure() plt.title('d. Monthly mumps vs measles cases (log scale)') plt.loglog(mumpsCases, measlesCases, '.') plt.xlabel('Number of Mumps cases') plt.ylabel('Number of Measels cases') plt.show() #%% Answer to Q10.e answer = 'If plotted in linear space, the relationship between two variables is difficulty to see.' print('\n\nAnswer to e: ' + answer)
from stream import Stream DITTO = "DITTO" class Token(object): def __init__(self, purpose, text, line, character): self.purpose = purpose self.text = text self.line = line self.character = character def __repr__(self): if self.text != "": return "<%s:%s>" % (self.purpose, self.text) return "<%s>" % (self.purpose) class Tokenizer(object): def __init__(self, reader, purpose): self.reader = reader self.purpose = purpose def applies(self, stream): return self.reader.read(stream) def token(self, stream, i, j): text = stream.string[i:j] if self.purpose == DITTO: return Token(text, text, stream.line(), stream.position()) else: return Token(self.purpose, text, stream.line(), stream.position()) class Scanner(object): def initialize_scan(self, string): self.tokens = [] self.stream = Stream(string) def produce(self, token): self.tokens.append(token) def tokenize(self): while self.tokenize_one(): pass return self.tokens def tokenize_one(self): i = self.stream.index if self.stream.eof(): self.eof() return False for tokenizer_pair in self.state: tokenizer = tokenizer_pair[0] action = tokenizer_pair[1] if tokenizer.applies(self.stream): j = self.stream.index action(self, tokenizer.token(self.stream, i, j)) return True raise StandardError("No tokenizer applied.")
class Stream(object): def __init__(self, string): self.string = string self.index = 0 self.line_stack = [] self.position_stack = [] def set_index(self, n): while self.line_stack and self.line_stack[-1][0] > n: self.line_stack.pop() while self.position_stack and self.position_stack[-1][0] > n: self.position_stack.pop() self.index = n def track_position(self): if self.string[self.index] == "\n": self.position_stack.append((self.index, 0)) self.line_stack.append((self.index, self.line() + 1)) else: self.position_stack.append((self.index, self.position())) def eof(self): return self.index >= len(self.string) def get(self): if self.eof(): raise EOFError() self.track_position() ret = self.string[self.index] self.index += 1 return ret def get_n(self, n): ret = [] for i in range(n): ret.append(self.get()) return "".join(ret) def position(self): if self.position_stack: return self.position_stack[-1][1] return 0 def line(self): if self.line_stack: return self.line_stack[-1][1] return 0
#subroutine to calculate number of stops between two stops on the victoria line def victoria_line(): victoria = ["Brixton", "Stockwell", "Vauxhall", "Pimlico", "Victoria", "Green Park", "Oxford Circus","Warren Street", "Euston","King's Cross","Highbury & Islington", "Finsbury Park","Seven Sisters","Tottenham Hale", "Blackhorse Road and Walthamstow Central"] #outputs all the stations for station in victoria: print("- " + station + "\n",end="") print() #validates station while True: start = input("Please enter your start station.\n> ") if start in victoria: break else: print("Please enter a valid station.") #validates station and makes sure it is not the same while True: end = input("Please enter your final station.\n> ") if end in victoria and end != start: break else: print("Please enter a valid station.") start_num = victoria.index(start) + 1 end_num = victoria.index(end) + 1 total_stops = 0 #calculates station difference if it goes past the end of the loop if end_num < start_num: total_stops = 15-start_num total_stops += end_num #subtracts the final stop total_stops -= 1 #calculates difference normally else: total_stops = end_num - start_num - 1 print("Total number of stops between {} and {} is {}".format(start,end,total_stops)) #main program victoria_line()
import pygame import colors class Tile: """A tile with x and y position""" def __init__(self,x,y,z, color) -> None: self.x = x self.y = y self.z = z self.color = color def allow_fall(self,snake): return False def allow_through(self,snake): return False def died(self, snake): """True if snake is in same tile and either its a wall or the tile is in another elevation(except bridges)""" if (snake.z > self.z) and not self.allow_fall(): return snake.fall() def render(self, display): pygame.draw.rect(display, self.color, [self.x*20, self.y*20, 20, 20]) def __str__(self) -> str: return self.__class__.__name__ + " at:(" + str(self.x) + "," + str(self.y) + "," + str(self.z) + ")" class Base(Tile): """The base tile""" def __init__(self,x,y,z,colour) -> None: super().__init__(x,y,z,colour) def allow_through(self,snake): return snake.z >= int(self.z) class Wall(Tile): """An actual wall""" def __init__(self,x,y,z) -> None: super().__init__(x,y,z,colors.black) class Stair(Base): """A stair tile to change elevation level""" def __init__(self, x, y, z, dir) -> None: super().__init__(x,y,z, colors.grey) self.dir = dir # From lower to upper elevation (e.g. "UP" has the lower level under it) def allow_through(self, snake): return super().allow_through(snake) and (snake.direction % 2) == (self.direction % 2) def allow_fall(self,snake): return (snake.direction % 2) == (self.direction % 2) and (snake.get_elevation() == self.z + 1) class Bridge(Base): """A Bridge""" def __init__(self, x, y, z, dir) -> None: super().__init__(x,y,z,colors.brown) self.dir = dir # UP/DOWN and LEFT/RIGHT are the same def allow_through(self, snake): return True
from random import choice # Implements strategies the bot player might choose def random_strategy(state): "Returns a random card from the hand" return choice(hand(state)) def near_treasure_strategy(state): "Returns one of the three cards nearest the treasure" treasure = state['turns'][0]['treasure'] cards_near_treasure = [card for dist, card in sorted([(abs(i - treasure), i) for i in hand(state)])] return choice(cards_near_treasure[:3]) def hand(state): return state['players']['bot']['hand'] strategies = { 'RANDOM': random_strategy, 'NEAR_TREASURE': near_treasure_strategy }
# EP-de-soft-eduardo-e-theo Lista_de_produtos = {} Escolha = int(input('''0 - Sair 1 - Adicionar item 2 - Remover item 3 - Alterar item 4 - Imprimir estoque Faça sua escolha:''')) while Escolha != 0: if Escolha == 1: Produto = input('Nome do produto:') Quantidade = int(input('Quantidade:')) Lista_de_produtos[Produto] = {} Lista_de_produtos[Produto]['Quantidade'] = Quantidade if Produto in Lista_de_produtos: print('Produto já cadastrado') print('{0}: Quantidade: {1}'.format(Produto, Quantidade)) elif Escolha == 2: Produto = input('Nome do produto:') Quantidade = int(input('Quantidade:')) del Lista_de_produtos[Produto] print('Produto não encontrado') elif Escolha == 3: if Produto == input('Nome do produto:'): Quantidade_2 = int(input('Quantidade:')) Quantidade_2 += Quantidade print(Quantidade_2) elif Escolha == 4: print(Lista_de_produtos) Escolha = int(input('''0 - Sair 1 - Adicionar item 2 - Remover item 3 - Alterar item 4 - Imprimir estoque Faça sua escolha:''')) if Escolha == 0: print('Até mais!')
from Livro import Livro from Autor import Autor from Pilha import Pilha linha = "---------------------------" autor1 = Autor(1, "Fernando") autor2 = Autor(2, "Pittacus") autor3 = Autor(3, "Jay") autor1.print() autor2.print() autor3.print() print(linha) book1 = Livro(1, "O caçador", autor1) book2 = Livro(2, "Unidos somos um", autor2) book3 = Livro(3, "Nevernight", autor3) book1.print() book2.print() book3.print() print(linha) pilha = Pilha() print(pilha.peek()) print(linha) pilha.push(book1) pilha.push(book2) pilha.push(book3) print(pilha.peek()) print(linha) pilha.pop() print(pilha.peek())
#!/usr/bin/env python3 from planegeometry.structures.points import Point from planegeometry.algorithms.geomtools import orientation class GrahamScan1: """Graham's scan algorithm for finding the convex hull of points. https://en.wikipedia.org/wiki/Graham_scan """ def __init__(self, point_list): """The algorithm initialization.""" if len(point_list) < 3: raise ValueError("small number of points") self.point_list = point_list self.convex_hull = [] # acting as a stack def run(self): """Executable pseudocode.""" # Find the lowest y-coordinate and leftmost point. p_min = min(self.point_list, key=lambda p: (p.y, p.x)) # Sort points by polar angle with p_min, if several points have # the same polar angle then only keep the farthest. self.point_list.sort(key=lambda p: ((p-p_min).alpha(), (p-p_min)*(p-p_min))) # After sorting p_min will be at the beginning of point_list. for point in self.point_list: # Pop the last point from the stack if we turn clockwise # to reach this point. while len(self.convex_hull) > 1 and orientation( self.convex_hull[-2], self.convex_hull[-1], point) <= 0: self.convex_hull.pop() self.convex_hull.append(point) def swap(L, left, right): """Swap two items on a list.""" L[left], L[right] = L[right], L[left] class GrahamScan2: """Graham's scan algorithm for finding the convex hull of points.""" def __init__(self, point_list): """The algorithm initialization.""" if len(point_list) < 3: raise ValueError("small number of points") self.point_list = point_list self.convex_hull = None def run(self): """Executable pseudocode.""" p_min = min(self.point_list, key=lambda p: (p.y, p.x)) self.point_list.sort(key=lambda p: ((p-p_min).alpha(), (p-p_min)*(p-p_min))) m = 1 # index of the last point included to convex hull i = 2 # index of the next point to test while i < len(self.point_list): if orientation(self.point_list[m-1], self.point_list[m], self.point_list[i]) > 0: # left turn # self.point_list[m] outside m += 1 swap(self.point_list, m, i) i += 1 else: # self.point_list[m] inside or on the edge if m > 1: # do not move i, because we need to test m m -= 1 else: # we can move i, but still m=1 swap(self.point_list, m, i) i += 1 self.convex_hull = self.point_list[0:m+1] GrahamScan = GrahamScan1 # EOF
class Zaman: def __init__(self, tarih): self.gun, self.ay, self.yil = map(int, tarih.split('/')) def __str__(self): return "{gun} / {ay} / {yil} ".format(**self.__dict__) def __sub__(self, other): return self.yil-other.yil def kalan_zaman(self,other): pass if __name__ == '__main__': bugun_tarihi = Zaman("28/07/2018") dogum_gunum = Zaman("16/12/1993") yasi = bugun_tarihi-dogum_gunum print("Yaş: ".format(yasi))
# def carpma(say,say2): # return say *say2 # # # # a = lambda say,say2:say*say2 #Yukarıdaki kod ile aynı işlevi görür. # print(a(10,15)) # # b = lambda deger:deger #Fonksiyon kullanmak yerine lambda kullanmak bazen daha cazip gelebilir. # print(b("Örnek")) # # def sayi_dondur(): # for say in range(1,10): # yield say # # siradaki = sayi_dondur() # print(siradaki.__next__()) #next fonksiyonu her defasında sonraki değeri getiriyor. # print(siradaki.__next__()) # print(siradaki.__next__()) # bir_dizi_var = [5,10,2,18,21,55] # # yeni_deger = map(b, bir_dizi_var) # print(list(yeni_deger)) # print(list(yeni_deger)) # # string_deger = [] # for deger in bir_dizi_var: # string_deger.append(str(deger)) # # print(bir_dizi_var,string_deger,sep="\n") # # yeni_deger = map(lambda deger: str(deger), bir_dizi_var) # print(list(yeni_deger)) # sonuc = filter(lambda say : say %2 ==0 , bir_dizi_var ) # print(list(sonuc)) from functools import reduce print(bir_dizi_var) toplam=0 for deg in bir_dizi_var: toplam += deg print(toplam) resp = reduce(lambda x,y : x+y,bir_dizi_var) # Bir üstteki for döngüsü ile aynı işlevi görür. print(resp)
test_degiskeni = "Bu bir test değişkenidir" print(test_degiskeni.upper()) #String değerlerini büyük harf yapar. print(test_degiskeni.lower()) #String değerlerini küçük harf yapar. print(test_degiskeni.capitalize()) #String değerinin ilk karakterini büyük harf yapar. print(test_degiskeni.split()) #String değerindeki boşlukları göstermez. print(test_degiskeni.rsplit()) #String değerinin sonundaki boşlukları göstermez. print(test_degiskeni.lstrip()) #String değerinin başındaki boşluğu göstermez. print(test_degiskeni.strip().capitalize()) #String değerinin boşuklarını silip ilk harf büüyk yapar. test_degiskeni2 = "\r\n Bu bir test değişkenidir." # Boşluk ve satır atlar.
minutes = 42 seconds = 42 seconds_in_a_minute = 60 total_seconds = (minutes * seconds_in_a_minute) + seconds print(total_seconds)
data = """ INDIA Runs:231, Wickets:3, Overs:50 ENGLAND Runs:187, Wickets:10, Overs:50 BANGLADESH Runs:220, Wickets:8,Overs:50 AUSTRALIA Runs:250,Wickets:9, Overs:50 """ COUNTRY_NAME : {"Runs":int, "Wickets":int,"Overs":int} d1 = {"Runs": 231, "Wickets": 3, "Overs": 50} d2 = {"Runs": 187, "Wickets": 10, "Overs": 50} d3 = {"Runs": 220, "Wickets": 8, "Overs": 50} d4 = {"Runs": 250, "wickets": 9, "Overs": 50} name = input("Enter Country Name:") if name == "INDIA": print(d1) elif name == "ENGLAND": print(d2) elif name == "BANGLADESH": print(d3) else: print(d4)
''' 题目:暂停一秒输出。 程序分析:使用 time 模块的 sleep() 函数。 ''' import time a = {1: 1, 'a': 'fff', 'd': '2'} for key in a: print(a[key]) time.sleep(1) print('bye')
import difflib import csv as csv INPUT_PATH = "C:/Users/Divya moorjaney/Documents/FIS ADA/CompareCSV/" def comparecsv(sqlfile, scalafile, split): d = difflib.Differ() sql_open = open(INPUT_PATH + sqlfile, 'r') # open file sql_colcount = len(sql_open.readline().strip().split(split)) # get col counts ## TODO This will only check for number of cols in the first line, what if there is a delimiter mismatch in some other line in the file? sql = csv.reader(sql_open) # read file sql_rowcount = len(list(sql)) # count of rows in the file # sql_open.close() scala_open = open(INPUT_PATH + scalafile, 'r') scala_colcount = len(scala_open.readline().strip().split(split)) ## TODO This will only check for number of cols in the first line, what if there is a delimiter mismatch in some other line in the file? scala = csv.reader(scala_open) scala_rowcount = len(list(scala)) # scala_open.close() if sql_rowcount != scala_rowcount or sql_colcount != scala_colcount: print('Row and column counts do not match') print('Number of columns in SQL output is '+str(sql_colcount)) print('Number of columns in Scala output is ' +str(scala_colcount)) print('Number of rows in SQL output is ' +str(sql_rowcount)) print('Number of rows in Scala output is ' +str(scala_rowcount)) ## TODO the program should exit safely at this stage and do nothing else else: # print('Row counts and column counts match') # outFile = open('difference_sql_scala.csv', 'w') for line in sql: ## TODO: Why are we doing this? Will be extremely expensive for larger files # result = d.compare(line1, line2) print('|'.join(line)) ## TODO: What happens after this? The later portions are all commented out # sqlTraining = pd.read_csv(r"C:\Users\Divya moorjaney\PycharmProjects\CompareCSV\venv\contact_attrition_108_20180321.csv", sep = ",") # scalaTraining = pd.read_csv(r"C:\Users\Divya moorjaney\PycharmProjects\CompareCSV\venv\Contact_Attrition_Training.csv", sep = ",") # print(scalaTraining.shape[0]) # to give the row count 181775 # print(scalaTraining.shape[1]) # to give column count 57 # print(scalaTraining.shape) # gives the shape of the data frame (181775, 57) # print(sqlTraining.shape) # (151704, 57) # sqlRead = csv.reader(r"C:\Users\Divya moorjaney\PycharmProjects\CompareCSV\venv\contact_attrition_108_20180321.csv") # scalaRead = csv.reader(r"C:\Users\Divya moorjaney\PycharmProjects\CompareCSV\venv\Contact_Attrition_Training.csv") # sql = open(r'C:\Users\Divya moorjaney\PycharmProjects\CompareCSV\venv\contact_attrition_108_20180321.csv', 'r') # scala = open(r'C:\Users\Divya moorjaney\PycharmProjects\CompareCSV\venv\Contact_Attrition_Training.csv', 'r') # iterate each file by line - read in the file line by line # sqlRead = sql.readlines() # change to read line by line # scalaRead = scala.readlines() # sql.close() # scala.close() # outFile = open('difference_sql_scala.csv', 'w') # x = 0 # for i in sqlRead: # if i != scalaRead[x]: # outFile.write(scalaRead[x]) # x += 1 # outFile.close() # reader1 = csv.reader(r"C:\Users\Divya moorjaney\PycharmProjects\CompareCSV\venv\contact_attrition_108_20180321.csv") # reader2 if __name__ == "__main__": comparecsv(sqlfile='sql.csv', scalafile='sql.csv', split='|')
while True: x = input("수를 입력하세요:") try: x = int(x) sum = 0 for i in range(1, x + 1): if i % 3 == 0: sum += i print("1부터 ", i, "까지 3의 배수의 합 : ", sum) break except Exception as e: print("정수가 아닙니다. 다시 입력하세요.")
# 함수의 정의 def dummy(): # 구현부가 없을때 pass def none(): # return만 하면 None이 반환 return def times(a, b): return a * b dummy() print(none()) # None print(times(10, 20)) # 함수 자체도 객체 fun = times # 심볼로 할당 print(type(fun)) print(callable(fun)) if callable(fun): print(fun(10, 20)) # 함수의 return def bigger(a, b): if a > b: return a else: return b print(bigger(10, 20)) # 여러 값의 반환 -> Tuple로 처리 def swap(a, b): return b, a result = swap(10, 20) print(result, type(result)) print(result[0], result[1]) res_a, res_b = swap(10, 20) # 리턴값의 언패킹 print(res_a, res_b)