text
stringlengths
37
1.41M
""" Short script to create a dictionary for PR algo. Requires python 3.6+ for default ordered dictionaries. Use main() to get the dictionary. Dictionary contains swimmer names as keys, and meet[] objects as values. Concrete example: {'Phelps Michael' : [2016 Olympics, Worlds], 'Adrian, Nathan G' :[2016 Olympics, Pan America]} """ import json from Meet import Meet """ Helper function used to load .json files as dictionaries. I is the ith json file to load """ def load_data(i): with open('result' + str(i) + '.json', 'r') as fp: dict1 = json.load(fp) return dict1 """ Merges two dictionaries. For conflicting keys, appends a '1' at the end to remove key conflicts and ensure that they are all added. DICT adds it's key-value pairs into MERGE. """ def merge_data(merge, dict): for comp in dict: dummy = comp while dummy in merge: dummy += '1' merge[dummy] = dict[comp] """ Uses merge_data() and load_data() to create a dictionary with swimmer-meet[] key-value pairs. Returns this dictionary. """ def main(): merge = load_data(1) dict2 = load_data(2) dict3 = load_data(3) dict4 = load_data(4) dict5 = load_data(5) dict6 = load_data(6) dict7 = load_data(7) dict8 = load_data(8) dict9 = load_data(9) dict10 = load_data(10) dict11 = load_data(11) dict12 = load_data(12) merge_data(merge, dict2) merge_data(merge, dict3) merge_data(merge, dict4) merge_data(merge, dict5) merge_data(merge, dict6) merge_data(merge, dict7) merge_data(merge, dict8) merge_data(merge, dict9) merge_data(merge, dict10) merge_data(merge, dict11) merge_data(merge, dict12) print(len(merge)) swimmer_dict = {} for competition in merge: lost_to = [competition] for competitor in merge[competition]: time = merge[competition][competitor][1] meet = Meet(competition, lost_to[:], time) if competitor in swimmer_dict.keys(): swimmer_dict[competitor].append(meet) else: swimmer_dict[competitor] = [meet] lost_to.append(competitor) swimmer_dict[competition] = [Meet(competition, lost_to[1:], time)] return swimmer_dict
def clean_data(data): return list(map(int, data[0].split())) def get_max(data): # ties are broken by order, so first largest is largest current_max = [0,0] for i, val in enumerate(data): if val > current_max[1]: current_max = [i, val] return current_max def redistribute_data(data): index, data_to_redistribute = get_max(data) data[index] = 0 for i in range(1, data_to_redistribute+1): # go to the next memory bank after max and redistribute the data # wrap around to the start of the list data[(index+i)%len(data)]+=1 return data # how many redistributions until state is seen again def part1(data): # list of lists, need to use comprehension since [data] would be a reference of data # so when data is modified so is [data], messing up while condition states = [[v for v in data]] count = 1 data = redistribute_data(data) while data not in states: states.append([v for v in data]) data = redistribute_data(data) count += 1 return count # run until state is seen again # then how long does it take until state is seen again def part2(data): for i in range(part1(data)): data = redistribute_data(data) return part1(data)
import itertools def clean_data(data): # passphrases are strings of characters separated by spaces return list(map(lambda x:x.split(" "), data)) def is_unique(passphrase): # passphrase contains duplicate words if casting to set changes (reduces) length return len(passphrase) == len(set(passphrase)) def is_anagram(word1, word2): # word is an anagram if sorting it makes it the same return sorted(word1) == sorted(word2) def contains_anagram(passphrase): # if any two words in the passphrase are an anagram, passphrase is invalid for words in itertools.combinations(passphrase, r=2): if is_anagram(*words): return True return False def part1(data): return len([passphrase for passphrase in data if is_unique(passphrase)]) def part2(data): return len([passphrase for passphrase in data if is_unique(passphrase) and not contains_anagram(passphrase)])
import random database = {} def init(): import datetime print("Welcome to HorlarBank") print("=== ==== ====== ==== ====================") datetime_object = datetime.datetime.now() print(datetime_object) print("=== ==== ====== ==== ====================") haveAccount = int(input("Do you have an account with us: 1 (yes) 2 (no) \n")) if(haveAccount == 1): login() elif(haveAccount == 2): register() else: print("You have selected invalid option") init() def login(): print("********* Enter Your Login Details ********") accountNumberFromUser = int(input("What is your account number? \n")) password = input("What is your password: \n") for accountNumber, userDetails in database.items(): if(accountNumber == accountNumberFromUser): if(userDetails[3] == password): bankOperation(userDetails) #isLoginSuccessful = True else: print("Invalid Login Details") login() def register(): print("****** Sign Up Here *******") email = input("Enter email address: \n") first_name = input("Enter your first name? \n") last_name = input("Enter your last name? \n") password = input("Create a password: \n") accountNumber = generationAccountNumber() database[accountNumber] = [ first_name, last_name, email, password] print("Your Account has been created") print("=== ==== ====== ==== ===") print("Your account number is: %d" %accountNumber) print("=== ==== ====== ==== ====================") print("DISCLAIMER : Do not share your details with anyone") print("=== ==== ====== ==== ===") login() def bankOperation(user): print("Welcome %s %s " % ( user[0], user[1] ) ) selectedOption = int(input("What would you like to do?: (1) Deposit (2) Withdarwal (3) Logout (4) Exit \n")) if(selectedOption == 1): depositOpration() elif(selectedOption == 2): withdrawalOperation() elif(selectedOption == 3): Logout() elif(selectedOption == 4): exit() else: print("Invalid Option Selected") bankOperation(user) def withdrawalOperation(): input("How much would you like to withdraw: \n") print('Take Your Cash') def depositOpration(): amount = input("How much would you like to deposit \n") print('Current Balance : %s' % amount) def generationAccountNumber(): return random.randrange(111111,999999) def Logout(): print(" ") print("THANK YOU FOR BANKING WITH US") login() init()
# -*- coding: utf-8 -*- import os import sys import math print("Oblicz dzienne zapotrzebowanie kaloryczne") name = input("Podaj swoje imię: \n") if name[-1] == "a": name = int(-161) else: name = int(+5) height = int(input("Podaj swój wzrost w centymetrach: \n")) weight = int(input("Podaj swoją wagę w kilogramach: \n")) age = int(input("Podaj swój wiek \n")) ppm = (10 * weight) + (6.25 * height) - (5 * age) + name print("Wybierz aktywnosc") print("Praca siedząca, brak dodatkowej aktywności fizycznej \n [a]") print("Praca niefizyczna, mało aktywny tryb życia \n [b]") print( "Lekka praca fizyczna, regularne ćwiczenia 3-4 razy print(ok. 5h) w tygodniu \n [c]") print( "Praca fizyczna, regularne ćwiczenia od 5razy (ok. 7h) w tygodniu \n [d]") print("Praca fizyczna ciężka, regularne ćwiczenia 7 razy w tygodniu \n [e] ") activity = input() if activity == "a": activity = 1.2 elif activity == "b": activity = 1.4 elif activity == "c": activity = 1.6 elif activity == "d": activity = 1.8 elif activity == "e": activity = 2.0 print("Dzienne zapotrzebowanie kaloryczne wynosi:", ppm * activity, "kcal")
''' Lorin Vandegrift 2/7/2015 Assigment 1: -- Number Operations: add, sub, mul, div, eq, lt, gt -- Boolean Operators: and, or, not Sequencing Operators: if, ifelse -- Create Dictionary: dictz (No operands) -- Stack Operations: begin, end -- Name definition: def (takes value and name) -- entire stack printing: stack -- top-of-stack printing operator: = ''' import sys import re #Program Variables # The User Dictionary is checked before the system dictionary # If the name is in the dictionary, it either pushes the value onto the stack # preforms the operation # Else, it raises an error #All Dictionaries are kept on the dictionary stack systemDictionary = {'add':add, 'sub':sub, 'mul':mul, 'div':div, 'eq':eq, 'lt':lt, 'gt':gt} userDictionary = {} dictStack = [userDictionary, systemDictionary] if __name__ == "__main__": fileContents = open(sys.argv[1]).readlines() #Setup Dictionaries and other variables def init(): pass ''' Parsing the PostScript ''' def evalLoop (tokens): p = 0 # control the loop by idex p while p < len(tokens): t = tokens[p] p += 1 # handle number, push to the stack # handle operator, execute operator # handle { # push everything between { and } to the stack # handle stack operations pop, clear, stack # handle def # push name and array to the dict stack # handle if # recursively call “evalLoop” to execute the code array # handle ifelse # recursively call “evalLoop” to execute the code array # handle dict # define empty dict # begin: push dict to the dictionary stack # end: pop dict from the dictionary stack def parseProgram (fileContents): pass ''' Dictionary Operations ''' #Adds new item to the stack def spush(item): stack.append(item) return None #Removes Item from the top of the stack #Throws error is the stack is empty def spop(): if not stack: err("Error in pop: Stack is empty...") return None else: return stack.pop() #Returns the number of items in the stack def slen(): pass #Empties the stack def sclear(): pass #Duplicates the top item on the stack def dup(): pass #Exhanges the top two item on the stack def exch(): pass ''' Utility Functions ''' #Check if item is a number def isNum(item): if isinstance(item, float): return item else: err("Variable not a float.") def isDict(item): if isinstance(item, dict): return item else: err("Variable not a dictionary.") ''' Math Operations ''' #Addition def add(): if slen() >= 2: spush(spop()+spop()) else: return None #Subtraction def sub(): if slen() >= 2: secondOperand = spop() firstOperand = spop() spush(firstOperand-secondOperand) else: return None #Multiplication def mul(): if slen() >= 2: spush(spop() * spop()) else: return None #Division def div(): if slen() >= 2: secondOperand = spop() firstOperand = spop() spush(firstOperand / secondOperand) else: return None ''' Boolean Operations ''' #Equals def eq(): if slen() >= 2: if spop() == spop(): spush('true') else: spush('false') return None #Less than def lt(): if slen() >= 2: secondOperand = spop() firstOperand = spop() if firstOperand < secondOperand: spush('true') else: spush('false') return None #Greater Than def gt(): if slen() >= 2: secondOperand = spop() firstOperand = spop() if firstOperand > secondOperand: spush('true') else: spush('false') return None #And def sand(): if slen() >= 2: secondOperand = spop() firstOperand = spop() if isBool(firstOperand) and isBool(secondOperand): if firstOperand == 'true' and secondOperand == 'true': spush('true') else: spush('false') else: err("Not Boolean") return None #Or def sor(): if slen() >= 2: secondOperand = spop() firstOperand = spop() if isBool(firstOperand) and isBool(secondOperand): if firstOperand == 'true' or secondOperand == 'true': spush('true') else: spush('false') else: err("Not Boolean") return None #Not def snot(): if slen() >= 2: firstOperand = spop() if isBool(firstOperand): if firstOperand == 'true': spush('false') else: spush('true') else: err("Not Boolean") return None ''' Logical Operators ''' #If def sif(): ifcode = isCode(spop()) # Make sure it is code (a list) if chBool(spop()): evalLoop(ifcode) return None #elseif def selseif(): ifcode = isCode(spop()) # Make sure it is code (a list) if chBool(spop()): evalLoop(ifcode) else: return None ''' Dictionary Operators ''' #Adds a new dictionary to the top of the stack def dictz (): newDict = dict() dictStack.append(newDict) #Wasn't sure how this is supposed to be different def begin (): dictz () def end (): if(len(dictStack) > 0): dictStack.pop() ''' Variable Operations ''' #Defines a key variable with a given value def sdef (): if slen() >= 2: name = spop () value = spop () dictStack[-1][name] = value ''' Stack Operations ''' #Prints out contents of the stack without changing it def sprint (): for i in mainStack: print i #Prints the top item in the stack def top (): print mainStack[-1]
from itertools import permutations n=input() a=[] a=list(permutations(n)) for i in range(0,len(a)): print(*a[i],sep='')
""" Day 1 - Single Number LeetCode Easy Problem Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 """ class Solution: def singleNumber(self, nums: List[int]) -> int: for n in nums: if nums.count(n) == 1: return n
n = int(input("lutfen bir sayi giriniz :")) for i in range(1,n+1): print(("#"*i).rjust(n), end="\n")
# Credit to KINOCK SEBASTIAN for this code import tweepy # Reading Consumer key and secret from consumerKeys File consumerKeyFile = open("consumerKeys", "r") consumerKey = consumerKeyFile.readline().strip() consumerSecret = consumerKeyFile.readline().strip() consumerKeyFile.close() # authenticating twitter consumer key auth = tweepy.OAuthHandler(consumerKey, consumerSecret) auth.secure = True authUrl = auth.get_authorization_url() # go to this url print("Please Visit This link and authorize the app ==> " + authUrl) print("Enter The Authorization PIN") # writing access tokes to file pin = raw_input().strip() token = auth.get_access_token(verifier=pin) accessTokenFile = open("accessTokens", "w") accessTokenFile.write(token[0] + '\n') accessTokenFile.write(token[1] + '\n') ''' Here we initialize our consumer key and consumer secret with auth = tweepy.OAuthHandler(). With the auth object just create we get the authorization url using get_authorization_url() method of tweepy. Now user can got to this url and enter his/her login credentials and verify app. After verifying a pin will be returned. We accept this pin and calls method get_access_toke(verifier = pin) with pin as argument and fetch access token and access token secret. We save this in a file and use it when ever needed. This token wont expire until user revoke access or we delete the application. '''
from openpyxl import Workbook sheet = workbook.active # Let's say you have two sheets: "Products" and "Company Sales" print(workbook.sheetnames) # You can select a sheet using its title products_sheet = workbook["Products"] sales_sheet = workbook["Company Sales"] products_sheet.title = "New Products" print(workbook.sheetnames) operations_sheet = workbook.create_sheet("Operations") print(workbook.sheetnames) # You can also define the position to create the sheet at hr_sheet = workbook.create_sheet("HR", 0) print(workbook.sheetnames) # To remove them, just pass the sheet as an argument to the .remove() workbook.remove(operations_sheet) print(workbook.sheetnames) workbook.remove(hr_sheet) print(workbook.sheetnames) workbook.copy_worksheet(products_sheet) print(workbook.sheetnames)
import os,time,keyboard,json,hashlib,ast,numpy,menu import system_choose as sc import score as ds import matplotlib.pyplot as plt if __name__ == "__main__": score = dict() with open("score.json","r",encoding = "UTF-8-sig") as f: some_string = f.read() if not some_string: score = {} else: score = json.loads(some_string) while(True): menu.menu() choice = input("Enter your choice:\n=>") if choice == "E" or choice == "e" : sc.Subject_system(score) elif choice == "C" or choice == "c": sc.Score_system(score) elif choice == "Q" or choice == "q": break else: print("Enter Again...(Wait for few second)") time.sleep(3)
import openpyxl # create workbook # wb = openpyxl.Workbook() # for loading the existing workbooks wb = openpyxl.load_workbook('transactions.xlsx') # print(wb.sheetnames) sheet = wb['Sheet1'] # wb.create_sheet('Sheet2',0) # wb.remove_Sheet(sheet) # to get the cell # cell = sheet['a1'] # print(cell.value) # to change the value # cell.value = 1 # print(cell.row) # print(cell.column) # print(cell.coordinate) # THE OTHER METHOD IS THE USE THE CELL METHOD # usefull when iterating over the rows and columns cell1 = sheet.cell(row=1, column=1) # print(sheet.max_row) # print(sheet.max_column) # for row in range(1, sheet.max_row+1): # for column in range(1, sheet.max_column+1): # cell = sheet.cell(row, column) # print(cell.value) column = sheet['a'] # print(column) cells = sheet['a:c'] print(cells) sheet.append([1, 2, 3]) # sheet.insert_cols # sheet.insert_rows # sheet.delete_cols # sheet.delete_rows wb.save('transactions2.xlsx')
numbers = [1,5,7,5,8,1,9,6,4,7,13,9,7,1,36,3,5] uniques = [] for number in numbers: if number not in uniques: uniques.append(number) print(uniques)
def phone_magic(): phone = input("phone: ") # A new dictionary (key, value) digits_mapping= { "1": "One", "2": "Two", "3": "Three", "4": "Four", "5": "Five" } output = "" for ch in phone: output += digits_mapping.get(ch, "!") + " " print(output) def another_function(a, b): print(a*b) print("start") phone_magic() print("finish") print("#" *10) print("start") print("multiply integers") x= input(">") y= input(">") another_function(int(x), int(y)) print("finish")
# A new tuple, it cannot be changed. # You can't add, remove or change any item. Like a constant. numbers = (7,5,1) x, y, z = numbers #unpacking the values of numbers tuple print(x) print(y) print(z) coordinates = [10.25, 54.88, 124.56, 8.96] # a new List x, y, z, w = coordinates #unpacking the values print(x) print(y) print(z) print(w)
import random # standard module of python3 library print("random float nums") for i in range(3): print(random.random()) print("\nrandom integers") for i in range(5): print(random.randint(0, 10)) print("\nSelect leader") members = ['Vaios', 'John', 'Mary', 'Dimitra'] leader = random.choice(members) print(leader)
import turtle var=turtle.Turtle() s=turtle.getscreen() turtle.screensize(1800,3200) s.bgcolor("black") var.hideturtle() var.pencolor("red") var.penup() var.setposition(140,-270) var.pendown() var.write("Stay Home, Stay Safe!",'false','right', font=('Showcard Gothic',20)) var.penup() var.setposition(100, -325) var.pendown() var.pencolor('orange') var.write("Wear Face Mask.\n Wash hands often.\n Use Sanitizer.\n Cook food thoroughly.") var1=0 var2=0 var.penup() var.setposition(620,-325) var.pencolor("pink") var.pendown() var.write("By Priyanka Ghosh",'false','right', font=('Showcard Gothic',10)) var.speed(0) var.pencolor("dark green") var.pensize(1) var.penup() var.goto(0,230) var.pendown() while True: var.fd(var1) var.rt(var2) var1+=3 var2+=1 if var2==207: break var.hideturtle() turtle.done()
class Rectangle: def __init__(self, b, l): self.b = b self.l = l def area(self): return self.l * self.b def perimeter(self): return 2 * (self.l + self.b) l = int(input("enter length of 1st rectangle:")) b = int(input("enter breadth of 1st rectangle:")) arr = Rectangle(l, b) print("area of 1st rectangle", arr.area()) l = int(input("enter length of 2nd rectangle:")) b = int(input("enter breadth of 2nd rectangle:")) ar = Rectangle(l, b) print("area of 2nd rectangle", ar.area()) print("1st rectangle perimeter=", arr.perimeter()) print("2nd rectangle perimeter=", ar.perimeter()) r1 = arr.area() r2 = ar.area() if r1 > r2: print("area of 1st rectangle is greater") else: print("area of 2nd rectangle is greater")
# Priklad definicie triedy. Zbytocnej triedy class Person: name = "Michal" def print_name(): print(f"Name is {Person.name}") Person.print_name() # Trieda je nejaky predpis niecoho v tomto pripade je to predpis osoby kazda osoba ma meno a priezvisko class Person: def __init__(self, name, surname): self.name=name self.surname=surname def introduce_yourself(self): print(f"Hi I am {self.name} {self.surname}") michal = Person("Michal", "Hucko") michal.introduce_yourself() katka = Person("Katka", "Huckova") katka.introduce_yourself() # Volanie metody v konstruktore class Person: def __init__(self, name, surname): self.name=name self.surname=surname self.introduce_yourself() def introduce_yourself(self): print(f"Hi I am {self.name} {self.surname}") michal = Person("Michal", "Hucko") katka = Person("Katka", "Huckova") # Co je to ten self ? Je to skratka v pythone zoberme si nasledujucu triedu class Classroom: def __init__(self, student_number): self.student_number = student_number def get_info(self): print(f"Student number is {self.student_number}") new_class = Classroom(10) new_class.get_info() # sa vnutorne prepise na Classroom.get_info(new_class) # !!!! Self v pripade prveho parametru funkcie sa nemusi volat self ale moze byt pouzite akekolvek meno # Vacsinou sa pouziva self class Classroom2: def __init__(self, student_number): self.student_number = student_number def get_info(another_self): print(f"Student number is {another_self.student_number}") new_class = Classroom2(20) new_class.get_info() # sa vnutorne prepise na
# OVERLOADING class Person: def __init__(self, name, surname): self.name = name self.surname = surname def say_hello(self, name=None): print("Hello") if not name else print(f"Hello {self.name}") person = Person("Michal" ,"Hucko") person.say_hello() person.say_hello(name=True) # V jave sa nedaju pouzit optional parametre preto sa tam vyuziva nieco taketo # class Person: # def __init__(self, name, surname): # self.name = name # self.surname = surname # def say_hello(self): # print("Hello") # def say_hello(self, name=True): # print(f"Hello {self.name}") # TOTO sa vsak neda pouzit v pythone lebo nevieme deklarovat dve funkcie s rovnakymi nazvami # OVERRIDING class Employee(Person): def say_hello(self): print("I am person and i will say something completely different than Person") # Vsimnite si ze z rodica viem vytvorit kolko len vetiev chcem class Student(Person): def __init__(self, name, surname, studentId): super().__init__(name,surname) self.studentId = studentId student = Student("Michal", "Hucko", 106) print(student.studentId) student.say_hello()
#while(true): try: def add(): n1=int(input('enter a number\n')) n2=int(input('enter a number\n')) sum=n1+n2 print('n1 and n2 equal=',sum) add() except ValueError: print('plz enter a integer type value')
myDate = int(input('Enter a number\n')) month = myDate // 30 + 1 day = myDate % 30 if day == 0: day = 30 month -= 1 print('The day is: %d and the month is: %d' % (day, month))
# Search for a word in a sorted list def search_in_list(thelist, word): if len(thelist) == 0: return False if len(thelist) == 1: if word == thelist[0]: return True else: return False mid = len(thelist) // 2 if word >= thelist[mid]: thelist = thelist[mid:] else: thelist = thelist[:mid] return search_in_list(thelist, word)
""" Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch. """ import time print('**** started ****') seconds_in_a_day = 24 * 60 * 60 the_time = time.time() print('time:', the_time) days = the_time // seconds_in_a_day print('days: ', days) total_seconds_today = int(the_time % seconds_in_a_day) print('seconds_today: ', total_seconds_today) hours_today = (total_seconds_today // 3600) - 8 + 1 - 12 # +1 is for summer time print('hours_today: ', hours_today) minutes_today = int((total_seconds_today % 3600) / 60) print('minutes_today: ', minutes_today) seconds_today = (total_seconds_today % 3600) % 60 print('seconds_today: ', seconds_today) print('Current time Vancouver: ' + str(hours_today) + ':' + str(minutes_today) + ':' + str(seconds_today))
import sys import listsearch sys.path.append(r"C:\DevLcl\Sandbox\python-sandbox\think_python\chapter_10") fin = open(r'C:\DevLcl\Sandbox\python-sandbox\think_python\words.txt') def word_list(): thelist = [] for line in fin: thelist.append(line.strip()) return thelist def find_reverse_pair(mylist, word): res = word[::-1] if (listsearch.search_in_list(mylist, res)): print(word, res) mylist = word_list() mylist.sort() for word in mylist: find_reverse_pair(mylist, word)
def is_triangle(a, b, c): if a > b+c or b > a+b or c > a+b: print('No') else: print('Yes') print('Give me "a", "b", "c" one after eachother') a = int(input()) b = int(input()) c = int(input()) is_triangle(a, b, c)
class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return 'Point is located at: x=%g, y=%g' % (self.x, self.y) def __add__(self, other): if isinstance(other, Point): return self.add_point(other) elif isinstance(other, tuple): return self.add_tuple(other) else: raise TypeError(type(other), "data type is now supported for the 'other' object") def __radd__(self, other): return self.__add__(other) def add_point(self, other): self.x += other.x self.y += other.y return self def add_tuple(self, tup): self.x += tup[0] self.y += tup[1] return self def __lt__(self, other): if self.x < other.x and self.y < other.y: return True else: return False ############################################## def print_attributes(obj): for attr in vars(obj): print(attr, getattr(obj, attr)) # p = Point(2, 3) # p1 = Point(10, 10) # print(p) # print(p1) # print('p is less than p1:', p > p1) # print(p + p1) p = Point(2, 3) p1 = Point(10, 10) p2 = Point(100, 200) p3 = Point(2000, 3000) all = sum([p, p1, p2, p3], Point(0,0)) # we should give sum a valid Point to start otherwies is passes 'int=0' total = p + p1 + p2 + p3 print('total point:', total) print_attributes(p) print(vars(p)) # print('try:') # try: # p = Point(2, 3) # print(p + (100, 200)) # p = Point(2, 3) # print(p + 100, 200) # except Exception as e: # print(e)
target = 999 def sumDivisibleBy(n): p = target // n sum = n * (p * (p + 1)) / 2 return sum result = sumDivisibleBy(3) + sumDivisibleBy(5) - sumDivisibleBy(15) print(result)
def main(): from math import sqrt a=4 b=5 oper1 = float((2*(3/4)) + (4*(2/3))- (3*(1/5)) + (5*(1/2))) oper2 = float(2*math.sqrt(35**2) + 4*math.sqrt(36**3) - 6*math.sqrt(49**2)) oper3 = float((a**3 + 2*b**2) / (4*a)) oper4 = float((2*((a+b)**2) + 4*((a-b)**2)) / (a*b**2)) oper5 = float((math.sqrt((a+b)**2 + 2**(a+b))) / (2*a + 2*b)**2) print(round(oper1,4)) print(round(oper2,4)) print(round(oper3,4)) print(round(oper4,4)) print(round(oper5,4)) if __name__ == '__main__': main()
""" Monte Carlo Tic-Tac-Toe Player """ import random import poc_ttt_gui import poc_ttt_provided as provided # Constants for Monte Carlo simulator # You may change the values of these constants as desired, but # do not change their names. NTRIALS = 100 # Number of trials to run SCORE_CURRENT = 1.0 # Score for squares played by the current player SCORE_OTHER = 1.0 # Score for squares played by the other player # TTTBoard constants # provided.EMPTY # provided.PLAYERX # provided.PLAYERO # provided.DRAW # provided.switch_player(player) def mc_trial(board, player): """ Input board, start game with input player by random play rotate between player, modify board. return when game over """ #b_dim = board.get_dim() while (board.check_win() == None): empty_list = board.get_empty_squares(); # print empty_list player_move = random.choice(empty_list) board.move(player_move[0],player_move[1], player) if ( player == provided.PLAYERX): player = provided.PLAYERO else: player = provided.PLAYERX #print board.__str__() return def mc_update_scores(scores, board, player): """ update scores(a grid of score as the dimention of the board """ b_dim = board.get_dim() winner = board.check_win() if ( winner == provided.PLAYERX ): other = provided.PLAYERO for col in range(b_dim): for row in range(b_dim): if (board.square(row, col) == winner): scores[row][col] += SCORE_CURRENT elif (board.square(row,col) == other): scores[row][col] -= SCORE_OTHER elif (board.square(row,col) == provided.EMPTY): scores[row][col] += 0 #print scores elif ( winner == provided.PLAYERO ): other = provided.PLAYERX for col in range(b_dim): for row in range(b_dim): if (board.square(row, col) == winner): scores[row][col] += SCORE_CURRENT elif (board.square(row, col) == other): scores[row][col] -= SCORE_OTHER elif (board.square(row, col) == provided.EMPTY): scores[row][col] += 0 #print scores print "scores for games so far: ", scores return def get_best_move(board, scores): """ when board is not empty, return (row, column)tuple for best move random if there is more than one for the best move """ best_scores = [] b_dim = board.get_dim() empty_list = board.get_empty_squares(); if (not empty_list): return empty_squre = random.choice(empty_list) value = scores[empty_squre[0]][empty_squre[1]] for col in range(b_dim): for row in range(b_dim): if (scores[row][col] == value): if ((row,col) in empty_list): best_scores.append((row, col)) elif (scores[row][col] > value): if ((row,col) in empty_list): best_scores = [] best_scores.append((row, col)) value = scores[row][col] print best_scores return random.choice(best_scores) def mc_move(board, player, trials): """ Implement MC method for best move, return (row, column)tuple my_score is 3x3 grid ie """ b_dim = board.get_dim() print board.__str__() mc_score=[[0 + 0 for dummy_col in range(b_dim)] for dummy_row in range(b_dim)] mc_board = board.clone() for dummy in range(trials): mc_trial(mc_board, player) mc_update_scores(mc_score, mc_board, player) print mc_score return get_best_move(board, mc_score) # Test game with the console or the GUI. Uncomment whichever # you prefer. Both should be commented out when you submit # for testing to save time. #provided.play_game(mc_move, NTRIALS, False) poc_ttt_gui.run_gui(3, provided.PLAYERX, mc_move, NTRIALS, False) # mov = get_best_move(provided.TTTBoard(2, False, [[provided.EMPTY, provided.EMPTY], [provided.EMPTY, provided.EMPTY]]), [[0, 0], [3, 0]]) # print mov # mov = get_best_move(provided.TTTBoard(3, False, [[provided.PLAYERX, provided.PLAYERX, provided.PLAYERO], [provided.PLAYERO, provided.PLAYERX, provided.PLAYERX], [provided.PLAYERO, provided.EMPTY, provided.PLAYERO]]), [[0, 2, 0], [0, 2, 0], [0, 2, 0]]) # print mov #mov = get_best_move(provided.TTTBoard(3, False, [[provided.EMPTY, provided.PLAYERX, provided.EMPTY], [provided.PLAYERO, provided.PLAYERX, provided.EMPTY], [provided.PLAYERO, provided.EMPTY, provided.EMPTY]]), [[-3, 6, -2], [8, 0, -3], [3, -2, -4]]) #print mov #mov = get_best_move(provided.TTTBoard(3, False, [[provided.PLAYERX, provided.PLAYERX, provided.PLAYERO], [provided.PLAYERO, provided.PLAYERX, provided.PLAYERX], [provided.PLAYERO, provided.EMPTY, provided.PLAYERO]]), [[3, 2, 5], [8, 2, 8], [4, 0, 2]]) #print mov #mc_trial(provided.TTTBoard(2, False, [[provided.EMPTY, provided.EMPTY], [provided.EMPTY, provided.EMPTY]]), 2) #mc_trial(provided.TTTBoard(2, False, [[provided.EMPTY, provided.EMPTY], [provided.EMPTY, provided.EMPTY]]), 2) #mc_update_scores([[0, 0, 0], [0, 0, 0], [0, 0, 0]], provided.TTTBoard(3, False, [[provided.PLAYERX, provided.PLAYERX, provided.PLAYERO], [provided.PLAYERO, provided.PLAYERX, provided.EMPTY], [provided.EMPTY, provided.PLAYERX, provided.PLAYERO]]), 2) #mc_move(provided.TTTBoard(3, False, [[provided.PLAYERX, provided.PLAYERX, provided.PLAYERO], [provided.EMPTY, provided.PLAYERX, provided.PLAYERX], [provided.PLAYERO, provided.EMPTY, provided.PLAYERO]]), provided.PLAYERO, NTRIALS) #mc_move[provided.TTTBoard(3, False, [[provided.PLAYERX, provided.PLAYERX, provided.PLAYERO], [provided.EMPTY, provided.PLAYERX, provided.PLAYERX], [provided.PLAYERO, provided.PLAYERO, provided.PLAYERO]]), 3, 1, [(2, 1)]] #mc_move(provided.TTTBoard(3, False, [[provided.PLAYERX, provided.PLAYERX, provided.PLAYERO], [provided.PLAYERO, provided.PLAYERX, provided.PLAYERX], [provided.PLAYERO, provided.EMPTY, provided.PLAYERO]]), provided.PLAYERX, NTRIALS) #mc_move(provided.TTTBoard(3, False, [[provided.EMPTY, provided.PLAYERX, provided.PLAYERX], [provided.PLAYERO, provided.EMPTY, provided.PLAYERX], [provided.PLAYERO, provided.PLAYERX, provided.EMPTY]]), provided.PLAYERO, NTRIALS) #mc_move(provided.TTTBoard(3, False, [[provided.PLAYERX, provided.EMPTY, provided.EMPTY], [provided.PLAYERO, provided.PLAYERO, provided.EMPTY], [provided.EMPTY, provided.PLAYERX, provided.EMPTY]]), provided.PLAYERX, NTRIALS) #mc_update_scores([[0, 0, 0], [0, 0, 0], [0, 0, 0]], provided.TTTBoard(3, False, [[provided.PLAYERX, provided.EMPTY, provided.EMPTY], [provided.EMPTY, provided.PLAYERX, provided.PLAYERX], [provided.PLAYERO, provided.PLAYERO, provided.PLAYERO]]), 2)
from Animal.Role import * from Animal.Danaus.plexippus import * from Land_Use.Developed.farm import * import numpy as np import pandas as pd from Functions.Tests import * def iterate_field(group: list = None, number_fields: int = 2) -> CropField: """ Iterate groups of fields to find optimal arrangements. Group is a list of CropField objects, or we'll create some from the standard tests. :param group: The field group to be optimized :param number_fields: How many from the group to select. :return: Optimal cropfield >>> """ if group: pass else: group = ['standard', 'food heavy', 'shelter heavy', "middle food windbreak", 'middle shelter windbreak', 'middle shelter windbreak 2', 'fallow'] total = [] for i in range(number_fields): temp = np.random.choice(group) if temp == 'standard': created = StandardTest(34) elif temp == 'food heavy': created = HeavyFoodTest(34) elif temp == 'shelter heavy': created = ShelterHeavyTest(34) elif temp == 'middle food windbreak': created = MiddleFoodWindbreakTest(34) elif temp == 'middle shelter windbreak': created = MiddleShelterWindbreakTest(34) elif temp == 'middle shelter windbreak 2': created = MiddleShelterWindbreakTest2(34) elif temp == 'fallow': created = FallowTest(34) else: created = temp total.append(created) return total def optimize_field_group(number_of_fields: int=5, dead_goal: int = 25, exit_goal: int = 50, num_iters: int = 1000, total_iters: int=100) -> tuple: ''' The goal of this function is to find an optimal arrangement of fields. It will start with a single field and repeat it across several rows and columns, then run butterflies through the entire set and see if we can find an optimal arrangement of fields. For example, maybe a fallow field in the middle is best, or maybe if there are food borders around each field works best. :param number_of_fields: :param dead_goal: :param exit_goal: :param num_iters: :param total_iters: :return: ''' master_list = [] result_list = [] exit_pct = 0 dead_pct = 100 iters = 0 while exit_pct <= exit_goal and dead_pct >= dead_goal and iters <= total_iters: arrangement = iterate_field(number_fields=number_of_fields) master_field = arrangement[0] for i in range(1, len(arrangement)): master_field.concatenate(arrangement[i].array) # Simulate to see how well the field does for i in range(num_iters): b1 = Monarch(master_field) while b1.status == 'alive': b1.move_one_day() result_list.append(b1.status) dead_pct = result_list.count("dead")/len(result_list) * 100 exit_pct = result_list.count("exit")/len(result_list) * 100 master_list.append((iters, arrangement, dead_pct, exit_pct)) if iters % 5 == 0: print("Working on iteration {}".format(iters)) iters += 1 dead_pct = [] for item in master_list: dead_pct.append(item[2]) min_index = dead_pct.index(min(dead_pct)) return master_list[min_index]
# python3 import sys def swap_by_index(values, a, b): temp = values[a] values[a] = values[b] values[b] = temp def selection_sort(values): for i in range(0, len(values)): min_index = i for j in range(i + 1, len(values)): if values[j] <= values[min_index]: min_index = j swap_by_index(values, i, min_index) return values if __name__ == '__main__': print(selection_sort( [4, 3, 2, 20, 18, 14, 1, 4, 3, 2, 20, 18, 14, 1, 4, 3, 2, 20, 18, 14, 1, 4, 3, 2, 20, 18, 14, 1]))
#!/usr/bin/python """ this is the code to accompany the Lesson 3 (decision tree) mini-project use an DT to identify emails from the Enron corpus by their authors Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() ######################################################### ### your code goes here ### from sklearn import tree from sklearn.metrics import accuracy_score # train model clf = tree.DecisionTreeClassifier(min_samples_split=40) print 'number of features: ', len(features_train[0]) t0 = time() clf.fit(features_train, labels_train) print "\ntraining time:", round(time()-t0, 3), "s" # predict labels t0 = time() labels_pred = clf.predict(features_test) print "prediction time:", round(time()-t0, 3), "s" # calculate accuracy accuracy = accuracy_score(labels_test, labels_pred) print 'Accuracy: ', accuracy ######################################################### # OUTPUT # Decision Tree with min_sample_split=40 # training time: 69.636 s # prediction time: 0.018 s # Accuracy: 0.97838452787 ######################################################### # number of features: 3785 ######################################################### # Using SelectPercentile = 1% # number of features: 379 # # training time: 4.719 s # prediction time: 0.001 s # Accuracy: 0.96700796359
# Python common data structures # data structures are just ways for us to store information for easy access and use names = ["Adam", "Bill", "Steve"] # lists will reisize as needed and can store any type # lists are MUTABLE always add or remove elements # lists can contain duplicates stuff = ["Apple", 4, [[],1], 9.8, 4 ,4 ,4 ,4] print(stuff) stuff2 = stuff # points to the same list print(stuff2 is stuff) # NOT THE EQUALITY operator. Are they the same EXACT OBJECT IN MEMORY # to create a list my_list = [] print(my_list) my_list.append("Hello") print(my_list) my_list.append("World") # always adds at the end of the list print(my_list) # delete an item from a list del my_list[1] print(my_list) my_list.insert(1,"!") stuff2.append("Added just random string") print(stuff)
# a lambda is an anonymous function # () =>{} # popular in funcitonal programming nums = [1,2,3,4,5,6] result = map(lambda n : n*10,nums) # Lambdas are NOWHERE near as common or useful in python as in other languages JS for r in result: print(r)
# a simple greeting app that supports saying hello in many different languages import english # import the python file (A python file is called a module) from spanish import hola from germanic_languages.german import gutentag name = "Adam" english.hello(name) # if you import just the module # you have to use the module name to access the global funcitons anvariables # if you use from you can specify what functions you want it particular and do not need to # prefix with the module name hola(name) gutentag(name) # Python is an interpreted language that executes line by line # Most python interpreters (the software that reads you python code and executes it) # will (compile imported files into lower level code native the the computer) # by default .pyc C implemention of your python code # A python file is a module # A folder that contains one or many python modules is called a package # __init__.py file in a package Older versions of python required this exact file name # to be in a package otherwise it would not import the modules correctly # every module has a built-in variable called __name__ # the value of that variable is the name of the module # UNLESS you are running that module directly # the __name__ value is "__main__" if it is the file you are DIRECTLY executing otherwise it # is the name of the file print(__name__) # Essentially python's way of creating a entrypoint main method that you might see in # other programming languages if __name__ == "__main__": print("I can only run if you direclty execute this file")
# Common Errors in Python # LookUpError: get an index that does not exist from a list or tuple or use dictionary key that does not exist # TypeError: when you pass in a variable that is of the wrong type (pass in a str instead of int/float) # ValueError: when the type is right but the value of that variable is wrong # NameError: you reference a variable that does not exist # OFTEN functions will raise errors and NOT handle them # For functions that might be used throughout the program you can handle the errors # differently / most appropriately def celcius_to_farenheit(c): # Exceptions give you information on WHY something failed # And you might want to address them different if type(c) != int and type(c) != float: raise TypeError("Temperature must be a numeric type") # all errors are objects if c < -273: raise ValueError(f"Input Temperature {c} is below absoulate zero -273 C") f = c*9/5 +32 return f try: result = celcius_to_farenheit(-400) except TypeError as e: # if you want the object put print(e) # prints out the message you passed when you created the Error # the __str__ for errors is to return the message it was created with except ValueError as e: print(e) except Exception as e: print(type(e)) # is a value error
#!/usr/bin/env python """ generate_graph.py Generates a random graph for grading. For use please run the module with --help """ __author__ = "Bobby Streit" __version__ = "1.0" __maintainer__ = "Bobby Streit" __email__ = "[email protected]" import argparse import random MAX_WEIGHT = 100 PARSER = argparse.ArgumentParser() PARSER.add_argument("path", help="Output file path") PARSER.add_argument("numvertices", help="Number of Vertices", type=int) PARSER.add_argument("-d", "--dense", help="Create a dense graph") PARSER.add_argument("-s", "--sparsity", help="Percent chance of an edge between two nodes occuring (50 by default)", type=int) PARSER.add_argument("-dc", "--disconnected", help="Create a disconnected graph") ARGS = PARSER.parse_args() if ARGS.sparsity: SPARSITY = ARGS.sparsity else: SPARSITY = 50 def main(): vertices = [] edgecount = 0 for i in range(ARGS.numvertices): vertices.append([0] * ARGS.numvertices) if not ARGS.disconnected: for i in range(ARGS.numvertices): for j in range(i + 1, ARGS.numvertices): if ARGS.dense or random.randint(0, 99) < SPARSITY: weight = random.randint(1, MAX_WEIGHT) vertices[i][j] = weight vertices[j][i] = weight edgecount += 1 f = open(ARGS.path, "w") f.write(str(ARGS.numvertices) + " " + str(edgecount)) for i in range(ARGS.numvertices): f.write("\n" + str(i)) for j in range(ARGS.numvertices): if vertices[i][j] != 0: f.write(" " + str(j)) f.write("\n" + str(i)) for j in range(ARGS.numvertices): if vertices[i][j] != 0: f.write(" " + str(vertices[i][j])) if __name__ == "__main__": main()
N = int(input()) star = '*' stars = '* ' stars2 = ' *' for i in range(N): if N%2==0: print(stars*(N//2)) print(stars2*(N//2)) else: print(star + stars2*(N//2)) print(stars2*(N//2))
# RPG based on the game of fadishouis # 12 issue run: January 2020 -January 2020 import sys print("fadishouis: The game changing the earth") print("Valid actions for current location") # valid directions and actions for the characters valid_actions = {"directions": ["north", "south", "east", "west"], "actions": ["explore", "attack", "defend", "heal"]} # after user input, print out the action choosen by the user # print a list a valid actions before user input. Organized according to # possible direction and actions for user_action in valid_actions: # prints out a list of valid directions from the list in valid_actions if user_action == "directions": # define possible_directions as the list that is the value # attached to directions in valid_actions possible_directions = valid_actions["directions"] # using a loop, print out all the directions the user can go for direction in possible_directions: print(f"* {direction}") if user_action == "actions": # prints out a list of valid actions from the list in valid_actions print(f"Complete one of the following {user_action}:") possible_actions = valid_actions["actions"] # using a loop, print out all the actions the user can use for action in possible_actions: print(f"* {action}") action_input = input("Action: ") direction = valid_actions["directions"] action = valid_actions["actions"] # convert the user input to all lower case to prevent errors # print out the action chosen if action_input.lower() in direction: print(f"Go {action_input}!") if action_input == "quit": sys.exit() if action_input.lower() in action: print(f"{action_input}!") print("Invalid action") continue
class Node: def __init__(self, v): self.value = v self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None self.current = None def add_in_tail(self, item): if self.tail is None: self.head = item self.current = item else: self.tail.next = item self.tail = item def print_all_nodes(self): node = self.head while node != None: print(node.value) node = node.next def find(self, value): node = self.head while node != None: if node.value == value: return node node = node.next return None def remove_by_value(self, value): node = self.head prior = None while node != None: if node.value == value: if prior == None: self.head = self.head.next return True else: prior.next = node.next return True prior = node node = node.next return False def remove_all_by_value(self, value): node = self.head prior = None while node != None: if node.value == value: if prior == None: self.head = self.head.next else: prior.next = node.next prior = node node = node.next def clear(self): self.head = None self.tail = None def find_all(self, value): node = self.head found_items = [] while node != None: if node.value == value: found_items.append(node) node = node.next return found_items def length(self): node = self.head length = 0 while node != None: length += 1 node = node.next return length def __iter__(self): return self def next(self): current = self.current if current != None: self.current = self.current.next return current.value else: raise StopIteration l = LinkedList() for x in xrange(1,100): l.add_in_tail(Node(x)) for x in l: print(x)
class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class OrderedList: def __init__(self, sort_ascending = True): self.head = None self.tail = None self.sort_ascending = sort_ascending def print_all_nodes(self): node = self.head while node != None: print(node.value) node = node.next def print_all_nodes_reverse(self): node = self.tail while node != None: print(node.value) node = node.prev def add_in_tail(self, item): if self.head is None: self.head = item item.prev = None item.next = None else: self.tail.next = item item.prev = self.tail self.tail = item def find(self, value): node = self.head while node != None and self.compare(node.value, value) < 1: print(node.value) if node.value == value: return node node = node.next return None def get_at(self, index): node = self.head current = 0 while node != None: if current == index: return node current += 1 node = node.next return node def remove_by_value(self, value): node = self.head while node != None: if node.value == value: if node.prev == None: self.head = self.head.next return True else: node.prev.next = node.next return True node = node.next return False # Home work def compare(self, a, b): if self.sort_ascending: return a - b else: return b - a def insert(self, item): if self.head is None: self.head = item self.tail = item item.prev = None item.next = None else: node = self.head while node != None and self.compare(node.value, item.value) < 1: node = node.next if node != None: item.next = node item.prev = node.prev if node.prev != None: node.prev.next = item else: self.head = item item.prev = None node.prev = item else: self.tail.next = item item.prev = self.tail item.next = None self.tail = item class StringOrderedList(OrderedList): def compare(self, a, b): stripedA = a.strip() strpedB = b.strip() if stripedA > strpedB: r = 1 elif stripedA < strpedB: r = -1 else: r = 0; if self.sort_ascending == False: r = -r return r
import pygame import time import random pygame.init() pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 30) screen = pygame.display.set_mode((1280,720)) done = False #set initial variables p1_x,p1_y=30,30 p2_x,p2_y=(screen.get_width()-60),30 ball_x,ball_y=((screen.get_width())/2),((screen.get_height())/2) slope_x,slope_y=2,2 #set constants paddle_width = screen.get_width()/64 paddle_height = screen.get_height()/3.6 #define Paddle class class Paddle: def __init__(self,x,y): self.x=x self.y=y self.player=pygame.draw.rect(screen, (255,255,255), pygame.Rect(self.x,self.y,paddle_width,paddle_height)) self.rect=pygame.Rect(self.x,self.y,paddle_width,paddle_height) def draw(self): self.player=pygame.draw.rect(screen, (255,255,255), pygame.Rect(self.x,self.y,paddle_width,paddle_height)) self.rect=pygame.Rect(self.x,self.y,paddle_width,paddle_height) def up(self): if self.y>0: self.y-=3 def down(self): if self.y<screen.get_height()-200: self.y+=3 #define ball class class Ball: def __init__(self,x,y): self.x=x self.y=y self.slope_x=slope_x self.slope_y=slope_y self.ball=pygame.draw.rect(screen, (255,255,255), pygame.Rect(self.x,self.y,paddle_width,paddle_width)) self.rect = pygame.Rect(self.x,self.y,paddle_width,paddle_width) def draw(self): #make ball movement self.x+=self.slope_x self.y+=self.slope_y if self.y <= 0 or self.y >= (screen.get_height()): self.slope_y*=-1 if self.x <= 0: self.slope_x*=-1 #p2_score+=1 self.x,self.y=((screen.get_width())/2),((screen.get_height())/2) time.sleep(1) if self.x >= (screen.get_width()): self.slope_x*=-1 #p1_score+=1 self.x,self.y=((screen.get_width())/2),((screen.get_height())/2) time.sleep(1) #collision if self.rect.colliderect(p1.rect) or self.rect.colliderect(p2.rect): self.col() self.player=pygame.draw.rect(screen, (255,255,255), pygame.Rect(self.x,self.y,paddle_width,paddle_width)) self.rect = pygame.Rect(self.x,self.y,paddle_width,paddle_width) def col(self): self.slope_x*=-1 if self.slope_y>0: self.slope_y=random.randint(1,3) * -1 else: self.slope_y=random.randint(1,3) self.x+=(self.slope_x*3) self.y+=self.slope_y #set initial conditions p1_score,p2_score=0,0 p1=Paddle(p1_x,p1_y) p2=Paddle(p2_x,p2_y) ball=Ball(ball_x,ball_y) #main loop while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pressed=pygame.key.get_pressed() #controls #p1 if pressed[pygame.K_w]: p1.up() if pressed[pygame.K_s]: p1.down() #p2 if pressed[pygame.K_UP]: p2.up() if pressed[pygame.K_DOWN]: p2.down() #make players and ball screen.fill((0,0,0)) score = myfont.render(str(p1_score)+" "+str(p2_score), True, (255,255,255)) screen.blit(score, ((screen.get_width()/2)-20,0)) p1.draw() p2.draw() ball.draw() pygame.display.flip()
# Natural Language Toolkit: Language Model Unit Tests # # Copyright (C) 2001-2023 NLTK Project # Author: Ilia Kurenkov <[email protected]> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT from functools import partial from itertools import chain from nltk.util import everygrams, pad_sequence flatten = chain.from_iterable pad_both_ends = partial( pad_sequence, pad_left=True, left_pad_symbol="<s>", pad_right=True, right_pad_symbol="</s>", ) pad_both_ends.__doc__ = """Pads both ends of a sentence to length specified by ngram order. Following convention <s> pads the start of sentence </s> pads its end. """ def padded_everygrams(order, sentence): """Helper with some useful defaults. Applies pad_both_ends to sentence and follows it up with everygrams. """ return everygrams(list(pad_both_ends(sentence, n=order)), max_len=order) def padded_everygram_pipeline(order, text): """Default preprocessing for a sequence of sentences. Creates two iterators: - sentences padded and turned into sequences of `nltk.util.everygrams` - sentences padded as above and chained together for a flat stream of words :param order: Largest ngram length produced by `everygrams`. :param text: Text to iterate over. Expected to be an iterable of sentences. :type text: Iterable[Iterable[str]] :return: iterator over text as ngrams, iterator over text as vocabulary data """ padding_fn = partial(pad_both_ends, n=order) return ( (everygrams(list(padding_fn(sent)), max_len=order) for sent in text), flatten(map(padding_fn, text)), )
# Natural Language Toolkit: API for alignment and translation objects # # Copyright (C) 2001-2023 NLTK Project # Author: Will Zhang <[email protected]> # Guan Gui <[email protected]> # Steven Bird <[email protected]> # Tah Wei Hoon <[email protected]> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT import subprocess from collections import namedtuple class AlignedSent: """ Return an aligned sentence object, which encapsulates two sentences along with an ``Alignment`` between them. Typically used in machine translation to represent a sentence and its translation. >>> from nltk.translate import AlignedSent, Alignment >>> algnsent = AlignedSent(['klein', 'ist', 'das', 'Haus'], ... ['the', 'house', 'is', 'small'], Alignment.fromstring('0-3 1-2 2-0 3-1')) >>> algnsent.words ['klein', 'ist', 'das', 'Haus'] >>> algnsent.mots ['the', 'house', 'is', 'small'] >>> algnsent.alignment Alignment([(0, 3), (1, 2), (2, 0), (3, 1)]) >>> from nltk.corpus import comtrans >>> print(comtrans.aligned_sents()[54]) <AlignedSent: 'Weshalb also sollten...' -> 'So why should EU arm...'> >>> print(comtrans.aligned_sents()[54].alignment) 0-0 0-1 1-0 2-2 3-4 3-5 4-7 5-8 6-3 7-9 8-9 9-10 9-11 10-12 11-6 12-6 13-13 :param words: Words in the target language sentence :type words: list(str) :param mots: Words in the source language sentence :type mots: list(str) :param alignment: Word-level alignments between ``words`` and ``mots``. Each alignment is represented as a 2-tuple (words_index, mots_index). :type alignment: Alignment """ def __init__(self, words, mots, alignment=None): self._words = words self._mots = mots if alignment is None: self.alignment = Alignment([]) else: assert type(alignment) is Alignment self.alignment = alignment @property def words(self): return self._words @property def mots(self): return self._mots def _get_alignment(self): return self._alignment def _set_alignment(self, alignment): _check_alignment(len(self.words), len(self.mots), alignment) self._alignment = alignment alignment = property(_get_alignment, _set_alignment) def __repr__(self): """ Return a string representation for this ``AlignedSent``. :rtype: str """ words = "[%s]" % (", ".join("'%s'" % w for w in self._words)) mots = "[%s]" % (", ".join("'%s'" % w for w in self._mots)) return f"AlignedSent({words}, {mots}, {self._alignment!r})" def _to_dot(self): """ Dot representation of the aligned sentence """ s = "graph align {\n" s += "node[shape=plaintext]\n" # Declare node for w in self._words: s += f'"{w}_source" [label="{w}"] \n' for w in self._mots: s += f'"{w}_target" [label="{w}"] \n' # Alignment for u, v in self._alignment: s += f'"{self._words[u]}_source" -- "{self._mots[v]}_target" \n' # Connect the source words for i in range(len(self._words) - 1): s += '"{}_source" -- "{}_source" [style=invis]\n'.format( self._words[i], self._words[i + 1], ) # Connect the target words for i in range(len(self._mots) - 1): s += '"{}_target" -- "{}_target" [style=invis]\n'.format( self._mots[i], self._mots[i + 1], ) # Put it in the same rank s += "{rank = same; %s}\n" % (" ".join('"%s_source"' % w for w in self._words)) s += "{rank = same; %s}\n" % (" ".join('"%s_target"' % w for w in self._mots)) s += "}" return s def _repr_svg_(self): """ Ipython magic : show SVG representation of this ``AlignedSent``. """ dot_string = self._to_dot().encode("utf8") output_format = "svg" try: process = subprocess.Popen( ["dot", "-T%s" % output_format], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) except OSError as e: raise Exception("Cannot find the dot binary from Graphviz package") from e out, err = process.communicate(dot_string) return out.decode("utf8") def __str__(self): """ Return a human-readable string representation for this ``AlignedSent``. :rtype: str """ source = " ".join(self._words)[:20] + "..." target = " ".join(self._mots)[:20] + "..." return f"<AlignedSent: '{source}' -> '{target}'>" def invert(self): """ Return the aligned sentence pair, reversing the directionality :rtype: AlignedSent """ return AlignedSent(self._mots, self._words, self._alignment.invert()) class Alignment(frozenset): """ A storage class for representing alignment between two sequences, s1, s2. In general, an alignment is a set of tuples of the form (i, j, ...) representing an alignment between the i-th element of s1 and the j-th element of s2. Tuples are extensible (they might contain additional data, such as a boolean to indicate sure vs possible alignments). >>> from nltk.translate import Alignment >>> a = Alignment([(0, 0), (0, 1), (1, 2), (2, 2)]) >>> a.invert() Alignment([(0, 0), (1, 0), (2, 1), (2, 2)]) >>> print(a.invert()) 0-0 1-0 2-1 2-2 >>> a[0] [(0, 1), (0, 0)] >>> a.invert()[2] [(2, 1), (2, 2)] >>> b = Alignment([(0, 0), (0, 1)]) >>> b.issubset(a) True >>> c = Alignment.fromstring('0-0 0-1') >>> b == c True """ def __new__(cls, pairs): self = frozenset.__new__(cls, pairs) self._len = max(p[0] for p in self) if self != frozenset([]) else 0 self._index = None return self @classmethod def fromstring(cls, s): """ Read a giza-formatted string and return an Alignment object. >>> Alignment.fromstring('0-0 2-1 9-2 21-3 10-4 7-5') Alignment([(0, 0), (2, 1), (7, 5), (9, 2), (10, 4), (21, 3)]) :type s: str :param s: the positional alignments in giza format :rtype: Alignment :return: An Alignment object corresponding to the string representation ``s``. """ return Alignment([_giza2pair(a) for a in s.split()]) def __getitem__(self, key): """ Look up the alignments that map from a given index or slice. """ if not self._index: self._build_index() return self._index.__getitem__(key) def invert(self): """ Return an Alignment object, being the inverted mapping. """ return Alignment(((p[1], p[0]) + p[2:]) for p in self) def range(self, positions=None): """ Work out the range of the mapping from the given positions. If no positions are specified, compute the range of the entire mapping. """ image = set() if not self._index: self._build_index() if not positions: positions = list(range(len(self._index))) for p in positions: image.update(f for _, f in self._index[p]) return sorted(image) def __repr__(self): """ Produce a Giza-formatted string representing the alignment. """ return "Alignment(%r)" % sorted(self) def __str__(self): """ Produce a Giza-formatted string representing the alignment. """ return " ".join("%d-%d" % p[:2] for p in sorted(self)) def _build_index(self): """ Build a list self._index such that self._index[i] is a list of the alignments originating from word i. """ self._index = [[] for _ in range(self._len + 1)] for p in self: self._index[p[0]].append(p) def _giza2pair(pair_string): i, j = pair_string.split("-") return int(i), int(j) def _naacl2pair(pair_string): i, j, p = pair_string.split("-") return int(i), int(j) def _check_alignment(num_words, num_mots, alignment): """ Check whether the alignments are legal. :param num_words: the number of source language words :type num_words: int :param num_mots: the number of target language words :type num_mots: int :param alignment: alignment to be checked :type alignment: Alignment :raise IndexError: if alignment falls outside the sentence """ assert type(alignment) is Alignment if not all(0 <= pair[0] < num_words for pair in alignment): raise IndexError("Alignment is outside boundary of words") if not all(pair[1] is None or 0 <= pair[1] < num_mots for pair in alignment): raise IndexError("Alignment is outside boundary of mots") PhraseTableEntry = namedtuple("PhraseTableEntry", ["trg_phrase", "log_prob"]) class PhraseTable: """ In-memory store of translations for a given phrase, and the log probability of the those translations """ def __init__(self): self.src_phrases = dict() def translations_for(self, src_phrase): """ Get the translations for a source language phrase :param src_phrase: Source language phrase of interest :type src_phrase: tuple(str) :return: A list of target language phrases that are translations of ``src_phrase``, ordered in decreasing order of likelihood. Each list element is a tuple of the target phrase and its log probability. :rtype: list(PhraseTableEntry) """ return self.src_phrases[src_phrase] def add(self, src_phrase, trg_phrase, log_prob): """ :type src_phrase: tuple(str) :type trg_phrase: tuple(str) :param log_prob: Log probability that given ``src_phrase``, ``trg_phrase`` is its translation :type log_prob: float """ entry = PhraseTableEntry(trg_phrase=trg_phrase, log_prob=log_prob) if src_phrase not in self.src_phrases: self.src_phrases[src_phrase] = [] self.src_phrases[src_phrase].append(entry) self.src_phrases[src_phrase].sort(key=lambda e: e.log_prob, reverse=True) def __contains__(self, src_phrase): return src_phrase in self.src_phrases
# Natural Language Toolkit: Simple Tokenizers # # Copyright (C) 2001-2023 NLTK Project # Author: Edward Loper <[email protected]> # Steven Bird <[email protected]> # URL: <https://www.nltk.org> # For license information, see LICENSE.TXT r""" Simple Tokenizers These tokenizers divide strings into substrings using the string ``split()`` method. When tokenizing using a particular delimiter string, use the string ``split()`` method directly, as this is more efficient. The simple tokenizers are *not* available as separate functions; instead, you should just use the string ``split()`` method directly: >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks." >>> s.split() # doctest: +NORMALIZE_WHITESPACE ['Good', 'muffins', 'cost', '$3.88', 'in', 'New', 'York.', 'Please', 'buy', 'me', 'two', 'of', 'them.', 'Thanks.'] >>> s.split(' ') # doctest: +NORMALIZE_WHITESPACE ['Good', 'muffins', 'cost', '$3.88\nin', 'New', 'York.', '', 'Please', 'buy', 'me\ntwo', 'of', 'them.\n\nThanks.'] >>> s.split('\n') # doctest: +NORMALIZE_WHITESPACE ['Good muffins cost $3.88', 'in New York. Please buy me', 'two of them.', '', 'Thanks.'] The simple tokenizers are mainly useful because they follow the standard ``TokenizerI`` interface, and so can be used with any code that expects a tokenizer. For example, these tokenizers can be used to specify the tokenization conventions when building a `CorpusReader`. """ from nltk.tokenize.api import StringTokenizer, TokenizerI from nltk.tokenize.util import regexp_span_tokenize, string_span_tokenize class SpaceTokenizer(StringTokenizer): r"""Tokenize a string using the space character as a delimiter, which is the same as ``s.split(' ')``. >>> from nltk.tokenize import SpaceTokenizer >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks." >>> SpaceTokenizer().tokenize(s) # doctest: +NORMALIZE_WHITESPACE ['Good', 'muffins', 'cost', '$3.88\nin', 'New', 'York.', '', 'Please', 'buy', 'me\ntwo', 'of', 'them.\n\nThanks.'] """ _string = " " class TabTokenizer(StringTokenizer): r"""Tokenize a string use the tab character as a delimiter, the same as ``s.split('\t')``. >>> from nltk.tokenize import TabTokenizer >>> TabTokenizer().tokenize('a\tb c\n\t d') ['a', 'b c\n', ' d'] """ _string = "\t" class CharTokenizer(StringTokenizer): """Tokenize a string into individual characters. If this functionality is ever required directly, use ``for char in string``. """ _string = None def tokenize(self, s): return list(s) def span_tokenize(self, s): yield from enumerate(range(1, len(s) + 1)) class LineTokenizer(TokenizerI): r"""Tokenize a string into its lines, optionally discarding blank lines. This is similar to ``s.split('\n')``. >>> from nltk.tokenize import LineTokenizer >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks." >>> LineTokenizer(blanklines='keep').tokenize(s) # doctest: +NORMALIZE_WHITESPACE ['Good muffins cost $3.88', 'in New York. Please buy me', 'two of them.', '', 'Thanks.'] >>> # same as [l for l in s.split('\n') if l.strip()]: >>> LineTokenizer(blanklines='discard').tokenize(s) # doctest: +NORMALIZE_WHITESPACE ['Good muffins cost $3.88', 'in New York. Please buy me', 'two of them.', 'Thanks.'] :param blanklines: Indicates how blank lines should be handled. Valid values are: - ``discard``: strip blank lines out of the token list before returning it. A line is considered blank if it contains only whitespace characters. - ``keep``: leave all blank lines in the token list. - ``discard-eof``: if the string ends with a newline, then do not generate a corresponding token ``''`` after that newline. """ def __init__(self, blanklines="discard"): valid_blanklines = ("discard", "keep", "discard-eof") if blanklines not in valid_blanklines: raise ValueError( "Blank lines must be one of: %s" % " ".join(valid_blanklines) ) self._blanklines = blanklines def tokenize(self, s): lines = s.splitlines() # If requested, strip off blank lines. if self._blanklines == "discard": lines = [l for l in lines if l.rstrip()] elif self._blanklines == "discard-eof": if lines and not lines[-1].strip(): lines.pop() return lines # discard-eof not implemented def span_tokenize(self, s): if self._blanklines == "keep": yield from string_span_tokenize(s, r"\n") else: yield from regexp_span_tokenize(s, r"\n(\s+\n)*") ###################################################################### # { Tokenization Functions ###################################################################### # XXX: it is stated in module docs that there is no function versions def line_tokenize(text, blanklines="discard"): return LineTokenizer(blanklines).tokenize(text)
# Natural Language Toolkit: Positive Naive Bayes Classifier # # Copyright (C) 2012 NLTK Project # Author: Alessandro Presta <[email protected]> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT """ A variant of the Naive Bayes Classifier that performs binary classification with partially-labeled training sets. In other words, assume we want to build a classifier that assigns each example to one of two complementary classes (e.g., male names and female names). If we have a training set with labeled examples for both classes, we can use a standard Naive Bayes Classifier. However, consider the case when we only have labeled examples for one of the classes, and other, unlabeled, examples. Then, assuming a prior distribution on the two labels, we can use the unlabeled set to estimate the frequencies of the various features. Let the two possible labels be 1 and 0, and let's say we only have examples labeled 1 and unlabeled examples. We are also given an estimate of P(1). We compute P(feature|1) exactly as in the standard case. To compute P(feature|0), we first estimate P(feature) from the unlabeled set (we are assuming that the unlabeled examples are drawn according to the given prior distribution) and then express the conditional probability as: | P(feature) - P(feature|1) * P(1) | P(feature|0) = ---------------------------------- | P(0) Example: >>> from nltk.classify import PositiveNaiveBayesClassifier Some sentences about sports: >>> sports_sentences = [ 'The team dominated the game', ... 'They lost the ball', ... 'The game was intense', ... 'The goalkeeper catched the ball', ... 'The other team controlled the ball' ] Mixed topics, including sports: >>> various_sentences = [ 'The President did not comment', ... 'I lost the keys', ... 'The team won the game', ... 'Sara has two kids', ... 'The ball went off the court', ... 'They had the ball for the whole game', ... 'The show is over' ] The features of a sentence are simply the words it contains: >>> def features(sentence): ... words = sentence.lower().split() ... return dict(('contains(%s)' % w, True) for w in words) We use the sports sentences as positive examples, the mixed ones ad unlabeled examples: >>> positive_featuresets = map(features, sports_sentences) >>> unlabeled_featuresets = map(features, various_sentences) >>> classifier = PositiveNaiveBayesClassifier.train(positive_featuresets, ... unlabeled_featuresets) Is the following sentence about sports? >>> classifier.classify(features('The cat is on the table')) False What about this one? >>> classifier.classify(features('My team lost the game')) True """ from collections import defaultdict from nltk.classify.naivebayes import NaiveBayesClassifier from nltk.probability import DictionaryProbDist, ELEProbDist, FreqDist ##////////////////////////////////////////////////////// ## Positive Naive Bayes Classifier ##////////////////////////////////////////////////////// class PositiveNaiveBayesClassifier(NaiveBayesClassifier): @staticmethod def train( positive_featuresets, unlabeled_featuresets, positive_prob_prior=0.5, estimator=ELEProbDist, ): """ :param positive_featuresets: An iterable of featuresets that are known as positive examples (i.e., their label is ``True``). :param unlabeled_featuresets: An iterable of featuresets whose label is unknown. :param positive_prob_prior: A prior estimate of the probability of the label ``True`` (default 0.5). """ positive_feature_freqdist = defaultdict(FreqDist) unlabeled_feature_freqdist = defaultdict(FreqDist) feature_values = defaultdict(set) fnames = set() # Count up how many times each feature value occurred in positive examples. num_positive_examples = 0 for featureset in positive_featuresets: for fname, fval in featureset.items(): positive_feature_freqdist[fname][fval] += 1 feature_values[fname].add(fval) fnames.add(fname) num_positive_examples += 1 # Count up how many times each feature value occurred in unlabeled examples. num_unlabeled_examples = 0 for featureset in unlabeled_featuresets: for fname, fval in featureset.items(): unlabeled_feature_freqdist[fname][fval] += 1 feature_values[fname].add(fval) fnames.add(fname) num_unlabeled_examples += 1 # If a feature didn't have a value given for an instance, then we assume that # it gets the implicit value 'None'. for fname in fnames: count = positive_feature_freqdist[fname].N() positive_feature_freqdist[fname][None] += num_positive_examples - count feature_values[fname].add(None) for fname in fnames: count = unlabeled_feature_freqdist[fname].N() unlabeled_feature_freqdist[fname][None] += num_unlabeled_examples - count feature_values[fname].add(None) negative_prob_prior = 1.0 - positive_prob_prior # Create the P(label) distribution. label_probdist = DictionaryProbDist( {True: positive_prob_prior, False: negative_prob_prior} ) # Create the P(fval|label, fname) distribution. feature_probdist = {} for fname, freqdist in positive_feature_freqdist.items(): probdist = estimator(freqdist, bins=len(feature_values[fname])) feature_probdist[True, fname] = probdist for fname, freqdist in unlabeled_feature_freqdist.items(): global_probdist = estimator(freqdist, bins=len(feature_values[fname])) negative_feature_probs = {} for fval in feature_values[fname]: prob = ( global_probdist.prob(fval) - positive_prob_prior * feature_probdist[True, fname].prob(fval) ) / negative_prob_prior # TODO: We need to add some kind of smoothing here, instead of # setting negative probabilities to zero and normalizing. negative_feature_probs[fval] = max(prob, 0.0) feature_probdist[False, fname] = DictionaryProbDist( negative_feature_probs, normalize=True ) return PositiveNaiveBayesClassifier(label_probdist, feature_probdist) ##////////////////////////////////////////////////////// ## Demo ##////////////////////////////////////////////////////// def demo(): from nltk.classify.util import partial_names_demo classifier = partial_names_demo(PositiveNaiveBayesClassifier.train) classifier.show_most_informative_features()
# Natural Language Toolkit: Minimal Sets # # Copyright (C) 2001-2023 NLTK Project # Author: Steven Bird <[email protected]> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT from collections import defaultdict class MinimalSet: """ Find contexts where more than one possible target value can appear. E.g. if targets are word-initial letters, and contexts are the remainders of words, then we would like to find cases like "fat" vs "cat", and "training" vs "draining". If targets are parts-of-speech and contexts are words, then we would like to find cases like wind (noun) 'air in rapid motion', vs wind (verb) 'coil, wrap'. """ def __init__(self, parameters=None): """ Create a new minimal set. :param parameters: The (context, target, display) tuples for the item :type parameters: list(tuple(str, str, str)) """ self._targets = set() # the contrastive information self._contexts = set() # what we are controlling for self._seen = defaultdict(set) # to record what we have seen self._displays = {} # what we will display if parameters: for context, target, display in parameters: self.add(context, target, display) def add(self, context, target, display): """ Add a new item to the minimal set, having the specified context, target, and display form. :param context: The context in which the item of interest appears :type context: str :param target: The item of interest :type target: str :param display: The information to be reported for each item :type display: str """ # Store the set of targets that occurred in this context self._seen[context].add(target) # Keep track of which contexts and targets we have seen self._contexts.add(context) self._targets.add(target) # For a given context and target, store the display form self._displays[(context, target)] = display def contexts(self, minimum=2): """ Determine which contexts occurred with enough distinct targets. :param minimum: the minimum number of distinct target forms :type minimum: int :rtype: list """ return [c for c in self._contexts if len(self._seen[c]) >= minimum] def display(self, context, target, default=""): if (context, target) in self._displays: return self._displays[(context, target)] else: return default def display_all(self, context): result = [] for target in self._targets: x = self.display(context, target) if x: result.append(x) return result def targets(self): return self._targets
#5.5 #while x=1 while x<=100: print str(x) x=x+1 #for words=["This","is","an","ex","parrot"] for word in words: print word #range for number in range(1,101): print number #key,value d={"x":1,"y":2,"z":3} for key,value in d.items(): print "key="+key+" value="+str(value)
#9.6 class Fibs: def __init__(self): self.a=0 self.b=1 #implement __iter__ def __iter__(self): return self #implement next def next(self): self.a,self.b=self.b,self.a+self.b return self.a fibs=Fibs() for f in fibs: if f>1000: print f break class TestIterator: value=0 def __iter__(self): return self def next(self): self.value=self.value+1 if self.value>10: raise StopIteration return self.value Ti=TestIterator() print list(Ti)
#example2-1 months=["January","February","March","April","May","June","July","August","September", "October","November","December"] endings=["st","nd","rd"]+17*["th"]+["st","nd","rd"]+7*["th"]+["st"] year=raw_input("year: ") month=raw_input("Month(1-12): ") day=raw_input("Day(1-31): ") month_number=int(month) day_number=int(day) month_name=months[month_number-1] ordinal=day+endings[day_number-1] print month_name+" "+ordinal+", "+year
############################################# # This class implements the interface for a typical cipher. # It defines functions usually used in a cipher ############################################# class CipherInterface: ############################################ # Sets the key to use # @param key - the key to use # @return - True if the key is valid and False otherwise ############################################# def setKey(self,key): return False ################################################## # Encrypts a plaintext string # @param plaintext - the plaintext string # @return - the encrypted ciphertext string ################################################## def encrypt(self,plaintext): return "" ################################################### # Decrypts a string of ciphertext # @param ciphertext - the ciphertext # @return - the plaintext ################################################### def decrypt(self,ciphertext): return "" # Example to check functions #cipher = CipherInterface() #text = cipher.setKey(1)
import pandas as pd from pandas import Series, DataFrame import numpy as np np.set_printoptions(precision=4) obj = Series(range(3), index=['a', 'b', 'c']) index = obj.index print(index) print(obj) print(index[1:])
""" source: https://leetcode.com/problems/search-insert-position/ author: hpjhc date: 2018/10/21 """ class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ try: return nums.index(target) except ValueError: l = 0 r = len(nums) while l < r - 1: mid = (l + r) // 2 if nums[mid] < target: l = mid else: r = mid return l if nums[l] > target else l + 1
""" source:https://leetcode.com/problems/roman-to-integer/ author: hpjhc date: 2018/10/12 """ class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} res = 0 for i, key in enumerate(s): nxt = s[i+1:i+2] res += dict[key] if nxt != '' and dict[key] < dict[nxt]: res -= dict[key] * 2 return res
""" source:https://leetcode.com/problems/1-bit-and-2-bit-characters/ author: hpjhc date: 2018/9/21 """ class Solution: def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ bits.pop() res = 0 while(bits and bits.pop()): res += 1 return res % 2 == 0
import re # Reg Expression # Removing Begining of a String str = ' hello python ' str = re.sub(r"^\s+", "", str, flags=re.UNICODE) print("removed spaces at left side :",str) # Ending of a string str = ' hello python ' str = re.sub(r"\s+$", "", str, flags=re.UNICODE) print("removed spaces at right side :",str) # Removing Begining and Ending str = ' hello python ' str = re.sub("^\s+|\s+$", "", str, flags=re.UNICODE) print("removed spaces at both sides :",str) # Removing all spaces str = ' hello python ' pattern = re.compile(r'\s+') str = re.sub(pattern, '', str) print(str)
# importing pandas module import pandas as pd # defining File path fpath = "Fruit.xlsx" # method to be used to read the excel file data2 = pd.read_excel(fpath,sheet_name='sweet or sour',header=[0]) print(data2) #Reading custom no. of rows and columns: import pandas as pd # File path fpath = "Fruit.xlsx" # method to be used to read the data data2 = pd.read_excel(fpath,usecols=['Fruit','Sweetness','Soreness'],index_col='Fruit',nrows = 5) print(data2) #Reading selective rows import pandas as pd fpath = "Fruit.xlsx" data3 = pd.read_excel(fpath,header=None,nrows=4,skiprows=2) print(data3)
if __name__ == '__main__': languages = ['python', 'perl', 'groovy', 'java', 'curl', 'javascript'] for num, name in enumerate(languages): print( num, name) # index starts from 1 for num, name in enumerate(languages, start =1): print( num, name) # count of list items for count, name in enumerate(languages, start=1): print(name) print(f'There were {count} items in the list')
persons = { 'user_name':'chandra', 'first_name':'chandra shekhar', 'last_name':'goka' } #Looping key,values for key,value in persons.items(): print(f"Key: {key} - Value: {value}") favorite_subjects={ 'chandra':'Computers', 'panvith':'Physics', 'jon':'Mathematics', 'robert':'Computers' } for name,fav_subject in favorite_subjects.items(): print(f"{name} likes {fav_subject}") #Order for name,fav_subject in sorted(favorite_subjects.items()): print(f"{name} likes {fav_subject}") #Keys in Order for name in sorted(favorite_subjects.keys()): print(name) #Values in Order for fav_subject in sorted(favorite_subjects.values()): print(fav_subject) #Remove duplicates in values for fav_subject in sorted(set(favorite_subjects.values())): print(fav_subject)
# A program to do simple math while demonstrating the use of Functions def adding(num1, num2): answer = num1 + num2 return answer def subtracting(num1, num2): answer = int(num1) - int(num2) return answer def multiplying(num1, num2): answer = int(num1) * int(num2) return answer def dividing(num1, num2): answer = int(num1) / int(num2) return answer num1 = input("Enter the first number: ") num2 = input("Enter the second number: ") operation = input("Enter + - * / \n") if operation == "+": answer = adding(num1, num2) elif operation == "-": answer = subtracting(num1, num2) elif operation == "*": answer = multiplying(num1, num2) elif operation == "/": answer = dividing(num1, num2) print("The result of " + str(num1) + " " + operation + " " + str(num2) + " = " + str(answer))
def display_board(x): """ This function displays the board for the X and O game before and after each turn. """ #prints the game table print('|',x[0],'|',x[1],'|',x[2],'|') print('|',x[3],'|',x[4],'|',x[5],'|') print('|',x[6],'|',x[7],'|',x[8],'|') def turn(y): """ Decides whose turn it is and allows them to play. returns True if game is over """ #X's turn if (y.count('x') == y.count('o')): #x inputs and check x's input value = valid_location('X',y) #add x's table to data y[value] = 'x' #display table display_board(y) #check if X won checker = check_board(y) #returns value to stop game if checker == True: return checker #check if game is a draw elif y.count('x') == 5: print(' Game is a draw') return True #O's turn elif (y.count('x') > y.count('o')): #o inputs and check o's input value = valid_location('O',y) #add o's table to data y[value] = 'o' #display table display_board(y) #check if O won checker = check_board(y) #returns value to stop game if checker == True: return checker def check_board(a): """ This function checks if the game is won. displays the winner of the game returns True if game is won. """ #check horizontal rows if (a[0] == a[1] == a[2] == 'x') or (a[0] == a[1] == a[2] == 'o'): print(a[0], 'WINS') return True if (a[3] == a[4] == a[5] == 'x') or (a[3] == a[4] == a[5] == 'o'): print(a[3], 'WINS') return True if (a[6] == a[7] == a[8] == 'x') or (a[6] == a[7] == a[8] == 'o'): print(a[6], 'WINS') return True #check vertical rows if (a[0] == a[3] == a[6] == 'x') or (a[0] == a[3] == a[6] == 'o'): print(a[0], 'WINS') return True if (a[1] == a[4] == a[7] == 'x') or (a[1] == a[4] == a[7] == 'o'): print(a[1], 'WINS') return True if (a[2] == a[5] == a[8] == 'x') or (a[2] == a[5] == a[8] == 'o'): print(a[2], 'WINS') return True #check diagnoals if (a[0] == a[4] == a[8] == 'x') or (a[0] == a[4] == a[8] == 'o'): print(a[0], 'WINS') return True if (a[2] == a[4] == a[6] == 'x') or (a[2] == a[4] == a[6] == 'o'): print(a[2], 'WINS') return True def play(z): """ starts the game """ #if cont is True game is over cont = turn(z) #if cont is None then game isn't over while cont == None: cont = turn(z) def valid_location(j,b): """ takes in j as player and b as list. checks if input is valid returns valide input """ validity = False while not False: value = int(input(j+"'s turn to play, choose location: ")) value -= 1 if b[value] == '-': validity = True return value else: continue def main(): affirm = False while not affirm: #defines board values board_values = ['-','-','-','-','-','-','-','-','-'] #displays board display_board(board_values) #game plays play(board_values) #check if game wants to continue answer = input("Do you want to play again {y is yes, anything else is no}: ") if answer != 'y': affirm = True if __name__ == "__main__": main()
#!/usr/bin/env python3 """tuple typeanotation create a tuple """ from typing import Tuple, Callable def make_multiplier(multiplier: float) -> Callable[[float], float]: """make a multiplier call Args: multiplier (float): [number to use] Returns: Callable[[float], float]: [function to make the operation] """ def f(num: float) -> float: """return the multiplication Args: num (float): [float num to mult] Returns: float: [result of num * multiplier] """ return num * multiplier return f
""" This code is part of Data Science Dojo's bootcamp Copyright (c) 2016-2018 Objective: Explore and visualize data using Python Data Source: Multiple Python Version: 3.4+ Packages: matplotlib, pandas, seaborn """ # Script for following along in Data Exploration and Visualization module # Set your working directory to the bootcamp root with os.chdir() # Copy-paste line by line into an iPython shell import matplotlib.pyplot as plt import pandas as pd import seaborn as sns # Import iris data into Pandas DataFrame iris = pd.read_csv('Datasets/Iris_Data.csv') iris.head() # Pandas boxplot iris.boxplot(column='Sepal.Length', by='Species', return_type='axes') # Pandas boxplots with notches plt.figure() iris_box = iris.boxplot(column='Sepal.Length', by='Species', notch=True, return_type='axes') # Saving Plots. # Saves to current working directory (os.cwd()) by default plt.figure() iris_box['Sepal.Length'].get_figure().savefig("myplot.pdf", format='pdf') # Matplotlib histogram plt.figure() plt.hist(iris['Petal.Width'], bins=20) # Pandas density plot plt.figure() iris['Petal.Length'].plot(kind='kde') # Seaborn multiple density plots fig = plt.figure() ax = fig.add_subplot(111) for name, group in iris['Petal.Width'].groupby(iris['Species']): sns.distplot(group, hist=False, rug=True, ax=ax, label=name) ax.legend() # Exercise 1: # Make a 2-D scatter plot of Sepal Length vs Sepal Width and # Petal Length vs Petal Width using core. Then recreate the same graphs in # lattice, this time coloring the individual points by species. # Matplotlib scatter plot plt.figure() plt.scatter(x=iris['Sepal.Length'], y=iris['Sepal.Width']) # Pandas segmented scatter plot plt.figure() iris_groups = iris.groupby('Species') ax = iris_groups.get_group('setosa').plot(kind='scatter', x='Sepal.Length', y='Sepal.Width', label='Setosa', color='Blue') iris_groups.get_group('virginica').plot(kind='scatter', x='Sepal.Length', y='Sepal.Width', label='Virginica', color='Green', ax=ax) iris_groups.get_group('versicolor').plot(kind='scatter', x='Sepal.Length', y='Sepal.Width', label='Versicolor', color='Red', ax=ax) # Seaborn regression lines ## Ungrouped plt.figure() sns.lmplot(x='Petal.Length', y='Petal.Width', data=iris) ## Grouped plt.figure() sns.lmplot(x='Petal.Length', y='Petal.Width', data=iris, hue='Species') # Seaborn scatter plot matrix plt.figure() sns.pairplot(data=iris, hue='Species', diag_kind='kde', palette='husl', markers=['o', 's', 'D']) #### Extended Titanic Exploration #### # Read in the data and check structure titanic = pd.read_csv('Datasets/titanic.csv') titanic.head() titanic.info() # Casting & Readability titanic['Survived'] = titanic['Survived'].astype('category') titanic['Survived'].cat.categories = ['Dead', 'Survived'] titanic['Survived'].value_counts() titanic['Embarked'] = titanic['Embarked'].astype('category') titanic['Embarked'].cat.categories = ['Cherbourg', 'Queenstown', 'Southampton'] titanic['Embarked'].value_counts() titanic.loc[:,['Survived', 'Embarked']].describe() # Pie Chart plt.figure() titanic['Survived'].value_counts().plot(kind='pie') # Is Sex a good predictor? male = titanic[titanic['Sex']=='male'] female = titanic[titanic['Sex']=='female'] sex_values = pd.DataFrame({'male':male['Survived'].value_counts(), 'female':female['Survived'].value_counts()}) plt.figure() sex_values.plot(kind='pie', subplots=True, figsize=(8,4)) # Is Age a good predictor? titanic['Age'].describe() titanic[titanic['Survived']=='Dead']['Age'].describe() titanic[titanic['Survived']=='Survived']['Age'].describe() # Exercise 3: # Create 2 box plots of Age, one segmented by Sex, the other by Survived # Create a histogram of Age # Create 2 density plot of Age, also segmented by Sex and Survived plt.figure() titanic.boxplot(by='Sex', column='Age') plt.figure() titanic.boxplot(by='Survived', column='Age') plt.figure() titanic['Age'].hist(bins=12) fig = plt.figure() ax_sex = fig.add_subplot(211) ax_surv = fig.add_subplot(212) for name, group in titanic['Age'].groupby(titanic['Sex']): sns.distplot(group, hist=False, label=name, ax=ax_sex) for name, group in titanic['Age'].groupby(titanic['Survived']): sns.distplot(group, hist=False, label=name, ax=ax_surv) ax_sex.legend() ax_surv.legend() # Exercise 4: # Create a new column "Child", and assign each row either "Adult" or "Child" # based on a consistent metric. Then create a series of box plots # relating Fare, Child, Sex, and Survived child = titanic['Age'] child.loc[child < 13] = 0 child.loc[child >= 13] = 1 titanic['Child'] = child.astype('category') titanic['Child'].cat.categories = ['Child', 'Adult'] # Run these next two lines as one block plt.figure() child_facets = sns.FacetGrid(data=titanic, row='Sex', col='Survived', sharey=True) child_facets = child_facets.map(sns.boxplot, "Fare", "Child")
""" This code is part of Data Science Dojo's bootcamp Copyright (c) 2016-2018 Objective: Machine Learning of the Kyphosis dataset with a Decision Tree Data Source: bootcamp root/Datasets/kyphosis.csv Python Version: 3.4+ Packages: scikit-learn, pandas, numpy, pydotplus """ from sklearn.tree import DecisionTreeClassifier from sklearn import metrics, tree from sklearn.externals.six import StringIO import pydotplus import pandas as pd import numpy as np import matplotlib.pyplot as plt # Import data. Remember to set your working directory to the bootcamp root. kyphosis = pd.read_csv('Datasets/kyphosis.csv', index_col=0) kyphosis["Kyphosis"] = pd.Categorical(kyphosis["Kyphosis"], categories=['absent', 'present']) # Data exploration and visualization kyphosis.boxplot(by='Kyphosis') pd.tools.plotting.scatter_matrix(kyphosis.iloc[:,1:]) plt.show() # Randomly choose 60% of the data as training data (Why 60% instead of 70%?) np.random.seed(27) kyphosis.is_train = np.random.uniform(0, 1, len(kyphosis)) <= .6 kyphosis_train = kyphosis[kyphosis.is_train] kyphosis_test = kyphosis[kyphosis.is_train == False] # Train model kyphosis_features = kyphosis.columns[1:] kyphosis_dt_clf = DecisionTreeClassifier(criterion='entropy', max_depth=None, min_samples_split=2, min_samples_leaf=1) kyphosis_dt_clf = kyphosis_dt_clf.fit(kyphosis_train[kyphosis_features], kyphosis_train['Kyphosis']) # Print a string representation of the tree. # If you have graphviz (www.graphviz.org) installed, you can write a pdf # visualization using graph.write_pdf(filename) kyphosis_dt_data = StringIO() tree.export_graphviz(kyphosis_dt_clf, out_file=kyphosis_dt_data) kyphosis_dt_graph = pydotplus.parser.parse_dot_data(kyphosis_dt_data.getvalue()) print(kyphosis_dt_graph.to_string()) # Predict classes of test set and evaluate kyphosis_dt_pred = kyphosis_dt_clf.predict(kyphosis_test[kyphosis_features]) kyphosis_dt_cm = metrics.confusion_matrix(kyphosis_test['Kyphosis'], kyphosis_dt_pred, labels=['absent', 'present']) print(kyphosis_dt_cm) kyphosis_dt_acc = metrics.accuracy_score(kyphosis_test['Kyphosis'], kyphosis_dt_pred) kyphosis_dt_prec = metrics.precision_score(kyphosis_test['Kyphosis'], kyphosis_dt_pred, pos_label='absent') kyphosis_dt_rec = metrics.recall_score(kyphosis_test['Kyphosis'], kyphosis_dt_pred, pos_label='absent') kyphosis_dt_f1 = metrics.f1_score(kyphosis_test['Kyphosis'], kyphosis_dt_pred, pos_label='absent') print("accuracy: " + str(kyphosis_dt_acc) + "\n precision: " + str(kyphosis_dt_prec) + "\n recall: " + str(kyphosis_dt_rec) + "\n f1-score: " + str(kyphosis_dt_f1))
a=3 b=4 print('the value of a+b is ',3+4) #Arithmetic Operators print('the value of a-b is ',3-4) #Arithmetic Operators print('the value of a*b is ',3*4) #Arithmetic Operators print('the value of a/b is ',3/4) #Arithmetic Operators print('the value of a%b is ',type(3%4)) #Arithmetic Operators #Assignment operators a=34 a+=12 print(a) # Comparison opera b=14<7 print (b) # Logical Operators bool1=True bool2=False print("The value of bool1 and bool2 is :",(bool1 and bool2)) print("The value of not bool2 is :",(not bool2)) print("The value of bool1 or bool2 is :",(bool1 or bool2))
# inspired from https://www.bogotobogo.com/python/Multithread/python_multithreading_Synchronization_Producer_Consumer_using_Queue.php import threading import time import random import queue q = queue.Queue() class ProducerThread(threading.Thread): def __init__(self, target=None, name=None): super(ProducerThread, self).__init__() self.target = target self.name = name def run(self): while True: item = random.randint(1, 10) q.put(item) print("+ item " + str(item)) time.sleep(2) return class ConsumerThread(threading.Thread): def __init__(self, target=None, name=None, pool_size=10): super(ConsumerThread, self).__init__() self.target = target self.name = name self.pool_size = pool_size return def run(self): while True: time.sleep(3) if not q.qsize() >= self.pool_size: elems = [] for i in range(0, self.pool_size): elems.append(q.get()) print("- items " + str(elems)) return if __name__ == '__main__': p = ProducerThread(name='producer') c = ConsumerThread(name='consumer') p.start() c.start()
#!/usr/bin/python3 # Prints the weather from the command line. # From Automate the boring stuff. import json import requests location = input("Enter the City: ") countrycode = input("Enter country code: ") # Getting the DATA url = 'http://api.openweathermap.org/data/2.5/forecast?q=%s,%s&APPID=(KEY)' % ( location, countrycode) response = requests.get(url) response.raise_for_status() # Load JSON Data and make it readable. weatherData = json.loads(response.text) # Print weather. w = weatherData['list'] print('Current weather in %s:' % (location)) print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0] ['description'], '-' + '' + 'Wind: ', w[0]['wind']['speed']) print() print('Tomorrow:') print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0] ['description'], '-' + '' + 'Wind: ', w[1]['wind']['speed']) print() print('Day after tomorrow:') print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0] ['description'], '-' + '' + 'Wind: ', w[2]['wind']['speed'])
""" All decisions are based on the number of occupied seats adjacent to a given seat (one of the eight positions immediately up, down, left, right, or diagonal from the seat). The following rules are applied to every seat simultaneously: If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied. If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty. Otherwise, the seat's state does not change. Floor (.) never changes; seats don't move, and nobody sits on the floor. Simulate your seating area by applying the seating rules repeatedly until no seats change state. How many seats end up occupied? """ from enum import Enum class CellType(Enum): FLOOR = 1 SEAT = 2 class CellState(Enum): EMPTY = 1 OCCUPIED = 2 class Cell: FLOOR = '.' EMPTY = 'L' OCCUPIED = '#' INPUT_TO_CELL_TYPE_KEY = { FLOOR: CellType.FLOOR, EMPTY: CellType.SEAT, OCCUPIED: CellType.SEAT, } INPUT_TO_CELL_STATE_KEY = { FLOOR: None, EMPTY: CellState.EMPTY, OCCUPIED: CellState.OCCUPIED, } FORMAT_STR_KEY = { CellState.EMPTY: EMPTY, CellState.OCCUPIED: OCCUPIED, } def __init__(self, type_, state): self.type = type_ self.state = state @classmethod def from_input_char(cls, input_char): return cls( type_=cls.INPUT_TO_CELL_TYPE_KEY[input_char], state=cls.INPUT_TO_CELL_STATE_KEY[input_char], ) @classmethod def init_empty(cls): return cls( type_=CellType.SEAT, state=CellState.EMPTY, ) @classmethod def init_occupied(cls): return cls( type_=CellType.SEAT, state=CellState.OCCUPIED, ) def __str__(self): if self.type == CellType.FLOOR: return Cell.FLOOR else: return self.FORMAT_STR_KEY[self.state] @property def is_occupied(self): return self.state == CellState.OCCUPIED @property def is_seat(self): return self.type == CellType.SEAT def matches_cell(self, other_cell): return self.type == other_cell.type and self.state == other_cell.state class Grid: def __init__(self, cell_rows): self.cell_rows = cell_rows self.width = len(cell_rows[0]) self.height = len(cell_rows) @classmethod def from_input_lines(cls, lines): cell_rows = [] for line in lines: cell_rows.append([Cell.from_input_char(cell) for cell in list(line)]) return cls(cell_rows=cell_rows) def __str__(self): joined_cells = [] for cell_row in self.cell_rows: joined_cells.append('|'.join([str(cell) for cell in cell_row])) return '\n'.join(joined_cells) def cell_at(self, row_col_tuple): row, col = row_col_tuple return self.cell_rows[row][col] def adjacent_cell_coords_from_position(self, row_col_tuple): row, col = row_col_tuple adjacent_cell_tuples = [] upper_bound = 0 if row == 0 else row - 1 lower_bound = self.height - 1 if row == self.height - 1 else row + 1 left_bound = 0 if col == 0 else col - 1 right_bound = self.width - 1 if col == self.width - 1 else col + 1 for row in range(upper_bound, lower_bound + 1): for col in range(left_bound, right_bound + 1): if (row, col) != row_col_tuple: adjacent_cell_tuples.append((row, col)) return adjacent_cell_tuples def adjacent_cells_from_position(self, row_col_tuple): adjacent_cell_tuples = self.adjacent_cell_coords_from_position(row_col_tuple) return [self.cell_at(adjacent_cell_tuple) for adjacent_cell_tuple in adjacent_cell_tuples] def num_occupied_cells_from_cells(self, cells): occupied_fn = lambda cell: cell.type == CellType.SEAT and cell.state == CellState.OCCUPIED filtered_cells = list(filter(occupied_fn, cells)) return len(filtered_cells) def next_cell_iteration_for_cell_at_adjacent(self, row_col_tuple): current_cell = self.cell_at(row_col_tuple) if current_cell.type == CellType.FLOOR: return current_cell adjacent_cells = self.adjacent_cells_from_position(row_col_tuple) num_occupied_adjacent_cells = self.num_occupied_cells_from_cells(adjacent_cells) if current_cell.state == CellState.EMPTY and num_occupied_adjacent_cells == 0: return Cell.init_occupied() if current_cell.state == CellState.OCCUPIED and num_occupied_adjacent_cells >= 4: return Cell.init_empty() return current_cell def visible_cell_coords_from_position(self, row_col_tuple): visible_cell_tuples = [] # up left row, col = row_col_tuple while row > 0 and col > 0: row -= 1 col -= 1 cell = self.cell_at((row, col)) if cell.is_seat: visible_cell_tuples.append((row, col)) break # up row, col = row_col_tuple while row > 0: row -= 1 cell = self.cell_at((row, col)) if cell.is_seat: visible_cell_tuples.append((row, col)) break # up right row, col = row_col_tuple while row > 0 and col < self.width - 1: row -= 1 col += 1 cell = self.cell_at((row, col)) if cell.is_seat: visible_cell_tuples.append((row, col)) break # left row, col = row_col_tuple while col > 0: col -= 1 cell = self.cell_at((row, col)) if cell.is_seat: visible_cell_tuples.append((row, col)) break # right row, col = row_col_tuple while col < self.width - 1: col += 1 cell = self.cell_at((row, col)) if cell.is_seat: visible_cell_tuples.append((row, col)) break # down left row, col = row_col_tuple while row < self.height - 1 and col > 0: row += 1 col -= 1 cell = self.cell_at((row, col)) if cell.is_seat: visible_cell_tuples.append((row, col)) break # down row, col = row_col_tuple while row < self.height - 1: row += 1 cell = self.cell_at((row, col)) if cell.is_seat: visible_cell_tuples.append((row, col)) break # down right row, col = row_col_tuple while row < self.height - 1 and col < self.width - 1: row += 1 col += 1 cell = self.cell_at((row, col)) if cell.is_seat: visible_cell_tuples.append((row, col)) break return visible_cell_tuples def visible_cells_from_position(self, row_col_tuple): visible_cell_tuples = self.visible_cell_coords_from_position(row_col_tuple) return [self.cell_at(visible_cell_tuple) for visible_cell_tuple in visible_cell_tuples] def num_occupied_visible_seats(self, row_col_tuple): visible_cells = self.visible_cells_from_position(row_col_tuple) num_occupied_visible_cells = self.num_occupied_cells_from_cells(visible_cells) return num_occupied_visible_cells def next_cell_iteration_for_cell_at_visible(self, row_col_tuple): current_cell = self.cell_at(row_col_tuple) if current_cell.type == CellType.FLOOR: return current_cell num_occupied_visible_seats = self.num_occupied_visible_seats(row_col_tuple) if current_cell.state == CellState.EMPTY and num_occupied_visible_seats == 0: return Cell.init_occupied() if current_cell.state == CellState.OCCUPIED and num_occupied_visible_seats >= 5: return Cell.init_empty() return current_cell def next_cell_iteration_for_cell_at(self, row_col_tuple, lookup_version): if lookup_version == 'ADJACENT': return self.next_cell_iteration_for_cell_at_adjacent(row_col_tuple) else: return self.next_cell_iteration_for_cell_at_visible(row_col_tuple) @classmethod def from_previous_grid(cls, previous_grid, lookup_version): new_cell_rows = [] for i in range(previous_grid.height): new_row = [] for j in range(previous_grid.width): new_row.append(previous_grid.next_cell_iteration_for_cell_at((i, j), lookup_version)) new_cell_rows.append(new_row) return cls(cell_rows=new_cell_rows) def changed_from_previous_state(self, previous_grid): for i in range(self.height): for j in range(self.width): if not self.cell_at((i, j)).matches_cell(previous_grid.cell_at((i, j))): return True return False def num_occupied_seats(self): return sum([sum([1 for cell in row if cell.is_occupied]) for row in self.cell_rows]) def find_occupied_seats_at_equilibrium(lines, lookup_version): previous_grid = Grid.from_input_lines(lines) next_grid = Grid.from_previous_grid(previous_grid, lookup_version) count = 0 while next_grid.changed_from_previous_state(previous_grid): count += 1 previous_grid = next_grid next_grid = Grid.from_previous_grid(previous_grid, lookup_version) print('found equilibrium at %r iterations' % count) return next_grid.num_occupied_seats() def main(): with open('day11.txt') as f: lines = [line.strip() for line in f.readlines()] lookup_version = 'ADJACENT' result = find_occupied_seats_at_equilibrium(lines, lookup_version) print(result) lookup_version = 'VISIBLE' result = find_occupied_seats_at_equilibrium(lines, lookup_version) print(result) if __name__ == '__main__': main()
def fizzbuzz(): list = [] for x in range(1,101): if(x%3==0 and x%5==0): list.append("FizzBuzz") elif(x%3 == 0 ): list.append('Fizz') elif(x%5 == 0): list.append("Buzz") else: list.append(x) return list print(fizzbuzz())
def longest_run(L): """ Assumes L is a list of integers containing at least 2 elements. Finds the longest run of numbers in L, where the longest run can either be monotonically increasing or monotonically decreasing. In case of a tie for the longest run, choose the longest run that occurs first. Does not modify the list. Returns the sum of the longest run. """ increasing_count = 0 decreasing_count = 0 maxcount = 0 result = 0 for i in range(len(L) - 1): if L[i] <= L[i + 1]: increasing_count += 1 if increasing_count > maxcount: maxcount = increasing_count result = i + 1 else: increasing_count = 0 if L[i] >= L[i + 1]: decreasing_count += 1 if decreasing_count > maxcount: maxcount = decreasing_count result = i + 1 else: decreasing_count = 0 startposition = result - maxcount return sum(L[startposition:result + 1]) ''' increasing_run = [] decreasing_run = [] longest_run = [] count = 0 i = count increasing_run.append(L[i]) decreasing_run.append(L[i]) for i in range(len(L) - 1): if L[i] <= L[i + 1]: increasing_run.append(L[i + 1]) count += 1 if len(increasing_run) > len(longest_run): longest_run = increasing_run if L[i] >= L[i + 1]: increasing_run = [] if L[i] >= L[i + 1]: decreasing_run.append(L[i + 1]) count += 1 if len(decreasing_run) > len(longest_run): longest_run = decreasing_run return longest_run print(longest_run([10, 4, 3, 8, 3, 4, 5, 7, 7, 2])) print(len([5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1])) ''' print(longest_run([5, 6, 5, 7])) # print(longest_run([5, 4, 10])) a = [] b = [5, 6, 7, 8] print(range(len(b))) print(len(a)) print(len(b)) print(len(a) + len(b))
n1 = int(input('Digite um numero: ')) ant = n1 - 1 dep = n1 + 1 print('O nuemro que você digitou é {}, o numero antecessor a ele é {} e por fim o numero depois é {}'.format(n1, ant, dep))
n1 = float(input('Digite o tamanho de largura: ')) n2 = float(input('Digite o tamanho de altura: ')) a = (n1*n2)/2 l1 = a / 2 print('Sabendo que a lagura de sua parede é {} e a sua altura {} o espaço em é {}m2 e a quantidade de tinta usada ' 'será {}'.format(n1, n2, a, l1))
from LinkedListNode import node l=[1,2,3,4,5,6,7,8,9,10] head=node(l[0]) for i in range(1,len(l)): head.appendToLast(node(l[i])) def kThLast(k): p1=head p2=head for i in range(k): if p1.next==None: return None else: p1=p1.next while p1.next!=None: p2=p2.next p1=p1.next return p2 # print(kThLast(5).data)
from LinkedListNode import node l=[3,5,8,5,10,2,1] head=node(l[0]) for i in range(1,len(l)): head.appendToLast(node(l[i])) def part(pivot): linked1=None linked2=None temp=head while temp!=None: newNode = node(temp.data) if temp.data<pivot: if linked1==None: linked1=newNode else: linked1.appendToLast(newNode) else: if linked2==None: linked2=newNode else: linked2.appendToLast(newNode) temp=temp.next linked1.appendToLast(linked2) return linked1 node=part(5) node.printAll()
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-04-01 00:03:12 # @Author : Yong Lee ([email protected]) # @Link : http://www.cnblogs.com/honkly/ # @Version : 1.0 class Car(): """A simple attempt to represent a car.""" def __init__(self, manufacturer, model, year): """Initialize attributes to describe a car.""" self.manufacturer = manufacturer self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model return long_name.title() def read_odometer(self): """Print a statement showing the car's mileage.""" print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """ Set the odometer reading to the given value. Reject the change if it attempts to roll the odometer back. """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """Add the given amount to the odometer reading.""" self.odometer_reading += miles # 9.2.1 Car类 print("9.2.1") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) # 9.2.2 给属性指定默认值 print("9.2.2") # def __init__(self, manufacturer, model, year): # """Initialize attributes to describe a car.""" # self.manufacturer = manufacturer # self.model = model # self.year = year # self.odometer_reading = 0 my_new_car.read_odometer() # 9.2.3 修改属性的值 print("9.2.3") my_new_car.odometer_reading = 23 my_new_car.read_odometer() # 通过方法修改属性的值 my_new_car.update_odometer(30) my_new_car.read_odometer() # 通过方法对属性的值进行递增 my_new_car.increment_odometer(100) my_new_car.read_odometer() print("------动手试一试------") # 9-4 就餐人数 print("9-4") class Restaurant(): """docstring for Restaurant""" def __init__(self, restaurant_name, restaurant_type): self.name = restaurant_name self.type = restaurant_type self.number_served = 0 def describe_restaurant(self): print(self.name + ":" + self.type) def open_restaurant(self): print("Restaurant is OPEN!") def print_number_served(self): print("There are " + str(self.number_served) + " number served") def set_number_served(self, number): self.number_served = number def increment_number_serverd(self): self.number_served += 10 restaurant = Restaurant('ALAN', 'restaurant') restaurant.print_number_served() restaurant.number_served = 13 restaurant.print_number_served() restaurant.set_number_served(666) restaurant.print_number_served() restaurant.increment_number_serverd() restaurant.print_number_served() # 9-5 尝试登陆次数 print("9-5") class User(): """docstring for User""" def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.login_attempts = 0 def describe_user(self): print(self.first_name.title() + ' ' + self.last_name.title()) def greet_user(self): print("Hello! " + self.first_name.title() + ' ' + self.last_name.title()) def increment_login_attempts(self): self.login_attempts += 1 def reset_login_attempts(self): self.login_attempts = 0 def print_login_attempts(self): print("Login attempts are " + str(self.login_attempts)) user_test = User('knight', 'Lee') user_test.print_login_attempts() user_test.increment_login_attempts() user_test.increment_login_attempts() user_test.print_login_attempts() user_test.reset_login_attempts() user_test.print_login_attempts()
print("第一次打印时读取整个文件:") with open('learning_python.txt') as file_object: print(file_object.read()) print("第二次打印时遍历文件对象:") with open('learning_python.txt') as file_object: for line in file_object: print(line.strip()) print("第三次打印时将各行存储在一个列表中, 再在with 代码块外打印它们") with open('learning_python.txt') as file_object: words_list = file_object.readlines() for word in words_list: print(word.strip())
filename = 'guest_book.txt' while True: name = input("Please input your name:\n") print("Hello! " + name) with open(filename,'a') as file_object: file_object.write(name + '\n')
# numero = int(input("Digite um numero: ")) # vai verificar a condicao while numero < 100: # caso a condicao seja verdadeira, o bloco abaixo sera executado print(f"\t {numero}") numero = numero + 1 # ao fim do bloco, volta para o inicio e verifica se a condicao ainda esta verdadeira print("PROGRAMA ENCERRADO!")
class SortingRobot: def __init__(self, l): """ SortingRobot takes a list and sorts it. """ self._list = l # The list the robot is tasked with sorting self._item = None # The item the robot is holding self._position = 0 # The list position the robot is at self._light = "OFF" # The state of the robot's light self._time = 0 # A time counter (stretch) def can_move_right(self): """ Returns True if the robot can move right or False if it's at the end of the list. """ return self._position < len(self._list) - 1 def can_move_left(self): """ Returns True if the robot can move left or False if it's at the start of the list. """ return self._position > 0 def move_right(self): """ If the robot can move to the right, it moves to the right and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. """ self._time += 1 if self._position < len(self._list) - 1: self._position += 1 return True else: return False def move_left(self): """ If the robot can move to the left, it moves to the left and returns True. Otherwise, it stays in place and returns False. This will increment the time counter by 1. """ self._time += 1 if self._position > 0: self._position -= 1 return True else: return False def swap_item(self): """ The robot swaps its currently held item with the list item in front of it. This will increment the time counter by 1. """ self._time += 1 # Swap the held item with the list item at the robot's position self._item, self._list[self._position] = self._list[self._position], self._item def compare_item(self): """ Compare the held item with the item in front of the robot: If the held item's value is greater, return 1. If the held item's value is less, return -1. If the held item's value is equal, return 0. If either item is None, return None. """ if self._item is None or self._list[self._position] is None: return None elif self._item > self._list[self._position]: return 1 elif self._item < self._list[self._position]: return -1 else: return 0 def set_light_on(self): """ Turn on the robot's light """ self._light = "ON" def set_light_off(self): """ Turn off the robot's light """ self._light = "OFF" def light_is_on(self): """ Returns True if the robot's light is on and False otherwise. """ return self._light == "ON" def sort(self): """ OLD PLAN I HAD ------------------ The robot is capable of moving left and right inside the list. The robot is capable of comparing an item he's holding vs the item he's looking at. The robot can swap items. The robot starts at position 0. Loop through the entire length of the list Pick up the item at position 0, then move right and compare the item you have to that item. If the item is larger than the one in the robot's hand, swap it. Go back through the list in the opposite direction, this time comparing in an opposite fashion if the item is smaller than the one in the robot's hand, swap it. ------------------------------------------- The robot starts at position 0. Pick up the initial item. While the robot can move right, move him right. If the item he has is larger, swap the item. At this point, there's actually "None" in the position behind. Move left, swap items with "None" (basically, the robot's hand is empty) Move back to the right, and swap "None" with the new card If the item has has is smaller, you want to place the card back down and pick up the new card: Move back to the left and "swap" the item with "None" Move back to the right and swap None with the new highest card Once the robot can not move right anymore, he is at the end of the array NEED A WAY TO TELL IF THE ROBOT HAS FINISHED MOVING ALL THE WAY RIGHT -- the robot's light The last item in the array will be a "None" because he just swapped with that position. Swap again with "None" so the robot's hand is empty. Move the robot all the way back to the beginning of the array While the robot can move left Move left until he can't move left anymore Reset the light RECURSION ------------------------------------------------ If the held item's value is greater, return 1. If the held item's value is less, return -1. If the held item's value is equal, return 0. If either item is None, return None. """ self.swap_item() # self.set_light_on() while self.can_move_right(): self.move_right() # self.set_light_on() if self.compare_item() == 1: self.set_light_on() self.swap_item() self.move_left() self.swap_item() self.move_right() self.swap_item() else: self.move_left() self.swap_item() self.move_right() self.swap_item() # continue # break else: self.swap_item() if self.light_is_on(): while self.can_move_left(): self.move_left() self.set_light_off() self.sort() # ACTS AS A RESET, BINGO # while self.can_move_right(): # self.move_right() # # print("Line 118: Moving right!") # if self.compare_item() == 1: # self.swap_item() # self.move_left() # self.swap_item() # self.move_right() # self.swap_item() # elif self.compare_item() == -1: # self.move_left() # self.swap_item() # self.move_right() # self.swap_item() # else: # while self.can_move_left(): # self.move_left() # # print("Line 133: Moving left!") # self.swap_item() # self.move_left() # if self.compare_item() == -1: # self.swap_item() # self.move_right() # self.swap_item() # self.move_left() # self.swap_item() # elif self.compare_item() == 1: # self.move_right() # self.swap_item() # self.move_left() # self.swap_item() # while self.can_move_left(): # self.move_left() # if self.compare_item() == -1: # self.swap_item() # self.move_right() # self.swap_item() # self.move_left() # self.swap_item() # elif self.can_move_left() == False and self.compare_item() == None: # break # elif self.compare_item() == 1: # self.move_left() # for i in (0, len(self._list)): # while self.can_move_right(): # self.move_right() # print(f"Line 117: Moving right!") # if self.compare_item() == -1: # self.swap_item() # else: # self.move_right() # while self.can_move_left(): # print(f"Line 125: Moving left!") # if self.compare_item() == 1: # self.swap_item() # self.move_left() # else: # self.move_left() # self.set_light_on() # for i in (0, len(self._list)): # while self.light_is_on(): # while self.can_move_right(): # self.move_right() # print(f"Line 117: Moving right!") # if self.compare_item() == -1: # self.swap_item() # else: # self.move_right() # while self.can_move_left(): # print(f"Line 125: Moving left!") # if self.compare_item() == 1: # self.swap_item() # self.move_left() # elif self.can_move_left() == False and self.compare_item() == None: # self.set_light_off() # else: # self.move_left() # self.set_light_off() # l = [15, 41, 58, 49, 26, 4, 28, 8, 61, 60, 65, 21, 78, 14, 35, 90, 54, 5, 0, 87, 82, 96, 43, 92, 62, 97, 69, 94, 99, 93, 76, 47, 2, 88, 51, 40, 95, 6, 23, 81, 30, 19, 25, 91, 18, 68, 71, 9, 66, 1, 45, 33, 3, 72, 16, 85, 27, 59, 64, 39, 32, 24, 38, 84, 44, 80, 11, 73, 42, 20, 10, 29, 22, 98, 17, 48, 52, 67, 53, 74, 77, 37, 63, 31, 7, 75, 36, 89, 70, 34, 79, 83, 13, 57, 86, 12, 56, 50, 55, 46] # robot = SortingRobot(l) # print(robot.can_move_right()) # print(robot.sort()) # print(robot._position) # print(robot._item) # print(robot._list) if __name__ == "__main__": # Test our your implementation from the command line # with `python robot_sort.py` l = [15, 41, 58, 49, 26, 4, 28, 8, 61, 60, 65, 21, 78, 14, 35, 90, 54, 5, 0, 87, 82, 96, 43, 92, 62, 97, 69, 94, 99, 93, 76, 47, 2, 88, 51, 40, 95, 6, 23, 81, 30, 19, 25, 91, 18, 68, 71, 9, 66, 1, 45, 33, 3, 72, 16, 85, 27, 59, 64, 39, 32, 24, 38, 84, 44, 80, 11, 73, 42, 20, 10, 29, 22, 98, 17, 48, 52, 67, 53, 74, 77, 37, 63, 31, 7, 75, 36, 89, 70, 34, 79, 83, 13, 57, 86, 12, 56, 50, 55, 46] robot = SortingRobot(l) robot.sort() print(robot._list)
from pyspark.sql import SparkSession from pyspark.sql.functions import explode, col def count_per_skill(df): """ :param df: dataframe with schema: [name: string, technical_skills: array<string>] :return : dataframe with two columns - 1) skill name, 2) distinct # of people who have that skill """ # Write function logic here skills_count = (df.select( col("name"), explode(col("technical_skills")).alias("skill_name") ).groupBy("skill_name").agg({"name": "count"})) return skills_count if __name__ == '__main__': spark = SparkSession.builder.appName("pyspark-example-app").getOrCreate() input_df = spark.read.json("data") skills_count_df = count_per_skill(input_df) skills_count_df.write.csv("output_data")
""" Not in use when import outstanding_balance = float(raw_input("What is your outstanding balance? ")) annual_interest_rate = float(raw_input("What is your annual interest rate? ")) """ monthly_lower_bound = outstanding_balance / 12.0 # 12 is set because we are looking to pay this off in a year monthly_upper_bound = (outstanding_balance * (1 + (annual_interest_rate / 12.0)) ** 12.0) / 12.0 # (Balance * (1 + (Annual interest rate / 12.0)) ** 12.0) / 12.0 print "lower" + str(monthly_lower_bound) print "higher" + str(monthly_upper_bound) epsilon = .1 def paying_debt_year(outstanding_balance, monthly_lower_bound, monthly_upper_bound): previous_balance = outstanding_balance monthly_interest_rate = annual_interest_rate / 12.0 month = 0 # minimum_monthly_payment minimum_monthly_payment = (monthly_upper_bound + monthly_lower_bound) / 2.0 while previous_balance > epsilon: month += 1 updated_balance_each_month = previous_balance * (1 + monthly_interest_rate) - minimum_monthly_payment previous_balance = updated_balance_each_month if month >= 12: break if abs(previous_balance) > epsilon: if previous_balance > 0: monthly_lower_bound = minimum_monthly_payment paying_debt_year(outstanding_balance, monthly_lower_bound, monthly_upper_bound) elif previous_balance < 0: monthly_upper_bound = minimum_monthly_payment paying_debt_year(outstanding_balance, monthly_lower_bound, monthly_upper_bound) else: if previous_balance > 0: monthly_lower_bound = minimum_monthly_payment paying_debt_year(outstanding_balance, monthly_lower_bound, monthly_upper_bound) else: print "********** RESULTS **********" print "Monthly payment to pay off debt in 1 year: " + str(minimum_monthly_payment) print "Number of months needed: " + str(month) print "Balance: " + str(updated_balance_each_month) paying_debt_year(outstanding_balance, monthly_lower_bound, monthly_upper_bound)
out_file = open("name.txt", "w") name = input("What is thy name? ") print(name, file=out_file) out_file.close() in_file = open("name.txt", "r") name = in_file.read().strip() print("your name is ", name) in_file.close() in_file = open("numbers.txt", "r") line1 = int(in_file.readline()) line2 = int(in_file.readline()) print(line1 + line2) in_file.close() # Quick Program 3 extended - sum of all numbers in_file = open("numbers.txt", "r") total = 0 for line in in_file: number = int(line) total += number print(total) in_file.close()
numbers = [3, 1, 4, 1, 5, 9, 2] print(numbers[0], "\n", numbers[-1], "\n", numbers[3], "\n", numbers[:-1], "\n", numbers[3:4], "\n", 5 in numbers, "\n", 7 in numbers, "\n", "3" in numbers, "\n", numbers + [6, 5, 3]) numbers[0] = "ten" numbers[-1] = 1 print(numbers[2:]) print(9 in numbers) print(numbers)
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixed line telephones in Bangalore. Fixed line numbers include parentheses, so Bangalore numbers have the form (080)xxxxxxx.) Part A: Find all of the area codes and mobile prefixes called by people in Bangalore. - Fixed lines start with an area code enclosed in brackets. The area codes vary in length but always begin with 0. - Mobile numbers have no parentheses, but have a space in the middle of the number to help readability. The prefix of a mobile number is its first four digits, and they always start with 7, 8 or 9. - Telemarketers' numbers have no parentheses or space, but they start with the area code 140. Print the answer as part of a message: "The numbers called by people in Bangalore have codes:" <list of codes> The list of codes should be print out one per line in lexicographic order with no duplicates. Part B: What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Print the answer as a part of a message:: "<percentage> percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore." The percentage should have 2 decimal digits """ def all_numbers_from_bangalore(call): prefix = set() for item in call: if "(080)" in item[0]: prefix.add(item[1]) return sorted(prefix) def landline_numbers(call): data = all_numbers_from_bangalore(call) landline = set() for item in data: if "(" in item: landline.add(item) return sorted(landline) def landline_number_prefix(call): data = list(landline_numbers(call)) prefix = set() for item in data: prefix.add(item[0:item.find(")")+1]) return sorted(prefix) def mobile_numbers(call): data = all_numbers_from_bangalore(call) mobile = [] for item in data: if "(0" not in item: mobile.append(item) return set(mobile) def mobile_number_prefix(call): data = list(mobile_numbers(call)) prefix = set() for item in data: prefix.add(item[0:4]) return sorted(prefix) def all_calls(call): landline = landline_number_prefix(call) mobile = mobile_number_prefix(call) new_list = landline + mobile str1 = "\n" str1 = str1.join(new_list) return "The numbers called by people in Bangalore have codes:\n{}".format(str1) def banglore_to_banglore(call): btob = 0 btoa = 0 for item in call: if "(080)" in item[0]: if "(080)" in item[1]: btob += 1 for item in call: if "(080)" in item[0]: btoa += 1 percentage = round(((btob/btoa)*100),2) return "{} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore."\ .format(percentage) # print(all_numbers_from_banagalore(calls)) # print(landline_numbers(calls)) # print(landline_number_prefix(calls)) # print(mobile_numbers(calls)) # print(mobile_number_prefix(calls)) print(all_calls(calls)) print(banglore_to_banglore(calls))
def mean(mylist): the_mean = sum(mylist) / len(mylist) return the_mean print(mean([1, 4, 5])) print(type(mean), type(sum)) #Type of > <class 'function'> <class 'builtin_function_or_method'>
# LinearRegression is a machine learning library for linear regression from sklearn.linear_model import LinearRegression # pandas and numpy are used for data manipulation import pandas as pd import numpy as np # matplotlib and seaborn are used for plotting graphs import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') # yahoo finance is used to fetch data import yfinance as yf # Read data Df = yf.download('GC=F', '2000-01-01', '2021-02-15', auto_adjust=True) #GC=F = gold #BTC-USD = btc #USDT = USDT-USD # Only keep close columns Df = Df[['Close']] # Drop rows with missing values Df = Df.dropna() # Plot the closing price of GLD Df.Close.plot(figsize=(20, 14),color='r') plt.ylabel("Gold ETF Prices") plt.title("Gold ETF Price Series") plt.show() # Define explanatory variables Df['S_3'] = Df['Close'].rolling(window=3).mean() Df['S_9'] = Df['Close'].rolling(window=9).mean() Df['next_day_price'] = Df['Close'].shift(-1) Df = Df.dropna() X = Df[['S_3', 'S_9']] # Define dependent variable y = Df['next_day_price'] print('nexdayprice') print(y) # Split the data into train and test dataset t = .8 t = int(t*len(Df)) # Train dataset X_train = X[:t] y_train = y[:t] # Test dataset X_test = X[t:] y_test = y[t:] print('train') # Create a linear regression model linear = LinearRegression().fit(X_train, y_train) print("Linear Regression model") print("Gold ETF Price (y) = %.2f * 3 Days Moving Average (x1) \ + %.2f * 9 Days Moving Average (x2) \ + %.2f (constant)" % (linear.coef_[0], linear.coef_[1], linear.intercept_)) print('endtrain') # Predicting the Gold ETF prices predicted_price = linear.predict(X_test) predicted_price = pd.DataFrame( predicted_price, index=y_test.index, columns=['price']) predicted_price.plot(figsize=(20, 14)) y_test.plot() plt.legend(['predicted_price', 'actual_price']) plt.ylabel("Gold ETF Price") plt.show() print('show grapth2') # R square r2_score = linear.score(X[t:], y[t:]) float("{0:.2f}".format(r2_score)) print('r2score') print(r2_score) gold = pd.DataFrame() gold['price'] = Df[t:]['Close'] gold['predicted_price_next_day'] = predicted_price gold['actual_price_next_day'] = y_test gold['gold_returns'] = gold['price'].pct_change().shift(-1) gold['signal'] = np.where(gold.predicted_price_next_day.shift(1) < gold.predicted_price_next_day,1,0) gold['strategy_returns'] = gold.signal * gold['gold_returns'] ((gold['strategy_returns']+1).cumprod()).plot(figsize=(20,14),color='g') plt.ylabel('Cumulative Returns') plt.show() print('show signal') 'Sharpe Ratio %.2f' % (gold['strategy_returns'].mean()/gold['strategy_returns'].std()*(252**0.5)) data = yf.download('GC=F', '2000-01-01', '2021-02-15', auto_adjust=True) data['S_3'] = data['Close'].rolling(window=3).mean() data['S_9'] = data['Close'].rolling(window=9).mean() data = data.dropna() XX = data[['S_3', 'S_9']] data['predicted_gold_price'] = linear.predict(XX) data['signal'] = np.where(data.predicted_gold_price.shift(1) < data.predicted_gold_price,"Buy","No Position") data.to_csv('dataframe.csv') #data.tail(7)
#!/usr/bin/python # # Script to fetch indices from user and store it in encrypted form in /etc/user_indices # import fileinput from M2Crypto import * import sys import base64 username = raw_input('Enter a username: ') indices = raw_input('Enter indices (space separated): ') try: indices_list = indices.split(" ") if (len(indices_list) == 0) or (len(indices_list) == 1): print("Invalid indices, please use spaces to separate them") sys.exit(1) for index in indices_list: int_value = int(index, 10) except: print("Invalid indices, please use spaces to separate them") sys.exit(1) indices_cs = ",".join(indices.split()) user_str = "%s = %s" % (username, indices_cs) priv = RSA.load_key("/etc/auth_private_key.pem") pub = RSA.load_pub_key("/etc/auth_public_key.pem") data_fd = open("/etc/user_indices", "rw+") enc_data = data_fd.read() file_was_empty = 0 if enc_data == "": ctxt = pub.public_encrypt(user_str, RSA.pkcs1_oaep_padding) data_fd.write(ctxt.encode('base64')) file_was_empty = 1 else: dec_data = base64.b64decode(enc_data) dec_content = priv.private_decrypt(dec_data, RSA.pkcs1_oaep_padding) if file_was_empty == 1: sys.exit(0) else: user_indices_dict = {} for line in dec_content.split("\n"): try: (user, indices_str) = line.split("=") except ValueError: pass user = user.strip() indices_str = indices_str.strip() user_indices_dict[user] = indices_str user_indices_dict[username] = indices_cs data_fd.close() open("/etc/user_indices", "rw").close() data_fd = open("/etc/user_indices", "rw+") to_write = "" for key in user_indices_dict: to_write = to_write + "%s = %s\n" % (key, user_indices_dict[key]) ctxt = pub.public_encrypt(to_write, RSA.pkcs1_oaep_padding) data_fd.write(ctxt.encode('base64')) data_fd.close()
# Simple Linear Regression # Importing the Libraries import numpy as np import matplotlib.pyplot as plt # Co-Efficient estimation Function def estimate_coefficent(x,y): x_size = np.size(x) mean_x, mean_y = np.mean(x), np.mean(y) SS_xy = np.sum(y*x - x_size*mean_y*mean_x) SS_xx = np.sum(x*x - x_size*mean_x*mean_x) coeff_b_1 = SS_xy / SS_xx coeff_b_0 = mean_y - coeff_b_1*mean_x return (coeff_b_0, coeff_b_1) # Function to plot the regression Line def plot_regressor_line(x, y, b): plt.scatter(x, y, color = "m", marker = "x", s = 20) y_pred = b[0] + b[1]*x print(y_pred) plt.plot(x, y_pred, color = 'g') plt.xlabel('x') plt.ylabel('y') plt.show() # Prediction Function which takes Value and predict by using our calculated coefficients def pred_value(val, b): ypred = b[0] + b[1]*val return ypred if __name__ == "__main__": # Series of data point. This could be taken from csv file by reading and making a dataframe X = np.array([0,1,2,3,4,5,6,7,8,9]) y = np.array([0,2,4,6,8,10,12,14,16,18]) # Calculating the coefficients b = estimate_coefficent(X,y) # checking the coefficient values print('Co-efficient B0: ',b[0]) print('Co-efficient B1: ',b[1]) # Visualizing Regression Line with the data points plot_regressor_line(X, y, b) # Predicting another data point entered by user value = int(input('Enter index to predict:')) pred_val = pred_value(value, b) print(pred_val)
# Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. a = 1 b = 2 c = 3 d = a + (b * c) print(a, b, c, d) name = input('Введите Ваше имя: ') name = 'Привет ' + name + '! Меня зовут Альберт!' print(name) case = input('Сколько тебе лет? ') case = 'Мне тоже ' + case print(case)
# -*- coding: utf-8 -*- class Location: def __init__(self, location=0): self._location = location def get(self): return self._location def set(self, new_location): self._location = new_location def decrease(self, delta=1): self._location -= delta def increase(self, delta=1): self._location += delta def __str__(self): return self.__repr__() def __repr__(self): return str(self._location) class LocationRange: def __init__(self, start=0, end=0): self._start = Location(start) self._end = Location(end) def get_start(self): return self._start def get_end(self): return self._end def get_left(self): return self._start if self._start.get() <= self._end.get() else self._end def get_right(self): return self._start if self._start.get() > self._end.get() else self._end def __str__(self): return self.__repr__() def __repr__(self): return "(" + str(self._start) + "," + str(self._end) + ")" def is_empty(self): return self._start.get() == self._end.get() def clone(self): return LocationRange(self._start.get(), self._end.get())
# -*- coding: utf-8 -*- import requests import keys import constants from objects import Location # This function get the latitude and longitude of an address through Google Geocoding API. # Return an object with the address, latitude and longitude. # https://developers.google.com/maps/documentation/geocoding/start def geocoding(location_address): payload = { "address" : location_address, "key" : keys.GOOGLEAPI_KEY, "language" : "es", "region" : "es", "components" : "country:ES" } r = requests.get(url=constants.GEOCODEAPI_URL, params=payload) response = r.json() if response["status"] == "OK": lat = response["results"][0]["geometry"]["location"]["lat"] lng = response["results"][0]["geometry"]["location"]["lng"] address = response["results"][0]["formatted_address"] else: address = '' lat = 0 lng = 0 loc = Location(address, lat, lng) return loc # This function get the weather of an address through DarkSky API. # The API only works with the coordinates (latitude and longitude) for this reason its necessary use the geocoding function. # https://darksky.net/dev/docs#forecast-request def weather(location_query): location = geocoding(location_query) if len(location.address) != 0: latlong = str(location.latitude) + str(",") + str(location.longitude) url = constants.DARKSKYAPI_URL.format(keys.DARKSKY_KEY, latlong) payload = { "lang" : "es", "units" : "si", "exclude" : "minutely, hourly, daily" } r = requests.get(url=url, params=payload) response = r.json() #print r.url #print r.text print response['currently']['summary'] print response['currently']['temperature'] print response['currently']['precipProbability'] else: response = '' return response def weatherY(location): url = "https://query.yahooapis.com/v1/public/yql?" query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='{}') and u='c'" params = { "q" : query.format(location), "format" : "json" } r = requests.get(url=url, params=params) response = r.json() print r.url print r.text print '\n' location = response['query']['results']['channel']['location'] if __name__ == "__main__": weather('totana')
num = float(input("Enter number\n")) intPart = num - (num % 1) tmpInt = intPart tmp = num while int(tmp) != tmp: tmp *= 10 tmpInt *= 10 floatPart = int(tmp - tmpInt) print(floatPart) def reverse(num): ret = 0 while num >= 1: ret *= 10 ret += num % 10 num //= 10 return ret floatPart = reverse(floatPart) intPart = reverse(intPart) while intPart >=1: intPart /= 10 print(str(floatPart + intPart))
import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression import constants as c class RegressionHandler: """ This class encapsulates the logic for calculating and plotting a linear regression. """ @staticmethod def plot_regression(dataframe, sex=c.Sex.MALE): """ Plot a linear regression with the GDP per capita being the X-variable and the mean height the Y-variable. :param dataframe: dataframe containing the data to plot :param sex: either MALE (0) or FEMALE (1) - specifies the sex for which the given dataframe contains data :return: nothing """ # sort by GDP/capita so that plot can use logarithmic scale dataframe = dataframe.sort_values([c.GDP], 0) sex_label = 'males' if sex == c.Sex.MALE else 'females' X = dataframe.loc[:, c.GDP].values.reshape(-1, 1) # values converts it into a numpy array Y = dataframe.loc[:, c.AVG_HEIGHT].values.reshape(-1, 1) # -1 means that calculate the dimension of rows, but have 1 column linear_regressor = LinearRegression() # create object for the class linear_regressor.fit(X, Y) # perform linear regression Y_pred = linear_regressor.predict(X) # make predictions plt.scatter(X, Y) plt.plot(X, Y_pred, color='red') plt.xscale('log') plt.xlabel('GDP per capita [USD]') plt.ylabel('average height of {0} aged 19 [cm]'.format(sex_label)) plt.savefig('out/regression_{0}.png'.format(sex_label)) plt.show()
def largestPerimeter(nums) -> int: def is_triangle_valid(nums0, nums1, nums2): valid = True if nums0 >= nums1 + nums2: valid = False elif nums1 >= nums2 + nums0: valid = False elif nums2 >= nums1 + nums0: valid = False return valid nums.sort() max_perimeter = 0 for i in range(0, len(nums)-2): if is_triangle_valid(nums[i], nums[i + 1], nums[i + 2]): perimeter = nums[i] + nums[i + 1] + nums[i + 2] print(perimeter) max_perimeter = max(perimeter, max_perimeter) return max_perimeter print(largestPerimeter([3,2,3,4]))
# https://leetcode.com/problems/word-search-ii/ def word_search_2(grid, words): R = len(grid) C = len(grid[0]) found_list = [] for word in words: print(f"finding {word}") found = "" i = 0 j = 0 k = 0 while 0 <= i < R and 0 <= j < C and k < len(word): if grid[i][j] == word[k]: found += word[k] elif grid[i + 1][j] == word[k]: i += 1 found += word[k] elif grid[i][j + 1] == word[k]: j += 1 found += word[k] # elif grid[i - 1][j] == word[k]: # i -= 1 # found += word[k] # elif grid[i][j - 1] == word[k]: # j -= 1 # found += word[k] k += 1 print(found) if found in words: found_list.append(found) print(found_list) # board = [["o", "a", "a", "n"], ["e", "t", "a", "e"], ["i", "h", "k", "r"], ["i", "e", "a", "t"]] # words = ["oath", "pea", "eat", "rain"] # word_search(board, words) def word_search(grid, word): found = False visited = [] visited_set = set() R = len(grid) C = len(grid[0]) def dfs(i, j, k, visited, visited_set, found): if i < 0 or i >= R or j < 0 or j >= C or word[k] != grid[i][j] or (i, j) in visited_set or not found: return if k == len(word): return True visited += [(i, j)] visited_set.add((i, j)) dirs = [(0, 1), (-1, 0), (1, 0), (0, -1)] for r, c in dirs: X = i + r Y = j + c dfs(X, Y, k + 1, visited, visited_set, found) if not found: visited_set.remove(visited.pop()) for i in range(R): for j in range(C): return dfs(i, j, 0, visited, visited_set, found) return False # if word_search(board, "oath"): # print("true") # else: # print("false") def word_search_1(board, word): R = len(board) C = len(board[0]) def dfs(i, r, c): if i == len(word): return True if 0 <= r < R and 0 <= c < C and board[r][c] == word[i]: board[r][c] = '#' d1 = dfs(i + 1, r + 1, c) d2 = dfs(i + 1, r - 1, c) d3 = dfs(i + 1, r, c + 1) d4 = dfs(i + 1, r, c - 1) board[r][c] = word[i] return any([d1, d2, d3, d4]) return False for j in range(R): for k in range(C): if board[j][k] == word[0] and dfs(0, j, k): return True return False board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]] word = "ABFD" if word_search_1(board, word): print(True) else: print(False)
# -*- coding: utf-8 -*- """ Created on Mon Aug 19 22:22:27 2019 @author: jayada1 Consider a game where a player can score 3 or 5 or 10 points in a move. Given a total score n, find number of distinct combinations to reach the given score. Input: The first line of input contains an integer T denoting the number of test cases. T testcases follow.The first line of each test case is n. Output: For each testcase, in a new line, print number of ways/combinations to reach the given score. """ #code t = int(input()) def find_ways(n): a = [0 for i in range(n+1)] a[0] = 1 for i in range(3,n+1): a[i] += a[i-3] for i in range(5,n+1): a[i] += a[i-5] for i in range(10,n+1): a[i] += a[i-10] print(a[n]) while t>0: n = int(input()) find_ways(n) t -= 1 word_dict = dict() l = list() l.append(1) l.pop(2)
def insert_char_at_all_positions(char, perm_list): res = [] for perm in perm_list: n = len(perm) for i in range(n + 1): new_perm = perm[:i] + char + perm[i:] if new_perm not in res: res.append(new_perm) return res def generate_all_permutations(str1, n): if n == 0: return [str1[n]] p = insert_char_at_all_positions(str1[n], generate_all_permutations(str1, n - 1)) return p all_perm = generate_all_permutations('abcdd', len('abcdd') - 1) print(all_perm) print(len(all_perm)) # recursively find the permutations for bigger inputs. # we start with a P(a) = [a] # P(ab) = [ab, ba] # P(abc) = [cab, acb, abc] + [cba, bca, bac] # P(n) = Generate strings by appending the nth char at all positions of P(n-1)
# -*- coding: utf-8 -*- """ Created on Sat Aug 3 13:04:06 2019 @author: jayada1 """ """ Given an MxN matrix, find the number of ways of reaching bottom right element from top left element only right and down movements allowed. """ #Solution 1: Recursion def numpaths(m,n): if m==1 or n==1: return 1 else: return numpaths(m-1,n) + numpaths(m,n-1) print(numpaths(3,3)) #Solution 2: Dynamic programming def numpaths_dp(m,n): count = [[0 for i in range(n)] for j in range(m)] for i in range(1,n): count[0][i] = 1 for i in range(1,m): count[i][0] = 1 for i in range(1,m): for j in range (1,n): count[i][j] = count[i-1][j] + count[i][j-1] return count[m-1][n-1] print(numpaths_dp(3,3))