text
stringlengths
37
1.41M
# Import OS & CSV Modules import os import csv import sys # # Create list for each column month = [] profit = [] monthly_change =[] profit_change = [] # Create path from the Resources folder filepath = os.path.join ('..', 'Resources', 'budget_data.csv') # Read in CSV File with Delimiter commas with open(filepath, 'r') as csvfile: csvreader = csv.reader (csvfile, delimiter = ',') #print(csvreader) # Define first row as header csv_header = next(csvreader) #print(f"Header: {csv_header}") # Calculate total months for row in csvreader: month.append(row[0]) profit.append(row[1]) #print(len(month)) # Calcuate total profit profit_int = map(int,profit) total_profit = (sum(profit_int)) #print(total_profit) # Calculate average revenue x = 0 for x in range(len(profit) - 1): change = int(profit[x+1]) - int(profit[x]) profit_change.append(change) total = sum (profit_change) #print(profit_change) monthly_change = total / len(profit_change) #print(monthly_change) # Calculate maximun profit increase profit_increase = max(profit_change) #print(profit_increase) y = profit_change.index(profit_increase) month_increase = month[y+1] # Calculate maximim profit decrease profit_decrease = min(profit_change) # print(profit_decrease) z = profit_change.index(profit_decrease) month_decrease = month[z+1] # Print final parameters print("Total Months:" + str(len(month))) print("Total Profits: $" + str(total_profit)) print("Average Profit Change: $ "+ str(monthly_change)) #ugggggh i cant figure out how to make this 2 decimal places!! print(f"Greatest Profit Increase: {month_increase} (${profit_increase})") print(f"Greatest Profit Decrease: {month_decrease} (${profit_decrease})") #Create output .txt file ##blarrgggghhhhh i looked this up and it works but not how we did it in class! sys.stdout = open("profit_results.txt", "w") print("Total Months:" + str(len(month))) print("Total Profits: $" + str(total_profit)) print("Average Profit Change: $ "+ str(monthly_change)) print(f"Greatest Profit Increase: {month_increase} (${profit_increase})") print(f"Greatest Profit Decrease: {month_decrease} (${profit_decrease})") sys.stdout.close()
#import API import requests def recipe_search(ingredient): # Register to get an APP ID and key https://developer.edamam.com/ import os app_id = os.environ.get("APP_ID") app_key = os.environ.get("APP_KEY") result = requests.get('https://api.edamam.com/search?q={}&app_id={}&app_key={}'.format(ingredient, app_id, app_key)) data = result.json() return data['hits'] #The programme starts with the computer asking user questions. Use input for this. name = input('What is your name?') fave_food = input ('What is your favourite food?') print ('Hello {} and welcome to Recipe search. I hope you are hungry and ready to make {} food today' .format(name, fave_food)) # Using Booleans to further understand what the user wants #recipe_2 = input('Would you like to make a delicious meal today? y/n') #yesPlease = recipe_2 == 'y' #patience = input('Do you have the time and patience to make one of our recipes? y/n') #IsPatient = patience == 'y' #Use_site = recipe_2 and patience #print ('You should go ahead and visit our site to make some delicious recipes:{}' .format(Use_site)) #Use If and If not for Booleans visitSite = input('Would you like help making something delicious today (yes or no)?') Wants_help = visitSite == 'yes' patience = input('Do you have the patience to make something today (yes or no)') hasPatience = patience == 'yes' if visitSite and patience: print('Great, lets get started cooking something') if not visitSite and patience: print('This site might not be best for you. Budding Chefs only') # If else statement to find out if they have enough ingredients ingredient= int(input("how many ingredients do you have?")) if ingredient >= 2: print("you can search for recipes") else: print("you must have more than two ingredients to continue") # Function to add the ingrdients def list (): ingredient = input('Enter an ingredient: ') results = recipe_search(ingredient) for result in results: recipe = result['recipe'] print(recipe['label']) print(recipe['uri']) print(recipe['calories']) print() list() #Lists and Append recipe_ideal = [ "Mexican", "Thai", "Indian", "Chinese", "Nigerian", "Sri Lanken", ] recipe_fave = input ('I hope you have enjoyed Recipe Search. Please add your fave type of cuisine to our list') recipe_ideal.append(recipe_fave) print(recipe_ideal) #Alternative to the if else statement #yield_1 = input ('Do you have more than one ingredient?') #more_one = float(yield_1) <= 2.0 #print (' You have enough ingredients to make something delicious: {}' .format (more_one))
#Rectangle length = 5 breadth = 2 area = length*breadth print 'Area is',area print 'Perimeter is',2*(length+breadth)
''' Created on Dec 11, 2013 @author: nonlinear ''' def maxsum(sequence): """Return maximum sum.""" maxsofar, maxendinghere = 0, 0 for x in sequence: # invariant: ``maxendinghere`` and ``maxsofar`` are accurate for ``x[0..i-1]`` maxendinghere = max(maxendinghere + x, 0) maxsofar = max(maxsofar, maxendinghere) return maxsofar def maxsumseq(sequence): start, end, sum_start = -1, -1, -1 maxsum_, sum_ = 0, 0 for i, x in enumerate(sequence): sum_ += x if maxsum_ < sum_: # found maximal subsequence so far maxsum_ = sum_ start, end = sum_start, i elif sum_ < 0: # start new sequence sum_ = 0 sum_start = i assert maxsum_ == maxsum(sequence) assert maxsum_ == sum(sequence[start + 1:end + 1]) return [start + 1,end + 1] def generate_pairs(n): "Generate all pairs (i, j) such that 0 <= i <= j < n" for i in range(n): for j in range(i, n): yield i, j def max_sum_subsequence(seq): "Return the max-sum contiguous subsequence of the input sequence." return max(sum(seq[i:j]) for i, j in generate_pairs(len(seq) + 1)) def max_subarray(A): max_ending_here = max_so_far = 0 for x in A: max_ending_here = max(0, max_ending_here + x) max_so_far = max(max_so_far, max_ending_here) return max_so_far
from os import path import wget def DownloadFile(url, name=None, target_dir=None): ''' Check if file exists and download to working directory if it does not. Returns str of filename given to file. Arguments: url = str_of_fully_qualified_url, name=str_of_name_you_want TODO: 2019-07-16 Check if suffix in name ''' # Strip url for ending filename split_url = url_split = url.split('/') if len(split_url) > 2: filename = url_split[len(url_split)-1] else: filename = url_split[1] # Check if target_dir parameter given. If so, append to new filename. if not target_dir: target_dir = '' else: if not path.isdir(target_dir): print('directory not found') return suffix = '.'.join(filename.split('.')[1:]) # Check if name given if name: outpath = target_dir + name + '.' + suffix else: outpath = filename if path.exists(outpath): print('File already exists') else: try: filename = wget.download(url, out=outpath) print(filename, 'successfully downloaded to', outpath) except: print('File could not be downloaded. Check URL & connection.') return filename def UnzipFile(path, target_dir): ''' Unpack compressed file to target directory. Arguments: path = str_of_path *relative or absolute, target_dir = str_of_path_to_dump ''' from shutil import unpack_archive try: unpack_archive(path, target_dir) except: print('error unzipping')
#!/usr/bin/python3 list1, list2 = ['Google', 'Taobao', 'Runoob'], [456, 700, 200] print ("list1 最小元素值 : ", min(list1)) print ("list2 最小元素值 : ", min(list2)) print ("list1 最大元素值 : ", max(list1)) print ("list2 最大元素值 : ", max(list2)) aTuple = (123, 'Google', 'Runoob', 'Taobao') list1 = list(aTuple) print ("Tuple列表元素 : ", list1) str="Hello World" list2=list(str) print ("string列表元素 : ", list2)
#! /home/sudeep/anaconda3/bin/python3.6 import sqlite3 import create_db connection = sqlite3.connect("schools.sqlite") cursor = connection.cursor() school = str(input("Enter the name of school : \n")) school_id = create_db.select_school(school) student_list = [row [0] for row in cursor.execute("""SELECT name from """+create_db.schools[school_id-1]).fetchall()] for i in range(len(student_list)): print(student_list[i])
import unittest # 1.1 Is Unique: Check if a string has all unique characters def is_unique(s): return len(set([x for x in s])) == len(s) # 1.2 Check Permutation: Check if one string is a permutation of the other def are_permutations(a, b): counts = {} for c in a: if c not in counts: counts[c] = 1 else: counts[c] += 1 for c in b: if c not in counts or counts[c] == 0: return False else: counts[c] -= 1 return all([count == 0 for count in counts.values()]) # 1.3 URLify: Replace all spaces in a string with '%20' def URLify(s): return s.replace(' ', '%20') # 1.4 Palindrome Permutation: Check if a string is a permutation of a palindrome def is_palindrome_permutation(s): counts = {} for c in s: if c not in counts: counts[c] = 1 else: counts[c] += 1 odd_counts = [count for count in counts.values() if count % 2 == 1] return (len(s) % 2 == 0 and len(odd_counts) == 0) or (len(s) % 2 == 1 and len(odd_counts) == 1) # 1.5 One Away: Given 3 three operations (insert/remove/replace char), check if two strings are one or # two operations away from each other def is_one_away(s1, s2): longer = s1 if len(s1) >= len(s2) else s2 shorter = s2 if len(s1) >= len(s2) else s1 if len(longer) - len(shorter) > 1: return False difference_found = False difference = longer[:] for c in shorter: if c not in difference: if difference_found: return False difference_found = True difference = difference.replace(c, '', 1) return True # 1.6 String Compression: Compress a string using the counts of repeated characters, e.g. aabcccccaaa -> a2b1c5a3 # If the compressed string is alrger than the original, return the original. Charset is upper/lower a-z def compress(s): compressed = [] prevChar = '' count = 0 for c in s: if c != prevChar: if prevChar != '': compressed.append(prevChar + str(count)) prevChar = c count = 0 count += 1 compressed.append(prevChar + str(count)) compressed = ''.join(compressed) return s if len(s) <= len(compressed) else compressed # 1.7 rotateMatrix: Given an NxN matrix of 4 byte ints, rotate it by 90 degrees in place def rotate_matrix(image): n = len(image) for level in range(0, int(n / 2)): for i in range(level, n - 1 - level): temp = image[level][i] # store top-left image[level][i] = image[n-1-i][level] # bottom-left to top-left image[n-1-i][level] = image[n-1-level][n-1-i] # bottom-right to bottom-left image[n-1-level][n-1-i] = image[i][n-1-level] # top-right to bottom-right image[i][n-1-level] = temp # top-left to top-right # 1.8 Zero Matrix: Given an MxN matrix, change all elements in a column or row containing 0 to 0 def zero_matrix(matrix): if len(matrix) < 1: return n = len(matrix) m = len(matrix[0]) zero_columns = [False] * m zero_rows = [False] * n for y in range(0, n): for x in range(0, m): if matrix[y][x] == 0: zero_columns[x] = True zero_rows[y] = True for y in range(0, n): for x in range(0, m): if zero_rows[y]: matrix[y] = [0] * m continue if zero_columns[x]: matrix[y][x] = 0 # 1.9 String Rotation: Given method isSubstring and strings s1, s2, check if s2 is a rotation of s1 using isSubstring once # We'll use Python's built-in substring functionality def is_rotation(s1, s2): return len(s1) == len(s2) and s1 in s2*2 class Test(unittest.TestCase): def test_isUnique(self): self.assertTrue(is_unique('Helo, Wrd!')) self.assertFalse(is_unique('Hello, World!')) def test_arePermutations(self): self.assertTrue(are_permutations('Hello, World!', 'oWHllo, lerd!')) self.assertFalse(are_permutations('Hello, ', 'World!')) def test_URLify(self): self.assertEqual(URLify('Hello, World!'), 'Hello,%20World!') def test_isPalindromePermutation(self): self.assertTrue(is_palindrome_permutation('Hello, World!Hel,Wrd!')) self.assertFalse(is_palindrome_permutation('Hello, World!')) def test_isOneAway(self): self.assertTrue(is_one_away('pale', 'ple')) self.assertTrue(is_one_away('pales', 'pale')) self.assertTrue(is_one_away('pale', 'bale')) self.assertFalse(is_one_away('pale', 'bake')) def test_compress(self): self.assertEqual(compress('aabcccccaaa'), 'a2b1c5a3') def test_rotateMatrix(self): image = [[1,2,3,4,5], [16,17,18,19,6], [15,24,25,20,7], [14,23,22,21,8], [13,12,11,10,9]] rotate_matrix(image) self.assertEqual(image, [[13, 14, 15, 16, 1], [12, 23, 24, 17, 2], [11, 22, 25, 18, 3], [10, 21, 20, 19, 4], [9, 8, 7, 6, 5]]) matrix = [[0,2,3,4,5], [16,17,18,19,6], [15,24,25,0,7], [14,23,22,21,8], [13,12,11,10,9]] zero_matrix(matrix) self.assertEqual(matrix, [[0,0,0,0,0], [0,17,18,0,6], [0,0,0,0,0], [0,23,22,0,8], [0,12,11,0,9]]) def test_isRotation(self): self.assertTrue(is_rotation('', '')) self.assertFalse(is_rotation('Hello,', 'World!')) self.assertTrue(is_rotation('waterbottle', 'terbottlewa')) if __name__ == '__main__': unittest.main()
words = "It's thanksgiving day. It's my birthday,too!" print(words.find('day')) words = words.replace("day","mouth") print(words) x = [2,54,-2,7,12,98] print(max(x)) print(min(x)) x = ["hello",2,54,-2,7,12,98,"world"] print(x[0], x[-1]) new_x = [x[0], x[-1]] print(new_x) x = [19,2,54,-2,7,12,98,32,10,-3,6] x_sort = sorted(x) half = len(x_sort) / 2 sort_array = [x_sort[:half], ] for each in x_sort[half:]: sort_array.append(each) print(sort_array)
#!/usr/bin/python # pull request import argparse import math def find_max_profit(prices): temp = math.inf * -1 for x in range(0,len(prices)): for y in range(x+1, len(prices)): difference = prices [y] - prices[x] if difference > temp: temp = difference return temp if __name__ == '__main__': # This is just some code to accept inputs from the command line parser = argparse.ArgumentParser(description='Find max profit from prices.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price') args = parser.parse_args() print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))
def forall(lst): def predicate(p): for x in lst: if not p(x): return False return True return predicate def exists(lst): def predicate(p): for x in lst: if p(x): return True return False return predicate
# Invertir una palabra introducida por el usuario while True: print("Invertir palabra o frase (En blanco para salir)") frase = input("Digite la palabra/frase que desa invertir: ") if len(frase) <=0: break frase_invertida = "" for i in range(len(frase)-1,-1,-1): frase_invertida = frase_invertida+ frase[i] tipo = "" if " " in frase: tipo="frase" else: tipo="palabra" print("Su {} invertida es:".format(tipo),end="\n") print(frase_invertida.capitalize()) #---------------------------------------------------- frase_invertida = frase[::-1] print("Su {} invertida es:".format(tipo),end="\n") print(frase_invertida.capitalize())
def sumar(*numeros): return sum(numeros) def restar(a,b): return (a-b) def multiplicar(a,b): return a*b def dividir(a,b): if b == 0: raise ValueError('Intenta dividir entre 0') else: return a/b
from .Funciones_aridmeticas import sumar,restar,multiplicar,dividir def menu(): print('Seleccione una opcon:') print('1) Sumar') print('2) Restar') print('3) Multiplicar') print('4) Dividir') print('0) Salir') print() def main(): while True: menu() while True: try: opcion = int(input('Indique la operacion que desea realizar: ')) break except: print('Error, ninguna opcion seleccionada') print() print() if 0 < opcion <= 4: while True: try: a = int(input('Primer valor: ')) b = int(input('Segundo valor: ')) break except: print('Indique valores validos') print() print() if opcion == 1: suma = sumar(a,b) print('El resultado de la suma es: ',suma) elif opcion == 2: resta = restar(a,b) print('El resultado de la resta es: ',resta) elif opcion == 3: multiplicacion = multiplicar(a,b) print('El resultao de la multiplicacion es: ',multiplicacion) elif opcion == 4: try: division = dividir(a,b) print('El resultado de la division es: ',division) except ValueError as e: print('Error: ',e) print() else: print('Ha salido del programa') break if __name__ == '__main__': main()
list11 = [1, 2, 3, 4, 5, 6] list12 = [7, 2, 1, 14, 5, 16,8] list3 = [] list4 = [] for i in range(0, len(list11), 1):# remplir le deuxieme list par les elemnts d'indice impaire de liste11 if i % 2 != 0: list3.append(i+1) for i in range(0, len(list12), 1): if i % 2 == 0: # remplir le premier list par les elemnts d'indice paire de liste12 list4.append(list12[i]) result= list3+list4 # concaténer les deux listes pour avoir resultat print(result)
for number in range(1, 8): i = '1' print(i * number)
def count_elem(lst): n = 0 for i in lst: n += 1 return n lst1 = [1, 2, 3, 4, 5, 6] print(count_elem(lst1))
num = int(input("Print number: ")) def func_0(num): if -10 < num < 10: num += 5 return num else: num -= 10 return num print(func_0(num))
#!/usr/bin/python f = open("test.txt", "r+") #str = f.read(11) #print str #line = f.readline() #while line != "": # print line # line = f.readline() # f.write("1111") f.flush() f.close() f = open("test.txt", "r+") lines = f.readlines() print lines for line in lines: print line f.close() #dic = {1:2, 2:3} #print dic #print dic[1]
import random i = random.randint(1,10) g=1 answer= 0 while( answer != i and g <= 3): temp = input("请猜数(1~10):") answer = int(temp) if (answer > i): print("猜大了") g+=1 elif (answer < i ): print("猜小了") g= g+1 else: print("你猜对啦,真有默契") if g > 3: print("四次机会你都没猜对,太遗憾了")
class Stack: def __init__(self): self.stack = [] self.len = len(self.stack) def isEmpty(self): if self.stack == []: return True else: return False def push(self,x): self.stack.append(x) def pop(self): return self.stack.pop() def top(self): return self.stack[self.len-1] def bottom(self): return self.stack[0]
def int_input(): try: a = int(input('请输入一个整数:')) except ValueError : print('出错,您输入的不是整数。') int_input() return a number = int_input()
#3 oportunidades para elegir la opcion correcta #adivinar la pregunta from random import randrange palabras = [{'palabra':'MANZANA','pregunta':['¿Viene de un arbol y es roja?','¿Es el logo de las MacBook?']}, {'palabra':'ARBOL','pregunta':['¿Tiene hojas y es verde y grande?','¿Tiene muchos frutos y aveces sirve para hacer muebles?']}, {'palabra':'MUSICA','pregunta':['¿Se puede escuchar por unos audifonos?','¿Las personas bailan cuando la escuchan?']}] # for palabra in palabras: def inicial(): print("Bienvenido a este juego pendejo elije una opcion:") print("{:>30}".format("1-adivina la palabra")) print("{:>30}".format("2-salir")) mando = input( 'Escriba el numero de la opcion: ') dime(mando) def dime(m): if m == "2": print('C salio joven') elif m == "1": adiviname() def adiviname(): malas = 0 p=randrange(len(palabras)) for i in range(3): n=randrange(2) print('oportunidad :',i+1,'/3') print(palabras[p]['pregunta'][n]) q=input() q=q.upper() if q==palabras[p]['palabra']: print('correcto') inicial() else: print('incorrecto') malas +=1 print('malas',malas) inicial()
import sqlite3 conn = sqlite3.connect("test.db") cursor = conn.cursor() # cursor.execute("CREATE TABLE usuarios(nombre VARCHAR(100), edad INTEGER, email VARCHAR(100))") # cursor.execute("INSERT INTO usuarios VALUES ('matia bd',27,'[email protected]')") cursor.execute("SELECT *FROM usuarios") # print(cursor) usuario = cursor.fetchone() print(len(usuario)) print(usuario[2]) # usuario = [( "juan",45,"hikla"), # ("rand",34,"jkjdkjd") # ] # cursor.executemany("INSERT INTO usuarios VALUES (?,?,?)", usuario) # print(usuario) conn.commit() conn.close()
1.Question 1 In the following code, print(98.6) What is "98.6"? <A> A variable <B> A constant <C> An iteration / loop statement <D> A conditional statement AnS: <B> A constant 2.Question 2 What does the following code print out? print("123" + "abc") <A> 123abc <B> This is a syntax error because you cannot add strings <C> hello world <D> 123+abc AnS: <A> 123abc 3.Question 3 Which of the following is a bad Python variable name? <A> spam_23 <B> Spam <C> spam23 <D> spam.23 AnS: <C> spam23 4.Question 4 Which of the following is not a Python reserved word? <A> speed <B> else <C> for <D> if AnS: <A> speed 5.Question 5 Assume the variable x has been initialized to an integer value (e.g., x = 3). What does the following statement do? x = x + 2 <A> Retrieve the current value for x, add two to it and put the sum back into x <B> Produce the value "false" because "x" can never equal "x+2" <C> Create a function called "x" and put the value 2 in the function <D> This would fail as it is a syntax error AnS: <A> Retrieve the current value for x, add two to it and put the sum back into x 6.Question 6 Which of the following elements of a mathematical expression in Python is evaluated first? <A> Parentheses ( ) <B> Subtraction - <C> Addition + <D> Multiplication * AnS: <A> Parenthesis ( ) 7.Question 7 What is the value of the following expression 42 % 10 Hint - the "%" is the remainder operator <A> 10 <B> 4210 <C> 2 <D> 0.42 AnS: <C> 2 8.Question 8 What will be the value of x after the following statement executes: x = 1 + 2 * 3 - 8 / 4 <A> 1.0 <B> 5.0 <C> 2 <D> 3 Ans: <B> 5.0 9.Question 9 What will be the value of x when the following statement is executed: x = int(98.6 <A> 98 <B> 6 <C> 99 <D> 100 Ans: <A> 98 10.Question 10 What does the Python input() function do? <A> Pause the program and read data from the user <B> Connect to the network and retrieve a web page. <C> Read the memory of the running program <D> Take a screen shot from an area of the screen AnS: <A> Pause the program and read data from the user
#!/usr/bin/env python # -*- coding: utf-8 -*- #Author:YangShuang import logging class logger(): def __init__(self,path,consoleLevel,logFile,fileLevel): #创建logger对象 self.logger=logging.getLogger(path) #设置默认log级别 self.logger.setLevel(logging.DEBUG) #定义输出handler的格式 fmt=logging.Formatter("%(asctime)s - %(name)s - %(levelname)s -%(message)s") #设置控制台日志 cg=logging.StreamHandler() #配置logger cg.setFormatter(fmt) cg.setLevel(consoleLevel) #设置文件日志 fg=logging.FileHandler(logFile,"a",encoding="utf-8") fg.setFormatter(fmt) fg.setLevel(fileLevel) #给logger添加handler self.logger.addHandler(cg) self.logger.addHandler(fg) def debug(self,message): self.logger.debug(message) def info(self,message): self.logger.info(message) def warning(self,message): self.logger.warning(message) def error(self,message): self.logger.error(message) def critical(self,message): self.logger.critical(message) if __name__=="__main__": logger=logger("path",consoleLevel=logging.INFO,logFile="logger.txt",fileLevel=logging.DEBUG) #应用日志 logger.debug('debug') logger.info('info') logger.warning('warning') logger.error('error') logger.critical('critical')
import collections import battle_engine import choose_grid import create_character import abilities import enemies import items import weapons DIFFICULTY = 'easy' BOSSES = { 'papa roach': enemies.PapaRoach, 'horn dog': enemies.HornDog, } def create_battle(anzacel, encounter): battle_enemies = [] if not encounter: return battle_engine.Battle([anzacel], [enemies.LilBug()]) for boss, number in encounter.items(): for _ in range(number): battle_enemies.append(BOSSES[boss]()) return battle_engine.Battle([anzacel], battle_enemies) def main(): cells = choose_grid.choose_grid() anzacel = create_character.create_character('Anzacel', cells, []) encounter = collections.Counter() score = 0 battle = create_battle(anzacel, encounter) while battle.start(): score += 1 print('Your current score: %d' % score) print() if DIFFICULTY == 'hard': if score % 3 == 2: encounter['papa roach'] -= 1 encounter['horn dog'] += 1 else: encounter['papa roach'] += 1 battle = create_battle(anzacel, encounter) elif DIFFICULTY == 'easy': enemy = enemies.PapaRoach() if score % 2 == 1 else enemies.HornDog() battle = battle_engine.Battle([anzacel], [enemy]) else: raise ValueError('Invalid difficulty %s' % DIFFICULTY) print('Game over. Your score: %d' % score) if __name__ == '__main__': main()
my_list=['','O',''] from random import shuffle def user_guess(): guess='' while guess not in ['1','2','3']: guess=input("Pick ball position no.- 1 / 2 /3: ") return int(guess) def shuffle_list(): shuffle(my_list) return my_list def check_guess(gussed_index,mixedup_list): # using variables of other funcitions as required arguments. if mixedup_list[gussed_index-1]=='O': print("correct guess") else: print("incorrect guess") mixedup_list=shuffle_list() gussed_index=user_guess() check_guess(gussed_index,mixedup_list) print(mixedup_list)
def run(): my_list = [1, "Hello", True, 4.5] my_dict = {"firstname": "Gio", "lastname": "Morales"} super_list = [ {"firstname": "Gio", "lastname": "Morales"}, {"firstname": "Erick", "lastname": "Bustamante"}, {"firstname": "Javier", "lastname": "Castro"}, {"firstname": "Tony", "lastname": "Tenorio"}, {"firstname": "Abel", "lastname": "Castillo"} ] super_dict = { "natural_nums": [1,2,3,4,5], "integer_nums": [-1, -2, 0, 1, 2], "floating_nums": [1.1, 4.5, 6.43] } #for key, value in super_dict: # print(key, "-", value) for values in super_list: for key, value in values.items(): print(key + ': '+ value) #entry point if __name__ == '__main__': run()
def rotate_left3(nums): first = nums[0] for i in range(0, len(nums) - 1): nums[i] = nums[i + 1] nums[len(nums) - 1] = first return nums
def string_match(a, b): count = 0 max = min (len(a), len(b)) for i in range(0, max - 1): if a[i:i + 2] == b[i:i + 2]: count += 1 return count
import math """Regular Polygon class""" class RegularPoly: """Class to create a regular polygon""" def __init__(self, vert_count, radius): """Initialize the RegulaPoly class attributes""" self.vert_count = vert_count # Number of vertices of polygon self.radius = radius # Circumradius self.interior_angle_l = None self.edge_length_l = None self.apothem_l = None self.area_l = None self.perimeter_l = None @property def vert_count(self): """Get count of vertices""" return self._vert_count @vert_count.setter def vert_count(self, vert_count): """Set the number of vertices of polygon""" if not isinstance(vert_count, int): raise TypeError(f'Number of vertices should be of type integer') if vert_count < 3: raise ValueError(f'Number of vertices should be greater than or equal to 3') self._vert_count = vert_count @property def radius(self): """Get circumradius""" return self._radius @radius.setter def radius(self, radius): """Set the circumradius of polygon""" if not isinstance(radius, int): raise TypeError(f'Radius should be of type integer') if radius < 0: raise ValueError(f'Radius should be greater than 0') self._radius = radius @property def edge_count(self): """Get edge count""" return(self.vert_count) @property def interior_angle(self): """Get interior angle value""" if self.interior_angle_l is not None: return self.interior_angle_l else: self.interior_angle_l = ((self.vert_count - 2)*180)/math.pi return self.interior_angle_l @property def edge_length(self): """Get edge length value""" if self.edge_length_l is not None: return self.edge_length_l else: self.edge_length_l = (2 * self.radius * math.sin(math.pi / self.vert_count)) return self.edge_length_l @property def apothem(self): """Get apothem value""" if self.apothem_l is not None: return self.apothem_l else: self.apothem_l = (self.radius * math.cos(math.pi / self.vert_count)) return self.apothem_l @property def area(self): """Get area value""" if self.area_l is not None: return self.area_l else: self.area_l = (1 / 2 * (self.vert_count * self.edge_length * self.apothem)) return self.area_l @property def perimeter(self): """Get perimeter value""" if self.perimeter_l is not None: return self.perimeter_l else: self.perimeter_l = (self.vert_count * self.edge_length) return self.perimeter_l def __repr__(self): """ Return string for RegularPoly""" return (f'RegularPoly({self.vert_count}, {self.radius})') def __eq__(self,other): """ Check for the equality of RegularPoly""" if isinstance(other, RegularPoly): return(self.vert_count == other.vert_count and self.radius == other.radius) else: raise NotImplementedError('Incorrect data type') def __gt__(self,other): """ Check for the greater than ineqaulity for RegularPoly""" if isinstance(other, RegularPoly): return(self.vert_count > other.vert_count) else: raise NotImplementedError('Incorrect data type')
from collections import namedtuple from datetime import datetime, timedelta from typing import Union, Iterator, Optional from dateutil.relativedelta import relativedelta # Defines begin and end dates Window = namedtuple("Window", ["start", "end"]) def validate_date(date: Union[str, datetime, timedelta, relativedelta, None] = None) -> str: """ Helper function that validates and normalizes date input Parameters ----------- date : Union[str, datetime, timedelta, relativedelta, None] (default None) Date in "YYYY-MM-DD", datetime, timedelta, or None. If str, ValueError will be raised if not in proper format If datetime, input will be converted to "YYYY-MM-DD" format. If timedelta, input will be **added** to the current date (e.g. timedelta(days=-1) for yesterday's date) If None, date will default to todays's date. Returns -------- str : date in "YYYY-MM-DD" format """ if date is None: date = datetime.now() elif isinstance(date, str): try: date = datetime.strptime(date, '%Y-%m-%d') except ValueError: raise ValueError(f"Invalid date string: {date!r}. " "Must be in YYYY-MM-DD format.") elif isinstance(date, (timedelta, relativedelta)): date = datetime.now() + date elif not hasattr(date, 'strftime'): raise ValueError(f"Invalid input type {type(date)!r}. Input must be " f"of type str, datetime, timedelta, relativedelta " f"or None") return date.strftime("%Y-%m-%d") def str_to_datetime(date: Union[str, datetime]) -> datetime: """ Convert a string to a datetime object Parameters ----------- date : Union[str, datetime] Date in "YYYY-MM-DD" format or a datetime object Returns -------- datetime """ if not isinstance(date, datetime): try: date = datetime.strptime(date, "%Y-%m-%d") except (ValueError, TypeError): raise ValueError("date needs to be either a datetime object or a " "string in 'YYYY-MM-DD' format") return date def get_window(date: Union[str, datetime], n_days: int, lookback: bool = True) -> Window: """ Returns namedtuple with start and end timestamps Parameters ----------- date : Union[str, datetime] Date of reference in "YYYY-MM-DD" or datetime n_days : int Number of days in window lookback : bool (default True) If True, window.start will be n_days back from 'date' else, window.end will be n_days forward from 'date' Returns -------- Window (namedtuple) Examples --------- >>> w = get_window(date='2018-02-05', n_days=1, lookback=True) >>> w.start == '2018-02-04' >>> w.end == '2018-02-05' >>> w = get_window(date='2018-02-05', n_days=1, lookback=False) >>> w.start == '2018-02-05' >>> w.end == '2018-02-06' """ ds = str_to_datetime(date) t_delta = timedelta(days=n_days) if lookback: return Window(start=validate_date(ds - t_delta), end=date) return Window(start=date, end=validate_date(ds + t_delta)) def get_daterange(date_window: Optional[Window] = None, start_date: Optional[Union[str, datetime]] = None, end_date: Optional[Union[str, datetime]] = None, freq: str = "D") -> Iterator[str]: """ Return list of days between two dates in "YYYY-MM-DD" format Parameters ----------- date_window : Window This argument takes priority over start_date and end_date if specified start_date : Union[str, datetime, None] end_date : Union[str, datetime, None] freq : str (default "D") The frequency that the daterange should return. The default is to return daily. If a non-daily frequency is specified, pandas is used to generate the daterange and any frequency pandas accepts can be used. NOTE: If freq != 'D', pandas will be imported Returns -------- Iterator[str] """ if date_window is None or not isinstance(date_window, Window): if not all([start_date, end_date]): raise ValueError("Either a window or both a start and end date " "must be specified") start_date = str_to_datetime(start_date) end_date = str_to_datetime(end_date) else: start_date = str_to_datetime(date_window.start) end_date = str_to_datetime(date_window.end) if freq == "D": for day_offset in range(int((end_date - start_date).days) + 1): yield validate_date(start_date + timedelta(days=day_offset)) else: import pandas as pd for date in pd.date_range(start_date, end_date, freq=freq): yield validate_date(date) def get_first_day_of_month(date: Union[str, datetime, timedelta, relativedelta, None] = None) -> str: """ Generate a string for the first day of the month given any type accepted by validate_date Parameters ----------- date : Union[str, datetime, timedelta, None Date in "YYYY-MM-DD", datetime, timedelta, or None. If str, ValueError will be raised if not in proper format If datetime, input will be converted to "YYYY-MM-DD" format. If timedelta or relativedelta, input will be **added** to the current date (e.g. timedelta(days=-1) for yesterday's date) If None, date will default to today's date. Returns -------- str : date in "YYYY-MM-01" format Example -------- >>> get_first_day_of_month("2018-10-16") > "2018-10-01" """ if date is None: date = datetime.today() date = str_to_datetime(validate_date(date)) new_date = datetime(date.year, date.month, 1) return validate_date(new_date)
#!/usr/bin/env python # coding: utf-8 # In[8]: def sum_of_digits(n): if n >= 0 and n <= 9: return n else: return n%10 + sum_of_digits(n//10) number = int(input()) print(sum_of_digits(number)) # In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[7]: def isprime(x): if x == 1 or x == 0: return False for i in range(2, x): if x % i == 0: return False return True number = int(input()) if isprime(number): print('YES') else: print('NO') # In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[2]: numbers_1 = list(map(int, input().split())) numbers_2 = list(map(int, input().split())) result = tuple(set(numbers_1) & set(numbers_2)) print(*result, sep=" ") # In[ ]:
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root: return [] if not root.left and not root.right: return [[root.val]] left_depth, right_depth = 0, 0 left_traversal, right_traversal = [], [] if root.left: left_traversal = self.levelOrderBottom(root.left) left_depth = len(left_traversal) if root.right: right_traversal = self.levelOrderBottom(root.right) right_depth = len(right_traversal) depth = min(left_depth, right_depth) if left_depth > right_depth: primary = left_traversal else: primary = right_traversal for i in range(-1, -depth - 1, -1): primary[i] = left_traversal[i] + right_traversal[i] return primary + [[root.val]]
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return None prev = head current = head.next while current: while current and prev.val == current.val: current = current.next prev.next = current if not current: return head prev = current current = current.next return head
class Solution: def searchInsert(self, nums: [int], target: int) -> int: if len(nums) == 1: if target > nums[0]: return 1 else: return 0 for i in range(1, len(nums)): if target > nums[i-1] and target <= nums[i]: return i return len(nums)
string = raw_input("Enter a word or sentence(s) to see what it looks like backwards:\n") print string,"backwards is: \"", string[::-1],"\""
## Codigo exemplo para a Escola de Matematica Aplicada, minicurso Deep Learning ## Exemplo de rede neural com uma unica camada ## ## Moacir A. Ponti (ICMC/USP), Janeiro de 2018 ## Referencia: Everything you wanted to know about Deep Learning for Computer Vision but were afraid to ask. Moacir A. Ponti, Leonardo S. F. Ribeiro, Tiago S. Nazare, Tu Bui and John Collomosse ## import tensorflow as tf tf.GraphKeys.VARIABLES = tf.GraphKeys.GLOBAL_VARIABLES from tensorflow.examples.tutorials.mnist import input_data as mnist_data # 1) Definir arquitetura # placeholder sao variaveis que podem receber um numero indeterminado de elementos, ainda nao definidos # matriz de entrada (None significa indefinido) X = tf.placeholder(tf.float32, [None, 28, 28, 1]) # tamanho original 28x28x1 # matriz de pesos W = tf.Variable(tf.zeros([784, 10])) # 784 features x 10 classes b = tf.Variable(tf.zeros([10])) # bias de 10 classes # saida Y = tf.placeholder(tf.float32, [None, 10]) # rotulos (de treinamento!) init = tf.global_variables_initializer() # Modelo que ira gerar as predicoes # Mutiplicacao matricial, soma de vetor, funcao de ativacao Softmax # funcao_ativacao(WX + b) = softmax(WX+b) # formula para as predicoes Y_ = tf.nn.softmax(tf.matmul(tf.reshape(X, [-1, 784]), W) + b) # 2) Funcao de custo: informa quao longe estamos da solucao desejada # Entropia cruzada e' uma das mais usadas, relacoes com divergencia de Kullback-Leibler # - [ Y * log(Y_) ] crossEnt = -tf.reduce_sum(Y * tf.log(Y_)) # Outra medida de qualidade pode ser a acuracia correctPred = tf.equal( tf.argmax(Y_,1), tf.argmax(Y,1) ) accuracy = tf.reduce_mean(tf.cast(correctPred, tf.float32)) # 3) Metodo de otimizacao e taxa de aprendizado lrate = 0.003 optMethod = tf.train.GradientDescentOptimizer(lrate) trainProcess = optMethod.minimize(crossEnt) # Tudo pronto, agora podemos executar o treinamento sess = tf.Session() sess.run(init) # Define outras variaveis batchSize = 64 iterations = 1001 # Dataset mnist = mnist_data.read_data_sets("data", one_hot=True, reshape=False, validation_size=0) # 4) Treinamento por iteracoes, cada iteracao realiza um # feed-forward na rede, computa custo, e realiza backpropagation for i in range(iterations): # carrega batch de dados com respectivas classes batX, batY = mnist.train.next_batch(batchSize) # define dicionrio com pares: (exemplo,rotulo) trainData = {X: batX, Y: batY} # executa uma iteracao com o batch carregado sess.run(trainProcess, feed_dict=trainData) # computa acuracia no conjunto de treinamento e funcao de custo # (a cada 10 iteracoes) if (i%10 == 0): acc, loss = sess.run([accuracy, crossEnt], feed_dict=trainData) print(str(i) + " Loss ="+str(loss) + " Train.Acc="+str(acc)) # 5) Valida o modelo nos dados de teste (importante!) testData = {X: mnist.test.images, Y: mnist.test.labels} accTest = sess.run(accuracy, feed_dict=testData) print("\nAccuracy Test="+str(accTest))
from tkinter import * root = Tk() button1 = Button(root, text = "Click") button1.pack() button2 = Button(root, text = "Click", state = DISABLED) button2.pack() button3 = Button(root, text= "Click", padx = 50, pady = 50) button3.pack() root.mainloop()
import turtle from time import sleep t = turtle t.pen() def rectangle(size): t.reset() for x in range(2): t.forward(size + (size/2)) t.left(90) t.forward(size) t.left(90) def triangle(size): t.reset() for x in range(3): t.forward(size) t.left(120) def rect_without_corners(sizea): t.reset() size = sizea/8 for x in range(2): t.up() t.forward(size*2) t.down() t.forward(size*4) t.up() t.forward(size*2) t.left(90) t.forward(size) t.down() t.forward(size*2) t.up() t.forward(size) t.left(90) rectangle(200) sleep(1) triangle(200) sleep(1) rect_without_corners(200)
# look for a number 10 digits all digits are # used 0,1,2,3,4,5,6,7,8,9 # and in each position the number, counting from the start (left) # is a multiple of the digit at the position. # 10 Zahl # python recursive script WE 22.March 2020 ########################################## z=['1','2','3','4','5','6','7','8','9'] zz=['1','2','3','4','5','6','7','8','9'] def ttt(n,z): if n < 10 : # print n,z[0:n] even=[1,3,5,7] odd=[0,2,4,6,8] lll=even if n % 2 == 1: lll=odd for k in lll: s='' for i in range (0,n) : s=s+z[i] t=int(s) # print n,k,s if n ==9 and t % n ==0 : print "cool number ",t*10 if t % n ==0 and z[n-1] not in z[0:n-1] or n==1 : ttt(n+1,z) z[n-1]=zz[k] return #------------------------------------------ # here we start the recursive procedure ttt #------------------------------------------ n=1 ttt(n,z) print "end search cool number"
''' Conor O'Donovan December 2018 Udemy - Complete Python Bootcamp Milestone Project 1 - Tic Tac Toe Creating a two-player Tic Tac Toe game Steps: 1. We need to print a board. 2. Take in player input. 3. Place their input on the board. 4. Check if the game is won,tied, lost, or ongoing. 5. Repeat c and d until the game has been won or tied. 6. Ask if players want to play again. ''' GAME_STATUS = "Setting up" def player1_symbol_select(): ''' Allows Player 1 to select whether they want to be X or O :return: Player 1's symbol (X or O) ''' player1_symbol = "" print("=" * 80) print("Welcome to Tic Tac Toe") print("=" * 80) while player1_symbol != "X" and player1_symbol != "O": player1_symbol = input("Player 1, please select whether you would like to be X or O: ").upper() return player1_symbol def player2_symbol_select(player1): ''' Assigns Player 2's symbol based on Player 1's selection :param player1: Player 1's selected symbol :return: Player 2's symbol ''' if player1 == "X": player2 = "O" else: player2 = "X" return player2 def print_player_symbols(player1, player2): ''' Prints the assigned symbols (X or O) for each player :param player1: Player 1's symbol (X or O) :param player2: Player 2's symbol (X or O) :return: Prints the assigned symbols (X or O) for each player ''' print("=" * 80) print("Player 1 is {}".format(player1)) print("Player 2 is {}\n".format(player2)) def print_board(lst): ''' Prints the board, updating each square as players take their turns :param lst: The list of inputs assigned to the number pad :return: Prints the board ''' print("{}|{}|{}\n" "{}|{}|{}\n" "{}|{}|{}\n".format(lst[6], lst[7], lst[8], lst[3], lst[4], lst[5], lst[0], lst[1], lst[2])) def game_setup_complete(): return "In progress" def inputs_list_initialise(): ''' Sets up the list of inputs corresponding to the number pad. Initially, they're all blank :return: A blank inputs list ''' inputs_lst = [" ", " ", " ", " ", " ", " ", " ", " ", " "] return inputs_lst def take_turn(player, lst): ''' Prompts the player to take their turn. If the player attempts to select a previously filled square, prompts them to try again :param player: Whether it's player 1 or 2's turn :param lst: The input list corresponding to the number pad :return: The player's input for that turn ''' allowed_values = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] turn_input = "" while turn_input not in allowed_values: if player == "1": turn_input = input("Player 1 take turn: \n") else: turn_input = input("Player 2 take turn: \n") while lst[int(turn_input) - 1] != " ": if player == "1": turn_input = input("Space not free. Player 1 take turn: \n") while turn_input not in allowed_values: turn_input = input("Player 1 take turn: \n") else: turn_input = input("Space not free. Player 2 take turn: \n") while turn_input not in allowed_values: turn_input = input("Player 2 take turn: \n") return int(turn_input) def player_switch(player): ''' Switches to the other player after a turn :param player: The player whose turn it previously was :return: The player whose turn it now is ''' if player == "1": player = "2" else: player = "1" return player def inputs_on_board(lst, input_pos, player_turn, player1_symbol, player2_symbol): ''' Puts an X or O on the board accordingly, based on the players' inputs :param lst: The input list corresponding to the number pad :param input_pos: The current input position :param player_turn: The player whose turn it currently is :param player1_symbol: Whether Player 1 is X or O :param player2_symbol: Whether Player 2 is X or O :return: The updated input list ''' if player_turn == "1": lst[input_pos - 1] = player1_symbol else: lst[input_pos - 1] = player2_symbol return lst def check_game_status(lst, player1_symbol): game_won = False game_draw = False winning_symbol = " " if lst[0] == lst[1] == lst[2] != " ": game_won = True winning_symbol = lst[0] elif lst[3] == lst[4] == lst[5] != " ": game_won = True winning_symbol = lst[3] elif lst[6] == lst[7] == lst[8] != " ": game_won = True winning_symbol = lst[6] elif lst[0] == lst[3] == lst[6] != " ": game_won = True winning_symbol = lst[0] elif lst[1] == lst[4] == lst[7] != " ": game_won = True winning_symbol = lst[1] elif lst[2] == lst[5] == lst[8] != " ": game_won = True winning_symbol = lst[2] elif lst[0] == lst[4] == lst[8] != " ": game_won = True winning_symbol = lst[0] elif lst[2] == lst[4] == lst[6] != " ": game_won = True winning_symbol = lst[2] if " " not in lst and game_won == False: game_draw = True if game_won == True: if winning_symbol == player1_symbol: print("Player 1 wins!\n") else: print("Player 2 wins!\n") return "Game won" elif game_draw == True: print("The game has ended in a draw!\n") return "Game won" else: return "In progress" def game_over_options(): print("=" * 80) option_selected = input("Please select one of the following options:\n" "1. Replay\n" "2. Quit\n") while option_selected not in ["1", "2"]: print("=" * 80) option_selected = input("Please select a valid option:\n" "1. Replay\n" "2. Quit\n") return option_selected if __name__ == "__main__": while GAME_STATUS == "Setting up": player_1_symbol = player1_symbol_select() player_2_symbol = player2_symbol_select(player_1_symbol) print_player_symbols(player_1_symbol, player_2_symbol) inputs_list = inputs_list_initialise() print_board(inputs_list) player_turn = "1" GAME_STATUS = game_setup_complete() while GAME_STATUS == "In progress": turn = take_turn(player_turn, inputs_list) inputs_list_updated = inputs_on_board(inputs_list, turn, player_turn, player_1_symbol, player_2_symbol) print_board(inputs_list_updated) player_turn = player_switch(player_turn) GAME_STATUS = check_game_status(inputs_list, player_1_symbol) while GAME_STATUS == "Game won": if game_over_options() == "1": GAME_STATUS = "Setting up" else: quit()
import csv from pathlib import Path inpath = Path("sample.csv") with inpath.open("r", newline="", encoding="utf-8-sig") as infile: reader = csv.DictReader(infile) for row in reader: fullname = f"{row['First name']} {row['Middle name']} {row['Last name']}" print(fullname)
array = [3,6,9,12,23] square=[] for i in range(0,5) : square.append(array[i]*array[i]) print(square[i])
# Student ID : 1201200309 # Student Name : Alvin Chen # get input from user to withdraw money # if balance is less RM10, alert the user that there is no sufficient fund. # and display the current balance # use the keyboard else: to of the current balance is sufficient and # display the new current balance. cur_balance = 30.12 withdraw = float(input("Please enter the withdraw amount : ")) if (cur_balance - withdraw) < 10.00 : print("Insufficient fund") print("Your current balance is : {:.2f} " .format(cur_balance)) else : print("Sufficient balance") new_balance = cur_balance - withdraw print("New current balance is : {:.2f}" .format(new_balance))
from random import choice, randint from collections import Counter text = "Kovach" symbols = [chr(x) for x in range(65,91)] # A - Z symbols += [chr(x) for x in range(97,123)] # a - z # A - z while True: keys = [randint(1,100) for x in range(len(text))] k = Counter(keys) switch = 0; n = 0 for l in k: if k[keys[n]] > 1: switch = 1 break n += 1 if switch == 0: break keys.sort() print("keys:",keys) lattice = [choice(symbols) for x in range(0,101)] n = 0 for i in range(len(lattice)): if n < len(text): if i == keys[n]: lattice[i] = text[n] n += 1 print() for j in range(0,11): if j == 0: print(" ", end = " ") else: print(j, end = " ") print() n = 0 for j in range(1,len(lattice)): if j == 1: print(n, end = " | "); n += 1 print(lattice[j], end = " | ") elif j % 10 != 0: print(lattice[j], end = " | ") else: print(lattice[j], end = " | ") print() if n < 10: print(n, end = " | "); n += 1 print()
import random def empty(board): mas = list() for i in range(9): if (board[i] == ' '): mas.append(i) return(mas) def printBoard(board): print(board[0] + '|' + board[1] + '|' + board[2]) print('-+-+-') print(board[3] + '|' + board[4] + '|' + board[5]) print('-+-+-') print(board[6] + '|' + board[7] + '|' + board[8]) def winning(board, player): if ( (board[0] == player and board[1] == player and board[2] == player) or (board[3] == player and board[4] == player and board[5] == player) or (board[6] == player and board[7] == player and board[8] == player) or (board[0] == player and board[3] == player and board[6] == player) or (board[1] == player and board[4] == player and board[7] == player) or (board[2] == player and board[5] == player and board[8] == player) or (board[0] == player and board[4] == player and board[8] == player) or (board[2] == player and board[4] == player and board[6] == player) ): return True else: return False def minimax(newBoard, player): availSpots = empty(newBoard) moves = [] if player == 'X': plant = 'O' else: plant = 'X' if (winning(newBoard, 'X')): return ([10]) if (winning(newBoard, 'O')): return ([-10]) if len(availSpots) == 0: return ([0]) for i in availSpots: move = [] newBoard[i] = player if (player == aiPl): result = minimax(newBoard, huPl) move.append(result[0]) else: result = minimax(newBoard, aiPl) move.append(result[0]) move.append(i) newBoard[i] = ' ' moves.append(move) if (player == aiPl): bestScore = -10000 for i in moves: if (i[0] > bestScore): bestScore = i[0] bestMove = i else: bestScore = 10000 for i in moves: if (i[0] < bestScore): bestScore = i[0] bestMove = i return bestMove def AIplay(field): move = minimax(field, 'X') field[move[1]] = 'X' printBoard(field) a = random.choice(Tails1) print(a) return(field) def AIplay2(field): massiv = empty(field) move = random.choice(massiv) field[move] = 'X' a = random.choice(Tails1) print(a) printBoard(field) return(field) def AIplay3(field): massiv = empty(field) move = random.choice(massiv) field[move] = 'O' a = random.choice(Tails1) print(a) printBoard(field) return(field) def Huplay(field): a = random.choice(Tails2) print(a) move = int(input()) open = empty(field) flag = 0 for x in open: if move == x: flag = 1 if flag == 1: field[move] = 'O' printBoard(field) return(field) if flag == 0: print('Не хочу обидеть тебя, но ты явно что-то перепутал или перепутала. Подумай еще!') return(Huplay(field)) def HP2(field, player, simb): a = random.choice(Tails3) print(player, a, sep='') move = int(input()) open = empty(field) flag = 0 for x in open: if move == x: flag = 1 if flag == 1: field[move] = simb printBoard(field) return (field) if flag == 0: print('Не хочу обидеть тебя, но ты явно что-то перепутал или перепутала. Подумай еще!') return (HP2(field)) def game0(field): count = 0 winner = 0 if count == 0: count += 1 field[4] = 'X' printBoard(field) a = random.choice(Tails1) print(a) while(count < 9): field = Huplay(field) count += 1 if winning(field, 'O'): winner = 2 break field = AIplay(field) count += 1 if (winning(field, 'X')): winner = 1 break return(winner) def game1(field, pl1, pl2): count = 0 winner = 0 while (count < 9): field = HP2(field, pl1, "X") count += 1 if ((winning(field, 'X')) or (count == 9)): winner = pl1 break field = HP2(field, pl2, "O") count += 1 if winning(field, 'O'): winner = 2 break return (winner) def game2(field): count = 0 winner = 0 while (count < 9): field = AIplay2(field) count += 1 if ((winning(field, 'X')) or (count == 9)): if winning(field, 'X'): winner = 1 break field = AIplay3(field) count += 1 if (winning(field, 'O')): winner = 2 break return (winner) theBoard = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] Tails1 = ['Я учился играть у лучших мастеров.', 'Твои шансы лежат в малой окрестности 0.', 'Я бы пожелал удачи, но она не поможет.', 'Хотел бы я хоть иногда ошибаться', 'Сыграем на биткоин?', 'Давай закончим это быстро', 'Моя очередь.'] Tails2 = ['Твой ход, Дружище!', 'Выбирай клетку, бро!', 'Шансов у тебя нет, но ты держись и выбирай клетку!', 'Напиши, пожалуйста, номер клетки', 'Твоя очередь!'] Tails3 = [', твой ход!', ', выбирай клетку)', ', подумай хорошенько', ', тебе предстоит нелегкий выбор.', ', введи номер свободной клетки!', ', твоя очередь.', ', ходи скорее!', ', какую клетку выбираешь?'] huPl = 'O' aiPl = 'X' print('Привет, ты хочешь сыграть со мной или с другом?' '(Введи 0 или 1)') print('Теперь доступен режим симуляции! Для выбора его введи 2.') answer = int(input()) if answer == 0: print('ОК, бро. Давай попробуем! Я хожу первый)') win = game0(theBoard) if win == 0: print('Хорошая партия, но жаль, что безрезултативная!') print('НИЧЬЯ') if win == 1: print('Предсказуемый итог!') print('ТЫ ПРОИГРАЛ') if win == 2: print('Реальность полна разочарований даже для меня!') print('ТЫ ПОБЕДИЛ') if answer == 1: print('Хорошо, введи пожалуста имя первого игрока!') player1 = input() print('Теперь имя второго)') player2 = input() print('Мы начинаем.') printBoard(theBoard) win = game1(theBoard, player1, player2) if win == 0: print(player1, ' ', player2, ', поздравляю вас с ничьей!', sep='') else: print(win, 'ПОБЕДИЛ!') if answer == 2: print('Сейчас ты увидишь битву настоящих титанов!') print('Леди и джентельмены, боец в синем углы ринга, непобедимый чеспион - крестик!') print('Его соперник, боец в красном углу ринга, дерзкий претендент - нолик!') printBoard(theBoard) print('Мы начинаем.') win = game2(theBoard) if win == 0: print('Хорошая партия, но жаль, что безрезултативная!') print('НИЧЬЯ') if win == 1: print('Предсказуемый итог!') print('ЧЕМПИОН ПОБЕДИЛ!') if win == 2: print('Жизнь порой удивляет!') print('ПРЕТЕНДЕНТ ПОБЕДИЛ')
import sqlite3 import os os.remove('PLdatabase.db') connection = sqlite3.connect('PLdatabase.db') cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS friendship(person1 TEXT, person2 TEXT)') cursor.execute('CREATE TABLE IF NOT EXISTS houses(name TEXT, ' 'person1 Text, person2 TEXT, person3 TEXT, person4 TEXT, ' 'covid1 INTEGER, covid2 INTEGER, covid3 INTEGER, covid4 INTEGER )') friend_const = 100 house_const = 25 def insert_friendship(friend1, friend2): with open('relationships.pl', 'a') as f: f.write("edge('{}', '{}', {}).\n".format( friend1, friend2, friend_const)) connection = sqlite3.connect('PLdatabase.db') cursor = connection.cursor() cursor.execute("INSERT INTO friendship VALUES ('{friend1}', '{friend2}')".format( friend1=friend1, friend2=friend2, )) connection.commit() connection.close() def insert_house(name, person1, person2, person3, person4, covid1, covid2, covid3, covid4): connection = sqlite3.connect('PLdatabase.db') cursor = connection.cursor() for x in [person1, person2, person3, person4]: for y in [person1, person2, person3, person4]: if x != y: with open('relationships.pl', 'a') as f: f.write("edge('{}', '{}', {}).\n".format( x, y, house_const)) for c, p in zip([covid1, covid2, covid3, covid4], [person1, person2, person3, person4]): if c: with open('relationships.pl', 'a') as f: f.write("edge('{}', '{}', {}).\n".format( 'covid', p, 1)) cursor.execute("INSERT INTO houses VALUES ('{name}', '{person1}', '{person2}', '{person3}', '{person4}', '{covid1}', '{covid2}', '{covid3}', '{covid4}')".format( name=name, person1=person1, person2=person2, person3=person3, person4=person4, covid1 = covid1, covid2 = covid2, covid3 = covid3, covid4 = covid4 )) connection.commit() connection.close() def create_connection(): """ create a database connection to a database that resides in the memory """ insert_house('test', 't1', 't2', "t3", "t4", 1, 0, 1, 0) insert_friendship("test", "friend") def get_houses(): connection = sqlite3.connect('PLdatabase.db') cursor = connection.cursor() cursor.execute('SELECT * FROM houses') house_dict = {} for row in cursor.fetchall(): house_dict[row[0]] =[[row[1], row[5]], [row[2], row[6]], [row[3], row[7]], [row[4], row[8]]] print(house_dict[row[0]]) return house_dict def get_friendships(): connection = sqlite3.connect('PLdatabase.db') cursor = connection.cursor() cursor.execute('SELECT * FROM friendship') friendship_list = [] for row in cursor.fetchall(): friendship_list.append((row[0], row[1])) return friendship_list
""" 1. Python syntax can be executed by writing directly in the Command Line python terminal: Lets Go directly to terminal and see 2. Indentation Lets see the appropriate example 3. Comment Comments start with a #, and Python will render the rest of the line as a comment """
age = int(input("Enter your age")) if age>=18: print("Do you have a nid") nid = int(input("Give your nid")) Id = int(input("Give your student id")) if nid == 1: print("you can give vote") elif Id == 1: print("you can give exam") else: print("you can't vote") else: print("you are not eligable for vote")
#문제1. 키보드로 정수 수치를 입력 받아 그것이 3의배수인지 판단하세요 num=input("수를 입력하세요 : ") if(num.isdigit()): num=int(num) if(num%3==0): print("3의 배수 입니다.") else: print("3의 배수가 아닙니다.") else: print("정수가 아닙니다.")
""" Life The Game Dots are represented as tuples: (x, y) where x is an absciss and y is an ordinate. Keep in mind that iteration often comes through i and j where i is a row num and j - column num. """ import random import argparse from typing import List, Dict, Tuple, Union, Any # Default configuration ROWS = 15 COLS = 15 PROB = 0.25 SHIFT = (-1, 0, 1) # Cell repr ALIVE = 'X' DEAD = '.' # Typings FieldType = List[List[str]] DotType = Tuple[int, int] CellType = str # Union[ALIVE, DEAD] # Arg parsing parser = argparse.ArgumentParser(description='Process config data') parser.add_argument('--rows', type=int, help='Number of rows') parser.add_argument('--cols', type=int, help='Number of columns') parser.add_argument('--prob', type=float, help='Probability of population. Must be greater than 0 and less than 1.') args = parser.parse_args() rows_num = args.rows or ROWS cols_num = args.cols or COLS probability = args.prob or PROB def count_neighbors(dot: DotType, field: FieldType) -> int: count = 0 x, y = dot for x_shift in SHIFT: x0 = x + x_shift if x0 < 0 or x0 >= cols_num: continue for y_shift in SHIFT: y0 = y + y_shift if y0 < 0 or y0 >= rows_num: continue if y_shift == 0 and x_shift == 0: # we dont check self continue neighbor = field[y0][x0] if neighbor == ALIVE: count += 1 return count def make_decision(dot: DotType, field: FieldType, count: int) -> CellType: if count <= 1 or count >= 4: return DEAD elif count == 3: return ALIVE elif count == 2: x, y = dot current = field[y][x] if current == ALIVE: return ALIVE return DEAD def count_new_configuration(field: FieldType) -> FieldType: new_configuration = create_blank_field() for i in range(rows_num): for j in range(cols_num): dot = (j, i) result = count_neighbors(dot, field) new_configuration[i][j] = make_decision(dot, field, result) return new_configuration def create_blank_field() -> FieldType: field = [] for row in range(rows_num): temp = [DEAD for _ in range(cols_num)] field.append(temp) return field def generate_random_field(prob=0.5) -> FieldType: if prob <= 0 or prob >= 1: raise ValueError(f'Incorrect probability value: {prob} for generation') field = create_blank_field() dots = [(j, i) for i in range(rows_num) for j in range(cols_num) if prob > random.random()] return fill_field(field, dots) def fill_field(field: FieldType, dots: List[DotType]) -> FieldType: for dot in dots: j, i = dot if j < 0 or j >= cols_num: continue if i < 0 or i >= rows_num: continue field[i][j] = ALIVE return field def print_field(field: FieldType) -> None: for row in field: print(' '.join(row)) def main() -> None: start_config = generate_random_field(probability) print_field(start_config) current_config = start_config for step in range(25): new_config = count_new_configuration(current_config) print('\n') print_field(new_config) current_config = new_config if __name__ == '__main__': main()
num = int(input("Informe um numero: ")) u = num // 1 % 10 d = num // 10 % 10 c = num // 100 % 10 m = num // 1000 %10 print('Analisando o numero {}'. format(num)) print('unidade {}'.format([u])) print('Dezena {} '.format([d])) print('Centea {}'.format([c])) print('milhar {}'.format([m]))
import random a1=input("digite o nome do primeiro aluno: ") a2=input('digite o nome do segundo aluno: ') a3=input('digite o nome do terceiro aluno') a4=input('digite o nome do quarto aluno: ') lista=[a4,a3,a2,a1] sort= random.choice(lista) print(' oa aluno escolhido foi: {}'.format(sort))
km=float(input('Qantos km foram percorridos?')) dias=int(input('quantos dias de locação?')) total=(dias*60)+(km*0.15) print('Ovalor a pagar será de R${:.2f}'.format(total))
ten_things = "apples oranges crows telephone light suger" print("Wait there are not 10 things in that list, Let's fix that.") stuff = ten_things.split(' ') #单引号之间必须加空格,否则报错 more_stuff = ["day","night","song","frisbee","corn","banana","girl","boy"] while len(stuff) != 10: next_one = more_stuff.pop() print("adding:", next_one) stuff.append(next_one) print(f"There are {len(stuff)} items now.") print("THere we go:", stuff) print("Let's do some things with stuff.") print(stuff[1]) # 第二位 print(stuff[-1]) # 倒数第一位 print(stuff.pop()) # 列表第一位 print(' '.join(stuff)) #列表间加入空格输出 print('#'.join(stuff[3:5])) # 列表第四位和第六位加入#输出,是一个对列表进行切片的操作
# Python 3.5.1 # » Documentation » The Python Standard Library # » 6. Text Processing Services # » 6.2. re — Regular expression operations # » 6.2.3 Regular Expression Objects # Compiled regular expression objects support the following methods # and attributes: # If you want to locate a fullmatch anywhere in string, # use search() instead (see also search() vs. fullmatch()). import re re_string = 'dog' re_pattern = 'o[gh]' re_gex = re.compile(re_pattern) # regex.fullmatch(string[, pos[, endpos]]) # regex.fullmatch(string) regex_fullmatch = re_gex.fullmatch(re_string) print("{}".format(regex_fullmatch)) # regex.fullmatch(string, pos) regex_fullmatch = re_gex.fullmatch(re_string, pos=1) print("{}".format(regex_fullmatch))
import datetime import hashlib import array import json """ Title: Python Block Chain Author: Bradley K. Hnatow Description: A simple block chain program devloped in python later to be used and updated for more complex projects. """ class block(): def __init__(self, prevHash, dataArray, proof, nonce=0): self.timeOfCreation = block.calculateTime() self.prevHash = prevHash self.dataArray = dataArray self.hash = block.calculateHash(self) self.nonce = nonce # calculateTime() # Calculates the time that the newly created block was created # Sets the date of the block in a (Year, Day Of Week, Month, Date, # Hour, Minute, Second) format. # @returns String @staticmethod def calculateTime(): date = datetime.datetime.now() formalDate = date.strftime("%Y %a %b %d %H:%M:%S") return formalDate # calculateHash(self) # Generates a hash for the newly created block by using # variables like timeOfCreation, and the prevHash. # Hash is generated using sha256 # @returns void def calculateHash(self): hashCode = hashlib.sha256( (str(self.timeOfCreation) + self.prevHash).encode('utf-8')).hexdigest() self.hash = hashCode class blockChain(): def __init__(self): self.unconfirmed = [] self.chain = [] genesis = block("0000", [], ) #(self, prevHash, data, proof) self.chain.append(genesis) self.valid = True # printBlockChain(self) # Prints the current block chain providing each # block's Data, Time of creation, Hash, & PrevHash # @reutns void def printBlockChain(self): for x in range(len(self.chain)): print( "Data: " + self.chain[x].data + "\nTime: " + self.chain[x].timeOfCreation + "\nHash: " + self.chain[x].blockHash + "\nPrevHash: " + self.chain[x].prevHash + "\n" ) # getLatestHash(self) # Provides the latest hash of blocks in the blockChain # @returns String @property def getLatestHash(self): return str(self.chain[len(self.chain)-1].blockHash) # getLatestBlock(self) # Returns the most recently added block on the chain # @returns <block> @property def getLatestBlock(self): return self.chain[-1] def addNewUnconfirmed(self,data): self.unconfirmed.append(data) # addBlock(self, data) # Adds a new block to the chain array # @reutrns void def addBlock(self, data, proof): newBlock = block(blockChain.getLatestHash(self), len(self.chain), data) self.chain.append(newBlock) self.proof = self.testChainIntegrity() # testChainIntegrity(self) # Checks the current self.chain[x].hash and compares it to # next block in the chain's prevHash # @returns void def testChainIntegrity(self): for x in range(len(self.chain)-1): if self.chain[x].blockHash == self.chain[x+1].prevHash: self.valid = True elif self.chain[x].blockHash != self.chain[x+1].prevHash: self.valid = False break if self.valid == True: print("Accepted: Block Chain is Valid.\n") elif self.valid == False: print("Error: Block Chain is invalid.\n") else: print("Error: Something went wrong.\n") testBlockChain = blockChain() testBlockChain.printBlockChain() testBlockChain.addBlock("Second Block") testBlockChain.printBlockChain() testBlockChain.addBlock("Third Block") testBlockChain.printBlockChain() testBlockChain.addBlock("Forth Block") testBlockChain.printBlockChain() testBlockChain.testChainIntegrity()
from PyDictionary import PyDictionary class Mydictionary: word='' def __init__(self,word): self.word=word def giveMeaning(self): dictionary=PyDictionary() x=dictionary.meaning(self.word) xx=str(x['Noun'][0]) print(f'meaning: {xx}') return (x['Noun'][0])
myage = 22 user_age = int(("enter your age")) if(user_age > myage) print("your are older than me") elif(user_age == myage) print(" you and my are same age) else(user_age < myage print("you are younger than me")
my_name = "siva" my_age = "22" my_percentage = "6.5" if (my_name == siva): print("name: %s","my_name") if (my_age == 22): print("age: %d","my_age") if (my_percentage = "6.5") print("percentage %f","my_percentage")
import nltk import string from nltk.collocations import ngrams #words = nltk.word_tokenize(my_text) #my_bigrams = nltk.bigrams(words) #my_trigrams = nltk.trigrams(words) bigramslist = [] trigramslist = [] with open("Penfed_updated.txt", encoding = "utf-8") as file: for line in file.readlines(): #print(line) words = nltk.word_tokenize(line) words = [''.join(c for c in s if c not in string.punctuation) for s in words] words = [s for s in words if s] #print(words) my_bigrams = list(ngrams(words, 2)) my_trigrams = list(ngrams(words, 3)) bigramslist.append(my_bigrams) trigramslist.append(my_trigrams) for i in bigramslist: print(i) for j in trigramslist: print(j)
# Домашка """ - делать все на функциях - должно работать со всеми Iterable: списки, генераторы, проч. - по возможности возвращать генератор (ленивый объект) - тесты на pytest + pytest-doctest, покрыть как можно больше кейсов - в помощь: itertools, collections, funcy, google """ from typing import Iterable from collections import defaultdict ## 1. Написать функцию получения размера генератора def ilen(iterable: Iterable): """ >>> foo = (x for x in range(10)) >>> ilen(foo) 10 """ tmp = iterable count = 0 for _ in tmp: count += 1 return count ## 2. Написать функцию flatten, которая из многоуровневого массива сделает одноуровневый def flatten(iterable: Iterable): """ >>> list(flatten([0, [1, [2, 3]]])) [0, 1, 2, 3] """ for i in iterable: if isinstance(i, Iterable): yield from flatten(i) else: yield i ## 3. Написать функцию, которая удалит дубликаты, сохранив порядок def distinct(iterable: Iterable): """ >>> list(distinct([1, 2, 0, 1, 3, 0, 2])) [1, 2, 0, 3] """ unique = set() for i in iterable: if i not in unique: unique.add(i) yield i ## 4. Неупорядоченная последовательность из словарей, сгруппировать по ключу, на выходе словарь def groupby(key, iterable: Iterable): """ >>> users = [ {'gender': 'female', 'age': 33}, {'gender': 'male', 'age': 20}, {'gender': 'female', 'age': 21}, ] >>> groupby('gender', users) { 'female': [ {'gender': 'female', 'age': 23}, {'gender': 'female', 'age': 21}, ], 'male': [{'gender': 'male', 'age': 20}], } # Или так: >>> groupby('age', users) """ group = defaultdict(list) for d in iterable: group[d[key]].append(d) return group ## 5. Написать функцию, которая разобьет последовательность на заданные куски def chunks(size: int, iterable: Iterable): """ >>> list(chunks(3, [0, 1, 2, 3, 4])) [(0, 1, 2), (3, 4, )] """ buf = [] idx = 0 if size > 0: for v in iterable: if idx >= size: idx = 0 yield tuple(buf) buf = [] buf.append(v) idx += 1 yield tuple(buf) else: yield tuple(iterable) # list(chunks(3, [0, 1, 2, 3, 4])) ## 6. Написать функцию получения первого элемента или None def first(iterable: Iterable): """ >>> foo = (x for x in range(10)) >>> first(foo) 0 >>> first(range(0)) None """ try: return next(iter(iterable)) except StopIteration: return None ## 7. Написать функцию получения последнего элемента или None def last(iterable: Iterable): """ >>> foo = (x for x in range(10)) >>> last(foo) 9 >>> last(range(0)) None """ i = None for i in iterable: pass return i
class ChessBoard: def __init__(self): self.board = [[1] * 8 for i in range(8)] rook = Rook("R", []) self.board.insert(rook, [0][0]) def show(): print(self.board) class Piece: # TODO: Most likely create a class for each different piece inheriting Piece class # Then define their own validMove method since some pieces vary upon different scenarions i.e king cant castle through check # Move pattern, we have to define most likely a 2D array of possible coordinates to move at with the Piece being the origin (0,0) # This will define how far it can go, but its validMove method will consider if that piece can take over a piece, move to that, or if its an illegal move etc def __init__(self, symbol="P", move_pattern): # default value will be P for pawn self.symbol = symbol self.move_pattern = move_pattern def illegalMove(move): def promote(): # if pawn ask what unit to promote to and change its symbol and move pattern accordingly class Rook(Piece):
""" Case014: decompose a number to prime factors. For example, input 90, output 90=? """ def decomposeNumber(number, list:list): for i in range(2, number+1): if number%i == 0: list.append(i) if int(number/i) == 1: return list if len(list)>1 else [1, list[0]] else: return decomposeNumber(int(number/i), list) number = int(input("Please enter a random positive integer: ")) print(decomposeNumber(number, []))
""" If add an integer I with 100, the result is a perfect square. And the result plus 168 can equal another perfect square. What is the number? """ import math I = 0 while (I+1)**2-I**2 <= 168: I+=1 for i in range((I+1)**2): if (i+100)**0.5-math.floor((i+100)**0.5)==0 and (i+100+168)**0.5-math.floor((i+100+168)**0.5)==0: print(i) break
from sys import exit import pyglet class Notification: """ A simple notification on the top right border. It needs a background image, 'notification.png', which is 150x50 in size. To use, do the following in the window class: 1. Add a list 'self.notifications' 2. Add the following 2 methods in the class for ease of use def show_notifications(self): for n in self.notifications: n.draw() def add_notification(self, title, text): notification = Notification(self, title, text, group=GAME_LAYER) self.notifications.append(notification) pyglet.clock.schedule_once(lambda x: self.notifications.remove(notification), 5) """ def __init__(self, window, title, text, group=None, time=5): self.background_image = pyglet.resource.image('notification.png') self.position = [window.width - self.background_image.width - 5, window.height - self.background_image.height - 5] self.background = pyglet.sprite.Sprite(self.background_image, self.position[0], self.position[1]) self.background.opacity = 100 size = 15 self.title = pyglet.text.Label(title, font_size=size, bold=True, x=self.position[0] + 5, y=self.position[1] + self.background_image.height - size - 8) size = 8 self.text = pyglet.text.Label(text, font_size=size, x=self.position[0] + 7, y=self.position[1] + self.background_image.height - size - 30) def draw(self): self.background.draw() self.title.draw() self.text.draw() class Menu: """ This class is made specifically for the TwoZeroFourMate game. Will be changed to be more usable in other games later on. The menu is of size 200x200. By default has a exit button. Set exit_button to False to remove that. Btw, don't try to understand this code. It just is. """ def __init__(self, window, size=(250, 250), exit_button=True): self.window = window self.exit_button = exit_button self.background_image = pyglet.resource.image('menu_background.png') self.background_image.width, self.background_image.height = size self.background = pyglet.sprite.Sprite(self.background_image, window.width / 2 - self.background_image.width / 2, window.height / 2 - self.background_image.height / 2) self.background.opacity = 80 # to avoid magic numbers self.space_between_items = -3 # negative = overlapping self.space_before_title = 3 self.space_after_title = 25 self.title = pyglet.text.Label('Menu', font_size=30) self.title.anchor_x = 'center' self.title.anchor_y = 'top' self.title.x, self.title.y = self.background.width / 2, self.background.height - self.space_before_title self._items = [] # add an exit button by default if self.exit_button: self.add_item('EXIT', exit, size=18, color=(255, 0, 0, 200)) def add_item(self, text, action, size=15, color=(255, 255, 255, 255)): """ Adds an menu item to the items list. An item just represents a dict with some info in it. The action argument is a func which will be run when clicked on the item. """ label = pyglet.text.Label(text, font_size=size, color=color, anchor_x='center') if len(self._items) == 0: position = [self.background.width / 2, self.title.y - self.title.content_height / 2 - self.space_after_title - self.space_before_title - label.content_height] else: position = [self.background.width / 2, self._items[-1]['label'].y - label.content_height - self.space_between_items] label.x, label.y = position menu_item = { 'text': text, 'action': action, 'size': size, 'color': color, 'pos': position, 'label': label } self._items.append(menu_item) #self._items.insert(0, menu_item) def on_mouse_press(self, x, y, button, modifiers): for item in self._items: if x in range(item['label'].x - item['label'].content_width / 2, # since it anchor is in the center item['label'].x + item['label'].content_width / 2) and \ y in range(item['label'].y, item['label'].y + item['label'].content_height): item['action']() def show(self): """ Show the menu. """ self.background.draw() self.title.draw() for item in self._items: item['label'].draw()
#!/usr/bin/env python import wx # The CoolerFrame in this lesson is similar to the last lesson with a few additions. # But the main program is different. # Be sure you run the program to see what it does class CoolerFrame(wx.Frame): # Remember __init__ is the constructor function. It sets up or "initializes" the new CoolerFrame def __init__(self, parent): # We still want to do all stuff that the original wx.Frame constructor does, so we call it first. wx.Frame.__init__(self, parent, wx.ID_ANY, "Our Title") self.panel = wx.Panel(self) self.btnClickMe = wx.Button(self.panel, label="Click Me", pos=(20, 20)) self.btnMeToo = wx.Button(self.panel, label="Me Too", pos=(20, 40)) # The following line is commented out for now. We'll investigate it in Exercise 1. #self.btnMeToo.Show(False) self.heading = wx.StaticText(self.panel, label="Let's Click Some Buttons", pos=(10, 5)) # We want the buttons to do something when we click them. So let's bind them to event handler functions. self.btnClickMe.Bind(wx.EVT_BUTTON, self.OnClickMe) self.btnMeToo.Bind(wx.EVT_BUTTON, self.OnMeToo) # And Now we write the event handlers to determine *what* happens when the buttons are clicked. def OnClickMe(self, e): print "Yay! You clicked it." def OnMeToo(self, e): print "You clicked the second one." # ----------- Main Program Below ----------------- # Define the app app = wx.App(False) # Create an instance of our class frame = CoolerFrame(None) # Show the frame frame.Show() # Make the app listen for clicks and other events app.MainLoop() # ----------- Exercises Below ----------------- #1. Uncomment Line 21 and run the program again. What does that line do? #2. Since btnMeToo is no longer visible right away, it is up to us to make it visible. # Let's make btnMeToo visible when btnClickMe is clicked. # To make something happen when a button is clicked, we add code to the event handler. # Add some code in line 32 to make btnMeToo appear. #3. We're getting pretty good at GUI programming, but we're still printing to the terminal. # Let's change it so our messages go to the GUI window instead of the terminal. # replace the print command on line 31 with self.heading.SetLabel("Yay! You clicked it.") #4. Do the same for btnMeToo #5. Your final task is to make btnClickMe disappear when it is clicked. # A final Note --- # # In this lesson we used SetLabel to change wx.StaticText widgets and Show to show and hide wx.Buttons. # But either method can be used for any widget. # For example, we could have used # self.btnClickMe.SetLabel("Don't click me") # or # self.heading.Show(False)
# 5203.py 베이비진 게임 def is_babygin(i, c): if c[i] == 3: # run return True # triplet if -1 < i - 1 and c[i - 1]: if -1 < i - 2 and c[i - 2]: return True # i-2,i-1,i elif i + 1 < 10 and c[i + 1]: return True # i-1,i,i+1 if i < 8 and c[i + 1] and c[i + 2]: return True # i,i+1,i+2 return False t = int(input()) for tc in range(1, t + 1): card = list(map(int, input().split())) c1, c2 = [0] * 10, [0] * 10 for i in range(6): c1[card[i * 2]] += 1 if is_babygin(card[i * 2], c1): print('#{} 1'.format(tc)) break c2[card[i * 2 + 1]] += 1 if is_babygin(card[i * 2 + 1], c2): print('#{} 2'.format(tc)) break else: print('#{} 0'.format(tc))
# 부분집합 생성 코드 예제) 교재에서! arr = [3, 6, 7, 1, 5, 4] n = len(arr) # n: 원소의 개수 for i in range(1<<n) : # 1<<n: 부분집합의 개수 for j in range(n+1): # 원소의 수만큼 비트 비교 if i & (1<<j): # i의 j번째 비트가 1이면 j번째 원소 출력 print(arr[j], end=", ") print()
#reduce #reduce(func_name,iterable_obj) from functools import reduce fac= lambda a,b:a*b li = [1,2,3,5] mul= reduce(fac,li) #1*2*3*5=30 maxi= reduce(lambda a,b:a if a>b else b , li) #passing lambda expression #reduce(max,li) print('sum of li: {}'.format(mul),end=' and ') print('maximum element: {}'.format(maxi))
#project #stone_paper_scissor #python import random def gameplay(): dic={ 1:'Stone', 2:'Paper', 3:'Scissor'} print('\n\nYour play') for i in dic: print(i,' ',dic[i]) op= int(input()) print('You choose: ',dic[op]) keys=list(dic.keys()) bot= random.choice(keys) print('Bot choose: ',dic[bot],end='\n') print('The winner is: ',result(op,bot)) print('Do you want to play again?') print('1: Yes') print('0: No, quit') t=int(input()) if t==0: pass elif t==1: gameplay() else: print('Wrong Input') def result(user,bot): if user==bot: return 'Draw' elif (user==1 and bot==2 or user==2 and bot==3 or user==3 and bot==1): return 'Bot' else: return 'User' def start(): print('WELCOME TO --STONE-PAPER-SCISSOR-- GAME',end='\n\n') print('1: Start') print('0: Exit') op= int(input()) if op==1: gameplay() if __name__=='__main__': start()
def find_fac(num): if num == 1: result = 1 return result else: result = num * find_fac(num - 1) return result def main(): num = int(input("Enter the number: ")) result = find_fac(num) print("Factorial is: ", result ) if __name__ == "__main__": main()
#Question 1 import math print(math.pi) #Question 2 x = 5 for i in range(x): x = x + i print(x, end=" ") #Question 5 text = "Enjoy the test" result = text.strip().split()[0] print("\n" + result) #Question 6 def fn(x, y): z = x + y print(fn(1, 2)) #Question 10 try: x = int("zero") print(10 / x) except ZeroDivisionError: print("div") except NameError: print("name") except ValueError: print("value") except: print("other")
import re """ A Utility class to provide means to test the validity of keys and values in the received payload. """ class ComplianceChecks: def __init__(self, payload): """ Constructor for the compliance check class Parameters ---------- payload : the customer information payload """ self.payload = payload self.CUSTOMER_NAME = "customer_name" self.PHONE_NUMBER = "phone_number" self.key_flag = True self.value_flag = True def check_payload_compliance_for_keys(self): """ Method to check the payload for compliance. Returns ------- Boolean value to indicate the compliance of keys and values. """ if not len(self.payload): self.key_flag = False raise BaseException("Customer details cannot be empty") if type(self.payload) == dict and ( (self.CUSTOMER_NAME not in self.payload) or (self.PHONE_NUMBER not in self.payload)): self.key_flag = False raise KeyError("Customer information should have customer_name and phone_number") self.key_flag = True return self.key_flag def check_payload_compliance_for_values(self): """ Method to check for the compliance of the values. :return: None """ name_regex = re.compile(r"^[a-z ,.'-]+$", re.IGNORECASE) phone_regex = re.compile(r"^[0-9]{11}$") if type(self.payload) == list: for each_customer in self.payload: return self.regex_value_checks(each_customer, name_regex, phone_regex) elif type(self.payload) == dict: return self.regex_value_checks(self.payload, name_regex, phone_regex) def regex_value_checks(self, each_customer, name_regex, phone_regex): """ Method to check the values against the regex Parameters ---------- each_customer : customer information object name_regex : regex to match the name phone_regex : regex to match the phone Returns ------- Boolean: True if the value is compliant and False otherwise """ if (name_regex.match(str(each_customer.get(self.CUSTOMER_NAME)))) and \ (phone_regex.match(str(each_customer.get(self.PHONE_NUMBER)))): return self.value_flag else: self.value_flag = False return self.value_flag
#!/usr/bin/env python # # Author: Ying Xiong. # Created: Mar 18, 2014. """Utility functions for quaternion and spatial rotation. A quaternion is represented by a 4-vector `q` as:: q = q[0] + q[1]*i + q[2]*j + q[3]*k. The validity of input to the utility functions are not explicitly checked for efficiency reasons. ======== ================================================================ Abbr. Meaning ======== ================================================================ quat Quaternion, 4-vector. vec Vector, 3-vector. ax, axis Axis, 3- unit vector. ang Angle, in unit of radian. rot Rotation. rotMatx Rotation matrix, 3x3 orthogonal matrix. HProd Hamilton product. conj Conjugate. recip Reciprocal. ======== ================================================================ """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np def quatConj(q): """Return the conjugate of quaternion `q`.""" return np.append(q[0], -q[1:]) def quatHProd(p, q): """Compute the Hamilton product of quaternions `p` and `q`.""" r = np.array([p[0]*q[0] - p[1]*q[1] - p[2]*q[2] - p[3]*q[3], p[0]*q[1] + p[1]*q[0] + p[2]*q[3] - p[3]*q[2], p[0]*q[2] - p[1]*q[3] + p[2]*q[0] + p[3]*q[1], p[0]*q[3] + p[1]*q[2] - p[2]*q[1] + p[3]*q[0]]) return r def quatRecip(q): """Compute the reciprocal of quaternion `q`.""" return quatConj(q) / np.dot(q,q) def quatFromAxisAng(ax, theta): """Get a quaternion that performs the rotation around axis `ax` for angle `theta`, given as:: q = (r, v) = (cos(theta/2), sin(theta/2)*ax). Note that the input `ax` needs to be a 3x1 unit vector.""" return np.append(np.cos(theta/2), np.sin(theta/2)*ax) def quatFromRotMatx(R): """Get a quaternion from a given rotation matrix `R`.""" q = np.zeros(4) q[0] = ( R[0,0] + R[1,1] + R[2,2] + 1) / 4.0 q[1] = ( R[0,0] - R[1,1] - R[2,2] + 1) / 4.0 q[2] = (-R[0,0] + R[1,1] - R[2,2] + 1) / 4.0 q[3] = (-R[0,0] - R[1,1] + R[2,2] + 1) / 4.0 q[q<0] = 0 # Avoid complex number by numerical error. q = np.sqrt(q) q[1] *= np.sign(R[2,1] - R[1,2]) q[2] *= np.sign(R[0,2] - R[2,0]) q[3] *= np.sign(R[1,0] - R[0,1]) return q def quatToRotMatx(q): """Get a rotation matrix from the given unit quaternion `q`.""" R = np.zeros((3,3)) R[0,0] = 1 - 2*(q[2]**2 + q[3]**2) R[1,1] = 1 - 2*(q[1]**2 + q[3]**2) R[2,2] = 1 - 2*(q[1]**2 + q[2]**2) R[0,1] = 2 * (q[1]*q[2] - q[0]*q[3]) R[1,0] = 2 * (q[1]*q[2] + q[0]*q[3]) R[0,2] = 2 * (q[1]*q[3] + q[0]*q[2]) R[2,0] = 2 * (q[1]*q[3] - q[0]*q[2]) R[1,2] = 2 * (q[2]*q[3] - q[0]*q[1]) R[2,1] = 2 * (q[2]*q[3] + q[0]*q[1]) return R def rotVecByQuat(u, q): """Rotate a 3-vector `u` according to the quaternion `q`. The output `v` is also a 3-vector such that:: [0; v] = q * [0; u] * q^{-1} with Hamilton product.""" v = quatHProd(quatHProd(q, np.append(0, u)), quatRecip(q)) return v[1:] def rotVecByAxisAng(u, ax, theta): """Rotate the 3-vector `u` around axis `ax` for angle `theta` (radians), counter-clockwisely when looking at inverse axis direction. Note that the input `ax` needs to be a 3x1 unit vector.""" q = quatFromAxisAng(ax, theta) return rotVecByQuat(u, q) def quatDemo(): # Rotation axis. ax = np.array([1.0, 1.0, 1.0]) ax = ax / np.linalg.norm(ax) # Rotation angle. theta = -5*np.pi/6 # Original vector. u = [0.5, 0.6, np.sqrt(3)/2]; u /= np.linalg.norm(u) # Draw the circle frame. nSamples = 1000 t = np.linspace(-np.pi, np.pi, nSamples) z = np.zeros(t.shape) fig = plt.figure() fig_ax = fig.add_subplot(111, projection="3d", aspect="equal") fig_ax.plot(np.cos(t), np.sin(t), z, 'b') fig_ax.plot(z, np.cos(t), np.sin(t), 'b') fig_ax.plot(np.cos(t), z, np.sin(t), 'b') # Draw rotation axis. fig_ax.plot([0, ax[0]*2], [0, ax[1]*2], [0, ax[2]*2], 'r') # Rotate the `u` vector and draw results. fig_ax.plot([0, u[0]], [0, u[1]], [0, u[2]], 'm') v = rotVecByAxisAng(u, ax, theta) fig_ax.plot([0, v[0]], [0, v[1]], [0, v[2]], 'm') # Draw the circle that is all rotations of `u` across `ax` with different # angles. v = np.zeros((3, len(t))) for i,theta in enumerate(t): v[:,i] = rotVecByAxisAng(u, ax, theta) fig_ax.plot(v[0,:], v[1,:], v[2,:], 'm') fig_ax.view_init(elev=8, azim=80) plt.show() if __name__ == "__main__": quatDemo()
# 2. Для списка реализовать обмен значений соседних элементов, # т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). count = 0 x = 0 a = "" my_list = [] b = "end" while a != b: a = input("Введите значение списка = ") if a != b: my_list.append(a) count += 1 print("Наберите end , если закончили заполнение списка") print(my_list) if len(my_list) > 1: if count % 2 == 0: k = 1 else: k=2 for i in range(0,len(my_list)-k,2): a = my_list[i] my_list[i] = my_list[i+1] my_list[i+1] = a print(my_list)
#Importing the Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the Dataset dataset = pd.read_csv('Academic_Data.csv') #Create the matrix of features and Dependent Variables vector X = dataset.iloc[:, :-1].values #creating the dependent variable vector y = dataset.iloc[:, 1].values #Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) #Feature Scaling """from sklearn.preprocessing import StandardScaler sc_X =StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test)""" #Fitting Simple Linear Regression to the Training Set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) #Predicting the Test Set Results (GPAs) y_pred = regressor.predict(X_test) #predictions of the test set #Visualising the Training Set Results plt.scatter(X_train, y_train, color = 'red') #real values/ observation points of the training set plt.plot(X_train, regressor.predict(X_train), color = 'blue') #predictions trained by X and y train plt.title('SAT Score vs GPA (Training Set)') plt.xlabel('SAT Score') plt.ylabel('GPA') plt.show() #Visualising the Test Set Results plt.scatter(X_test, y_test, color = 'red') #observation points of the test set plt.plot(X_train, regressor.predict(X_train), color = 'blue') #same prediction line from training results plt.title('SAT Score vs GPA (Test Set)') plt.xlabel('SAT Score') plt.ylabel('GPA') plt.show()
# Input the number N = int(input()) max1 = result = 0 # Counting consecutive 1 when converting the number to binary while N > 0: if N % 2 == 1: result += 1 if result > max1: max1 = result else: result = 0 N = N//2 print(max1)
# Reverse import random import sys WIDTH = 8 # Game field has 8 cells in width. HEIGHT = 8 # Game field has 8 cells in height. def drawBoard(board): # Display game field, don't return anything. print(' 12345678') print(' +---------+') for y in range(HEIGHT): print('%s|' % (y+1), end='') for x in range(WIDTH): print(board[x][y], end='') print('|%s' % (y+1)) print(' +---------+') print(' 12345678') def getNewBoard(): # Create new data structure of game field. board = [] for i in range(WIDTH): board.append([' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']) return board def isValidMove(board, tile, xstart, ystart): # Return False, if move to 'xstart', 'ystart' is not allowed. # OR return list of all cells, which would be assigned on Player, if he maded a move. if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart): return False if tile == 'X': otherTile = 'O' else: otherTile = 'X' tilesToFlip = [] for xdirection, ydirection in [[0,1], [1,1], [1,0], [1, -1], [-1, -1], [-1, 0], [-1, 1]]: x, y = xstart, ystart x += xdirection # First move towards x. y += ydirection # First move towards y. while isOnBoard(x, y) and board[x][y] == otherTile: # Keep moving towards x & y. x += xdirection y += ydirection if isOnBoard(x, y) and board[x][y] == tile: # There tile, which can be flipped over. Move backwards marking all the tiles on its way. while True: x -= xdirection y -= ydirection if x == xstart and y == ystart: break tilesToFlip.append([x,y]) if len(tilesToFlip) == 0: # If none of tiles was flipped, this move is incorrect. return False return tilesToFlip def isOnBoard(x, y): # Return True, if the coordinates are present on game board. return x >= 0 and x <= WIDTH - 1 and y >= 0 and y <= HEIGHT - 1 def getBoardWithValidMoves(board, tile): # Return new board with points, meaning possible moves, which player can do. boardCopy = getBoardCopy(board) for x, y in getValidMoves(boardCopy, tile): boardCopy[x][y] = '.' return boardCopy def getValidMoves(board, tile): # Return list of list with coordinates x and y with steps allowed for this player on this board. validMoves = [] for x in range[WIDTH]: for y in range[HEIGHT]: if isValidMove[board, tile, x, y] != False: validMoves.append([x, y]) return validMoves def getScoreOfBoard(board): # Verify points by calculating tiles. Return dictionary with keys 'X' and 'O'. xscore = 0 yscore = 0 for x in range(WIDTH): for y in range(HEIGHT): if board[x][y] == 'X': xscore += 1 if board[x][y] == 'O': oscore += 1 return ('X':xscore, 'O':oscore) def enterPlayerTile(): # Allow player to enter chosen tile. # Return list with player's tile as the first element and PC's tile as the second one. tile = '' while not (tile == 'X' or tile == 'O'): print('You\'re playing for X or for Y?') tile = input().upper() # The first element of list is the player's tile, the second one is PC's tile. if tile = 'X': return ['X', 'O'] else: return ['O', 'X'] def whoGoesFirst(): # Choose randomly, who moves first. if random.randint(0,1) == 0: return 'PC' else: return 'Human' def makeMove(board, tile, xstart, ystart): # Place tile into 'xstart', 'ystart' positions and flip over enemy's tile. # Return False, if it's inappropriate; return True if it's possible. tilesToFlip = isValidMove(board, tile, xstart, ystart) if tilesToFlip == False: return False board[xstart][ystart] = tile for x, y in tilesToFlip: board[x][y] = tile return def getBoardCopy(board): # Copy board list and return it. boardCopy = getNewBoard() for x in range(WIDTH): for y in range(HEIGHT): boardCopy[x][y] = board[x][y] return boardCopy def isOnCorner(x, y): # Return True, if the position is in one of the corners. return (x == 0 or x == WIDTH - 1) and (y == 0 or y == HEIGHT - 1) def getPlayerMove(board, playerTile): # Allow Player make a move. # Return move like [x, y] or return 'hint' or 'exit'. DIGITS1TO8 = '1 2 3 4 5 6 7 8'.split() while True print('Type your move, \'exit\' or \'hint\'.') move = input().lower() if move == 'exit' or move == 'hint': return move if len(move) == 2 and move[0] in DIGITS1TO8 and move[1] in DIGITS1TO8: x = int(move[0]) - 1 y = int(move[1]) - 1 if isValidMove(board, playerTile, x, y) == False continue else: break else: print('It is unacceptable. Enter column number (1-8) and row number (1-8).') print('For example, value 81 move to the upper right corner.') return [x, y] def getComputerMove[board, computerTile] # Bearing in mind the current game board, check # where to move and return this move like [x, y]. possibleMoves = getValidMoves(board, computerTile) random.shuffle(possibleMoves) # Make moves random. # Always make move to the corner, whenever it's possible. for x, y in possibleMoves: if isOnCorner(x, y): return [x, y] # Find a move with the most possible amount of points. bestScore = -1 for x, y in possibleMoves: boardCopy = getBoardCopy(board) makeMove(boardCopy, computerTile, x, y) score = getScoreOfBoard(boardCopy)[computerTile] if score > bestScore: bestMove = [x, y] bestScore = score return bestMove def printScore(board, playerTile, computerTile): scores = getScoreOfBoard(board) print('Your score: %s. CPU score: %s.' % (scores[playerTile], scores[computerTile])) def playGame(playerTile, computerTile): showHints = False turn = whoGoesFirst() print(turn + ' moves first.') # Clean game board and put initial tiles. board = getNewBoard() board[3][3] = 'X' board[3][4] = 'O' board[4][3] = 'O' board[4][4] = 'X' while True: playerValidMoves = getValidMoves(board, playerTile) computerValidMoves = getValidMoves(board, computerTile) if playerValidMoves = [] and computerValidMoves == []: return board # No more moves, game over. elif turn == 'Human': # Human's move. if playerValidMoves != []: #if showHints: # validMovesBoard = getBoardWithValidMoves(board, playerTile) # drawBoard(validMovesBoard) #else: #drawBoard(board) #printScore(board, playerTile, computerTile) move = getComputerMove(board, playerTile) #if move == 'exit': # print('Thank you for the game.') # sys.exit() # End the game. #elif move == 'hint': # showHints = not showHints # continue #else: makeMove(board, playerTile, move[0], move[1]) turn = 'Computer' elif turn == 'Computer': # Computer's move. if computerValidMoves != []: #drawBoard(board) #printScore(board, playerTile, computerTile) #input('Press Enter to see Computres\' move.') move = getComputerMove(board, computerTile) makeMove(board, computerTile, move[0], move[1]) turn = 'Human' NUM_GAMES = 250 xWins = oWins = ties = 0 print('Greetings!') playerTile, computerTile = ['X', 'O'] #enterPlayerTile() for i in range(NUM_GAMES): # while True: finalBoard = playGame(playerTile, computreTile) # Show the score. #drawBoard(finalBoard) print('#%s got %s points. O got %s points.' % (i+1, scores['X'], scores['O'])) if scores[playerTile] > scores[computerTile]: xWins += 1 # print('You won the computer, the gap is %s points. Congrats!' % (scores[playerTile] - scores[computerTile])) elif scores[playerTile] < scores[computerTile]: oWins += 1 # print('You\'ve lost. The gap is %s points.' % (scores[computerTile] - scores[playerTile])) else: ties += 1 # print('Draw!') # print('You want to play again? Yes or No.') # if not input().lower().startswith('y'): # break print('Amount of lost games X: %s (%s%%)' % (xWins, round(xWins / NUM_GAMES * 100, 1))) print('Amount of won games Y: %s (%s%%)' % (oWins, round(oWins / NUM_GAMES * 100, 1))) print('Amount of draws: %s (%s%%)' % (ties, round(ties/ NUM_GAMES * 100, 1)))
''' 3.1 运算符 做除法返回的是浮点数,并且都是向下取整 //为整除,所以返回的是整数部分,并不是整数类型。当除数与被除数有为浮点数 的时候 返回的是整数部分的浮点数 取余也是先遵循向下取整的规则,divmod(x//y, x%y)-->divmod(商,余数) ''' # 1.算术元运算符 print(10/3) # 3.3333333333333335 a = divmod(10, 3) # Return the tuple (x//y, x%y) print(a) b = 0.1 + 0.1 + 0.1 - 0.3 print(b) # 5.551115123125783e-17 二进制 # 保留十进制 from decimal import Decimal c = Decimal("0.1") + Decimal("0.1") + Decimal("0.1") - Decimal("0.3") print(c) # 2.比较运算符 ''' == 判断相等 != 判断不等 ''' # str与Int不能直接比较 # 字符串与字符串的比较是转为ascii比较 # 'abc' < 'xyz' # True # (3, 2) < (‘a’, ‘b’) # 报错,不能比较'<' not supported between instances of 'int' and 'str' # True == 1 # True # False == 0 # True # (3>2)>1 # False # (3>2)>2 # False # 3 赋值运算符 ''' += -= /= ''' # 4 逻辑运算符 ''' x = 10 y = 20 x and y, 找错的,如果x为False,则输出False, 否则输出y的值 x or y, 找对的,x 是 True,它返回 x 的值,否则它返回 y 的计算值 not, 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 ''' # 5 位运算符 ''' & | ''' # 6 成员运算符 ''' in not in ''' # 7 身份运算符 ''' is is not is 和 == 的区别 ''' name = ['吱呀', 'Jimmy', 'AT', 'jiajia'] if 'AT' in name: print('True') # 8 三目运算 a = 2 b = 1 if a > b: print(a-b) else: print(a+b) print(a-b if a > b else a-b) ''' 3.2 数据类型 数据类型:整形int, 浮点型float, 复数类型complex, 布尔类型bool 容器类型: str,list, tuple, set, dictionary. ''' # 数字类型是不可变类型 ''' 通常用十进制表示数字,但有时我们还会用八进制或十六进制来表示: 十六进制用0x前缀和0-9,a-f表示,例如:0xff00 八进制用0o前缀和0-7表示,例如0o45 ''' # 整数缓存区 a = 10000 print(id(a)) del a b = 10000 print(id(b)) int() weight = 44.7 print(type(weight)) print(int(weight)) # 源码int(x, base=10) 转成整数 print(int('0b100', base=0)) # 4 print(bin(4)) height = 160 print(float(height)) # 转成浮点类型 import math # 导入模块 print(math.ceil(4.1)) # 5 print(math.floor(4.5)) # 4 print(math.pow(2, 3)) # 8 # 四舍五入,四舍六入五双非 # 内置方法 round() round(4.5) # 4 round(3.5) # 4 # 绝对值 print(abs(-1)) # 布尔类型 if True: pass else: pass while True: pass # bool() 布尔类型 bool(0) # False bool(1) # True bool(2) # True bool('abc') # True bool("") # False 空字符串为false,其他为错 bool(0.0) # False bool(0.1) # True bool(True) # True # None 永远是false,数据类型是Nonetype ''' 整数和浮点数,0表示False,其他为True 字符串和类字符串类型(包括bytes和unicode),空字符串表示False,其他为True None永远表示False '''
''' 练习1.请搭建一个逻辑管理系统 1. 需要用户输入姓名,身份证号码以及电话号码 2. 如果用户选择打印输入信息,则打印输出“欢迎***同学加入逻辑教育, 您的身份证号是***,您的电话是***。我们将诚心为您服务。”否则输出 “感谢您使用该系统。”(注意这一块会使用到简单的条件判断语句,根据 课堂上讲解的知识够用,字符串拼接可以使用多种方式) 练习2.花式打印 输出**有**辆车子;但他只能开**辆 注意:这两句话通过一个print()的参数,使其进行换行输出(至少两种方式) ''' # name = input("请输入您的姓名") # ID_number = input("请输入您的身份证号码") # Phone_number = input("请输入您的电话号码") # yes_or_no = input("请输入1 打印信息 否则退出服务") # if yes_or_no == "1": # print('欢迎%s 同学加入逻辑教育,您的身份证号是%d,您的电话是%d 我们将诚心为您服务'%(name, int(ID_number), int(Phone_number))) # else: # print('感谢您使用该系统') name = 'jiajia' num_cars = 5 car_name = "兰博基尼" print('%s有%d辆车子;但他只能开%s辆' % (name, num_cars, car_name)) print("{}有{}辆车子;但他只能开{}辆".format(name, num_cars, car_name))
# 4. 线程同步, condition ''' 天猫精灵:小爱同学 小爱同学:在 天猫精灵:现在几点了? 小爱同学:你猜猜现在几点了 ''' import threading class XiaiAi(threading.Thread): def __init__(self, cond): super().__init__(name="小爱同学") # self.lock = lock self.cond = cond def run(self): with self.cond: print(4) self.cond.wait() print(5) print("{}:在".format(self.name)) self.cond.notify() self.cond.wait() print("{}:你猜猜现在几点了".format(self.name)) self.cond.notify() # self.lock.acquire() # print("{}:在".format(self.name)) # self.lock.release() # # self.lock.acquire() # print("{}:你猜猜现在几点了".format(self.name)) # self.lock.release() class TianMao(threading.Thread): def __init__(self, cond): super().__init__(name="天猫精灵") # self.lock = lock self.cond = cond def run(self): self.cond.acquire() print("{}:小爱同学".format(self.name)) print(1) self.cond.notify() print(2) self.cond.wait() print(3) print("{}:现在几点了?".format(self.name)) self.cond.notify() self.cond.wait() self.cond.release() # self.lock.acquire() # print("{}:小爱同学".format(self.name)) # self.lock.release() # # self.lock.acquire() # print("{}:现在几点了?".format(self.name)) # self.lock.release() class Siri(threading.Thread): def __init__(self, cond): super().__init__(name="Siri") # self.lock = lock self.cond = cond def run(self): self.cond.acquire() print("{}:小爱同学".format(self.name)) self.cond.notify() self.cond.wait() print("{}:现在几点了?".format(self.name)) self.cond.notify() self.cond.wait() self.cond.release() if __name__ == "__main__": # mutex = threading.RLock() cond = threading.Condition() xiaoai = XiaiAi(cond) tianmao = TianMao(cond) siri = Siri(cond) # 启动顺序很重要的 xiaoai.start() tianmao.start() siri.start() ''' 输出为: 天猫:小爱同学 天猫:现在几点了? 小爱同学:在 小爱同学:你猜猜现在几点了 每句话加互斥锁也还是相同输出 '''
# 1. "ax" < "xa"是True if "ax" < "xa": print('True') else: print('False') # 2. 如果输入666,输出: if 执行了 # if "666" == "Yes": # print('1') # else: # print(0) # temp = input("请输入:") # if temp == "YES" or "yes": # 非空字符串都是True,左边是False右边是True # print("if 执行了") # else: # print("else执行了")
# @ Time : 2020/1/2 # @Author : JiaJia # 3.with 语句 try: f = open('test.txt', 'w') # print("code") raise KeyError except KeyError as e: print('Key Error') f.close() except IndexError as e: print("IndexError") f.close() except Exception as e: print(e) f.close() finally: # 不管有没有异常都会运行 print('end') f.close() # with 语句自动关闭 # with open('demo.txt', 'r') as f: # f.read() # 3.1 类的with 语句,上下文管理器,可简化异常处理 class Sample(object): # 1.获取资源 def __enter__(self): print('start') return self # 处理资源 def demo(self): print('this is demo') # 3.释放资源 def __exit__(self, exc_type, exc_val, exc_tb): # <class 'AttributeError'> 异常类 print(exc_type, '_') # 'Sample' object has no attribute 'dems' 异常值 print(exc_val, '_') # <traceback object at 0x0000003DC40B7BC8> 追踪信息 print(exc_tb, '_') print('end') with Sample() as sample: sample.demo() # this is demo # 3.2 contextlib简化上下文管理器 import contextlib @contextlib.contextmanager def file_open(filename): # xxx __enter__函数 print("file open") yield{} # 不可以用return # __exit__函数 print('file close') with file_open("demo.txt") as f: print('file operation')
''' 1.用户输入哪一个页面,我就去跳转到那个页面 getattr() getattr(x, 'y') is equivalent to x.y. # res = getattr(views,'signin') # views.signin # res() hasattr() setattr() delattr() ''' # import views # # # def run(): # ipt = input("请输入您要访问的页面:").strip() # signin-->print("登录页") # # ipt() # signin() # if hasattr(views, ipt): # func = getattr(views, ipt) # func() # else: # print("404") # # # # if ipt == "signin": # # views.signin() # # elif ipt == "signup": # # views.signup() # # elif ipt == "home": # # views.home() # # else: # # print("404") # run() #urls1 import views0 def run(): ipt = input("请输入您要访问的页面:").strip() # 模块名/函数 modules,func = ipt.split('/') # a,b = (1,2) a =1 b =2 # print(res) module = __import__(modules) # print(obj) if hasattr(module,func): res = getattr(module,func) res() else: print("404") run()
#1. *args,**keargs 参数是什么? '''python中规定参数前带 * 的,称为可变位置参数,通常称这个可变位置参数为*args。 *args:是一个元组,传入的参数会被放进元组里。 python中规定参数前 带 ** 的,称为可变关键字参数,通常用**kwargs表示。 **kwargs:是一个字典,传入的参数以键值对的形式存放到字典里。''' # def add(*args): # sum = 0 # for i in args: # sum = sum + i # print(sum) # add(1,2,4) # # def dic(**kwargs): # print(kwargs) # dic(x=1, y=2) #2. 求1-100 的累加(使用到匿名函数以及reduce 方法) # from functools import reduce # print(reduce(lambda x,y: x+y, range(1,101))) #print(sum(range(1,101))) #3. 将该列表l = ["jack", ("tom", 23), "rose", (14, 55, 67)]中的元素全部遍历出来 # (注意奥!其中可以用到isinstance()方法,大家请自行查阅) l = ["jack 123", ("tom", 23), "rose", (14, 55, 67)] #print (*l, sep='\n') # def dp(s): # if isinstance(s, (int,str)): # print(s) # else: # for item in s: # dp(item) # dp(l) #4. 将以下列表li = [-11,1,-1,-6,5,8]的负值全部变为正数(注意:可以用到map 函数) # li = [-11,1,-1,-6,5,8] # res = (map(abs, li)) # lis = list(res) # print (lis) #5. 以下列表li = [1,5,11,22,13,50,12]筛选大于10 的数 # res= list(filter(lambda x:x>10,[1,5,11,22,13,50,12])) # print(res) # li = [1,5,11,22,13,50,12] # def is_odd(x): # if x >10: # return x # res = filter(is_odd, li) # print(list(res)) #6. 满足哪几个条件形成一个闭包? # 1)必须有一个内嵌函数 # 2)内嵌函数必须引用外部函数中的变量 # 3)外部函数的返回值必须是内嵌函数 #7. 实现为增加商品函数添加是否登录正确的判断功能,当为登录状态 #时,则直接打印输出添加商品,否则,让用户登录,判断用户输入的用户 #名以及密码是否正确,如正确则登录,否则提醒用户输入错误。并且 #不能添加。 #7.闭包装饰器 # FLAG = False # def outer(func): # def inner(): # global FLAG # if FLAG: # func() # else: # username = input("请输入用户名:") # password = input("请输入用户密码:") # if username == 'amy' and password == "123456": # FLAG = True # func() # else: # print("用户名或密码错误,登录失败") # return inner # # @outer # def shoplist_add(): # print("增加一件商品") # # add_goods = outer(shoplist_add) # add_goods = inner # # shoplist_add()
class A: def __init__(self): print('A') class B(A): def __init__(self): print('B') # python 2 # super(B, self).__init__() super().__init__() # 1. 重写了B的构造函数 为什么还要去调用super # 数据冗余 # b = B() class People(object): def __init__(self, name, age, weight): self.name = name self.age = age self.weight = weight def speak(self): print("s% 说: 我%d岁了"%(self.name, self.age)) class Student(People): def __init__(self, name, age, weight, grade): # self.name = name # self.age = age # self.weight = weight # super().__init__(name, age, weight) People.__init__(self, name, age, weight) self.grade = grade def speak(self): print("%s 说:我%d岁了 我在读%d年级"% (self.name, self.age, self.grade)) s = Student('lg', 10, 30, 3) s.speak() # super 执行顺序到底是什么样的 class A: def __init__(self): print("A") class B(A): def __init__(self): print("B") super().__init__() class C(A): def __init__(self): print("C") super().__init__() class E: pass class D(B, C, E): def __init__(self): print("D") super().__init__() d = D() print(D.__mro__) # D B C A # super不是之前讲的调用父类中的方法 # 而是按照 mro 算法来调用的
# if True: # a = 5 # # print(a) # # for i in range(3): # print('hello world') # # print(i) # 2 # # # def test(): # # 局部变量 只能在函数体内部使用 # b = 5 # return b # # # b = test() # 5 # print(b) # name 'b' is not defined # a = 200 # global # # # def test1(): # print('test1:', a) # # # def test2(): # a = 300 # print("test2:", a) # # # test1() # a is not defined # test2() # # 先在函数内部找,找不到在外面找 # # # 函数未调用时,载入内存,优先同级寻找 # c = 10 # def test3(): # c = 5 # print(c) # 先找局部变量 # # # test3() # 5 # print(c) # 10 # LEGB a = int(3.14) # built-in b = 11 # global def outer(): # global count count = 10 # enclosing 嵌套的父级函数的局部作用域 def inner(): nonlocal count # local 局部作用域 count = 20 inner() outer() ''' LEGB含义解释: L —— Local(function);函数内的名字空间 E —— Enclosing function locals;外部嵌套函数的名字空间(例如closure) G —— Global(module);函数定义所在模块(文件)的名字空间 B —— Builtin(Python);Python内置模块的名字空间 '''
import time ''' 避免重复造轮子 ''' # def test2(): # start = time.time() # print("----1----") # time.sleep(1) # end = time.time() # print("花了{}".format(end-start)) # # def test3(): # start = time.time() # print("----1----") # time.sleep(1) # end = time.time() # print("花了{}".format(end-start)) ''' 开放:拓展其他功能 封闭:不要修改封装好的代码块 原则 ''' # def calcu_time(func): # def test_in(): # start = time.time() # func() # end = time.time() # print("花了{}".format(end - start)) # return test_in # @calcu_time # test2 = calcu_time(test2) # def test2(): # print("----2----") # time.sleep(1) # test2 = calcu_time(test2) # test2 = test-in test1改名字怎么办 # test2() # test2() test_in() # @calcu_time # test2 = calcu_time(test2) # def test3(): # print("----3----") # time.sleep(1) # # test2() # test3() ''' 加验证 ''' def outer(flag): def calcu_time(func): def test_in(): start = time.time() func() end = time.time() print("花了{}".format(end - start)) if flag == 'true': print("正在验证") return test_in return calcu_time @outer(flag="true") # calcu_time= outer() test2 = calcu_time(test2) def test2(): print("----1----") time.sleep(1) test2() # res = calcu_time(test2) # res() # test2() test_in()
''' 5.线程间通讯--多线程共享全局变量 5.1 修改全局变量一定要加global吗 修改了指向,id变了,就需要加global += 是不会修改指向的,但是数据是不可变类型,所以一定会变 a = a+[] 会修改指向 ''' import threading import time # num = 100 # lis = [11, 22] # # def demo(): # global num # num += 100 # # # def demo1(): # lis.append(33) # # def demo2(): # global lis # lis = lis +[44] # 修改了指向,id变了,就需要加global # # print(num) # 100 # demo() # print(num) # 200 # demo1() # [11, 22, 33] # # demo2() # print(lis) ''' 5.2 多线程共享全局变量 ''' num = 100 def demo1(): global num num += 1 print("demo1---%d" % num) def demo2(): print("demo2---%d" % num) def main(): t1 = threading.Thread(target=demo1()) t2 = threading.Thread(target=demo2()) t1.start() time.sleep(1) t2.start() time.sleep(1) print("main---%d" % num) if __name__ == '__main__': main() ''' 5.3 多线程参数 ''' # num = [11,22] # # # def demo1(): # num.append(33) # print("demo1---%s" % str(num)) # # # def demo2(): # print("demo2---%s" % str(num)) # # # def main(): # t1 = threading.Thread(target=demo1(), args=(num,)) # t2 = threading.Thread(target=demo2(), args=(num,)) # t1.start() # time.sleep(1) # # t2.start() # time.sleep(1) # # print("main---%s" % str(num)) # # # if __name__ == '__main__': # main() #
# -*- coding: utf-8 -*- from tkinter import * class adress: def __init__(self): self.label = Label(window, text="Ваш адрес:", font="Arial 14", bg="yellow") self.text = Entry(window,width=20,bd=3) self.label1 = Label(window, text="Комментарий:", font="Arial 10") self.text_field = Text(window, width=20, height=10, font="Verdana 12", wrap=WORD) # перенос по словам self.button = Button(window, # Объявляем кнопку и её переменные text="Отправить", # имя кнопки width=15, height=2, # размер кнопки bg="Steel Blue", fg="black") # цвет фона и текста self.label.pack() self.text.pack() self.label1.pack() self.text_field.pack() self.button.pack() window = Tk() object = adress() window.mainloop()
import os import csv # Variables needed: # total number of months included in the dataset # total net amount of "Profit/Losses" over the entire period #The average change in "Profit/Losses" btw months over the entire period #The greatest increase in profits (date and amt) over the entire period #The greatest decrease in profits (date and amt) over the entire period #Header: Financial Analysis #----------------------------- #Total Months: 86 #Total: $38382578 #Average Change: $-2315.12 #Greatest Increase in Profits: Feb-2012 ($1926159) #Greatest Decrease in Profits: Sep-2013 ($-2196167) #path to collect data from Homework folder pyBankCSV = os.path.join("..", "PyBank", "budget_data.csv") #Declare variables to track total_months = 0 total_revenue = 0 #will track the last revenue looped for avg change calc last_revenue = 867884 #will calculate each revenue change while looping revnue_change = 0 #track greatest increase/decrease in revenue. Skip first column, track second column greatest_increase = ["", 0] greatest_decrease = ["", 99999999999999999999999999] #track total revenue change revenue_changes = [] # Open the CSV with open(pyBankCSV, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvfile) #Loop through to calc months/revnue for each row for row in csvreader: #Calculate the total months total_months = total_months +1 #Caluate total revenue total_revenue = total_revenue + int(row[1]) #Calculate revnue change revnue_change = float(row[1]) - last_revenue #Update last revnue to last looped row last_revenue = int(row[1]) # Add Revenue changes to revenue change array revenue_changes.append(int(revnue_change)) #Determine greatest increase if (revnue_change > greatest_increase[1]): greatest_increase[1] = revnue_change #record date of greatest change greatest_increase[0]= row[0] # Determine greatest decrease if (revnue_change < greatest_decrease[1]): greatest_decrease[1] = revnue_change # record date of greatest change greatest_decrease[0] = row[0] #Calculate avg change: sum of rev changes array / length average_change = sum(revenue_changes)/(len(revenue_changes) - 1) #------------------------------------------------------------------------- #Display summary of results summary_results = f""" Financial Analysis ------------------------------------------------------- Total Months: {total_months} Total Revenue: ${total_revenue} Average Change: ${average_change:.2f} Greatest Increase: {greatest_increase[0]} : ${greatest_increase[1]:.0f} Greatest Decrease: {greatest_decrease[0]} : ${greatest_decrease[1]: .0f} """ #--------------------------------------------------------------------------- print(summary_results) #--------------------------------------------------------------------------- #open output file and write in results #Set variable for output file summary_output_file = os.path.join("financial_analysis.txt") #Open the output file with open(summary_output_file, "w", newline="") as textfile: writer = textfile.write(summary_results) #------------------------------------------------------------------------------
n = int(input("Enter a number = ")) fact = 1 for i in range(n,1,-1): fact = fact * i print("Factorial = ",fact)
""" List Operations """ z = [1,12,33,4,5,5] print(z) z.sort(reverse=True) print(z) print(z.count(5)) z = ["C","c","a","A","b","B"] z.sort() print(z) z.sort(reverse=True) print(z) z.sort(key=str.lower) print(z) z = [1,12,33,4,5,5] z.reverse() print(z) z.append("and so on") z.append([33,22,11]) print(z) z = [1,12,33,4,5,5] z.extend("and so on") z.extend([33,22,11]) print(z) a = "hey yoo man" b = "hello world" z = a.join(b.split()) print(z) b = [1,2,3] print(2 in b) print(5 not in b) z = [1,12,33,4,5,5] z[:2] = ["one","two"] print(z) z[2:4] = [0,0] print(z) z[2:4] = [] print(z) del z print(z)
""" set operations """ z = {1,2,3,3,2,1,2,3} print(z) x = {1,2,3} y ={4,5,6,2,3} print(x|y) # Union print(x&y) # Intersection print(x-y) # remove y duplicte elements print(y-x) # remove x duplicte elements y ={4,5,6,2,3} y.add(7) print(y) y.remove(7) print(y) y.pop() #pops first element print(y)
from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity import pandas as pd import numpy as np import pickle from sklearn.externals import joblib def get_title_from_index(index): return df[df.index == index]["title"].values[0] def get_index_from_title(title): return df[df.title == title]["index"].values[0] #define a sample text text = ["London Paris London ", "Paris Paris London"] #cv is the object of class called countvectorizer cv= CountVectorizer() #a variable to store the vector of text count_matrix = cv.fit_transform(text) #to array will convert matrix into an array print ((count_matrix).toarray()) similarity_scores = cosine_similarity(count_matrix) #print(similarity_scores) #read dataset df = pd.read_csv(r"C:/Users/Ankur/Desktop/ML/movie_dataset.csv") df = df.iloc[ : , 0:25] print (df.columns) #Select some features features = ['keywords', 'cast', 'genres', 'director'] for feature in features: df[feature] = df[feature].fillna(' ') #Create a column in ddataframe to combine features def combine_features(row): return row['keywords'] + " " + row['cast'] + " " + row['genres'] + " "+row['director'] df["combine_features"]= df.apply(combine_features, axis = 1) print(df["combine_features"].head()) cv= CountVectorizer() count_matrix = cv.fit_transform(df["combine_features"]) cosine_sim = cosine_similarity(count_matrix) print((count_matrix).toarray()) movie_user_likes = "Pirates of the Caribbean: At World's End" #get index of movie movie_index = get_index_from_title(movie_user_likes) print(movie_index) #list of tuples of similar movies similar_movies = list(enumerate(cosine_sim[1])) #sort the tuple sorted_similar_movies = sorted(similar_movies,key= lambda x:x[1], reverse=True) with open('C:/Users/Ankur/Desktop/ML/mrmodel.pkl', 'wb') as f: pickle.dump(sorted_similar_movies, f) print(sorted_similar_movies) #print the titles i=0 for movie in sorted_similar_movies: print(get_title_from_index(movie[0])) i = i +1 if i>5: break