blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
05d3835f466737814bb792147e8d7b34a28d912f | qiqi06/python_test | /python/static_factory_method.py | 1,038 | 4.1875 | 4 | #-*- coding: utf-8 -*-
"""
练习简单工厂模式
"""
#建立一工厂类,要用是,再实例化它的生产水果方法,
class Factory(object):
def creatFruit(self, fruit):
if fruit == "apple":
return Apple(fruit, "red")
elif fruit == "banana":
return Banana(fruit, "yellow")
class Fruit(object):
def __init__(self, name, color):
self.color = color
self.name = name
def grow(self):
print "%s is growing" %self.name
class Apple(Fruit):
def __init__(self, name, color):
super(Apple, self).__init__(name, color)
class Banana(Fruit):
def __init__(self, name, color):
super(Banana, self).__init__(name, color)
self.name = 'banana'
self.color = 'yellow'
def test():
#这里是两个对象, 一个是工厂,一个是我要订的水果
factory = Factory()
my_fruit = factory.creatFruit('banana')
my_fruit.grow()
if __name__ == "__main__":
print "The main module is running!"
test() |
bf1579ed5e6abab53aa502637d8be30591fef51a | sdurgut/ToyProjects | /NetflixMovieRecommendationSystem/testProject2Phase1a.py | 2,066 | 3.59375 | 4 | '''
>>> userList = createUserList()
>>> len(userList)
943
>>> userList[10]["occupation"]
'other'
>>> sorted(userList[55].values())
[25, '46260', 'M', 'librarian']
>>> len([x for x in userList if x["gender"]=="F"])
273
>>> movieList = createMovieList()
>>> len(movieList)
1682
>>> movieList[27]["title"]
'Apollo 13 (1995)'
>>> movieList[78]["title"].split("(")[0]
'Fugitive, The '
>>> sorted(movieList[1657].values())
[[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], '', '06-Dec-1996', 'Substance of Fire, The (1996)', 'http://us.imdb.com/M/title-exact?Substance%20of%20Fire,%20The%20(1996)']
>>> numUsers = len(userList)
>>> numMovies = len(movieList)
>>> rawRatings = readRatings()
>>> rawRatings[:2]
[(196, 242, 3), (186, 302, 3)]
>>> len(rawRatings)
100000
>>> len([x for x in rawRatings if x[0] == 1])
272
>>> len([x for x in rawRatings if x[0] == 2])
62
>>> sorted([x for x in rawRatings if x[0] == 2][:11])
[(2, 13, 4), (2, 50, 5), (2, 251, 5), (2, 280, 3), (2, 281, 3), (2, 290, 3), (2, 292, 4), (2, 297, 4), (2, 303, 4), (2, 312, 3), (2, 314, 1)]
>>> [x for x in rawRatings if x[1] == 1557]
[(405, 1557, 1)]
>>> [rLu, rLm] = createRatingsDataStructure(numUsers, numMovies, rawRatings)
>>> len(rLu)
943
>>> len(rLm)
1682
>>> len(rLu[0])
272
>>> min([len(x) for x in rLu])
20
>>> min([len(x) for x in rLm])
1
>>> sorted(rLu[18].items())
[(4, 4), (8, 5), (153, 4), (201, 3), (202, 4), (210, 3), (211, 4), (258, 4), (268, 2), (288, 3), (294, 3), (310, 4), (313, 2), (319, 4), (325, 4), (382, 3), (435, 5), (655, 3), (692, 3), (887, 4)]
>>> len(rLm[88])
275
>>> movieList[88]["title"]
'Blade Runner (1982)'
>>> rLu[10][716] == rLm[715][11]
True
>>> commonMovies = [m for m in range(1, numMovies+1) if m in rLu[0] and m in rLu[417]]
>>> commonMovies
[258, 269]
>>> rLu[0][258]
5
>>> rLu[417][258]
5
>>> rLu[0][269]
5
>>> rLu[417][269]
5
'''
#-------------------------------------------------------
from project2Phase1a import *
#-------------------------------------------------------
if __name__ == "__main__":
import doctest
doctest.testmod()
|
c056c7e6e90f54a6a42b7a7d5c408c749debffed | michaszo18/python- | /serdnio_zaawansowany/sekcja_1/funkcja_id_operator_is.py | 1,399 | 4 | 4 | a = "hello world"
b = a
print(a is b)
print(a == b)
print(id(a), id(b))
b += "!"
print(a is b)
print(a == b)
print(id(a), id(b))
b = b[:-1]
print(a is b)
print(a == b)
print(id(a), id(b))
a = 1
b = a
print(a is b)
print(a == b)
print(id(a), id(b))
b += 1
print(a is b)
print(a == b)
print(id(a), id(b))
b -= 1
print(a is b)
print(a == b)
print(id(a), id(b))
# Wniosek - int w pythonie przehowowany są pod tym samym adresem (optymalizator pythona), a string po zmianie
# Zadanie
print("\n\n#################################\n\n")
a = b = c = 10
print(a, id(a))
print(b, id(b))
print(c, id(c))
a = 20
print(a, id(a))
print(b, id(b))
print(c, id(c))
print("\n\n#################################\n\n")
a = b = c = [1, 2, 3]
print(a, id(a))
print(b, id(b))
print(c, id(c))
a.append(4)
print(a, id(a))
print(b, id(b))
print(c, id(c))
"""
W pierwszym przykładzie a, b, c były wskaźnikami do komórki pamięci, w której była zapisana liczba, czyli końcowa wartość.
W drugim przykładzie a, b, c to wskaźnik do komórki pamięci, w której jest lista. Lista jest wskaźnikiem do elementów tej listy.
Kiedy dodajesz nowy element do listy, nie modyfikujesz podstawowej komórki pamięci z listą, dlatego id się nie zmienił.
"""
print("\n\n#################################\n\n")
x = 10
y = 10
print(x, id(x))
print(y, id(y))
y = y + 1234567890 - 1234567890
print(x, id(x))
print(y, id(y)) |
f98a82205815d1acef54f565f03bfafe1df4f0aa | mertcankurt/temizlik_robotu_simulasyonu | /evarobotmove_gazebo/scripts/Interface/Database.py | 583 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
def createTable():
connection = sqlite3.connect('login.db')
connection.execute("CREATE TABLE USERS(USERNAME TEXT NOT NULL,EMAIL TEXT,PASSWORD TEXT)")
connection.execute("INSERT INTO USERS VALUES(?,?,?)",('motar','motar@gmail.com','motar'))
connection.commit()
result = connection.execute("SELECT * FROM USERS")
for data in result:
print("Username : ",data[0])
print("Email : ",data[1])
print("Password :",data[2])
connection.close()
createTable()
|
478ea10daafffde5120ff8962eba92c173cd1ade | nosy0411/Object_Oriented_Programming | /homework2/example.py | 285 | 3.546875 | 4 | # import turtle
# # t=turtle.Turtle()
# # for i in range(5):
# # t.forward(150)
# # t.right(144)
# # turtle.done()
# spiral = turtle.Turtle()
# for i in range(20):
# spiral.forward(i*20)
# spiral.right(144)
# turtle.done()
# import turtle
# pen = turtle.Turtle()
|
e3c32038f58505113c4477596d1708390c510d98 | dgriffis/autocomplete | /MyAutoComplete.py | 3,298 | 4.15625 | 4 | #!/usr/bin/env python
import sys
class Node:
def __init__(self):
#establish node properties:
#are we at a word?
self.isaWord = False
#Hash that contains all of our keys
self.keyStore = {}
def add_item(self, string):
#Method to build out Trie
#This is done using recursive call
#Method entry to check for end of recursion
if len(string) == 0:
#We are adding full words so if the string len is now 0 then
#we are at a word marker - set the bool and get out
self.isaWord = True
return
#Now check to see if key exists and react accordingly
key = string[0] #key is the first character
string = string[1:] #and the string will be one less
if self.keyStore.has_key(key):
self.keyStore[key].add_item(string) #if the key exists then recurse
else:
node = Node() #create a new node
self.keyStore[key] = node #set the node into the keyStore
node.add_item(string) #recurse
def traverseTrie(self, foundWords=""):
# traverse the trie from this point on looking for words
#if we're at the end of the hash then print out what we have and return
if self.keyStore.keys() == []:
print 'A match is',foundWords
return
#or if we are at a word then print that but but also continue
#to traverse the trie looking for more words that start with our input string
if self.isaWord == True:
print 'A match is',foundWords
for key in self.keyStore.keys():
self.keyStore[key].traverseTrie(foundWords+key)
def search(self, string, foundWords=""):
#Method to traverse the trie and match and wildcard match the given string
#This is a recursive method
#Method entry check
if len(string) > 0 : #start gathering characters
key = string[0] #get our key
string = string[1:] #reduce the string length
if self.keyStore.has_key(key):
foundWords = foundWords + key
self.keyStore[key].search(string, foundWords)
else:
print 'No Match'
else:
if self.isaWord == True:
print 'A match is',foundWords
#Now we need to traverse the rest of the trie for wildcard matchs (word*)
for key in self.keyStore.keys():
self.keyStore[key].traverseTrie(foundWords+key)
def fileparse(filename):
'''Parse the input dictionary file and build the trie data structure'''
fd = open(filename)
root = Node()
line = fd.readline().strip('\r\n') # Remove newline characters \r\n
while line !='':
root.add_item(line)
line = fd.readline().strip('\r\n')
return root
if __name__ == '__main__':
#read in dictionary
#set root Node
#do search
myFile = 'dictionary.txt'
#root = fileparse(sys.argv[1])
root = fileparse(myFile)
#input=raw_input()
input = "win"
print "Input:",input
root.search(input) |
deae850e32102c9f22d108c817cfd69eebd4344f | szzhe/Python | /ActualCombat/TablePrint.py | 854 | 4.28125 | 4 | tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
# 要求输出如下:
# apples Alice dogs
# oranges Bob cats
# cherries Carol moose
# banana David goose
def printTable(data):
str_data = ''
col_len = []
for row in range(0, len(data[0])): # row=4
for col in range(0, len(data)): # col=3
col_len.append(len(data[col][row]))
max_col_len = max(col_len)
print("列表各元素长度为:", col_len)
print("列表中最大值为:", max_col_len) # 8
for row in range(0, len(data[0])):
for col in range(0, len(data)):
print(data[col][row].rjust(max_col_len), end='')
print()
return str_data
f_data = printTable(tableData)
print(f_data)
|
54033a39aaf84badb53bb8266b6f882ca5d5a96c | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /Grocery_List/main.py | 697 | 3.8125 | 4 | def remove_smallest(numbers):
y = numbers
if len(numbers) == 0:
return y , NotImplementedError("Wrong result for {0}".format(numbers))
y = numbers
y.remove(min(numbers))
return y, NotImplementedError("Wrong result for {0}".format(numbers))
print(remove_smallest([1, 2, 3, 4, 5])) # , [2, 3, 4, 5], "Wrong result for [1, 2, 3, 4, 5]")
print(remove_smallest([5, 3, 2, 1, 4])) # , [5, 3, 2, 4], "Wrong result for [5, 3, 2, 1, 4]")
print(remove_smallest([1, 2, 3, 1, 1])) # , [2, 3, 1, 1], "Wrong result for [1, 2, 3, 1, 1]")
print(remove_smallest([])) # [], "Wrong result for []"
def remove_smallest(numbers):
raise NotImplementedError("Wrong result for {0}")
|
91308a237cd5b5ac06c0c26d67f8dd1795819687 | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /BinaryHexadecimalConversion/main.py | 1,164 | 4.03125 | 4 | print("\n:: Welcome to the Binary/Hexadecimal Converter App ::")
computeCounter = int(input("\nCompute binary and hexadecimal value up to the following decimal number: "))
dataLists = []
for nums in range(computeCounter+1):
dataLists.append([nums, bin(nums), hex(nums)])
print(":: Generating Lists....complete! ::")
start = int(input("\nWhat decimal number would you like to start at? "))
stop = int(input("What decimal number would you like to stop at? "))
print("\nDecimal values from {0} to {1}".format(start, stop))
for nums in range(start, stop+1):
print(dataLists[nums][0])
print("\nBinary values from {0} to {1}".format(start, stop))
for nums in range(start, stop+1):
print(dataLists[nums][1])
print("\nHexadecimal values from {0} to {1}".format(start, stop))
for nums in range(start, stop+1):
print(dataLists[nums][2])
# Remove item 0
dataLists.pop(0)
x = input("\nPress Enter to see all values from 1 to {0}.".format(computeCounter))
print("\nDecimal ---- Binary ---- Hexadecimal")
print("-----------------------------------------------")
for nums in dataLists:
print('{0} --- {1} --- {2}'.format(nums[0], nums[1], nums[2])) |
30ad077dc68f5b4f369d146dd278be4d69c89fa9 | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /GuessMyNumberApp/main.py | 879 | 4.09375 | 4 | from random import randint
print(":: Welcome to the Guess My Number App ::\n")
name = input("Please input your name:\n")
number = randint(1, 20)
print("We the computer are thinking of a number between 1 - 20")
print("You have 5 tries to guess the number before we blow you up. Choose wisely\n")
for x in range(1,6):
guess = int(input("What is your guess number {0}?\n".format(x)))
if guess == number:
print("Well done {0} you get to live.\n".format(name))
break
elif x == 5:
print("You guessed wrong 5 times, to the processing plant with {0}\n".format(name))
else:
if guess > number:
print("Your guess is {0}, its to high.\n".format(guess))
else:
print("Your guess is {0}, its to low.".format(guess))
print("You have failed to guess right, you have {0} trie(s) left.".format(5-x))
|
52a4a2e5afcf1f190f75dc69e38ef404e392be79 | rudyardrichter/globus-automate-client | /globus_automate_client/cli/callbacks.py | 6,310 | 3.5625 | 4 | import json
import os
import pathlib
from typing import AbstractSet, List
from urllib.parse import urlparse
from uuid import UUID
import typer
import yaml
def url_validator_callback(url: str) -> str:
"""
Validates that a user provided string "looks" like a URL aka contains at
least a valid scheme and netloc [www.example.org].
Logic taken from https://stackoverflow.com/a/38020041
"""
if url is None:
return url
url = url.strip()
try:
result = urlparse(url)
if result.scheme and result.netloc:
return url
except:
pass
raise typer.BadParameter("Please supply a valid url")
def text_validator_callback(message: str) -> str:
"""
A user may supply a message directly on the command line or by referencing a
file whose contents should be interpreted as the message. This validator
determines if a user supplied a valid file name else use the raw text as the
message. Returns the text to be used as a message.
"""
# Reading from a file was indicated by prepending the filename with the @
# symbol -- for backwards compatability check if the symbol is present and
# remove it
if message.startswith("@"):
message = message[1:]
message_path = pathlib.Path(message)
if message_path.exists() and message_path.is_file():
with message_path.open() as f:
return f.read()
return message
def _base_principal_validator(
principals: List[str], *, special_vals: AbstractSet[str] = frozenset()
) -> List[str]:
"""
This validator ensures the principal IDs are valid UUIDs prefixed with valid
Globus ID beginnings. It will optionally determine if a provided principal
exists in a set of "special" values.
"""
groups_beginning = "urn:globus:groups:id:"
auth_beginning = "urn:globus:auth:identity:"
for p in principals:
if special_vals and p in special_vals:
continue
valid_beggining = False
for beggining in [groups_beginning, auth_beginning]:
if p.startswith(beggining):
uuid = p[len(beggining) :]
try:
UUID(uuid, version=4)
except ValueError:
raise typer.BadParameter(
f"Principal could not be parsed as a valid identifier: {p}"
)
else:
valid_beggining = True
if not valid_beggining:
raise typer.BadParameter(
f"Principal could not be parsed as a valid identifier: {p}"
)
return principals
def principal_validator(principals: List[str]) -> List[str]:
"""
A principal ID needs to be a valid UUID.
"""
return _base_principal_validator(principals)
def principal_or_all_authenticated_users_validator(principals: List[str]) -> List[str]:
"""
Certain fields expect values to be a valid Globus Auth UUID or one of a set
of special strings that are meaningful in the context of authentication.
This callback is a specialized form of the principal_validator where the
special value of 'all_authenticated_users' is accepted.
"""
return _base_principal_validator(
principals, special_vals={"all_authenticated_users"}
)
def principal_or_public_validator(principals: List[str]) -> List[str]:
"""
Certain fields expect values to be a valid Globus Auth UUID or one of a set
of special strings that are meaningful in the context of authentication.
This callback is a specialized form of the principal_validator where the
special value of 'public' is accepted.
"""
return _base_principal_validator(principals, special_vals={"public"})
def flows_endpoint_envvar_callback(default_value: str) -> str:
"""
This callback searches the caller's environment for an environment variable
defining the target Flow endpoint.
"""
return os.getenv("GLOBUS_AUTOMATE_FLOWS_ENDPOINT", default_value)
def input_validator_callback(body: str) -> str:
"""
Checks if input is a file and loads it, otherwise
returns the body string passed in
"""
# Callbacks are run regardless of whether an option was explicitly set.
# Handle the scenario where the default value for an option is empty
if not body:
return body
# Reading from a file was indicated by prepending the filename with the @
# symbol -- for backwards compatability check if the symbol is present and
# remove it
body = body.lstrip("@")
body_path = pathlib.Path(body)
if body_path.exists() and body_path.is_file():
with body_path.open() as f:
body = f.read()
elif body_path.exists() and body_path.is_dir():
raise typer.BadParameter("Expected file, received directory")
return body
def flow_input_validator(body: str) -> str:
"""
Flow inputs can be either YAML or JSON formatted
We can encompass these with just the YAML load checking,
but we need a more generic error message than is provided
by the other validators
"""
# Callbacks are run regardless of whether an option was explicitly set.
# Handle the scenario where the default value for an option is empty
if not body:
return body
# Reading from a file was indicated by prepending the filename with the @
# symbol -- for backwards compatability check if the symbol is present
# remove it if present
body = body.lstrip("@")
body_path = pathlib.Path(body)
if body_path.exists() and body_path.is_file():
with body_path.open() as f:
try:
yaml_body = yaml.safe_load(f)
except yaml.YAMLError as e:
raise typer.BadParameter(f"Invalid flow input: {e}")
elif body_path.exists() and body_path.is_dir():
raise typer.BadParameter("Expected file, received directory")
else:
try:
yaml_body = yaml.safe_load(body)
except yaml.YAMLError as e:
raise typer.BadParameter(f"Invalid flow input: {e}")
try:
yaml_to_json = json.dumps(yaml_body)
except TypeError as e:
raise typer.BadParameter(f"Unable to translate flow input to JSON: {e}")
return yaml_to_json
|
8c9bf8a07c5057a5b2bdd73f2b8a84d20b4b6b7d | CichonN/BikeRental | /BikeRental.py | 3,607 | 3.984375 | 4 | # ----------------------------------------------------------------------------------------------------------------------------------
# Assignment Name: Bicycle Shop
# Name: Neina Cichon
# Date: 2020-07-26
# ----------------------------------------------------------------------------------------------------------------------------------
#Declare Global Variables
rentHourly = 5.00
rentDaily = 20.00
rentWeekly = 60.00
discount = .3
bikeStock = 20
class Rental:
def __init__(self, rentalQty, rentalType):
self.rentalQty = rentalQty
self.rentalType = rentalType
#Get Rental type and Display Amount
def calcRental(self):
global bikeStock
if self.rentalQty <= 0:
raise Exception('Bike rental quantity must be greater than zero. You entered: {}'.format(self.rentalQty))
elif self.rentalQty > bikeStock:
print("We currently only have ", bikeStock, "bikes in stock.")
else:
if self.rentalType == 'hourly':
bikeStock -= self.rentalQty
global rentHourly
global rentAmount
rentAmount = rentHourly
return rentAmount
#Get Day/Time of Rental
elif self.rentalType == "daily":
bikeStock -= self.rentalQty
global rentDaily
rentAmount = rentDaily
#Get Day/Time of Rental
elif self.rentalType == "weekly":
bikeStock -= self.rentalQty
global rentWeekly
rentAmount = rentWeekly
return rentAmount
#Get Day/Time of Rental
else:
raise Exception('Rental Type was not "hourly", "daily", or "weekly". You entered: {}'.format(self.rentalType))
return rentalType
class Return:
def __init__(self, rentalQty, rentalType, rentalTime):
self.rentalQty = rentalQty
self.rentalType = rentalType
self.rentalTime = rentalTime
global bikeStock
bikeStock += rentalQty
#Process Return, add returned bikes to inventory, and display amount due
def calcReturn(self):
if self.rentalType == "daily":
global rentDaily
#Get Day/Time of Return
rentalAmount = (rentDaily * rentalTime) * rentalQty
elif self.rentalType == "weekly":
global rentWeekly
#Get Day/Time of Return
rentalAmount = (rentweekly * rentalTime) * rentalQty
else:
global rentHourly
#Get Day/Time of Return
rentalAmount = (rentHourly * rentalTime) * rentalQty
if rentalQty >= 3 and rentalQty <= 5:
print("Family Discount: $", (rentalAmount * discount))
amountDue = rentalAmount * (rentalAmount * discount)
return amountDue
else:
amountDue = rentalAmount
return amountDue
print("Amount Due: $", amountDue)
#-----------------------------------------------------
Rental1 = Rental(1, 'daily')
Rental2 = Rental(10, 'hourly')
Return1 = Return(1, "daily", 2)
#Return2 = Return(1, 2)
print( 'Qty of bikes in stock: ', (bikeStock))
#print("Renting", str(Rental.calcRental(rentalQty)), "bikes." "\nYou will be charged $", str(Rental.calcRental(rentAmount)), str(Rental(rentalType)), "for each bike.")
#print("Renting", Rental.calcRental(rentalQty), "bikes." "\nYou will be charged $", "per week for each bike.") |
63fbe3a8ecd0fd1716226f819458bc604a8faefe | dxfl/pywisdom | /try_one.py | 1,182 | 3.53125 | 4 | #!/usr/bin/env python3
'''
example adapted from stackoverflow:
https://stackoverflow.com/questions/26494211/extracting-text-from-a-pdf-file-using-pdfminer-in-python
'''
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
import io
import re
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = io.BytesIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 50 #max pages to process
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
fp.close()
device.close()
retstr.close()
return text
raw_text = convert_pdf_to_txt("DSCD-12-CO-203.PDF")
text = re.sub('\n+', '\n', raw_text.decode("utf-8", "ignore"))
print(text)
|
c6d84e1f238ac03e872eea8c8cb3566ac0913646 | Cpeters1982/DojoPython | /hello_world.py | 2,621 | 4.21875 | 4 | '''Test Document, leave me alone PyLint'''
# def add(a,b):
# x = a + b
# return x
# result = add(3, 5)
# print result
# def multiply(arr, num):
# for x in range(len(arr)):
# arr[x] *= num
# return arr
# a = [2,4,10,16]
# b = multiply(a,5)
# print b
'''
The function multiply takes two parameters, arr and num. We pass our arguments here.
for x in range(len(arr)) means
"for every index of the list(array)" and then "arr[x] *= num" means multiply
the indices of the passed in array by the value of the variable "num"
return arr sends arr back to the function
*= multiplies the variable by a value and assigns the result to that variable
'''
# def fun(arr, num):
# for x in range (len(arr)):
# arr[x] -= num
# return arr
# a = [3,6,9,12]
# b = fun(a,2)
# print b
'''
Important! The variables can be anything! Use good names!
'''
# def idiot(arr, num):
# for x in range(len(arr)):
# arr[x] /= num
# return arr
# a = [5,3,6,9]
# b = idiot(a,3)
# print b
# def function(arr, num):
# for i in range(len(arr)):
# arr[i] *= num
# return arr
# a = [10, 9, 8, 7, 6]
# print function(a, 8)
# def avg(arr):
# avg = 0
# for i in range(len(arr)):
# avg = avg + arr[i]
# return avg / len(arr)
# a = [10,66,77]
# print avg(a)
# Determines the average of a list (array)
weekend = {"Sun": "Sunday", "Sat": "Saturday"}
weekdays = {"Mon": "Monday", "Tue": "Tuesday", "Wed": "Wednesday", "Thu": "Thursday",
"Fri": "Friday"}
months = {"Jan": "January", "Feb": "February", "Mar": "March", "Apr": "April",
"May": "May", "Jun": "June", "Jul": "July",
"Aug": "August", "Sep": "September", "Oct": "October", "Nov": "November",
"Dec": "December"}
# for data in months:
# print data
# for key in months.iterkeys():
# print key
# for val in months.itervalues():
# print val
# for key,data in months.iteritems():
# print key, '=', data
# print len(months)
# print len(weekend)
# print str(months)
# context = {
# 'questions': [
# { 'id': 1, 'content': 'Why is there a light in the fridge and not in the freezer?'},
# { 'id': 2, 'content': 'Why don\'t sheep shrink when it rains?'},
# { 'id': 3, 'content': 'Why are they called apartments when they are all stuck together?'},
# { 'id': 4, 'content': 'Why do cars drive on the parkway and park on the driveway?'}
# ]
# }
# userAnna = {"My name is": "Anna", "My age is": "101", "My country of birth is": "The U.S.A", "My favorite language is": "Python"}
# for key,data in userAnna.iteritems():
# print key, data |
12769258a066d58da3c740c75205211755481d0f | Cpeters1982/DojoPython | /OOP_practice.py | 5,376 | 4.40625 | 4 | # # pylint: disable=invalid-name
# class User(object):
# '''Make a class of User that contains the following attributes and methods'''
# def __init__(self, name, email):
# '''Sets the User-class attributes; name, email and whether the user is logged in or not (defaults to true)'''
# self.name = name
# self.email = email
# self.logged = True
# # Login method changes the logged status for a single instance (the instance calling the method)
# def login(self):
# '''Creates a Login method for the User-class. This method logs the user in'''
# self.logged = True
# print self.name + " is logged in."
# return self
# # logout method changes the logged status for a single instance (the instance calling the method)
# def logout(self):
# '''Creates a Logout method for the User-class. This method logs the user out.'''
# self.logged = False
# print self.name + " is not logged in."
# return self
# def show(self):
# '''Creates a Show method for the User-class. Prints the users' name and email'''
# print "My name is {}. You can email me at {}".format(self.name, self.email)
# return self
# new_user = User("Chris", "chris@chris.com")
'''
Instantiates a new instance of the User_class with the name and email attributes assigned to "chris" and "chris@chris.com" respectively
'''
# print "Hello, my name is " + new_user.name, "and my email address is " + new_user.email
'''
Remember, objects have two important features: storage of information and ability to execute some
logic.
To review:
A class: Instructions on how to build many objects that share characteristics.
An object: A data type built according to specifications provided by the class definition.
An attribute: A value. Think of an attribute as a variable that is stored within an object.
A method: A set of instructions. Methods are functions that are associated with an object.
Any function included in the parent class definition can be called by an object of that class.
1. If we wanted to define a new class we would start with which line
def ClassName(object):
def ClassName(self):
class ClassName(self):
[x] class ClassName(object):
None of the above
2. How can we set attributes to an instance of a class
A. Initializing our attributes with the __init__() function
B. We create attributes by defining multiple setter methods in our class
C. This is impossible
D. We can set individual attributes to each instance - one by one
[x] Both A & D
3. The __init__() function gets called while the object is being constructed
True
[x] False
4. You cannot define an __init__() function that has parameters
True
[x] False
5. How do you pass arguments to the __init__() function?
Creating an object instance and calling the __init__() function on the object passing in the specified parameters
You cannot pass arguments into a __init__() function
[x] When creating an object instance you pass the arguments to the specified class you are creating an instance of
Creating an object within the class and calling the __init__() function passing the specified parameters
6. What is the purpose of an __init__() function?
To prevent you from rewriting the same code each time you create a new object
To set properties required to execute certain instance methods as soon as the object is instantiated
To execute whatever logic we want to for each object that is created
[x] All of the above
7. A constructor function cannot call any other methods inside the class.
True
[x] False
'''
# class Bike(object):
# '''
# Bike class!
# '''
# def __init__(self, price, max_speed, miles):
# self.price = price
# self.max_speed = max_speed
# self.miles = 0
# def displayinfo(self):
# '''
# Get that info, son!
# '''
# print "This bike costs ${}. It has a max speed of {}. It has been ridden {} miles.".format(self.price, self.max_speed, self.miles)
# return self
# def ride(self):
# '''
# Ride that bike!
# '''
# print "Riding "
# self.miles = self.miles+10
# return self
# def reverse(self):
# '''
# Better backpedal...
# '''
# self.miles = self.miles-5 if self.miles-5 > 0 else 0
# return self
# bike1 = Bike(200, 10, 0)
# bike2 = Bike(300, 20, 0)
# bike3 = Bike(600, 60, 0)
# bike1.ride().ride().ride().reverse().displayinfo()
# bike2.ride().ride().reverse().reverse().displayinfo()
# bike3.reverse().reverse().reverse().displayinfo()
# class Car(object):
# def __init__(self, price, speed, fuel, mileage):
# self.price = price
# self.speed = speed
# self.fuel = fuel
# self.mileage = mileage
# if self.price > 10000:
# self.tax = 0.15
# else:
# self.tax = 0.12
# self.display_all()
# def display_all(self):
# print 'Price: ' + str(self.price)
# print 'Speed: ' + self.speed
# print 'Fuel: ' + self.fuel
# print 'Mileage: ' + self.mileage
# print 'Tax: ' + str(self.tax)
# return self
# car1 = Car(20000, '100mph', 'Full', '30mpg')
# car2 = Car(1000, '45mph', 'Not full', '15mpg')
# car3 = Car(10000, '75mph', 'Full', '32mpg')
|
787b69242140019629701eaf9e35c4eb97eaec44 | Doctus5/FYS-STK4155 | /project2/nn.py | 11,991 | 3.625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math as m
#Fully Connected Neural Network class for its initialization and further methods like the training and test. Time computation is quite surprisingly due to the matrix operations with relative smallamount of datasets compared to life example datasets for training (near 10'000).
class NeuralNetwork:
#Function for initializing the Weights ands Biases of each layer of the NN accoirding to the specified architecture.
#Inputs:
#- input_size, number of hidden layers, number of neurons (list of numbers of neurons per each hidden layer), number of nodes for output, number of iterations, learning rate, activation function to use, penalty value (default is 0.0), parameter to define if softmax is to be used at the end or not (not recomenen for regression problems).
#Output:
#- the entire architecture with initialized weights and biases (type dictionary).
def __init__(self, X_input, Y_input, num_nodes, num_outputs, epochs, lr, act_type='relu', penalty=0.0, prob=True):
self.X_input = X_input
self.n_inputs, self.n_features = X_input.shape
self.W, self.B = {}, {}
self.Z, self.A = {}, {}
self.dW, self.dB = {}, {}
self.Y = Y_input
self.num_outputs = num_outputs
self.num_nodes = num_nodes
self.lr = lr
self.act_type = act_type
self.penalty = penalty
self.epochs = int(epochs)
self.prob = prob
for i in range(len(self.num_nodes)+1):
if i == 0:
self.W['W'+str(i)] = np.random.rand(self.n_features, self.num_nodes[i])
self.B['B'+str(i)] = np.zeros(self.num_nodes[i]) + 0.01
elif i == len(self.num_nodes):
self.W['W'+str(i)] = np.random.rand(self.num_nodes[i-1], self.num_outputs)
self.B['B'+str(i)] = np.zeros(self.num_outputs) + 0.01
else:
self.W['W'+str(i)] = np.random.rand(self.num_nodes[i-1], self.num_nodes[i])
self.B['B'+str(i)] = np.zeros(self.num_nodes[i]) + 0.01
def init_check(self):
print('report of Data, Weights and Biases shapes at Initialization:')
print(self.X_input.shape)
for ind in self.W.keys():
print(ind, self.W[ind].shape)
for ind in self.B.keys():
print(ind, self.B[ind].shape)
print(self.Y.shape)
#Sigmoid function used as an activation function.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def sigmoid(self, x):
return 1/(1 + np.exp(-x))
#Derivative of the Sigmoid function used as an activation function for backprop.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def dev_sigmoid(self, x):
return self.sigmoid(x)*(1 - self.sigmoid(x))
#Sigmoid function used as an activation function.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def tanh(self, x):
return np.tanh(x)
#Derivative of the Sigmoid function used as an activation function for backprop.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def dev_tanh(self, x):
return 1 - self.tanh(x)**2
#ReLU function used as an activation function.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def ReLu(self, x):
x[x <= 0] = 0
return x
#Heaviside function (derivative of ReLu) used as an activation function for backprop.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def dev_ReLu(self, x):
x[x <= 0] = 0
x[x > 0] = 1
return x
#Leaky ReLU function used as an activation function.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def Leaky_ReLu(self, x):
x[x <= 0] *= 0.01
return x
#Leaky_ReLU derivative function used as an activation function for backprop.
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def dev_Leaky_ReLu(self, x):
x[x <= 0] = 0.01
x[x > 0] = 1
return x
#Softmax function used in the last layer for targeting probabilities
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def softmax(self, x):
return np.exp(x)/np.sum(np.exp(x), axis=1, keepdims=True)
#Function for evaluationg which activation function to use according to the desired activation function initialized in the Neural Network
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x..
def activation(self, x):
if self.act_type == 'relu':
return self.ReLu(x)
elif self.act_type == 'sigmoid':
return self.sigmoid(x)
elif self.act_type == 'tanh':
return self.tanh(x)
elif self.act_type == 'leaky_relu':
return self.Leaky_ReLu(x)
#Function for evaluationg which derivate function to use according to the desired activation function initialized in the Neural Network
#Inputs:
#- value x.
#Output:
#- function evaluated in that value x.
def derivative(self, x):
if self.act_type == 'relu':
return self.dev_ReLu(x)
elif self.act_type == 'sigmoid':
return self.dev_sigmoid(x)
elif self.act_type == 'tanh':
return self.dev_tanh(x)
elif self.act_type == 'leaky_relu':
return self.dev_Leaky_ReLu(x)
#Feed Forwards function
#Input:
#- Initial parameters of weights, data set, biases and probability boolean to decide if Aoftmax is used or not.
#Output:
#- Calculated A and Z values for each hidden layer.
def feed_forward(self, X, W, B, prob):
iterations = len(W)
Z = {}
A = {}
for i in range(iterations):
if i == 0:
Z['Z'+str(i+1)] = X @ W['W'+str(i)] + B['B'+str(i)]
A['A'+str(i+1)] = self.activation(Z['Z'+str(i+1)])
elif i == (iterations - 1):
Z['Z'+str(i+1)] = A['A'+str(i)] @ W['W'+str(i)] + B['B'+str(i)]
if prob == True:
A['A'+str(i+1)] = self.softmax(Z['Z'+str(i+1)])
else:
A['A'+str(i+1)] = Z['Z'+str(i+1)]
else:
Z['Z'+str(i+1)] = A['A'+str(i)] @ W['W'+str(i)] + B['B'+str(i)]
A['A'+str(i+1)] = self.activation(Z['Z'+str(i+1)])
return Z, A
#Back Propagation function
#Input:
#- Initial parameters of weights, data set, biases, A and Z values of the hidden layers.
#Output:
#- Gradients for Weights and Biases in each hidden layer to use in the upgrade step.
def back_propagation(self, X, Y, W, B, A, Z):
layers = len(A)
m = len(X)
dW = {}
dB = {}
for i in range(layers-1,-1,-1):
if i == layers-1:
delta = A['A'+str(i+1)] - Y
dW['dW'+str(i)] = (1/m) * A['A'+str(i)].T @ delta
dB['dB'+str(i)] = (1/m) * np.sum(delta, axis=0)
elif i == 0:
delta = (delta @ W['W'+str(i+1)].T) * self.derivative(Z['Z'+str(i+1)])
dW['dW'+str(i)] = (1/m) * X.T @ delta
dB['dB'+str(i)] = (1/m) * np.sum(delta, axis=0)
else:
delta = (delta @ W['W'+str(i+1)].T) * self.derivative(Z['Z'+str(i+1)])
dW['dW'+str(i)] = (1/m) * A['A'+str(i)].T @ delta
dB['dB'+str(i)] = (1/m) * np.sum(delta, axis=0)
return dW, dB
#Parameters Upgrade function
#Input:
#- Weights and biases, gradients for update, learning rate and penalty parameter (0.0 if there is no penalty).
#Output:
#- Updates Weights and Biases per hidden layer.
def upgrade_parameters(self, dW, dB, W, B, lr, penalty):
for i in range(len(dW)):
if penalty != 0.0:
dW['dW'+str(i)] += penalty * W['W'+str(i)]
W['W'+str(i)] -= lr * dW['dW'+str(i)]
B['B'+str(i)] -= lr * dB['dB'+str(i)]
return W, B
#Train function.
#Do all the processes of feed_forward, back_propagation and upgrade_parameters for a certain amount of epochs until Weights and Biases are updated completely for this training set
#Input:
#-
#Output:
#-
def train(self):
for i in range(self.epochs):
#print(i)
self.Z, self.A = self.feed_forward(self.X_input, self.W, self.B, self.prob)
self.dW, self.dB = self.back_propagation(self.X_input, self.Y, self.W, self.B, self.A, self.Z)
self.W, self.B = self.upgrade_parameters(self.dW, self.dB, self.W, self.B, self.lr, self.penalty)
#Predict function.
#Based on an already train NN, it predicts the classes or output of a test set passed as argument.
#Input:
#- Test_set in the same type as the Train set used to initialize the NN.
#Output:
#- Values predicted or probabilities per nodes. To use as it is for regression problems, or probability logits to be decoded with the decoder function in method.py
def predict(self, test_set):
Zetas, As = self.feed_forward(test_set, self.W, self.B, self.prob)
classes = As['A'+str(len(self.num_nodes)+1)]
return classes
#Logistic Regression class and further methods like the training and test.
class Logistic_Regression:
#Function for initializing the Parameters, including the initial coefficients from 0 to 1.
#Inputs:
#- input data, target values, number of iterations, learning rate, penalty value (default is 0.0), threshold for binary classification in probability distribution (default is 0.5).
#Output:
#- initialized values.
def __init__(self, X_input, Y_input, epochs, lr, penalty=0.0, threshold=0.5):
self.X = X_input
self.n_inputs, self.n_features = X_input.shape
self.Y = Y_input
self.lr = lr
self.B = np.random.rand(self.n_features,1)
self.penalty = penalty
self.epochs = int(epochs)
self.prob = threshold
#Probability calculation function (Sigmoid function)
#Inputs:
#- values (array of values in column).
#Output:
#- evaluated values in sigmoid fucntion (array with size equal to the Input).
def probability(self, values):
return 1/(1 + np.exp(-values))
#Train function.
#Do all the processes of gradient descent, with a cost function defined on probabilty comparison. Penalty parametr also taked into accountto compute another gradient regularized in case that penalty is different from 0.0
#Input:
#-
#Output:
#-
def train(self):
t0, t1 = 5, 50
#print(self.B)
for i in range(self.epochs):
if self.penalty != 0.0:
G = self.X.T @ (self.Y - self.probability( self.X @ self.B )) + (self.penalty * self.B)
else:
G = self.X.T @ (self.Y - self.probability( self.X @ self.B ))
self.B += self.lr * G
#Predict function.
#Based on an already train Logistic Regression (updated coefficients).
#Input:
#- Test_set in the same type as the Train set used to initialize the class.
#Output:
#- Values predicted in the way of probabilities. It instantly translates to the desired class (0 or 1) (binary classification).
def predict(self, values):
results = self.probability( values @ self.B )
results[results < self.prob] = 0
results[results >= self.prob] = 1
return results
|
c02f664998073d00a27a016e5edfe0f289b785b9 | aditdamodaran/incan-gold | /deck.py | 898 | 3.875 | 4 | import random
class Deck:
# The game starts off with:
# 15 treasure cards
# represented by their point values,
# 15 hazards (3 for each type)
# represented by negative numbers
# 1 artifact (worth 5 points) in the deck
def __init__(self):
self.cards = [1,2,3,4,5,5,7,7,9,11,11,13,14,15,17] \
+ ([-1]*3) \
+ ([-2]*3) \
+ ([-3]*3) \
+ ([-4]*3) \
+ ([-5]*3) \
+ [50]
# Shuffles the deck
def shuffle(self):
random.shuffle(self.cards)
# Removes a card from the deck
def remove(self, value):
# print('removing')
counter = 0
for i, card in enumerate(self.cards):
if (card == value and counter == 0):
# print('popping', card)
self.cards.pop(i)
counter+=1
# Draws a card
def draw(self):
drawn = self.cards[0]
self.cards = self.cards[1:len(self.cards)]
return drawn |
c8633e4755e9dfd08535a9806245154b042526b2 | gersongroth/maratonadatascience | /Semana 01/01 - Estruturas Sequenciais/07.py | 135 | 3.84375 | 4 | lado = float(input("Informe o lado do quadrado: "))
area = lado ** 2
dobroArea = area * 2
print("dobro do área é %.1f" % dobroArea) |
cbbe2be00332fe79c2b2f47a9ee1abf4e3606d1c | gersongroth/maratonadatascience | /Semana 01/03 - Estruturas de Repetição/02.py | 444 | 3.859375 | 4 | """
Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
"""
def getUser():
user=input("Informe o nome de usuário: ")
password= input("Informe a senha: ")
return user,password
user,password=getUser()
while(user == password):
print("Senha não pode ser igual ao usuário")
user,password=getUser() |
44b81e47c1cd95f7e08a8331b966cf195e8c514d | gersongroth/maratonadatascience | /Semana 01/02 - Estruturas de Decisão/11.py | 1,156 | 4.1875 | 4 | """
As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes.
Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual:
salários até R$ 280,00 (incluindo) : aumento de 20%
salários entre R$ 280,00 e R$ 700,00 : aumento de 15%
salários entre R$ 700,00 e R$ 1500,00 : aumento de 10%
salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela:
o salário antes do reajuste;
o percentual de aumento aplicado;
o valor do aumento;
o novo salário, após o aumento.
"""
salario = float(input("Informe o salário: R$ "))
aumento = 0
if salario <= 280.0:
aumento = 20
elif salario < 700.0:
aumento = 15
elif salario < 1500:
aumento = 10
else:
aumento = 5
valorAumento = salario * (aumento / 100)
novoSalario = salario + valorAumento
print("Salario original: R$ %.2f" % salario)
print("Porcentagem de aumento: %d%%" % aumento)
print("Valor do aumento: R$ %.2f" % valorAumento)
print("Salario após reajuste: R$ %.2f" % novoSalario) |
e1ebae30cf58ae268c07ffa4f088c1b5dc3fe644 | gersongroth/maratonadatascience | /Semana 01/01 - Estruturas Sequenciais/10.py | 121 | 3.921875 | 4 | celsius = float(input("Informe a temperatura em celsius: "))
f = celsius * 9 / 5 + 32
print("%.1f graus Farenheit" % f) |
b2612751a0971f2191f1d65bd3e987ce611e9fb9 | DabicD/Studies | /The_basics_of_scripting_(Python)/Exercise2.py | 853 | 3.8125 | 4 | # Exercise description:
#
# "Napisz program drukujący na ekranie kalendarz na zadany miesiąc dowolnego roku
# (użytkownik wprowadza informację postaci: czerwiec 1997–nazwa miesiąca w języku polskim)."
#
##############################################################################################
import locale
locale.setlocale(locale.LC_ALL, 'pl')
import calendar
polishMonths = {
"styczen": 1,
"luty": 2,
"marzec": 3,
"kwiecien": 4,
"maj":5,
"czerwiec":6,
"lipiec":7,
"sierpien":8,
"wrzesien":9,
"pazdziernik":10,
"listopad":11,
"grudzien":12
}
try:
x1 = int(input("Year:"))
x2 = input("Month:")
cal = calendar.TextCalendar(calendar.MONDAY)
text = cal.formatmonth(x1, polishMonths[x2])
print(text)
except:
print("Wrong input")
|
b5a42001ab9ec5ec13c1c0538824fdcc1d9e4b83 | MarinaSergeeva/Algorithms | /day02_dijkstra.py | 1,301 | 3.78125 | 4 | import heapq
from math import inf
def dijkstra(graph, source):
visited = set([source])
distances = {v: inf for v in graph}
# parents = {v: None for v in graph}
distances[source] = 0
for (v, w) in graph[source]:
distances[v] = w
# parents[v] = source
vertices_heap = [(w, v) for (v, w) in graph[source]]
heapq.heapify(vertices_heap)
while len(visited) != len(graph):
(weight, next_vertex) = heapq.heappop(vertices_heap)
while next_vertex in visited:
(weight, next_vertex) = heapq.heappop(vertices_heap)
distances[next_vertex] = weight
visited.add(next_vertex)
for (v, w) in graph[next_vertex]:
if v not in visited:
new_distance = w + distances[next_vertex]
if new_distance < distances[v]:
distances[v] = new_distance
# parents[v] = next_vertex
heapq.heappush(vertices_heap, (new_distance, v))
return distances
def test_dijkstra():
graph = {0: [(1, 1), (2, 8), (3, 2)],
1: [(4, 6)],
2: [(4, 1)],
3: [(2, 3)],
4:[]}
res = {0: 0, 1: 1, 3: 2, 2: 5, 4: 6}
assert dijkstra(graph, 0) == res
if __name__ == "__main__":
test_dijkstra()
|
578a7c30e7e0df3e7e086223575e1a682f4c200e | MarinaSergeeva/Algorithms | /day12_median_maintenance.py | 1,415 | 3.765625 | 4 | import heapq
class MedianMaintainer:
def __init__(self):
self._minheap = [] # for smallest half of fthe array, uses negated numbers
self._maxheap = [] # for largest half of the array
self.median = None # if similar number of elements - use value form maxheap
def insert_element(self, el):
if len(self._minheap) == 0 and len(self._maxheap) == 0:
self._maxheap.append(el)
self.median = el
else:
if el >= self._maxheap[0]:
heapq.heappush(self._maxheap, el)
if len(self._maxheap) > len(self._minheap) + 1:
el_to_move = heapq.heappop(self._maxheap)
heapq.heappush(self._minheap, -el_to_move)
else:
heapq.heappush(self._minheap, -el)
if len(self._minheap) > len(self._maxheap):
el_to_move = - heapq.heappop(self._minheap)
heapq.heappush(self._maxheap, el_to_move)
self.median = self._maxheap[0]
def get_median(self):
return self.median
def test_maintain_median():
myMedianMaintainer = MedianMaintainer()
input_array = [1, 5, 7, 3, 4]
expected_medians = []
for el in input_array:
myMedianMaintainer.insert_element(el)
expected_medians.append(myMedianMaintainer.get_median())
assert expected_medians == [1, 5, 5, 5, 4]
|
023911c5beb0dc2cdb8b29f5f4447b6198a85b33 | MarinaSergeeva/Algorithms | /day07_quicksort.py | 757 | 3.921875 | 4 | def partition(array, low, high):
# uses array[low] element for the partition
pivot = array[low]
repl_index = low
for i in range(low + 1, high):
if array[i] < pivot:
repl_index += 1
array[i], array[repl_index] = array[repl_index], array[i]
array[low], array[repl_index] = array[repl_index], array[low]
return repl_index
def quick_sort(array, low=0, high=None):
if high is None:
high = len(array)
if low < high - 1:
partition_index = partition(array, low, high)
quick_sort(array, low, partition_index)
quick_sort(array, partition_index + 1, high)
def test_quicksort():
my_list = [3, 8, 1, 5, 2]
quick_sort(my_list)
assert my_list == [1, 2, 3, 5, 8]
|
5d185a1960ee3b49934bf30e2e03a48c5ac09db7 | HSabbir/Python-Challange | /day 1.py | 155 | 4.15625 | 4 | ## Print Multiplication table
number = int(input("Enter Your Number: "))
for i in range(10):
print(str(i+1)+' * '+str(number)+' = '+str(number*(i+1))) |
348084b89a6dda4fd185da2863c05cb4cb3b4a3f | Vrittik/LINEAR_REGRESSION_FROM_SCRATCH | /SLR_By_calc.py | 772 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statistics import mean
from ML_library import mlSkies
dataset=pd.read_csv("Salary_Data.csv")
X=dataset.iloc[:,0].values
y=dataset.iloc[:,1].values
X_train,X_test,y_train,y_test = mlSkies.train_test_split(X,y,split_index=0.2)
X_train=np.array(X_train , dtype=np.float64)
X_test=np.array(X_test, dtype=np.float64)
y_train=np.array(y_train , dtype=np.float64)
y_test=np.array(y_test , dtype=np.float64)
m,b=mlSkies.linear_regression(X_train,y_train)
mlSkies.plot_regression_line(X_train,y_train,m,b)
y_pred=mlSkies.linear_regression_predict(7,m,b)
print("The estimated salary for",7,"years of experience is",y_pred,"rupees")
|
89c3903452e5ee6c194159e3a3311fbe2d6ba04d | davidlowryduda/pynt | /pynt/base.py | 4,086 | 4.03125 | 4 | """
base.py
=======
Fundamental components for a simple python number theory library.
License Info
============
(c) David Lowry-Duda 2018 <davidlowryduda@davidlowryduda.com>
This is available under the MIT License. See
<https://opensource.org/licenses/MIT> for a copy of the license,
or see the home github repo
<https://github.com/davidlowryduda/pynt>.
"""
from typing import List, Tuple, Union
from itertools import product as cartesian_product
import numpy
def gcd(num1: int, num2: int) -> int:
"""
Returns the greatest common divisor of `num1` and `num2`.
Examples:
>>> gcd(12, 30)
6
>>> gcd(0, 0)
0
>>> gcd(-1001, 26)
13
"""
if num1 == 0:
return num2
if num2 == 0:
return num1
if num1 < 0:
num1 = -num1
if num2 < 0:
num2 = -num2
# This is the Euclidean algorithm
while num2 != 0:
num1, num2 = num2, num1 % num2
return num1
def smallest_prime_divisor(num: int, bound: Union[int, None] = None) -> int:
"""
Returns the smallest prime divisor of the input `num` if that divisor is
at most `bound`. If none are found, this returns `num`.
Input:
num: a positive integer
bound: an optional bound on the size of the primes to check. If not
given, then it defaults to `num`.
Output:
The smallest prime divisor of `num`, or `num` itself if that divisor is
at least as large as `bound`.
Raises:
ValueError: if num < 1.
Examples:
>>> smallest_prime_divisor(15)
3
>>> smallest_prime_divisor(1001)
7
"""
if num < 1:
raise ValueError("A positive integer is expected.")
if num == 1:
return num
for prime in [2, 3, 5]:
if num % prime == 0:
return prime
if bound is None:
bound = num
# Possible prime locations mod 2*3*5=30
diffs = [6, 4, 2, 4, 2, 4, 6, 2]
cand = 7
i = 1
while cand <= bound and cand*cand <= num:
if num % cand == 0:
return cand
cand += diffs[i]
i = (i + 1) % 8
return num
# primesfrom2to(n) from
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n
def primes(limit):
"""
Returns the numpy array of primes up to (and not including) `limit`.
Examples:
>>> primes(10)
array([2, 3, 5, 7])
"""
sieve = numpy.ones(limit // 3 + (limit % 6 == 2), dtype=numpy.bool)
for i in range(1, int(limit ** 0.5) // 3 + 1):
if sieve[i]:
k = (3 * i + 1) | 1
sieve[k * k // 3::2 * k] = False
sieve[k * (k - 2 * (i & 1) + 4) // 3:: 2 * k] = False
return numpy.r_[2, 3, ((3 * numpy.nonzero(sieve)[0][1:] + 1) | 1)]
def factor(num: int) -> List[Tuple[int, int]]:
"""
Returns the factorization of `num` as a list of tuples of the form (p, e)
where `p` is a prime and `e` is the exponent of that prime in the
factorization.
Input:
num: an integer to factor
Output:
a list of tuples (p, e), sorted by the size of p.
Examples:
>>> factor(100)
[(2, 2), (5, 2)]
>>> factor(-7007)
[(7, 2), (11, 1), (13, 1)]
>>> factor(1)
[]
"""
if num in (-1, 0, 1):
return []
if num < 0:
num = -num
factors = []
while num != 1:
prime = smallest_prime_divisor(num)
exp = 1
num = num // prime
while num % prime == 0:
exp += 1
num = num // prime
factors.append((prime, exp))
return factors
def factors(num: int) -> List[int]:
"""
Returns the list of factors of an integer.
Examples:
>>> factors(6)
[1, 2, 3, 6]
>>> factors(30)
[1, 2, 3, 5, 6, 10, 15, 30]
"""
factorization = factor(num)
primes_, exps = zip(*factorization)
exp_choices = cartesian_product(*[range(exp+1) for exp in exps])
ret = []
for exp_choice in exp_choices:
val = 1
for prime, exp in zip(primes_, exp_choice):
val *= (prime**exp)
ret.append(val)
return sorted(ret)
|
0685f7856c0b7032a146198548e1db5dc3a0bbad | numblr/glaciertools | /test/treehash/algorithm_test.py | 2,242 | 3.53125 | 4 | #!/usr/bin/python
from pprint import pprint
def next_itr(last):
for i in range(1, last + 1):
yield str(i)
def calculate_root(level, itr):
# Base case level
if level == 0:
return next(itr, None)
left = calculate_root(level - 1, itr)
right = calculate_root(level - 1, itr)
return combine(left, right) if right else left
def calculate_hash(left, level, itr):
if not left:
left = calculate_root(0, itr)
return calculate_hash(left, 0, itr) if left else None
right = calculate_root(level, itr)
return calculate_hash(combine(left, right), level + 1, itr) if right else left
def combine(a, b):
return "[" + ",".join([a,b]) + "]"
if __name__ == '__main__':
def assertEquals(a, b):
if not a == b:
raise ValueError(a + " - " + b)
assertEquals(calculate_hash(None, 0, next_itr(2)), "[1,2]")
assertEquals(calculate_hash(None, 0, next_itr(3)), "[[1,2],3]")
assertEquals(calculate_hash(None, 0, next_itr(4)), "[[1,2],[3,4]]")
assertEquals(calculate_hash(None, 0, next_itr(5)), "[[[1,2],[3,4]],5]")
assertEquals(calculate_hash(None, 0, next_itr(6)), "[[[1,2],[3,4]],[5,6]]")
assertEquals(calculate_hash(None, 0, next_itr(7)), "[[[1,2],[3,4]],[[5,6],7]]")
assertEquals(calculate_hash(None, 0, next_itr(8)), "[[[1,2],[3,4]],[[5,6],[7,8]]]")
assertEquals(calculate_hash(None, 0, next_itr(9)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],9]")
assertEquals(calculate_hash(None, 0, next_itr(10)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[9,10]]")
assertEquals(calculate_hash(None, 0, next_itr(11)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[9,10],11]]")
assertEquals(calculate_hash(None, 0, next_itr(12)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[9,10],[11,12]]]")
assertEquals(calculate_hash(None, 0, next_itr(13)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],13]]")
assertEquals(calculate_hash(None, 0, next_itr(14)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[13,14]]]")
assertEquals(calculate_hash(None, 0, next_itr(15)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[[13,14],15]]]")
assertEquals(calculate_hash(None, 0, next_itr(16)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[[13,14],[15,16]]]]")
|
5f4b7dc66789528b881bc081632e8b54fc6192f3 | bubblegumsoldier/kiwi | /kiwi-user-manager/app/lib/username_validator.py | 333 | 3.546875 | 4 | import re
username_min_string_length = 5
username_max_string_length = 30
username_regex = "^[a-zA-Z0-9_.-]+$"
def validate(username):
if not username_min_string_length <= len(username) <= username_max_string_length:
return False
if not re.match(username_regex, username):
return False
return True |
2280d3663399e1dcd1dc76de2ee713c3416c484d | ash-fu/coursera-algo | /Assign2.py | 1,711 | 3.703125 | 4 | count = 0
def mergeSort(alist):
# print("Splitting ",alist)
global count
# count = 0
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
# splitSort(lefthalf, righthalf,count)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
# print('inversion discover: ',len(lefthalf))
count=count+ (len(lefthalf) - i)
# print('count', count)
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
# print("Merging ",alist)
# def splitSort(left, right):
# i = 0
# j = 0
# k = 0
fname = 'list_67.txt'
with open(fname) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
alist = [x.strip() for x in content]
# print alist
# alist = [ 4, 80, 70, 23, 9, 60, 68, 27, 66, 78, 12, 40, 52, 53, 44, 8, 49, 28, 18, 46, 21, 39, 51, 7, 87, 99, 69, 62, 84, 6, 79, 67, 14, 98, 83, 0, 96, 5, 82, 10, 26, 48, 3, 2, 15, 92, 11, 55, 63, 97, 43, 45, 81, 42, 95, 20, 25, 74, 24, 72, 91, 35, 86, 19, 75, 58, 71, 47, 76, 59, 64, 93, 17, 50, 56, 94, 90, 89, 32, 37, 34, 65, 1, 73, 41, 36, 57, 77, 30, 22, 13, 29, 38, 16, 88, 61, 31, 85, 33, 54 ]
mergeSort(alist)
# print(alist)
print count |
f3ae407a822f0cd36fdfb490b705e35cd2a275d6 | SaraZ3964/Python | /pybank.py | 420 | 3.625 | 4 | import pandas as pd
file = "budget_data.csv"
data_df = pd.read_csv(file)
data_df.head()
Months = data_df["Date"].count()
Sum = data_df["Profit/Losses"].sum()
Ave = data_df["Profit/Losses"].mean()
Max = data_df["Profit/Losses"].max()
Min = data_df["Profit/Losses"].min()
print("Months:" + str(Months))
print("Total: " + str(Sum))
print("Average: "+ str(Ave))
print("Maximum: " + str(Max))
print("Minmium:" + str(Min))
|
37238eb1a843fb3a7d5e1d36364bf3f0b1bbd7ee | kylehovey/kylehovey.github.io | /spel3o/files/geohash.py | 2,354 | 3.8125 | 4 | import webbrowser
import math
ImTheMap = input("would you like a map site to look up your coordinates? ")
if ImTheMap == "yes":
print('look up your current location on this website')
webbrowser.open("https://csel.cs.colorado.edu/~nishimot/point.html")
else:
print('''okay then, let's continue''')
Lat = input('''Please input your current LATITUDE with spaces inbetween,
and zeros as placeholders. (ex: 32 05 12.20) ''')
if len(Lat) != 11:
print("entered incorrectly, quitting")
raise IOError('Wrong coordinate format')
else:
LatDeg = float(Lat[:2])
LatMin = float(Lat[3:5])
LatSec = float(Lat[6:])
Long = input('''Please input your current LONGITUDE with spaces inbetween,
and zeros as placeholders. (ex: 120 05 12.20) ''')
if len(Long) == 11:
LongDeg = float(Long[:2])
LongMin = float(Long[3:5])
LongSec = float(Long[7:])
elif len(Long) == 12:
LongDeg = float(Long[:3])
LongMin = float(Long[4:6])
LongSec = float(Long[6:])
else:
print("entered incorrectly, quitting")
raise IOError('Wrong coordinate format')
Cal = input("please enter the current date in MM/DD/YY format (ex: 03/06/11) ")
mm = int(Cal[:2])
dd = int(Cal[3:5])
yy = int(Cal[6:])
Prank = input("please confess yourself of all mortal sins ")
Prank = input('''oh come on, be honest ;) ''')
print('''haha.. just joking ;) Now, let's continue.''')
Prank = 0
val = (dd - mm) * yy
if val <= 48:
val = (val/60)*10
elif val >= 48:
val = (val/60)*4
if dd % 2 == 0:
val = -val
else:
val = val
longval = val * 0.18526362353047317310282957646406309593963452838196423660508102562977229905562196608078556292556795045922591488273554788881298750625
longval = round(longval, 1)
if val >= 8:
val = 8;
else:
val = val
lad = LatDeg
lam = LatMin + round(val, 1)
las = LatSec + val * 10
lod = LongDeg
lom = LongMin + round(val, 1)
los = LongSec + val*10
jumpthegun = 0
jumpthegunlong = 0
if las >= 60:
jumpthegun = 1
las = 59
else:
las = las
if los >= 60:
jumpthegunlong = 1
los = 59
else:
los = los
lam = round(lam, 1) + jumpthegun
lom = round(lom, 1) + jumpthegunlong
lom = lom - 5
las = round(las, 2)
los = round(los, 2)
final = input('''hit enter to see results ''')
print('''Your local geohash of the day is:''')
print('Latitude:')
print(lad, lam, las)
print('Longitude:')
print(lod, lom, los)
|
06abfdc014c7ef45be7f8c1ac53007c49983062c | TheAutomationWizard/learnPython | /pythonUdemyCourse/Concepts/General Concepts/slicing.py | 543 | 4.09375 | 4 | list = [1, 2, 34, 4, 56, 7, 8, 99, 2]
def various_slicing_in_python(list_object):
"""
slicing operations in python
:param list_object:
:return:
slice (Start, end , step)
"""
# Using slice method
print(list_object[slice(0, 4, 1)])
# Using index slicing +==> [start : stop+1 : steps]
# Step sign(+ or -), must be sign of stop+1 -start
print(list_object[::-1])
# Negative Indexing to slice
print(list_object[-1:-4:-1])
if __name__ == '__main__':
various_slicing_in_python(list)
|
4bf52a9a6adb7f222b981d2c48c51cd912324faa | TheAutomationWizard/learnPython | /pythonUdemyCourse/Concepts/OOPS/Inheritance/FiguresExample.py | 1,227 | 3.953125 | 4 | class Quadrilateral:
def __init__(self, length, height):
self.length = length
self.height = height
def quad_area(self):
area_ = self.length * self.height
print(f'Area of Quadrilateral with length {self.length} and height : {self.height} is = {area_}')
return area_
class Square(Quadrilateral):
def __init__(self, length):
super().__init__(length, length)
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
area_ = 3.14 * self.radius * self.radius
print(f'Area of circle with radius {self.radius} is = {area_}')
return area_
class Cylinder(Circle, Square):
def __init__(self, radius, height , *args, **kwargs):
self.radius = radius
self.height = height
def area(self):
base_area1 = super().area() * 2
base_length = 3.14 * self.radius * 2 * self.height
self.length = self.radius
quad_area = super().quad_area()
return base_area1 + base_length
radius = 2
height = 5
myCylinder = Cylinder(radius=radius, height=height)
print(myCylinder.area())
# print(2 * 3.14 * radius * (radius + height))
# print(2 * 3.14 * radius * height)
|
18d811c538e2db5846bdf7caf92fbca0eaac8f44 | TheAutomationWizard/learnPython | /pythonUdemyCourse/Concepts/OOPS/Inheritance/PythonicInheritance.py | 1,119 | 4.03125 | 4 | class A(object):
def __init__(self, a, *args, **kwargs):
print('I (A) am called from B super()')
print("A", a)
class B(A):
def __init__(self, b, *args, **kwargs):
print('As per inverted flow, i am called from class A1 super()')
super(B, self).__init__(*args, **kwargs)
print("B", b)
class A1(A):
def __init__(self, a1, *args, **kwargs):
print('A1 super will call, B super now! But without positional parameter "b" in super()')
super(A1, self).__init__(*args, **kwargs)
print("A1", a1)
class B1(A1, B):
def __init__(self, b1, *args, **kwargs):
super(B1, self).__init__(*args, **kwargs)
print("B1", b1)
B1(a1=6, b1=5, b="hello", a=None)
# *************************************
# Understand flow of kwargs & args
# *************************************
def ab(x, a=10, a1=20, **kwargs):
print(f'Value of x : {x}')
print(f'Value of a : {a}')
print(f'Value of a1 : {a1}')
print('value of kwargs')
print(kwargs)
kwarg_dict = {'x': 200, 'a': 50, 'a1': 100, 'b': 1000, 'c': 101}
ab(**kwarg_dict)
|
cc1812713296f1e020d7a5d426397c2f54622232 | fanying2015/algebra | /algebra/quadratic.py | 407 | 3.78125 | 4 |
def poly(*args):
"""
f(x) = a * x + b * x**2 + c * x**3 + ...
*args = (x, a, b)
"""
if len(args) == 1:
raise Exception("You have only entered a value for x, and no cofficients.")
x = args[0] # x value
coef = args[1:]
results = 0
for power, c in enumerate(coef):
results += c * (x ** (power + 1))
return results |
38d2e2e55b3ac7a05246a18367a4c82c4bd95cc8 | BOUYAHIA-AB/DeepSetFraudDetection | /split_data.py | 4,321 | 3.5 | 4 | """Build vocabularies of words and tags from datasets"""
from collections import Counter
import json
import os
import csv
import sys
import pandas as pd
def load_dataset(path_csv):
"""Loads dataset into memory from csv file"""
# Open the csv file, need to specify the encoding for python3
use_python3 = sys.version_info[0] >= 3
data = pd.load_csv(path_csv)
with (open(path_csv, encoding="windows-1252") if use_python3 else open(path_csv)) as f:
csv_file = csv.reader(f, delimiter=';')
dataset = []
words, tags = [], []
# Each line of the csv corresponds to one word
for idx, row in enumerate(csv_file):
if idx == 0: continue
sentence, word, pos, tag = row
# If the first column is non empty it means we reached a new sentence
if len(sentence) != 0:
if len(words) > 0:
assert len(words) == len(tags)
dataset.append((words, tags))
words, tags = [], []
try:
word, tag = str(word), str(tag)
words.append(word)
tags.append(tag)
except UnicodeDecodeError as e:
print("An exception was raised, skipping a word: {}".format(e))
pass
return dataset
def save_dataset(dataset, save_dir):
"""Writes sentences.txt and labels.txt files in save_dir from dataset
Args:
dataset: ([(["a", "cat"], ["O", "O"]), ...])
save_dir: (string)
"""
# Create directory if it doesn't exist
print("Saving in {}...".format(save_dir))
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# Export the dataset
with open(os.path.join(save_dir, 'sentences.txt'), 'w') as file_sentences:
with open(os.path.join(save_dir, 'labels.txt'), 'w') as file_labels:
for words, tags in dataset:
file_sentences.write("{}\n".format(" ".join(words)))
file_labels.write("{}\n".format(" ".join(tags)))
print("- done.")
def save_dict_to_json(d, json_path):
"""Saves dict to json file
Args:
d: (dict)
json_path: (string) path to json file
"""
with open(json_path, 'w') as f:
d = {k: v for k, v in d.items()}
json.dump(d, f, indent=4)
def update_vocab(txt_path, vocab):
"""Update word and tag vocabulary from dataset
Args:
txt_path: (string) path to file, one sentence per line
vocab: (dict or Counter) with update method
Returns:
dataset_size: (int) number of elements in the dataset
"""
with open(txt_path) as f:
for i, line in enumerate(f):
vocab.update(line.strip().split(' '))
return i + 1
def build_vocab(path_dir, min_count_word=1, min_count_tag=1) :
# Build word vocab with train and test datasets
print("Building word vocabulary...")
words = Counter()
size_train_sentences = update_vocab(os.path.join(path_dir, 'train/sentences.txt'), words)
#size_dev_sentences = update_vocab(os.path.join(path_dir, 'dev/sentences.txt'), words)
#size_test_sentences = update_vocab(os.path.join(path_dir, 'test/sentences.txt'), words)
print("- done.")
# Save vocabularies to file
print("Saving vocabularies to file...")
save_vocab_to_txt_file(words, os.path.join(path_dir, 'words.txt'))
save_vocab_to_txt_file(tags, os.path.join(path_dir, 'tags.txt'))
save_vocab_to_txt_file(tags_count, os.path.join(path_dir, 'tags_count.txt'))
print("- done.")
# Save datasets properties in json file
sizes = {
'train_size': size_train_sentences,
'dev_size': size_dev_sentences,
'test_size': size_test_sentences,
'max_size_size': len(words),
'number_of_features': len(tags),
}
save_dict_to_json(sizes, os.path.join(path_dir, 'dataset_params.json'))
# Logging sizes
to_print = "\n".join("- {}: {}".format(k, v) for k, v in sizes.items())
print("Characteristics of the dataset:\n{}".format(to_print))
if __name__ == '__main__':
print("Building vocabulary for science dataset...")
build_vocab("data/science", 1, 1)
print("Building vocabulary for disease dataset...")
build_vocab("data/disease", 1, 1)
|
c742ba20728912aac3293cf456bc83fe88a588cf | Danisaura/phrasalVerbs | /main.py | 6,114 | 3.703125 | 4 | from random import shuffle
# printing the welcome message
print("\n" + "---------------------------------------------------" + "\n" +
"Welcome! this is a script to practice phrasal verbs." + "\n" + "\n" +
"You will be shown sentences with blank spaces inside," + "\n" +
"try to fill them with the correct phrasal verb." "\n" + "\n" +
"You can ask for a hint in any moment typing 'hint'" + "\n" +
"instead of the requested solution, and you can see your" + "\n" +
"current mark by typing 'mark'." + "\n" + "\n"
"Let's start! Good luck! :)" + "\n"
"---------------------------------------------------" + "\n" + "\n")
# declaring variables
marks = 0
total = 0
final_mark = 0
used_hints = 0
shuffled_list = [x for x in range(0, 31)]
shuffle(shuffled_list)
sentences = {0: "Brian finally was brave enough to _ Judy _ ",
1: "The car was about to run over me when she shouted: _ _!",
2: "We have _ _ of clinex again... I'll buy more tomorrow.",
3: "You are too special, I can't __ on us.",
4: "I'm in a hurry! I have to __ these exercises to my teacher by tomorrow morning!",
5: "Only thing I disliked about the hotel was that we had to __ _ before 12am...",
6: "My grandma always tells the same story where a bottle of gas __ in her face.",
7: "I've been ____ __ about the topic, but nobody knows shit.",
8: "My expenses in burgers this month _ $350... omg...",
9: "Don't worry Gorra, we will __ you on this! -told we before leaving him alone again-.",
10: "I just ___ __ when I got the bad news: Gorra had died in horrible suffering.",
11: "It was a well secured building, but we managed to ___ __ the room and steal the money.",
12: "I'm so sad my grandpa ____ __ so soon.",
13: "This new push-up jeans hurt me! I have to ___ them __",
14: "I'm young, but not stupid. You have to stop _____ __ on me.",
15: "He is secluded at home today. His parents forced him to __ _ his little sister.",
16: "We were angry again this morning, but we __ fast because we had things to do.",
17: "Yesterday I _ __ an old school-friend. It was scary, I think he's a drug dealer now.",
18: "Hey, I'm sure you'll like arepas. C'mon, let's _ them _.",
19: "I hate this kind of formal events. I really don't want to _ for them, I hate suits!",
20: "It was sad they had to ___ because of the distance. They were a great couple.",
21: "I will never fail you, you always can ___ me.",
22: "You are still mad. You have to __ __ to drive the car, please.",
23: "__ there, soon everything will be OK!",
24: "Oh shit, I forgot my phone at the pub, __ here for a second, will be right back!",
25: "If you __ this marks , you will pass the english exam easily.",
26: "I'm sorry to ___ , but I have some information about Gorra that might help.",
27: "Please, don't _ me __. I'm fed up of being sad.",
28: "He only bought that fucking car to __ _ and prove he is richer than me.",
29: "Don't worry, she always __ _ when she smokes these Holland joints.",
30: "Everyone loves and _ _ with Gorra, but at the same time, everyone do bad to him..."}
solutions = {0: "ask out",
1: "watch out",
2: "run out",
3: "give up",
4: "hand in",
5: "check out",
6: "blew up",
7: "asking around",
8: "add up to",
9: "back up",
10: "broke down",
11: "break into",
12: "passed away",
13: "break down",
14: "look down",
15: "look after",
16: "made up",
17: "ran into",
18: "try out",
19: "dress up",
20: "break up",
21: "count on",
22: "calm down",
23: "hang in",
24: "hang on",
25: "keep up",
26: "break in",
27: "let down",
28: "show off",
29: "pass out",
30: "get along"}
hints = {0: "as_ _",
1: "ten cuidado!",
2: "r _",
3: "g_ ",
4: "h_ ",
5: "esta te la sabes tia",
6: "Explotar. b_ . Ojo al tiempo verbal.",
7: "He estado informandome. I've been as__ aro___",
8: "add ",
9: "Apoyar, estar ahi. Es igual que 'copia de seguridad'.",
10: "Cuando no puedes mas, cuando te ROMPES",
11: "Colarse: br___ ",
12: "Palmarla. En pasado. pa__ __",
13: "br_ something __, significa adecuar ropa a tu cuerpo... no se como se dice en espanol :P",
14: "Menospreciar. lo___ __",
15: "(secluded == recluido) __ after",
16: "tambien significa maquillaje",
17: "Encontrarse a alguien inesperadamente. Tambien puede ser toparse con algo. r__ __",
18: "Probar. t _",
19: "Vestirse formal. dr_ ",
20: "Cortar, romper con alguien. br_ ",
21: "Contar con!",
22: "Calmarse, tranquilizarse",
23: "Uh, este era dificil. Significa mantenerse positivo, aguantar con buena onda. ha_ ",
24: "h_ on",
25: "Mantener algo. k___ up",
26: "br___ ",
27: "l d___",
28: "Creo que es la traduccion mas cerca a FLIPARSE. s___ f",
29: "ahhhh que recuerdos... p_ _",
30: "Llevarse bien. g _"}
for x in range(0, len(shuffled_list)):
print(sentences[shuffled_list[x]])
sol = input()
if sol == "hint":
print(hints[shuffled_list[x]])
used_hints += 1
sol = input()
if sol == solutions[shuffled_list[x]]:
print("correct!")
marks += 1
total += 1
else:
print("wrong, the correct answer is: ", solutions[shuffled_list[x]])
total += 1
|
e6536e8399f1ceccd7eb7d41eddcc302e3dda66b | guv-slime/python-course-examples | /section08_ex04.py | 1,015 | 4.4375 | 4 | # Exercise 4: Expanding on exercise 3, add code to figure out who
# has the most emails in the file. After all the data has been read
# and the dictionary has been created, look through the dictionary using
# a maximum loop (see chapter 5: Maximum and Minimum loops) to find out
# who has the most messages and print how many messages the person has.
# Enter a file name: mbox-short.txt
# cwen@iupui.edu 5
# PASSED
# Enter a file name: mbox.txt
# zqian@umich.edu 195
# PASSED
# file_name = 'mbox-short.txt'
file_name = 'mbox.txt'
handle = open(file_name)
email_dic = dict()
for line in handle:
if line.startswith('From'):
words = line.split()
if len(words) < 3:
continue
else:
email_dic[words[1]] = email_dic.get(words[1], 0) + 1
most_mail = None
for email in email_dic:
if most_mail is None or email_dic[most_mail] < email_dic[email]:
# print('DA MOST AT DA MOMENT =', email, email_dic[email])
most_mail = email
print(most_mail, email_dic[most_mail])
|
f93dd7a14ff34dae2747f7fa2db22325e9d00972 | guv-slime/python-course-examples | /section08_ex03.py | 690 | 4.125 | 4 | # Exercise 3: Write a program to read through a mail log, build a histogram
# using a dictionary to count how many messages have come from each email
# address, and print the dictionary.
# Enter file name: mbox-short.txt
# {'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3,
# 'cwen@iupui.edu': 5, 'antranig@caret.cam.ac.uk': 1,
# 'rjlowe@iupui.edu': 2, 'gsilver@umich.edu': 3,
# 'david.horwitz@uct.ac.za': 4, 'wagnermr@iupui.edu': 1,
# 'zqian@umich.edu': 4, 'stephen.marquard@uct.ac.za': 2,
# 'ray@media.berkeley.edu': 1}
file_name = 'mbox-short.txt'
handle = open(file_name)
email_dic = dict()
for line in handle:
if line.startswith('From'):
words = line.split()
if len(words) < 3:
continue
else:
email_dic[words[1]] = email_dic.get(words[1], 0) + 1
print(email_dic)
|
995c34fb8474004731ba29407120537d9612529f | tacyi/tornado_overview | /chapter01/coroutine_test.py | 787 | 3.953125 | 4 | # 1.什么是协程
# 1.回调过深造成代码很难维护
# 2.栈撕裂造成异常无法向上抛出
# 协程,可被暂停并且切换到其他的协程运行的函数
from tornado.gen import coroutine
# 两种协程的写法,一种装饰器,一种3.6之后的原生的写法,推荐async
# @coroutine
# def yield_test():
# yield 1
# yield 2
# yield 3
#
# yield from yield_test()
#
# return "hello"
async def yield_test():
yield 1
yield 2
yield 3
async def main():
# await 只能写在 async下面
await yield_test()
async def main2():
# await 只能写在 async下面
# 按顺序执行,上面 遇到暂停,就进入此处的 await
await yield_test()
my_yield = yield_test()
for item in my_yield:
print(item)
|
cc7a0230928450b5bb71fa5fa6e57429a6e25882 | lmtjalves/CPD | /scripts/gen_random_big_parse_tests.py | 1,160 | 3.609375 | 4 | #!/bin/python
import sys, argparse, random
def test_rand(t):
if t == "both":
return random.randint(0,1)
elif t == "positive":
return 0
else:
return 1
parser = argparse.ArgumentParser(description="problem gen. clauses might be duplicate and have repeated variables")
parser.add_argument('min_num_vars', type=int)
parser.add_argument('max_num_vars', type=int)
parser.add_argument('min_clauses', type=int)
parser.add_argument('max_clauses', type=int)
parser.add_argument('min_vars_per_clause', type=int)
parser.add_argument('max_vars_per_clause', type=int)
parser.add_argument('--type', default="both", choices=["positive", "negative"])
args = parser.parse_args()
num_vars = random.randint(args.min_num_vars, args.max_num_vars)
num_clauses = random.randint(args.min_clauses, args.max_clauses)
print("{0} {1}".format(num_vars, num_clauses))
for i in range(1, num_clauses + 1):
num_clause_vars = random.randint(args.min_vars_per_clause, args.max_vars_per_clause)
print(" ".join([str(v) if test_rand(args.type) == 0 else str(-v) for v in [ random.randint(1, num_vars) for _ in range(num_clause_vars)]])+ " 0")
|
6214901ec8317a2ead9409991548282f5ce33c57 | bobgautier/rjgtoys-config | /examples/translate.py | 590 | 3.890625 | 4 | """
examples/translate.py: translate words using a dictionary
"""
import argparse
import os
from typing import Dict
from rjgtoys.config import Config, getConfig
class TranslateConfig(Config):
words: Dict[str, str]
cfg = getConfig(TranslateConfig)
def main(argv=None):
p = argparse.ArgumentParser()
cfg.add_arguments(p, default='translate.yaml', adjacent_to=__file__)
args, tail = p.parse_known_args(argv)
for word in tail:
result = cfg.words.get(word, "I don't know that word")
print(f"{word}: {result}")
if __name__ == "__main__":
main()
|
2d7724e5786f00b9f2c1e2f8640ebde7138f7c85 | maryamkh/MyPractices | /Find_Nearest_Smaller_Element.py | 1,930 | 3.90625 | 4 | '''
Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
Elements for which no smaller element exist, consider next smaller element as -1.
Output: An array of prev .smaller value of each item or -1(if no smaller value exists for one item.)
Example:
Input 1:
A = [4, 5, 2, 10, 8]
Output 1:
G = [-1, 4, -1, 2, 2]
Explaination 1:
index 1: No element less than 4 in left of 4, G[1] = -1
index 2: A[1] is only element less than A[2], G[2] = A[1]
index 3: No element less than 2 in left of 2, G[3] = -1
index 4: A[3] is nearest element which is less than A[4], G[4] = A[3]
index 4: A[3] is nearest element which is less than A[5], G[5] = A[3]
'''
class NearestSmallerElement:
# @param array : list of integers
# @return a list of integers
def prevSmaller(self, array):
nearestIndex = []
nearestIndex.append(-1) #first item in array does not have any item in its back==> no smaller value in its back
if len(array) == 1:
return nearestIndex
nearestItem = 0
for pivot in range(1,len(array)):
stack = array[:pivot]#array[:pivot]
while len(stack) > 0:
nearestItem = stack.pop()
if nearestItem < array[pivot]: #pivot:
nearestIndex.append(nearestItem) #len(stack) + 1
break
if len(nearestIndex) < pivot + 1: #array[i] has no value smaller than itself in its left side.===> inser -1 in nearestIndex array
nearestIndex.append(-1)
return nearestIndex
def main():
previousSmaller = NearestSmallerElement()
array = [2,7,-1,9,12,-3]
result = previousSmaller.prevSmaller(array)
print result
if __name__ == '__main__':
main()
|
ff2ac738c1718fa12bd84e447ddc9b0e1080420a | maryamkh/MyPractices | /Min_Sum_Path_Bottom_Up.py | 4,255 | 4.375 | 4 | #!usr/bin/python
'''
The approach is to calculate the minimum cost for each cell to figure out the min cost path to the target cell.
Assumpthion: The movementns can be done only to the right and down.
In the recursive approach there is a lot of redundent implementation of the sub-problems. With Dynamic programming we optimize the implementation. Dynamic programming is done by bottom-up approach in an iterative loop.
Main function: calMinCost()
'''
class MinCostPath:
def calMinCost(self, matrix, inRow, inCol):
if len(matrix) == len(matrix[0]) == 1:
return matrix[0][0]
#initialize the tracker matrix with 0
cost = [[0 for col in range(inCol)] for row in range(inRow)]
print 'cost after init...', cost
# In the first row and first column the min cost to reach each cell is equal of the cost of the cell + cost of passing all the previous cells
cost[0][0] = matrix[0][0]
#if row == 0:
#for col in range(1, len(matrix[0])):
for col in range(1, inCol):
cost[0][col] = cost[0][col-1] + matrix[0][col]
#print 'matrix[0][col]...', matrix[0][col]
#if col == 0:
#for row in range(1,len(matrix)):
for row in range(1,inRow):
cost[row][0] = cost[row-1][0] + matrix[row][0]
#print 'matrix[row][0]..', matrix[row][0]
print cost
# To calculate the min cost of other cells, for each cell we calculate the cost of reaching the cell above the target cell and the cell on the left side of the target cell (since the movements can be done only to the down and right) and choose the one which has min cost.
#for row in range(1,len(matrix)):
#for col in range(1,len(matrix[0])):
for row in range(1,inRow):
for col in range(1,inCol):
print 'row...col...', row, col
above = cost[row-1][col]
print 'above...', above
left = cost[row][col-1]
cost[row][col] = min(above, left) + matrix[row][col]
print 'cost[row][col]...,,,...', cost[row][col]
print 'row...col....cost[row-1][col-1]...', cost[row-1][col-1]
return cost[inRow-1][inCol-1]
#######################################################
def findPath(self, matrix, row, col):
print 'in function...'
if len(matrix) == len(matrix[0]) == 1:
return mtrix[0][0]
sum = 0
#untraversed rows/cols:
if row >= len(matrix)-1 or col >= len(matrix[0])-1:
while row < len(matrix) - 1: #we are in the last col of the matrix and should travers all the remaining rows till reaching the bottom-right corner
sum += matrix[row+1][-1]
print 'sum in row travers...', sum
row += 1
while col < len(matrix[0]) - 1: #we are on the last row of the matrix and should travers all the remaining columns to reach the bottom-right corner of the matrix
sum += matrix[-1][col+1]
print 'sum in column travers...', sum
col += 1
return sum
if row < len(matrix)-1 and col < len(matrix[0])-1:
if matrix[row][col+1] < matrix[row+1][col]: #make a right step
#sum += math.min(matrix[row][col+1], matrix[row+1][col])
#sum += matrix[row][col+1]
#col = col + 1
print 'matrix[row+1][col] in righ move...', matrix[row][col+1]
sum = matrix[row][col+1] + self.findPath(matrix, row, col+1)
else: #make a down step
#sum += matrix[row+1][col]
#row = row + 1
print 'matrix[row+1][col] in down step...', matrix[row+1][col]
sum = matrix[row+1][col] + self.findPath(matrix, row+1, col)
sum = sum + matrix[0][0]
return sum
def main():
#matrix = [[1,3], [5,2]]
matrix = [[1,7,9,2],[8,6,3,2],[1,6,7,8],[2,9,8,2]]
minPath = MinCostPath()
#result = minPath.calMinCost(matrix, 4, 4)
result = minPath.findPath(matrix, 1, 1)
print result
if __name__ == '__main__':
main()
|
bd745cc83163bd91f36ab2f2d034f7f0a02093c0 | maryamkh/MyPractices | /Pow_function_recursive.py | 697 | 3.921875 | 4 | '''
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Time Complexity: O(log(n))===> In this solution n is reduce to half and therefore this is the time cimplexity
Spcae Complexity: We need to do the computation for O(logn) times, so the space complexity is O(logn)
'''
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x = 1/x
n = abs(n)
if n==0:
return 1
res = self.myPow(x, n//2)
if n%2 == 0:
return res*res
else:
return res*res*x
|
d1917f2bd44d327224cfb121c1d18f68c5de2383 | maryamkh/MyPractices | /Stairs.py | 2,092 | 4.09375 | 4 | #!usr/bin/python
'''
Find the numbers of ways we can reach the top of the stairs if we can only clime 1 or 2 steps each time?
Input: Integer: The stair number in which we should reach to
Output: Integer: The numebr of ways we can clime up to reach target stair
Reaching any stair with only 1 step climing or 2 steps climing means that we should first reach either:
1- A stair one step below the target step them make 1 step climing to reach the target step or
2- Two steps below the target step and then make a 2 steps climing to reach the target
===> this means that the function to each step is a fonction of its pervious step + 1 OR the functions of its 2nd previous step + 2: f(n) = f(n-1) + f(n-2)==> This is the fibonnachi series
Note: For making steps of 1, 2 or 3 climings the function is: f(n) = f(n-1) + f(n-2) + f(n-3)
Solution:
1- the problem can be solved recursively which contanins many redundent of the implementation of the subproblems.
2- the second way is to do dynamic programming using buttom-up solution and solve the problem in linear time complexity.
'''
class StairsSteps:
def calSteps(self, stairs):
checkedSteps = []
for i in range(stairs+1): #init the array with 0
checkedSteps.append(0)
if stairs == 1 or stairs == 0:
checkedSteps[stairs] = 1
return 1
for step in range(2, stairs+1):
if checkedSteps[step] == 0:
checkedSteps[step] = self.calSteps(step-1) + self.calSteps(step-2)
else:
return checkedSteps[step]
return checkedSteps[step]
###############################################################
def calStepsRecursive(self, stairs):
if stairs == 0 or stairs == 1:
return 1
return self.calStepsRecursive(stairs-1) + self.calStepsRecursive(stairs-2)
def main():
steps = StairsSteps()
result = steps.calSteps(4)
#result = steps.calStepsRecursive(5)
print result
if __name__ == '__main__':
main()
|
f9a66f5b0e776d063d812e7a7185ff6ff3c5615f | maryamkh/MyPractices | /ReverseLinkedList.py | 2,666 | 4.3125 | 4 | '''
Reverse back a linked list
Input: A linked list
Output: Reversed linked list
In fact each node pointing to its fron node should point to it back node ===> Since we only have one direction accessibility to a link list members to reverse it I have to travers the whole list, keep the data of the nodes and then rearrange them backward.
Example:
Head -> 2-> 3-> 9-> 0
Head -> 0-> 9-> 3-> 2
Pseudocode:
currentNode = Head
nodeSet = set ()
While currentNode != None:
nodeSet.add(currentNode.next)
currentNode = currentNode.next
reversedSet = list(reverse(set))
currentNode = Head
while currentNode != None:
currentNode.value = reversedSet.pop()
currentNode = currentNode.next
Tests:
Head -> None
Head -> 2
Head -> 0-> 9-> 3-> 2
'''
class node:
def __init__(self, initVal):
self.data = initVal
self.next = None
def reverseList(Head):
currNode = Head
nodeStack = []
while currNode != None:
#listSet.add(currNode)
#nodeStack.append(currNode.data)
nodeStack.append(currNode)
currNode = currNode.next
# currNode = Head
# print (nodeStack)
# while currNode != None:
# #currNode.value = listSet.pop().value
# currNode.value = nodeStack.pop().data
# print (currNode.value)
# currNode = currNode.next
if len(nodeStack) >= 1:
Head = nodeStack.pop()
currNode = Head
#print (currNode.data)
while len(nodeStack) >= 1:
currNode.next = nodeStack.pop()
#print (currNode.data)
currNode = currNode.next
#print (currNode.data)
def showList(Head):
#print(f'list before reverse: {Head}')
while Head != None:
print(f'{Head.data}')
Head = Head.next
print(f'{Head}')
#Head = None
#print(f'list before reverse:\n')
#showList(Head)
#reverseList(Head)
#print(f'list after reverse:\n')
#showList(Head)
def reverse(Head):
nxt = Head.next
prev = None
Head = reverseList1(Head,prev)
print(f'new head is: {Head.data}')
def reverseList1(curr,prev):
#Head->2->3->4
#None<-2<-3<-4
if curr == None:
return prev
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return reverseList1(curr, prev)
n1 = node(2)
Head = n1
#print(f'list before reverse:\n')
#showList(Head)
#reverseList(Head)
#print(f'list after reverse:\n')
#showList(Head)
n2 = node(0)
n3 = node(88)
n4 = node(22)
n1.next = n2
n2.next = n3
n3.next = n4
Head = n1
print(f'list before reverse:\n')
showList(Head)
##reverseList(Head)
reverse(Head)
Head = n4
print(f'n1 value: {Head.data}')
showList(Head)
|
145413092625adbe30b158c21e5d27e2ffcfab50 | maryamkh/MyPractices | /Squere_Root.py | 1,838 | 4.1875 | 4 | #!/usr/bin/python
'''
Find the squere root of a number. Return floor(sqr(number)) if the numebr does not have a compelete squere root
Example: input = 11 ===========> output = 3
Function sqrtBinarySearch(self, A): has time complexity O(n), n: given input: When the number is too big it becomes combursome
'''
class Solution:
def sqrt(self, A):
n = 1
while n*n <= A:
n += 1
if A == n*n: return n
elif n < (n-.5) * (n-.5): return n-1
else: return n+1
def sqrtBinarySearch(self, A):
searchList = []
#print range(A)
for i in range(A):
searchList.append(i+1)
for i in range(len(searchList)):
mid = len(searchList)/2
#if mid > 0:
number = searchList[mid-1]
sqrMid = number * number
sqrMidPlus = (number+1) * (number+1)
#print 'sqrMid...sqrMidPlus...', sqrMid, sqrMidPlus
if sqrMid == A: return number
elif sqrMid > A: #sqrt is in the middle left side of the array
searchList = searchList[:mid]
#print 'left wing...', searchList
elif sqrMid < A and sqrMidPlus > A: # sqrMid< sqrt(A)=number.xyz <sqrMidPlus==> return floor(number.xyz)
print
if (number + .5) * (number + .5) > A: return number
return number+1
else:
searchList = searchList[mid:]
#print 'right wing...', searchList
def main():
inputNum = int(input('enter a number to find its squere root: '))
sqroot = Solution()
result = sqroot.sqrt(inputNum)
result1 = sqroot.sqrtBinarySearch(inputNum)
print result
print result1
if __name__ == '__main__':
main()
|
55ab2d3473fb7ff9485f1ff835dd599d427e0a5d | hokiespider/win_probability | /win_probability.py | 4,054 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import requests
import json
# What school are you analyzing?
school = "Virginia Tech"
# Get data from the API
df = pd.DataFrame()
for x in range(2013, 2020, 1): # Line data is only available 2013+
parameters = {
"team": school,
"year": x
}
response = requests.get("https://api.collegefootballdata.com/lines", params=parameters)
# Import the data into a pandas DataFrame
temp = pd.DataFrame(response.json()) # Create a DataFrame with a lines column that contains JSON
# need to fill NA line lists for 2020
temp = temp.explode('lines') # Explode the DataFrame so that each line gets its own row
temp = temp.reset_index(drop=True) # After explosion, the indices are all the same - this resets them so that you can align the DataFrame below cleanly
lines_df = pd.DataFrame(temp.lines.tolist()) # A separate lines DataFrame created from the lines JSON column
temp = pd.concat([temp, lines_df], axis=1) # Concatenating the two DataFrames along the vertical axis.
df = df.append(temp)
df = df[df.provider == 'consensus']
df['spread'] = df.spread.astype('float')
# Add Win/Loss columns
home_games = df[df.homeTeam == school].copy()
home_games['score_diff'] = home_games['homeScore'] - home_games['awayScore']
home_games['home_away'] = "Home"
home_games.loc[home_games['score_diff'] > 0, 'wins'] = 1
home_games.loc[home_games['score_diff'] < 0, 'losses'] = 1
away_games = df[df.awayTeam == school].copy()
away_games['score_diff'] = away_games['awayScore'] - away_games['homeScore']
away_games['home_away'] = "away"
away_games.loc[away_games['score_diff'] > 0, 'wins'] = 1
away_games.loc[away_games['score_diff'] < 0, 'losses'] = 1
away_games['spread'] = away_games['spread'] * -1
df = home_games.append(away_games)
#records = df.groupby(['season'])['wins', 'losses'].sum()
# Import the odds of winning
filename = '/Users/appleuser/Documents/win_probability/odds_of_winning_lines.csv'
odds = pd.read_csv(filename)
odds = odds.melt(id_vars='Spread', value_vars=['Favorite', 'Underdog'], var_name='Type', value_name="Expected Wins")
odds.loc[odds['Spread'] == '20+', 'Spread'] = 20
odds['Spread'] = odds.Spread.astype('float')
odds.loc[odds['Type'] == "Favorite", 'Spread'] = odds['Spread'] * -1
df.loc[df['spread'] >= 20, 'spread'] = 20
df.loc[df['spread'] <= -20, 'spread'] = -20
df = df.merge(odds, how='left', left_on='spread', right_on='Spread')
df.loc[df['spread'] < 0, 'spread_group'] = '3. 0.5-6.5 Favorites'
df.loc[df['spread'] < -6.5, 'spread_group'] = '2. 7-14 Favorites'
df.loc[df['spread'] < -13.5, 'spread_group'] = ' 1. 14+ Favorites'
df.loc[df['spread'] == 0, 'spread_group'] = '4. pick-em'
df.loc[df['spread'] > 0, 'spread_group'] = '5. 0.5-6.5 Dogs'
df.loc[df['spread'] > 6.5, 'spread_group'] = '6. 7-14 Dogs'
df.loc[df['spread'] > 13.5, 'spread_group'] = '7. 14+ Dogs'
df.loc[df['season'] >= 2016, 'Coach'] = 'Fuente 2016-2019'
df.loc[df['season'] < 2016, 'Coach'] = 'Beamer 2013 - 2015'
groups = df.groupby(['Coach', 'spread_group'])['wins', 'losses', 'Expected Wins'].sum().round(2)
groups['win_perc'] = groups.apply(lambda x: x['wins'] / (x['wins'] + x['losses']), axis=1).round(2)
groups['wins vs expectation'] = groups['wins'] - groups['Expected Wins'].round(2)
groups
groups.to_clipboard()
coaches = df.groupby(['Coach'])['wins', 'losses', 'Expected Wins'].sum().round(2)
coaches['win_perc'] = coaches.apply(lambda x: x['wins'] / (x['wins'] + x['losses']), axis=1).round(2)
coaches['wins vs expectation'] = coaches['wins'] - coaches['Expected Wins'].round(2)
coaches
years = df.groupby(['season', 'spread_group'])['wins', 'losses', 'Expected Wins'].sum().round(2)
years['win_perc'] = years.apply(lambda x: x['wins'] / (x['wins'] + x['losses']), axis=1).round(2)
years['wins vs expectation'] = years['wins'] - years['Expected Wins'].round(2)
years.reset_index()
years = years.drop(['wins', 'losses', 'Expected Wins', 'win_perc'], axis=1)
years = years.unstack('spread_group')
years
years.to_clipboard()
|
65256d3f3d66a41bd69be4dc55bb89b2c643036e | DaniRyland-Lawson/CP1404-cp1404practicals- | /prac_06/demo_program.py | 1,784 | 3.75 | 4 | """CP1404 Programming II demo program week 6 prac
0. Pattern based programming
1. Names based on problem domain
2. Functions at the same leve of abstraction( main should "look" the same
Menu- driven program
load products
- L_ist products
- S_wap sale status (get product number with error checking)
- Q_uit (save file)
"""
PRODUCTS_FILE = "products.csv"
MENU_STRING = ">>>"
def main():
products = load_products()
print(products)
print(MENU_STRING)
menu_selection = input(">").upper()
while menu_selection != "Q":
if menu_selection == "L":
list_products(products)
elif menu_selection == "S":
swap_sale_status(products)
else:
print("Invalid")
print(MENU_STRING)
menu_selection = input(">").upper()
save_products(products)
print("Finished")
def load_products():
print("loading")
products = [["Phone", 340, False], ["PC", 1420.95, True], ["Plant", 24.50, True]]
return products
def list_products(products):
print("list")
for product in products:
print(product)
def swap_sale_status(products):
list_products(products)
is_valid_input = False
while not is_valid_input:
try:
number = int(input("? "))
if number < 0:
print("Product must be >= 0")
else:
is_valid_input = True
except ValueError:
print("Invalid (not an integer)")
print(products[number])
# make CSV from list of lists
def save_products(products):
with open("products.csv", "r") as output_file:
for product in output_file:
sale_status = 'y' if product[2] else 'n'
print("{}, {}, {}".format(product[0], product[1], sale_status))
main()
|
e47f166763aad48f70da971a79953db8875531b7 | DaniRyland-Lawson/CP1404-cp1404practicals- | /prac_07/miles_to_kms.py | 1,154 | 3.53125 | 4 | """CP1404 Programming II Week 7 Kivy - Gui Program to convert Miles to Kilometres."""
from kivy.app import App
from kivy.lang import Builder
from kivy.app import StringProperty
MILES_TO_KM = 1.60934
class MilesToKilometres(App):
output_km = StringProperty()
def build(self):
self.title = "Convert Miles to Kilometres"
self.root = Builder.load_file('miles_to_kms.kv')
return self.root
def handle_convert(self, text):
"""handle calculation """
# print("handle calculation")
miles = self.convert_to_number(text)
self.update_result(miles)
def handle_increment(self, text, change):
"""handle button press up and down"""
# print("handle adding")
miles = self.convert_to_number(text) + change
self.root.ids.input_miles.text = str(miles)
def update_result(self, miles):
# print("update")
self.output_km = str(miles * MILES_TO_KM)
@staticmethod
def convert_to_number(text):
try:
value = float(text)
return value
except ValueError:
return 0.0
MilesToKilometres().run()
|
4a20f0a4d156b03c5e658e0073f8086ab5ca0b95 | DaniRyland-Lawson/CP1404-cp1404practicals- | /prac_08/unreliable_car_test.py | 676 | 3.640625 | 4 | """CP1404 Programming II
Test to see of UnreliableCar class works."""
from prac_08.unreliable_car import UnreliableCar
def main():
"""Test for UnreliableCars."""
# Create some cars for reliability
good_car = UnreliableCar("Good Car", 100, 90)
bad_car = UnreliableCar("Bad Car", 100, 10)
# Attempts to drive the cars multiple times
# Output is what the drove in kms
for i in range(1, 10):
print("Attempting to drive {}km: ".format(i))
print("{:10} drove {:2}km".format(good_car.name, good_car.drive(i)))
print("{:10} drove {:2}km".format(bad_car.name, bad_car.drive(i)))
print(good_car)
print(bad_car)
main()
|
de7b30a4f51727085b556dc01763180a3fdedffd | Monkin6/yarygin | /hm4.py | 132 | 3.5 | 4 | n = int(input())
maximum = -1
while n != 0:
if n % 10 > maximum:
maximum = n % 10
n = n // 10
print(maximum)
|
c0c510cbebedb03947bb2b9ed16c16efa23a4956 | Sahil-k1509/Python_and_the_Web | /Scripts/Miscellaneous/Email_extractor/extract_emails.py | 407 | 3.78125 | 4 | #!/usr/bin/env python3
import re
print("Enter the name of the input file: ")
file=str(input())
try:
f = open(file,"r")
except FileNotFoundError:
print("File does not exists")
email={}
for i in f:
em = re.findall('\S+@\S+\.\S+',i)
for j in em:
email[j]=email.get(j,0)+1
f.close()
for i in email:
if(email[i]>=2):
print(i,email[i])
else:
print(i)
|
d99e28fea0f6d213659694f220451d12930dcd84 | Mertvbli/JustTry | /CW_filter_list_7kyu.py | 363 | 3.640625 | 4 | def filter_list(l):
new_list = []
for number in l:
if str(number).isdigit() and str(number) != number:
new_list.append(number)
return new_list # or [number for number in l if isinstance(number, int)
print(filter_list([1,2,'a','b']))
print(filter_list([1,'a','b',0,15]))
print(filter_list([1,2,'aasf','1','123',123]))
|
ddbfeec96361f4c3576874c2ff007d88717f1566 | CodingDojoDallas/python_sep_2018 | /austin_parham/product.py | 948 | 3.671875 | 4 | class Product:
def __init__(self,price,item_name,weight,brand):
self.price = price
self.item_name = item_name
self.weight = weight
self.brand = brand
self.status = "for sale"
self.display_info()
def sell(self):
self.status = "sold"
return self
def add_tax(self,x):
self.price = (self.price * x) + self.price
self.display_info()
def return_item(self,reason_for_return):
if "like new" in reason_for_return:
self.status = "for sale"
else:
if "opened" in reason_for_return:
self.status = "used"
self.price = self.price - (self.price * .2)
else:
self.status = reason_for_return
self.price = 0
self.display_info()
def display_info(self):
print("Price:",self.price)
print("Name:",self.item_name)
print("Weight:",self.weight)
print("Brand",self.brand)
print("Status:",self.status)
print('*' * 80)
shoes = Product(45,"shoes","2kg","adidas")
shoes.sell()
shoes.return_item("opened") |
13dac1bd992f843d432a94f266a283671e39c2fa | CodingDojoDallas/python_sep_2018 | /Solon_Burleson/Basics.py | 370 | 3.796875 | 4 | # def allOdds():
# for x in range(3001):
# if x % 2 != 0:
# print (x)
# allOdds()
# def Iterate(arr):
# for x in arr:
# print (x)
# Iterate([1,2,3,4,5])
# def Sumlist(arr):
# sum = 0
# for x in arr:
# sum += x
# return sum
# print(Sumlist([1,2,3,4,5]))
list = [3,5,1,2]
for i in range(len(list)):
print(i) |
bb488183c87ed750f3cd459bda9d758416b5613e | CodingDojoDallas/python_sep_2018 | /austin_parham/func_intermediate_1.py | 819 | 3.828125 | 4 | def randInt():
import random
hold = (random.random()*100)
hold = int(hold)
print(hold)
randInt()
def randInt():
import random
hold = (random.random()*50)
hold = int(hold)
print(hold)
randInt()
def randInt():
import random
hold = (random.uniform(50,100))
hold = int(hold)
print(hold)
randInt()
def randInt(): #alternate method without uniform
import random
hold = (random.random()*100)
hold = int(hold)
while hold < 50:
hold = (random.random()*100)
hold = int(hold)
print(hold)
randInt()
def randInt():
import random
hold = (random.uniform(50,500))
hold = int(hold)
print(hold)
randInt()
def randInt(): #alternate method without uniform
import random
hold = (random.random()*500)
hold = int(hold)
while hold < 400:
hold = (random.random()*500)
hold = int(hold)
print(hold)
randInt() |
8b9f850c53a2a020b1deea52e301de0d2b6c47c3 | CodingDojoDallas/python_sep_2018 | /austin_parham/user.py | 932 | 4.15625 | 4 | class Bike:
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print(self.price)
print(self.max_speed)
print(self.miles)
print('*' * 80)
def ride(self):
print("Riding...")
print("......")
print("......")
self.miles = self.miles + 10
def reverse(self):
print("Reversing...")
print("......")
print("......")
self.miles = self.miles - 5
# def reverse(self):
# print("Reversing...")
# print("......")
# print("......")
# self.miles = self.miles + 5
# Would use to not subtract miles from reversing
bike1 = Bike(200,120,20000)
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
bike2 = Bike(600,150,5000)
bike2.ride()
bike2.ride()
bike2.reverse()
bike2.reverse()
bike2.displayInfo()
lance = Bike(4000,900,60000)
lance.reverse()
lance.reverse()
lance.reverse()
lance.displayInfo()
|
60abefff5fa43ad4a30bee1e102f3a31a08c15b6 | CodingDojoDallas/python_sep_2018 | /albert_garcia/python_oop/slist.py | 1,276 | 3.78125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class SList:
def __init__(self, value):
node = Node(value)
self.head = node
def Addnode(self, value):
node = Node(value)
runner = self.head
while (runner.next != None):
runner = runner.next
runner.next = node
def PrintAllValues(self, msg=""):
runner = self.head
print("\n\nhead points to head")
print("Printing the values in the list ---", msg,"---")
while (runner.next != None):
print("runner =", runner.value)
runner = runner.next
print("runner =", runner.value)
def RemoveNode(self, value):
runner = self.head
if self.head.value == value:
self.head = self.head.next
holder = runner
while runner.next != None:
if runner.value == value:
holder.next = runner.next
holder = runner
runner = runner.next
if runner.value == value and runner.next == None:
holder.next = None
return self
list = SList(5)
list.Addnode(7)
list.Addnode(9)
list.Addnode(1)
list.PrintAllValues()
list.RemoveNode(9) .PrintAllValues("Attempt 1") |
189bd9eb0029b856f348e9ff86f32ceb6f99d84b | CodingDojoDallas/python_sep_2018 | /Solon_Burleson/RunCode.py | 380 | 3.703125 | 4 | class MathDojo:
def __init__(self):
self.value = 0
def add(self, *nums):
for i in nums:
self.value += i
return self
def subtract(self, *nums):
for i in nums:
self.value -= i
return self
def result(self):
print(self.value)
x = MathDojo().add(2).add(2,5,1).subtract(3,2).result()
print(x)
|
ab847b8b4d3b115f88b96b560b41f076a7bd6bdc | CodingDojoDallas/python_sep_2018 | /Solon_Burleson/FunctionsIntermediateI.py | 195 | 3.65625 | 4 | import random
def randInt(max=0, min=0):
if max == 0 and min == 0:
print(int(random.random()*100))
else:
print(int(random.random()*(max-min)+min))
randInt(max=500,min=50)
|
36a4f28b97be8be2e7f6e20965bd21f554270704 | krismosk/python-debugging | /area_of_rectangle.py | 1,304 | 4.6875 | 5 | #! /usr/bin/env python3
"A script for calculating the area of a rectangle."
import sys
def area_of_rectangle(height, width = None):
"""
Returns the area of a rectangle.
Parameters
----------
height : int or float
The height of the rectangle.
width : int or float
The width of the rectangle. If `None` width is assumed to be equal to
the height.
Returns
-------
int or float
The area of the rectangle
Examples
--------
>>> area_of_rectangle(7)
49
>>> area_of_rectangle (7, 2)
14
"""
if width:
width = height
area = height * width
return area
if __name__ == '__main__':
if (len(sys.argv) < 2) or (len(sys.argv) > 3):
message = (
"{script_name}: Expecting one or two command-line arguments:\n"
"\tthe height of a square or the height and width of a "
"rectangle".format(script_name = sys.argv[0]))
sys.exit(message)
height = sys.argv[1]
width = height
if len(sys.argv) > 3:
width = sys.argv[1]
area = area_of_rectangle(height, width)
message = "The area of a {h} X {w} rectangle is {a}".format(
h = height,
w = width,
a = area)
print(message)
|
dda3e4ff366d47cea012f9bfede9819fac448af9 | BlueAlien99/minimax-reversi | /app/gui/utils.py | 8,441 | 3.515625 | 4 | import enum
import pygame
from typing import List
import pygame.freetype
from pygame_gui.elements.ui_drop_down_menu import UIDropDownMenu
from pygame_gui.elements.ui_text_entry_line import UITextEntryLine
import time
class Color(enum.Enum):
NO_COLOR = -1
BLACK = "#212121"
WHITE = "#f5f5f5"
GREEN = "#388e3c"
ORANGE = "#ffc107"
BROWN = "#795548"
class State(enum.Enum):
""" Different states of the board tile
UNCHECKED -- tile is unchecked (GREEN)
BLACK -- checked black
WHITE -- checked white """
UNCHECKED = 0
BLACK = 1
WHITE = 2
class Board:
""" Represents tiled game board """
class Tile:
""" Represents single board tile """
"""
big_rect is always black it is used to display border around tiles
if tile is in POSSIBLE_CHECK state:
* normal_rect is orange
* small rect is green
else:
* normal_rect is green
* small_rect is not displayed
"""
def __init__(self, screen, x: int, y: int):
self.screen = screen
self.x = x
self.y = y
self.big_rect = pygame.Rect(
self.x - Board.tile_size,
self.y - Board.tile_size,
2 * Board.tile_size,
2 * Board.tile_size
)
self.normal_rect = pygame.Rect(
self.x - Board.tile_size + Board.tile_b_size,
self.y - Board.tile_size + Board.tile_b_size,
2 * Board.tile_size - 2 * Board.tile_b_size,
2 * Board.tile_size - 2 * Board.tile_b_size
)
self.small_rect = pygame.Rect(
self.x - Board.tile_size + Board.tile_b_size2,
self.y - Board.tile_size + Board.tile_b_size2,
2 * Board.tile_size - 2 * Board.tile_b_size2,
2 * Board.tile_size - 2 * Board.tile_b_size2
)
def draw(self, state: State, is_possible_check: bool):
""" Draws a tile """
pygame.draw.rect(self.screen, Color.BLACK.value, self.big_rect)
if is_possible_check:
pygame.draw.rect(self.screen, Color.ORANGE.value, self.normal_rect)
pygame.draw.rect(self.screen, Color.GREEN.value, self.small_rect)
else:
pygame.draw.rect(self.screen, Color.GREEN.value, self.normal_rect)
if state == State.BLACK:
pygame.draw.circle(self.screen, Color.BLACK.value, (self.x, self.y),
Board.tile_size - Board.tile_padding)
elif state == State.WHITE:
pygame.draw.circle(self.screen, Color.WHITE.value, (self.x, self.y),
Board.tile_size - Board.tile_padding)
def is_clicked(self, x, y):
""" Returns True if tile was clicked """
return self.big_rect.collidepoint((x, y))
tile_size = 40
tile_padding = 10
# outer tile border size
tile_b_size = 2
# border size of the orange indicator displayed when there is possible move on the tile
tile_b_size2 = 6
rows = 8
cols = 8
def __init__(self, screen, board_x=0, board_y=0):
""" Creates tiled board of size 8x8 """
self.tiles = [
[
Board.Tile(screen, board_x + (2*c + 1)*self.tile_size, board_y + (2*r + 1)*self.tile_size)
for c in range(self.cols)
]
for r in range(self.rows)
]
def draw(self, board_state, valid_moves):
y = 0
for row in self.tiles:
x = 0
for tile in row:
tile.draw(State(board_state[x][y]), valid_moves[x][y] < 0)
x += 1
y += 1
def is_clicked(self, mouse_x, mouse_y) -> (int, int):
""" Checks if any tile was clicked
If a tile was clicked returns its coordinates
Returns (-1, -1) otherwise """
y = 0
for row in self.tiles:
x = 0
for tile in row:
if tile.is_clicked(mouse_x, mouse_y):
return x, y
x += 1
y += 1
return -1, -1
class Text:
""" Simple text field """
def __init__(self, screen, x: int, y: int, text: str, color: Color = Color.BLACK):
self.font = pygame.freetype.SysFont('Comic Sans MS', 24)
self.x = x
self.y = y
self.screen = screen
self.text = text
self.color = color
def set_text(self, text: str):
self.text = text
def draw(self):
text_surface, rect = self.font.render(self.text, self.color.value)
self.screen.blit(text_surface, (self.x, self.y))
class DropDownWithCaption:
""" Dropdown list with caption """
def __init__(self, screen, ui_manager, x: int, y: int,
options_list: List[str], starting_option: str, caption_text: str):
self.x = x
self.y = y
self.screen = screen
self.caption = Text(screen, x, y, caption_text)
self.current_option = starting_option
self.dropdown = UIDropDownMenu(options_list=options_list,
starting_option=starting_option,
relative_rect=pygame.Rect((x, y+24), (140, 40)),
manager=ui_manager)
def set_caption(self, caption_text: str):
self.caption.set_text(caption_text)
def update_current_option(self, option: str):
self.current_option = option
def get_current_option(self) -> str:
return self.current_option
def draw(self):
self.caption.draw()
class TextBoxWithCaption:
""" Text input box with caption """
def __init__(self, screen, ui_manager, x: int, y: int, caption_text: str, initial_value: str = "1"):
self.x = x
self.y = y
self.screen = screen
self.caption = Text(screen, x+7, y, caption_text)
self.text_box = UITextEntryLine(relative_rect=pygame.Rect((x, y+24), (30, 30)),
manager=ui_manager)
self.text_box.set_text(initial_value)
def get_int(self) -> int:
""" Returns the text that is currently in the box. Returns 1 if it is empty """
text = self.text_box.get_text()
if text == "":
return 1
else:
return int(self.text_box.get_text())
def __validate_input(self):
text = ""
try:
text = self.text_box.get_text()
val = int(text)
if val > 10:
self.text_box.set_text("10")
elif val <= 0:
self.text_box.set_text("1")
except ValueError:
if text == "":
self.text_box.set_text(text)
else:
self.text_box.set_text("1")
def draw(self):
self.__validate_input()
self.caption.draw()
class Timer:
""" Timer that displays minutes and seconds in mm:ss format """
def __init__(self, screen, x: int, y: int):
self.font = pygame.freetype.SysFont('Comic Sans MS', 24)
self.x = x
self.y = y
self.screen = screen
self.seconds = 0
self.minutes = 0
self.started = False
def tick(self):
if self.started:
self.seconds += 1
if self.seconds == 60:
self.minutes += 1
self.seconds = 0
def reset(self):
self.minutes = self.seconds = 0
self.started = False
def start(self):
self.started = True
def draw(self):
t = (2009, 2, 17, 17, self.minutes, self.seconds, 1, 48, 36)
t = time.mktime(t)
text = time.strftime("%M:%S", time.gmtime(t))
text_surface, rect = self.font.render(text, (0, 0, 0))
self.screen.blit(text_surface, (self.x, self.y))
""" Utility functions """
def draw_arrow(screen, x: int, y: int, size_x: int, size_y: int, color: Color = Color.BLACK):
pygame.draw.polygon(screen, color.value,
((x, y + 2*size_y), (x, y + 4*size_y), (x + 4*size_x, y + 4*size_y),
(x + 4*size_x, y + 6*size_y), (x + 6*size_x, y + 3*size_y),
(x + 4*size_x, y), (x + 4*size_x, y + 2*size_y)))
|
dacaf7998b9ca3a71b6b90690ba952fb56349ab9 | Kanthus123/Python | /Design Patterns/Creational/Abstract Factory/doorfactoryAbs.py | 2,091 | 4.1875 | 4 | #A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.
#Extending our door example from Simple Factory.
#Based on your needs you might get a wooden door from a wooden door shop,
#iron door from an iron shop or a PVC door from the relevant shop.
#Plus you might need a guy with different kind of specialities to fit the door,
#for example a carpenter for wooden door, welder for iron door etc.
#As you can see there is a dependency between the doors now,
#wooden door needs carpenter, iron door needs a welder etc.
class Door:
def get_descricao(self):
raise NotImplementedError
class WoodenDoor(Door):
def get_descricao(self):
print('Eu sou uma porta de Madeira')
def IronDoor(Door):
def get_descricao(self):
print('Eu sou uma porta de Ferro')
class DoorFittingExpert:
def get_descricao(self):
raise NotImplementedError
class Welder(DoorFittingExpert):
def get_descricao(self):
print('Eu apenas posso colocar portas de ferro')
class Carpenter(DoorFittingExpert):
def get_descricao(self):
print('Eu apenas posso colocar portas de madeira')
class DoorFactory:
def fazer_porta(self):
raise NotImplementedError
def fazer_profissional(self):
raise NotImplementedError
class WoodenDoorFactory(DoorFactory):
def fazer_porta(self):
return WoodenDoor()
def fazer_profissional(self):
return Carpenter()
class IronDoorFactory(DoorFactory):
def fazer_porta(self):
return IronDoor()
def fazer_profissional(self):
return Welder()
if __name__ == '__main__':
wooden_factory = WoodenDoorFactory()
porta = wooden_factory.fazer_porta()
profissional = wooden_factory.fazer_profissional()
porta.get_descricao()
profissional.get_descricao()
iron_factory = IronDoorFactory()
porta = iron_factory.fazer_porta()
profissional = iron_factory.fazer_profissional()
porta.get_descricao()
profissional.get_descricao()
|
ab049070f8348f4af8caeb601aee062cc7a76af2 | Kanthus123/Python | /Design Patterns/Structural/Decorator/VendaDeCafe.py | 1,922 | 4.46875 | 4 | #Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.
#Imagine you run a car service shop offering multiple services.
#Now how do you calculate the bill to be charged?
#You pick one service and dynamically keep adding to it the prices for the provided services till you get the final cost.
#Here each type of service is a decorator.
class Cofe:
def get_custo(self):
raise NotImplementedError
def get_descricao(self):
raise NotImplementedError
class CafeSimples(Cafe):
def get_custo(self):
return 10
def get_descricao(self):
return 'Cafe Simples'
class CafeComLeite(self):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 2
def get_descricao(self):
return self.cafe.get_descricao() + ', leite'
class CafeComCreme(Cafe):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 5
def get_descricao(self):
return self.cafe.get_descricao() + ', creme'
class Capuccino(Cafe):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 3
def get_descricao(self):
return self.cafe.get_descricao() + ', chocolate'
if __name__ == '__main__':
cafe = CafeSimples()
assert cafe.get_custo() == 10
assert coffee.get_description() == 'Cafe Simples'
cafe = CafeComLeite(cafe)
assert coffee.get_cost() == 12
assert coffee.get_description() == 'Cafe Simples, Leite'
cafe = CafeComCreme(cafe)
assert coffee.get_cost() == 17
assert coffee.get_description() == 'Cafe Simples, Leite, Creme'
cafe = Capuccino(cafe)
assert coffee.get_cost() == 20
assert coffee.get_description() == 'Cafe Simples, Leite, Chocolate'
|
4bcdaa732a2a499c3e52a902911b1a6cbc6636bf | Kanthus123/Python | /Design Patterns/Behavioral/Strategy/main.py | 817 | 3.671875 | 4 | #Strategy pattern allows you to switch the algorithm or strategy based upon the situation.
#Consider the example of sorting, we implemented bubble sort but the data started to grow and bubble sort started getting very slow.
#In order to tackle this we implemented Quick sort. But now although the quick sort algorithm was doing better for large datasets,
#it was very slow for smaller datasets. In order to handle this we implemented a strategy where for small datasets,
#bubble sort will be used and for larger, quick sort.
from order import Order
from calculate_shipping import CalculateShipping
from shippings import Default, Express
calculate_shipping = CalculateShipping()
order = Order(500)
calculate_shipping.execute_calculation(order, Default())
calculate_shipping.execute_calculation(order, Express())
|
478e6714f68fb421aff714cf178486c60d46980b | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-14/python/solution.py | 376 | 3.78125 | 4 | from functools import reduce
# 位运算 写法1
def singleNumber1(nums: [int]) -> int:
return reduce(lambda x, y: x ^ y, nums)
# 位运算 写法2
def singleNumber2(nums: [int]) -> int :
result = nums[0]
for i in range(1,len(nums)) :
result ^= nums[i]
return result
if __name__ == "__main__" :
nums = [2,3,4,3,2]
print(singleNumber2(nums)) |
ba0c5f0469a2b8ef74c669af85355c81c4a40eb6 | russellgao/algorithm | /dailyQuestion/2020/2020-10/10-10/python/solution.py | 891 | 4 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def partition(head: ListNode, x: int) -> ListNode:
first = first_head = ListNode(0)
second = second_head = ListNode(0)
while head:
if head.val < x:
first.next = head
first = first.next
else:
second.next = head
second = second.next
head = head.next
second.next = None
first.next = second_head.next
return first_head.next
if __name__ == "__main__" :
node = ListNode(1)
node.next = ListNode(4)
node.next.next = ListNode(3)
node.next.next.next = ListNode(2)
node.next.next.next.next = ListNode(5)
node.next.next.next.next.next = ListNode(2)
result = partition(node,3)
while result :
print(result.val)
result = result.next |
a6f65dc2d6ac9f5f160229c2dc76b2d74c150550 | russellgao/algorithm | /dailyQuestion/2020/2020-07/07-29/python/solution_n.py | 263 | 3.890625 | 4 |
# 一次遍历
def missingNumber(nums: [int]) -> int:
for i,v in enumerate(nums) :
if i != v :
return i
return nums[-1] + 1
if __name__ == "__main__" :
nums = [0,1,2,3,4,5,6,7,9]
result = missingNumber(nums)
print(result) |
1587894d5e65ee725de94d02e15cd0ec84f1987b | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-02/python/solution.py | 445 | 3.515625 | 4 |
def lengthOfLongestSubstring(s: str) -> int:
tmp = set()
result = 0
j = 0
n = len(s)
for i in range(n) :
if i != 0 :
tmp.remove(s[i-1])
while j < n and s[j] not in tmp :
tmp.add(s[j])
j += 1
result = max(result, j - i)
return result
if __name__ == "__main__" :
a = [23,4,5,6]
s = "abcabcbb"
result = lengthOfLongestSubstring(s)
print(result)
|
47ddbc6c436d80ff4ba68199da5e803edabf3402 | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-22/python/solution_dlinknode.py | 2,137 | 3.84375 | 4 | # 双向链表求解
class DlinkedNode():
def __init__(self):
self.key = 0
self.value = 0
self.next = None
self.prev = None
class LRUCache():
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.cache = {}
self.head = DlinkedNode()
self.tail = DlinkedNode()
self.head.next = self.tail
self.tail.prev = self.head
def _add_node(self, node):
""" 始终放在head的右边 """
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def _remove_node(self, node):
"""删除一个节点"""
_prev = node.prev
_next = node.next
_prev.next = _next
_next.prev = _prev
def _move_to_head(self, node):
"""
先删除再增加
:param node:
:return:
"""
self._remove_node(node)
self._add_node(node)
def _pop_tail(self):
"""
删除最后一个节点的前一个
:return:
"""
res = self.tail.prev
self._remove_node(res)
return res
def get(self, key: int) -> int:
node = self.cache.get(key, None)
if not node:
return -1
self._move_to_head(node)
return node.value
def put(self, key: int, value: int) -> None:
node = self.cache.get(key, None)
if not node:
node = DlinkedNode()
node.key = key
node.value = value
self.size += 1
self.cache[key] = node
self._add_node(node)
if self.size > self.capacity:
tail = self._pop_tail()
del self.cache[tail.key]
self.size -= 1
else:
node.value = value
self._move_to_head(node)
if __name__ == "__main__" :
lru = LRUCache(2)
lru.put(1,1)
lru.put(2,2)
a = lru.get(1)
lru.put(3,3)
b = lru.get(2)
lru.put(4,4)
c = lru.get(1)
d = lru.get(3)
e = lru.get(4)
print()
|
98786826bd97d037c30c7f2b4244b7101ccd963e | russellgao/algorithm | /data_structure/heap/python/002.py | 1,317 | 4.03125 | 4 | # 堆排序
def buildMaxHeap(lists):
"""
构造最大堆
:param lists:
:return:
"""
llen = len(lists)
for i in range(llen >> 1, -1, -1):
heapify(lists, i, llen)
def heapify(lists, i, llen):
"""
堆化
:param lists:
:param i:
:return:
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < llen and lists[left] > lists[largest]:
largest = left
if right < llen and lists[right] > lists[largest]:
largest = right
if largest != i :
swap(lists, i, largest)
heapify(lists, largest, llen)
def swap(lists, i, j):
"""
交换列表中的两个元素
:param lists:
:param i:
:param j:
:return:
"""
lists[i], lists[j] = lists[j], lists[i]
def heapSort(lists):
"""
堆排序,从小到大进行排序
需要构造一个最大堆,然后首位交换,然后lists 的长度-1, 重复这个过程,直至lists中只剩一个元素
:param lists:
:return:
"""
llen = len(lists)
buildMaxHeap(lists)
for i in range(len(lists)-1, 0, -1):
swap(lists, 0, i)
llen -= 1
heapify(lists, 0, llen)
return lists
if __name__ == "__main__":
arr = [8, 3, 5, 1, 6, 4, 9, 0, 2]
b = heapSort(arr)
print(b)
|
77ec5582550e18cce771f24058e78bc18686ec9a | russellgao/algorithm | /dailyQuestion/2020/2020-04/04-29/python/solution.py | 1,683 | 3.84375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 方法一
# 递归,原问题可以拆分成自问题,并且自问题和原问题的问题域完全一样
# 本题以前k个listnode 为原子进行递归
def reverseKGroup1(head: ListNode, k: int) -> ListNode:
cur = head
count = 0
while cur and count!= k:
cur = cur.next
count += 1
if count == k:
# 以k个进行递归
cur = reverseKGroup1(cur, k)
while count:
# 在k个单位内进行反转
tmp = head.next
head.next = cur
cur = head
head = tmp
count -= 1
head = cur
return head
# 方法二
def reverseKGroup2(head: ListNode, k: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
pre = dummy
tail = dummy
while True:
count = k
while count and tail:
count -= 1
tail = tail.next
if not tail:
break
head = pre.next
while pre.next != tail:
cur = pre.next # 获取下一个元素
# pre与cur.next连接起来,此时cur(孤单)掉了出来
pre.next = cur.next
cur.next = tail.next # 和剩余的链表连接起来
tail.next = cur # 插在tail后面
# 改变 pre tail 的值
pre = head
tail = head
return dummy.next
if __name__ == "__main__" :
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
node.next.next.next = ListNode(4)
node.next.next.next.next = ListNode(5)
result = reverseKGroup2(node,2)
print()
|
30cea365bbb1ea986b435692edfb5eb4118249cc | russellgao/algorithm | /dailyQuestion/2020/2020-08/08-06/python/solution_dict.py | 1,341 | 3.71875 | 4 | def palindromePairs(words: [str]) -> [[int]]:
indices = {}
result = []
n = len(words)
def reverse(word):
_w = list(word)
n = len(word)
for i in range(n >> 1):
_w[i], _w[n - 1 - i] = _w[n - i - 1], _w[i]
return "".join(_w)
def isPalindromes(word: str, left: int, right:int) -> bool:
for i in range(right - left + 1):
if word[left + i] != word[right - i]:
return False
return True
def findWord(word, left, right):
v = indices.get(word[left:right+1])
if v is not None :
return v
return -1
for i in range(n):
indices[reverse(words[i])] = i
for i in range(n):
word = words[i]
m = len(word)
for j in range(m + 1):
if isPalindromes(word, j, m - 1) :
leftid = findWord(word, 0 , j-1)
if leftid != -1 and leftid != i :
result.append([i,leftid])
if j > 0 and isPalindromes(word, 0,j-1) :
leftid = findWord(word,j,m-1)
if leftid != -1 and leftid != i :
result.append([i,leftid])
return result
if __name__ == "__main__" :
words = ["abcd", "dcba", "lls", "s", "sssll"]
result = palindromePairs(words)
print(result)
|
32c5ca8e7beb18feafd101e6e63da060c3c47647 | russellgao/algorithm | /data_structure/binaryTree/preorder/preoder_traversal_items.py | 695 | 4.15625 | 4 |
# 二叉树的中序遍历
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 迭代
def preorderTraversal(root: TreeNode) ->[int]:
result = []
if not root:
return result
queue = [root]
while queue:
root = queue.pop()
if root:
result.append(root.val)
if root.right:
queue.append(root.right)
if root.left:
queue.append(root.left)
return result
if __name__ == "__main__":
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
result = preorderTraversal(root)
print(result)
|
5723367d25964f32d4f5bc67a99e3f824309f639 | russellgao/algorithm | /dailyQuestion/2020/2020-10/10-01/python/solution.py | 927 | 4.03125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def increasingBST(root: TreeNode) -> TreeNode:
result = node = TreeNode(0)
queue = []
while root or len(queue) > 0 :
while root :
queue.append(root)
root = root.left
root = queue[len(queue)-1]
queue = queue[:len(queue)-1]
node.right = TreeNode(root.val)
node = node.right
root = root.right
return result.right
if __name__ == "__main__" :
node = TreeNode(3)
node.left = TreeNode(5)
node.right = TreeNode(1)
node.left.left = TreeNode(6)
node.left.right = TreeNode(2)
node.left.right.left = TreeNode(7)
node.left.right.right = TreeNode(4)
node.right.left = TreeNode(0)
node.right.right = TreeNode(8)
result = increasingBST(node)
print(result) |
b8189f9da4e8491b8871a75225d4376c9ea2cc0c | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-06/python/solution.py | 476 | 3.796875 | 4 |
def longestConsecutive(nums: [int]) -> int:
nums = set(nums)
longest = 0
for num in nums:
if num - 1 not in nums:
current = num
current_len = 1
while current + 1 in nums:
current += 1
current_len += 1
longest = max(longest, current_len)
return longest
if __name__ == "__main__" :
nums = [100, 4, 200, 1, 3, 2]
result = longestConsecutive(nums)
print(result)
|
cb8bdd7d8b00d9b6214787b82fe5766228741eee | russellgao/algorithm | /data_structure/sort/tim_sort.py | 2,031 | 3.734375 | 4 | import time
def binary_search(the_array, item, start, end): # 二分法插入排序
if start == end:
if the_array[start] > item:
return start
else:
return start + 1
if start > end:
return start
mid = round((start + end) / 2)
if the_array[mid] < item:
return binary_search(the_array, item, mid + 1, end)
elif the_array[mid] > item:
return binary_search(the_array, item, start, mid - 1)
else:
return mid
def insertion_sort(the_array):
l = len(the_array)
for index in range(1, l):
value = the_array[index]
pos = binary_search(the_array, value, 0, index - 1)
the_array = the_array[:pos] + [value] + the_array[pos:index] + the_array[index + 1:]
return the_array
def merge(left, right): # 归并排序
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
def timSort(the_array):
runs, sorted_runs = [], []
length = len(the_array)
new_run = []
for i in range(1, length): # 将序列分割成多个有序的run
if i == length - 1:
new_run.append(the_array[i])
runs.append(new_run)
break
if the_array[i] < the_array[i - 1]:
if not new_run:
runs.append([the_array[i - 1]])
new_run.append(the_array[i])
else:
runs.append(new_run)
new_run = []
else:
new_run.append(the_array[i])
for item in runs:
sorted_runs.append(insertion_sort(item))
sorted_array = []
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
print(sorted_array)
arr = [45, 2.1, 3, 67, 21, 90, 20, 13, 45, 23, 12, 34, 56, 78, 90, 0, 1, 2, 3, 1, 2, 9, 7, 8, 4, 6]
t0 = time.perf_counter()
timSort(arr)
t1 = time.perf_counter()
print('共%.5f秒' % (t1 - t0))
|
a4d555397fb194beb604dd993a6b08c746409046 | russellgao/algorithm | /dailyQuestion/2020/2020-07/07-11/python/solution.py | 546 | 3.828125 | 4 | def subSort(array: [int]) -> [int]:
n = len(array)
first,last = -1,-1
if n == 0 :
return [first,last]
min_a = float("inf")
max_a = float("-inf")
for i in range(n) :
if array[i] >= max_a :
max_a = array[i]
else :
last = i
if array[n-1-i] <= min_a :
min_a = array[n-1-i]
else :
first = n-i-1
return [first,last]
if __name__ == "__main__" :
array = [1,2,4,7,10,11,7,12,6,7,16,18,19]
result = subSort(array)
print(result) |
c836d3a26bb6d7432f734c7a771df38e8aaec095 | russellgao/algorithm | /dailyQuestion/2020/2020-07/07-18/python/solution_recurse.py | 708 | 3.875 | 4 | def isInterleave(s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
m = len(s1)
n = len(s2)
t = len(s3)
if m + n != t:
return False
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for i in range(m + 1):
for j in range(n + 1):
if i > 0:
dp[i][j] = dp[i][j] or (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1])
if j > 0:
dp[i][j] = dp[i][j] or (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])
return dp[m][n]
if __name__ == "__main__" :
s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbbaccc"
result = isInterleave(s1,s2,s3)
print(result)
|
bd9249d9d6593d652adca04e69220e3326615cd4 | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-14/python/solution_vertical.py | 432 | 3.96875 | 4 | def longestCommonPrefix(strs: [str]) -> str:
if not strs:
return ""
length, count = len(strs[0]), len(strs)
for i in range(length):
c = strs[0][i]
if any(i == len(strs[j]) or strs[j][i] != c for j in range(1, count)):
return strs[0][:i]
return strs[0]
if __name__ == "__main__":
strs = ["flower", "flow", "flight"]
result = longestCommonPrefix(strs)
print(result)
|
ff3ce63ef2e076344a7e1226b9fadf5a37a5653b | russellgao/algorithm | /dailyQuestion/2021/2021-03/03-20/python/solution.py | 961 | 3.515625 | 4 | class Solution:
def evalRPN(self, tokens: [str]) -> int:
stack = []
for i in range(len(tokens)) :
tmp = tokens[i]
if tmp == "+" :
num1 = stack.pop()
num2 = stack.pop()
stack.append(num2 + num1)
elif tmp == "-" :
num1 = stack.pop()
num2 = stack.pop()
stack.append(num2 - num1)
elif tmp == "*" :
num1 = stack.pop()
num2 = stack.pop()
stack.append(num2 * num1)
elif tmp == "/" :
num1 = stack.pop()
num2 = stack.pop()
stack.append(int(num2 / num1))
else :
stack.append(int(tmp))
return stack[0]
if __name__ == "__main__" :
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
s = Solution()
res = s.evalRPN(tokens)
print(res)
|
9d4fa8524fe6b0b3172debd49bf081e98f5a0282 | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-09/python/solution_mod.py | 335 | 3.6875 | 4 | # 动态求余法
def translateNum(num: int) -> int:
f_1 = f_2 = 1
while num:
pre = num % 100
f = f_1 + f_2 if pre >= 10 and pre <= 25 else f_1
f_2 = f_1
f_1 = f
num = num // 10
return f_1
if __name__ == '__main__' :
num = 12258
result = translateNum(num)
print(result)
|
861fab844f5dcbf86c67738354803e27a0a303e9 | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-31/python/solution_recursion.py | 950 | 4.21875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 递归
def isSymmetric(root: TreeNode) -> bool:
def check(left, right):
if not left and not right:
return True
if not left or not right:
return False
return left.val == right and check(left.left, right.right) and check(left.right, right.left)
return check(root, root)
if __name__ == "__main__":
# root = TreeNode(1)
# root.left = TreeNode(2)
# root.right = TreeNode(2)
#
# root.left.left = TreeNode(3)
# root.left.right = TreeNode(4)
#
# root.right.left = TreeNode(4)
# root.right.right = TreeNode(3)
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.right.right = TreeNode(3)
result = isSymmetric(root)
print(result)
|
21f1cf35cd7b3abe9d67607712b62bfa4732e4ce | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-01/python/solution.py | 944 | 4.125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def reverseList(head):
"""
递归 反转 链表
:type head: ListNode
:rtype: ListNode
"""
if not head :
return None
if not head.next :
return head
last = reverseList(head.next)
head.next.next = head
head.next = None
return last
def reverseList_items(head) :
"""
迭代 反转 链表
:type head: ListNode
:rtype: ListNode
"""
pre = None
current = head
while current:
tmp = current.next
current.next = pre
pre = current
current = tmp
return pre
if __name__ == '__main__':
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
node.next.next.next = ListNode(4)
node.next.next.next.next = ListNode(5)
result = reverseList(node)
print() |
86bee5da92c7b029a182b67d9e3aa4bb2eb1b949 | franztrierweiler/maths_python | /exercices_02mars.py | 2,000 | 3.8125 | 4 | from fractions import *
def somme():
S = 1
for i in range (1,21):
S = S + pow(Fraction(1,3),i)
# Converts fraction to float
# and returns the result
return float(S);
def compte_espaces(phrase):
nbre = 0
for caractere in phrase:
if caractere==" ":
nbre=nbre+1
return nbre
def Syracuse(n):
resultat = n
while (resultat!=1):
if (resultat % 2) == 0:
resultat = resultat // 2
else:
resultat = (3 * resultat) + 1
return resultat
def Syracuse2(n):
resultat = n
compteur = 0
while (resultat!=1):
compteur = compteur + 1
if (resultat % 2) == 0:
resultat = resultat // 2
else:
resultat = (3 * resultat) + 1
return compteur
def Maximum(n):
# We are looking for the value between 0 and n for which
# Syracuse2(n) is the greatest.
i = 1
candidat = i
temps_vol = 1
while (i <= n):
# Check if new flight length is greater than previous one !
if (Syracuse2(i) > temps_vol):
temps_vol = Syracuse2(i)
candidat = i
i = i + 1
return candidat
def produit_impairs(i):
P = 1
for k in range (1, i):
P = P * (2*k - 1)
return P
print ("Somme = " + str(somme() ))
la_phrase = "Voici une phrase pour le programmeur Badie"
print ("Il y a " + str(compte_espaces(la_phrase)) + " espaces dans la phrase - " + la_phrase + "-")
N=5000
print("Temps de vol le plus haut entre 1 et N = " + str(N) + " est pour n = " + str(Maximum(N)))
print("Il vaut " + str(Syracuse2(Maximum(N))))
n=10000000000
print("Syracuse(" + str(n) + ") = " + str(Syracuse(n)) + " avec un temps de vol de " + str(Syracuse2(n)))
N=2
print ("Produit des " + str(N) + "-1 premiers nombres impairs = " + str(produit_impairs(N)))
N=5
print ("Produit des " + str(N) + "-1 premiers nombres impairs = " + str(produit_impairs(N))) |
407273956e8e87a116912ee44dc192e8233f5fac | swainsubrat/Haw | /Dependencies/DataFrameBuilder.py | 5,313 | 3.9375 | 4 | """
Structures dataframes for plotting
"""
import re
import pandas as pd
from io import StringIO
from pandas.core.frame import DataFrame
def basicDataFrameBuilder(FILE: StringIO) -> DataFrame:
"""
Function to pre-process the raw text file and format it
to get a dataframe out of it
1. Datetime extraction.
2. Name extraction.
Args:
FILE(StringIO): File containing raw extracted text.
Returns:
df(DataFrame): Dataframe of the messages.
"""
lines = FILE.readlines()
list_df = []
for line in lines:
line = line.rstrip('\n').split(" - ")
if re.search(r"\d\d\/\d\d\/\d\d\d\d, (\d\d|\d):\d\d", line[0]):
name_message = line[1].split(": ")
if len(name_message) <= 1:
continue
date, time = line[0].split(", ")
name = name_message[0]
message = ""
for i in range(1, len(name_message)):
message += name_message[i]
list_df.append([date, time, name, message])
else:
try:
for item in line:
list_df[-1][-1] += item
except Exception as e:
print("Exception:", e)
df = DataFrame(list_df, columns=['Date', 'Time', 'Name', 'Message'])
df['Day'] = pd.DatetimeIndex(df['Date']).day
df['Month'] = pd.DatetimeIndex(df['Date']).month
df['Month_Year'] = pd.to_datetime(df['Date']).dt.to_period('M')
df['Year'] = pd.DatetimeIndex(df['Date']).year
return df
def messageDataFrameBuilder(FILE: StringIO,
TOP: int=10) -> dict:
"""
Function to process the messages of the members
1. Message count, group by Name.
2. Message count, group by Date.
3. Message count, group by Month.
4. Message count, group by Year.
Args:
FILE(StringIO): File containing raw extracted text.
TOP(int): Top n names to show and show others as Others.
Returns:
dfm(dict(DataFrame)): Dataframes after processing
"""
df = basicDataFrameBuilder(FILE=FILE)
dfm = df.groupby('Name').Message.count().\
reset_index(name="Message Count")
dfm.sort_values(
by="Message Count",
ascending=False,
inplace=True,
ignore_index=True
)
dfm.loc[dfm.index >= TOP, 'Name'] = 'Others'
dfm = dfm.groupby(
"Name"
)["Message Count"].sum().reset_index(name="Message Count")
dfm.sort_values(
by="Message Count",
ascending=False,
inplace=True,
ignore_index=True)
# dfmD = df.groupby('Date').Message.count().\
# reset_index(name='Count')
# dfmMY = df.groupby('Month_Year').Message.count().\
# reset_index(name='Count')
dfmY = df.groupby('Year').Message.count().\
reset_index(name='Count')
DFM = {
"dfm": dfm,
# "dfmD": dfmD,
# "dfmMY": dfmMY,
"dfmY": dfmY
}
return DFM
def emojiDataFrameBuilder(FILE: StringIO,
TOP: int=10) -> dict:
"""
Function to process the emojis of the members
1. Emoji count, group by Name.
2. Emoji count, group by Date.
3. Emoji count, group by Month.
4. Emoji count, group by Year.
5. Emoji count, group by Type.
Args:
FILE(StringIO): File containing raw extracted text.
TOP(int): Top n names to show and show others as Others.
Returns:
dfm(dict(DataFrame)): Dataframes after processing
"""
df = basicDataFrameBuilder(FILE=FILE)
import emoji
total = 0
count = {}
emoji_cnt = []
for message in df['Message']:
emoji_cnt.append(emoji.emoji_count(message))
emoji_list = emoji.emoji_lis(message)
for item in emoji_list:
if (item["emoji"] in count):
count[item["emoji"]] += 1
else:
count[item["emoji"]] = 1
total += emoji.emoji_count(message)
columns = ['Emojis', 'Count']
dfe = pd.DataFrame(columns=columns)
for key, value in count.items():
data = {'Emojis': key, 'Count': value}
dfe = dfe.append(data, ignore_index=True)
dfe.sort_values(by="Count",
ascending=False,
inplace=True,
ignore_index=True)
dfe.loc[dfe.index >= TOP, 'Emojis'] = 'Others'
dfe = dfe.groupby("Emojis")["Count"].sum().reset_index(name="Count")
df.insert(loc=6, column='Emoji Count', value=emoji_cnt)
# dfeD = df.groupby('Date')['Emoji Count'].sum().\
# reset_index(name='Count')
# dfeMY = df.groupby('Month_Year')['Emoji Count'].sum().\
# reset_index(name='Count')
dfeY = df.groupby('Year')['Emoji Count'].sum().\
reset_index(name='Count')
dfeg = df.groupby('Name')['Emoji Count'].sum().\
reset_index(name="Count")
dfeg.sort_values(
by="Count",
ascending=False,
inplace=True,
ignore_index=True
)
dfeg.loc[dfeg.index >= TOP, 'Name'] = 'Others'
dfeg = dfeg.groupby("Name")["Count"].sum().reset_index(name="Count")
DFE = {
"dfe": dfe,
"dfeg": dfeg,
# "dfeD": dfeD,
# "dfeMY": dfeMY,
"dfeY": dfeY
}
return DFE
|
fc94459d32944d0e67d1870d0b2e864263dc8319 | Narusi/Python-Kurss | /Uzdevums Lists.py | 3,209 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Klases Uzdevumi - Lists
# ## 1.a Vidējā vērtība
# Uzrakstīt programmu, kas liek lietotājam ievadīt skaitļus(float).
# Programma pēc katra ievada rāda visu ievadīto skaitļu vidējo vērtību.
# PS. 1a var iztikt bez lists
#
# 1.b Programma rāda gan skaitļu vidējo vērtību, gan VISUS ievadītos skaitļus
# PS Iziešana no programmas ir ievadot "q"
#
# 1.c Programma nerāda visus ievadītos skaitļus bet gan tikai TOP3 un BOTTOM3 un protams joprojām vidējo.
# In[2]:
numbs = []
while True:
numberStr = input("\nIevadiet skaitli: ")
if "q" not in numberStr.lower():
if "," in numberStr:
numberStr = numberStr.replace(',','.').strip()
numbs.append(float(numberStr))
print("Vidējā vērtība:",sum(numbs)/len(numbs))
numbs.sort()
print("Visi ievadītie skaitļi:",numbs)
if len(numbs) >= 6:
print("TOP3 un BOTTOM3:",numbs[:3] + numbs[-3:])
print("Pēdējais ievadītais skaitlis:",float(numberStr))
else:
break
# ## 2. Kubu tabula
# Lietotājs ievada sākumu (veselu skaitli) un beigu skaitli.
# Izvads ir ievadītie skaitļi un to kubi
# <br>Piemēram: ievads 2 un 5 (divi ievadi)
# <br>Izvads
# <br>2 kubā: 8
# <br>3 kubā: 27
# <br>4 kubā: 64
# <br>5 kubā: 125
# <br>Visi kubi: [8,27,64,125]
# <br><br>PS teoretiski varētu iztikt bez list, bet ar list būs ērtāk
# In[1]:
pirmaisSk = int(input("Ievadiet sākotnējo skaitli: "))
otraisSk = int(input("Ievadiet noslēdzošo skaitli: "))
kubi = []
for i in range(pirmaisSk, otraisSk+1):
print("{} kubā: {}".format(i, i**3))
kubi.append(i**3)
print('Visi kubi:', kubi)
# ## 3. Apgrieztie vārdi
# Lietotājs ievada teikumu.
# Izvadam visus teikuma vārdus apgrieztā formā.
# <br>Alus kauss -> Sula ssuak
# <br>PS Te varētu noderēt split un join operācijas.
# In[3]:
teikums = input("Ievadiet teikumu: ")
smukiet = []
jaunsTeik = True
for vards in teikums.split(" "):
if "." in vards:
smukiet.append(vards[:-1][::-1].lower()+".")
jaunsTeik = True
elif "!" in vards:
smukiet.append(vards[:-1][::-1].lower()+"!")
jaunsTeik = True
elif "?" in vards:
smukiet.append(vards[:-1][::-1].lower()+"?")
jaunsTeik = True
else:
if jaunsTeik:
smukiet.append(vards[::-1].title())
jaunsTeik = False
else:
smukiet.append(vards[::-1].lower())
print(" ".join(smukiet))
# ## 4. Pirmskaitļi
# šis varētu būt nedēļas nogales uzdevums, klasē diez vai pietiks laika
# Atrodiet un izvadiet pirmos 20 (vēl labāk iespēja izvēlēties cik pirmos pirmskaitļus gribam) pirmskaitļus saraksta veidā t.i. [2,3,5,7,11,...]
# In[5]:
numbCount = int(input("Ieavadiet pirmskaitļu skaitu: "))
nCount = 2
numb = 3
pirmsskaitli = [1, 2]
while nCount <= numbCount:
irPSkaitlis = True
for i in range(2,numb):
if numb % i == 0:
irPSkaitlis = False
if irPSkaitlis:
nCount += 1
pirmsskaitli.append(numb)
numb += 1
print(pirmsskaitli)
# In[ ]:
|
d278d8c5efedbd61317118887461b052690dd605 | wulinlw/leetcode_cn | /常用排序算法/quicksort.py | 828 | 3.8125 | 4 | #!/usr/bin/python
#coding:utf-8
# 快速排序
def partition(arr,low,high):
i = ( low-1 ) # 最小元素索引
pivot = arr[high]
for j in range(low , high):
# 当前元素小于或等于 pivot
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
# print(i,arr)
arr[i+1],arr[high] = arr[high],arr[i+1]#交换下i+1he结尾,用于下次基准比较
# print(arr)
return ( i+1 )
# 快速排序函数
# arr[] --> 排序数组
# low --> 起始索引
# high --> 结束索引
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
return arr
arr = [1,2,5,3,4]
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
re = quickSort(arr,0,n-1)
print(re) |
8beaa095846c553f6c970e062494b068733a5d6a | wulinlw/leetcode_cn | /leetcode-vscode/671.二叉树中第二小的节点.py | 2,205 | 3.734375 | 4 | #
# @lc app=leetcode.cn id=671 lang=python3
#
# [671] 二叉树中第二小的节点
#
# https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/description/
#
# algorithms
# Easy (45.43%)
# Likes: 61
# Dislikes: 0
# Total Accepted: 8.5K
# Total Submissions: 18.6K
# Testcase Example: '[2,2,5,null,null,5,7]'
#
# 给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或
# 0。如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。
#
# 给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。
#
# 示例 1:
#
#
# 输入:
# 2
# / \
# 2 5
# / \
# 5 7
#
# 输出: 5
# 说明: 最小的值是 2 ,第二小的值是 5 。
#
#
# 示例 2:
#
#
# 输入:
# 2
# / \
# 2 2
#
# 输出: -1
# 说明: 最小的值是 2, 但是不存在第二小的值。
#
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 最小的是root
# dfs查找,
# 边界条件是
# 1.到空节点还没发现比root大的,就是都相等,返回-1
# 2.找到立即返回
# 左边都小于root,那就在右边有大于的
# 右边都小于root,那就在左边有大于的
# 左右都大于就返回较小的
def findSecondMinimumValue(self, root: TreeNode) -> int:
if not root: return -1
minval = root.val
def dfs(root):
nonlocal minval
if not root :return -1
if root.val>minval:
return root.val
l = dfs(root.left)
r = dfs(root.right)
if l<0:return r
if r<0:return l
return min(l,r)
return dfs(root)
# @lc code=end
t1 = TreeNode(2)
t2 = TreeNode(2)
t3 = TreeNode(5)
t4 = TreeNode(5)
t5 = TreeNode(7)
root = t1
root.left = t2
root.right = t3
t3.left = t4
t3.right = t5
o = Solution()
print(o.findSecondMinimumValue(root)) |
8504344ee52ab7c26d4e0a926e97ad8a8874308f | wulinlw/leetcode_cn | /程序员面试金典/面试题01.05.一次编辑.py | 1,707 | 3.75 | 4 | #!/usr/bin/python
#coding:utf-8
# 面试题 01.05. 一次编辑
# 字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
# 示例 1:
# 输入:
# first = "pale"
# second = "ple"
# 输出: True
# 示例 2:
# 输入:
# first = "pales"
# second = "pal"
# 输出: False
# https://leetcode-cn.com/problems/one-away-lcci/
from typing import List
class Solution:
#编辑距离 类似题目,动态规划
#这题没有动态规划
def oneEditAway(self, first: str, second: str) -> bool:
if abs(len(first)-len(second)) > 1: #长度差大于1,false
return False
replace_count = 0
if len(first) == len(second): #长度相等,不同字符>2,false
for i in range(len(first)):
if first[i] != second[i]:
replace_count += 1
if replace_count >= 2:
return False
return True
#相差1的情况下,长串去掉当前字符,看看是否和短串一样
if len(second) > len(first): #长的放前面
first,second = second, first
if len(first) > len(second):
for i in range(len(first)): #遍历长的,每次取走一个,剩下的和second比是否一样
if first[0:i] + first[i+1:] == second:
return True
return False
first = "pale"
second = "ple"
o = Solution()
print(o.oneEditAway(first, second)) |
539c0e8e5f78fb080ec39bf80e69aa14161cbc3c | wulinlw/leetcode_cn | /剑指offer/55_2_平衡二叉树.py | 1,298 | 3.609375 | 4 | #!/usr/bin/python
#coding:utf-8
# // 面试题55(二):平衡二叉树
# // 题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中
# // 任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 归并的套路,先拿到子结果的集,在处理资结果的集
def IsBalanced(self, root):
if not root :return True, 0 #结束的时候是0
left, left_depth = self.IsBalanced(root.left)
right, right_depth = self.IsBalanced(root.right)
if left and right:
depth = left_depth - right_depth
if 1>=depth and depth>=-1: #高度不超过1
depth = 1+max(left_depth,right_depth)
return True,depth
return False,None
# 测试树
# 6
# 2 8
# 1 4 7 9
t1 = TreeNode(1)
t2 = TreeNode(2)
t4 = TreeNode(4)
t6 = TreeNode(6)
t7 = TreeNode(7)
t8 = TreeNode(8)
t9 = TreeNode(9)
root = t6
root.left = t2
root.right = t8
t2.left = t1
t2.right = t4
t8.left = t7
t8.right = t9
obj = Solution()
print(obj.IsBalanced(root)) |
28cb62abf374b9a10b964d944b5b858474c2422c | wulinlw/leetcode_cn | /leetcode-vscode/872.叶子相似的树.py | 1,729 | 3.921875 | 4 | #
# @lc app=leetcode.cn id=872 lang=python3
#
# [872] 叶子相似的树
#
# https://leetcode-cn.com/problems/leaf-similar-trees/description/
#
# algorithms
# Easy (62.23%)
# Likes: 49
# Dislikes: 0
# Total Accepted: 9.7K
# Total Submissions: 15.5K
# Testcase Example: '[3,5,1,6,2,9,8,null,null,7,4]\n' +
# '[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]'
#
# 请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。
#
#
#
# 举个例子,如上图所示,给定一颗叶值序列为 (6, 7, 4, 9, 8) 的树。
#
# 如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。
#
# 如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false 。
#
#
#
# 提示:
#
#
# 给定的两颗树可能会有 1 到 100 个结点。
#
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
def dfs(root,re):
if not root :return None
if not root.left and not root.right:
re.append(root.val)
dfs(root.left,re)
dfs(root.right,re)
return re
r1=dfs(root1,[])
r2=dfs(root2,[])
return r1==r2
# @lc code=end
# 2
# 2 5
# 5 7
t1 = TreeNode(2)
t2 = TreeNode(2)
t3 = TreeNode(5)
t4 = TreeNode(5)
t5 = TreeNode(7)
root = t1
root.left = t2
root.right = t3
t2.left = t4
t2.right = t5
o = Solution()
print(o.leafSimilar(root,root)) |
efcf849ffdf2209df24b021a2dff59c5138618aa | wulinlw/leetcode_cn | /程序员面试金典/面试题05.04.下一个数.py | 5,329 | 3.515625 | 4 | # #!/usr/bin/python
# #coding:utf-8
#
# 面试题05.04.下一个数
#
# https://leetcode-cn.com/problems/closed-number-lcci/
#
# 下一个数。给定一个正整数,找出与其二进制表达式中1的个数相同且大小最接近的那两个数(一个略大,一个略小)。
# 示例1:
#
#
# 输入:num = 2(或者0b10)
# 输出:[4, 1] 或者([0b100, 0b1])
#
#
# 示例2:
#
#
# 输入:num = 1
# 输出:[2, -1]
#
#
# 提示:
#
#
# num的范围在[1, 2147483647]之间;
# 如果找不到前一个或者后一个满足条件的正数,那么输出 -1。
#
#
#
# Medium 39.5%
# Testcase Example: 2
#
# 提示:
# 下一步:从每个蛮力解法开始。
# 下一个:想象一个二进制数,在整个数中分布一串1和0。假设你把一个1翻转成0,把一个0翻转成1。在什么情况下数会更大?在什么情况下数会更小?
# 下一步:如果你将1翻转成0,0翻转成1,假设 0 -> 1位更大,那么它就会变大。你如何使用这个来创建下一个最大的数字(具有相同数量的1)?
# 下一步:你能翻转0到1,创建下一个最大的数字吗?
# 下一步:把0翻转为1将创建一个更大的数字。索引越靠右,数字越大。如果有一个1001这样的数字,那么我们就想翻转最右边的0(创建1011)。但是如果有一个1010这样的数字,我们就不应该翻转最右边的1。
# 下一步:我们应该翻转最右边但非拖尾的0。数字1010会变成1110。完成后,我们需要把1翻转成0让数字尽可能小,但要大于原始数字(1010)。该怎么办?如何缩小数字?
# 下一步:我们可以通过将所有的1移动到翻转位的右侧,并尽可能地向右移动来缩小数字(在这个过程中去掉一个1)。
# 获取前一个:一旦你解决了“获取后一个”,请尝试翻转“获取前一个”的逻辑。
#
#
from typing import List
class Solution:
# 比 num 大的数:从右往左,找到第一个 01 位置,然后把 01 转为 10,右侧剩下的 1 移到右侧的低位,右侧剩下的位清0。
# 比 num 小的数:从右往左,找到第一个 10 位置,然后把 10 转为 01,右侧剩下的 1 移到右侧的高位,右侧剩下的位置0。
# https://leetcode-cn.com/problems/closed-number-lcci/solution/wei-yun-suan-by-suibianfahui/
def findClosedNumbers(self, num: int) -> List[int]:
mn, mx = 1, 2147483647
def findLarge(n):
# 从右开始找到第1个1
# 然后记录1的个数ones直到再遇到0或到最高位
# 然后将这个0变成1
# 然后右边的位数用000...111(ones-1个1)填充
checkMask = 1
bits = 0
while checkMask <= n and checkMask & n == 0: #找到左边第一个1为止
checkMask <<= 1
bits += 1 #右边0的个数
ones = 0
while checkMask <= n and checkMask & n != 0: #找到第一个0
ones = (ones << 1) + 1 #左边1的个数
checkMask <<= 1
bits += 1 #找到01,一共左移了多少位,
ones >>= 1 #因为ones初始化为1, 所以ones需要右移一位
n |= checkMask #01变10
# print("{:0>32b}".format(n))
n = (n >> bits) << bits #右边都变成0了
n |= ones #将右边填充上ones
return n if mn <= n <= mx else -1
def findSmall(n):
# 从右开始找到第1个0, 记录此过程1的个数ones
# 然后继续往左找直到再遇到1
# 然后将这个1变成0, ones也要左移一位(也可以初始化为1)
# 然后右边的位数用高位ones个1填充, 即构造出111...000, 可以直接基于ones构造
# 注意如果全为1的话是无解的, 直接返回-1
checkMask = 1
bits = 0
ones = 1
while checkMask <= n and checkMask & n != 0: #找到第一个0
checkMask <<= 1
bits += 1
ones = (ones << 1) + 1 #记录有多少1
if checkMask > n:
# 全部是1
return -1
while checkMask <= n and checkMask & n == 0: #在找第一个1
checkMask <<= 1
bits += 1
ones <<= 1
# print("{:0>32b}".format(ones))
ones >>= 1 #因为ones初始化为1, 所以ones需要右移一位
n &= ~checkMask #10变01
n = (n >> bits) << bits #右边都变成0了
n |= ones #将右边填充上ones
return n if mn <= n <= mx else -1
return [findLarge(num), findSmall(num)]
o = Solution()
print(o.findClosedNumbers(2)) |
c8eab7467ee25294d227d9d16ef6cea5f97d7ab2 | wulinlw/leetcode_cn | /程序员面试金典/面试题02.07.链表相交.py | 3,147 | 3.6875 | 4 | #!/usr/bin/python
#coding:utf-8
# 面试题 02.07. 链表相交
# 给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。
# 示例 1:
# 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
# 输出:Reference of the node with value = 8
# 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
# 示例 2:
# 输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
# 输出:Reference of the node with value = 2
# 输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
# 示例 3:
# 输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
# 输出:null
# 输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
# 解释:这两个链表不相交,因此返回 null。
# 注意:
# 如果两个链表没有交点,返回 null 。
# 在返回结果后,两个链表仍须保持原有的结构。
# 可假定整个链表结构中没有循环。
# 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
# https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def initlinklist(self, nums):
head = ListNode(nums[0])
re = head
for i in nums[1:]:
re.next = ListNode(i)
re = re.next
return head
def printlinklist(self, head):
re = []
while head:
re.append(head.val)
head = head.next
print(re)
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:return None
l1,l2=headA,headB
while l1!=l2:
l1=l1.next if l1 else headB
l2=l2.next if l2 else headA
return l1
#
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n1.next = n2
n2.next = n3 #第一个公共节点
n3.next = n4
n4.next = n5
n2_1 = ListNode(1)
n2_2 = ListNode(2)
n2_1.next = n2_2
n2_2.next = n3 #第一个公共节点
#测试用例需要造一个公共节点,ListNode内存地址是同一个
#不能用2个独立创建的链表
h = o.getIntersectionNode(n1, n2_1)
print(h.val)
# o.printlinklist(h)
|
b282517a21d331b04566b1697602e99244800f48 | wulinlw/leetcode_cn | /leetcode-vscode/15.三数之和.py | 2,939 | 3.546875 | 4 | #
# @lc app=leetcode.cn id=15 lang=python3
#
# [15] 三数之和
#
# https://leetcode-cn.com/problems/3sum/description/
#
# algorithms
# Medium (25.70%)
# Likes: 2228
# Dislikes: 0
# Total Accepted: 241.9K
# Total Submissions: 874.9K
# Testcase Example: '[-1,0,1,2,-1,-4]'
#
# 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0
# ?请你找出所有满足条件且不重复的三元组。
#
# 注意:答案中不可以包含重复的三元组。
#
#
#
# 示例:
#
# 给定数组 nums = [-1, 0, 1, 2, -1, -4],
#
# 满足要求的三元组集合为:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ]
#
#
#
from typing import List
# @lc code=start
class Solution:
# 特判,对于数组长度 nn,如果数组为 nullnull 或者数组长度小于 33,返回 [][]。
# 对数组进行排序。
# 遍历排序后数组:
# 若 nums[i]>0nums[i]>0:因为已经排序好,所以后面不可能有三个数加和等于 00,直接返回结果。
# 对于重复元素:跳过,避免出现重复解
# 令左指针 L=i+1L=i+1,右指针 R=n-1R=n−1,当 L<RL<R 时,执行循环:
# 当 nums[i]+nums[L]+nums[R]==0nums[i]+nums[L]+nums[R]==0,执行循环,判断左界和右界是否和下一位置重复,去除重复解。并同时将 L,RL,R 移到下一位置,寻找新的解
# 若和大于 00,说明 nums[R]nums[R] 太大,RR 左移
# 若和小于 00,说明 nums[L]nums[L] 太小,LL 右移
# https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
def threeSum(self, nums: List[int]) -> List[List[int]]:
n=len(nums)
res=[]
if(not nums or n<3):
return []
nums.sort() #先排序
res=[]
for i in range(n):
if(nums[i]>0): #当前大于0,后面的都大于他,和不可能为0,直接返回结果
return res
if(i>0 and nums[i]==nums[i-1]): #连续相同的跳过
continue
L=i+1 #初始化l为下一个,r为最右
R=n-1
while(L<R):
if(nums[i]+nums[L]+nums[R]==0):
res.append([nums[i],nums[L],nums[R]]) #找到了,下面跳过左右指针的相同值
while(L<R and nums[L]==nums[L+1]):
L=L+1
while(L<R and nums[R]==nums[R-1]):
R=R-1
L=L+1
R=R-1
elif(nums[i]+nums[L]+nums[R]>0): #大于0右边-1,反之左边+1
R=R-1
else:
L=L+1
return res
# @lc code=end
|
c1de2f72e8609e27c4c06ec7c843559d6ae6e447 | wulinlw/leetcode_cn | /程序员面试金典/面试题08.03.魔术索引.py | 1,651 | 3.84375 | 4 | # #!/usr/bin/python
# #coding:utf-8
#
# 面试题08.03.魔术索引
#
# https://leetcode-cn.com/problems/magic-index-lcci/
#
# 魔术索引。 在数组A[0...n-1]中,有所谓的魔术索引,满足条件A[i] = i。给定一个有序整数数组,编写一种方法找出魔术索引,若有的话,在数组A中找出一个魔术索引,如果没有,则返回-1。若有多个魔术索引,返回索引值最小的一个。
# 示例1:
#
# 输入:nums = [0, 2, 3, 4, 5]
# 输出:0
# 说明: 0下标的元素为0
#
#
# 示例2:
#
# 输入:nums = [1, 1, 1]
# 输出:1
#
#
# 提示:
#
#
# nums长度在[1, 1000000]之间
#
#
#
# Easy 65.5%
# Testcase Example: [0, 2, 3, 4, 5]
#
# 提示:
# 先试试蛮力算法。
# 蛮力算法的运行时间可能为O(N)。如果试图击败那个运行时间,你认为会得到什么运行时间。什么样的算法具有该运行时间?
# 你能以O(log N)的时间复杂度来解决这个问题吗?
# 二分查找有O(log n)的运行时间。你能在这个问题中应用二分查找吗?
# 给定一个特定的索引和值,你能确定魔术索引是在它之前还是之后吗?
#
#
from typing import List
class Solution:
def findMagicIndex(self, nums: List[int]) -> int:
if not nums:return -1
n = len(nums)
i = 0
while i<n:
if nums[i] == i:
return i
if nums[i] > i:
i = nums[i]
else:
i += 1
return -1
nums = [0, 2, 3, 4, 5]
nums = [1, 1, 1]
nums = [0, 0, 2]
nums = [1,2,6,7,8,9,10]
o = Solution()
print(o.findMagicIndex(nums)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.