blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
1863301063878a69104adf7ffa9c86df03cc3dbf | mvillalba/python-afip | /afip/utils.py | 458 | 3.640625 | 4 | import datetime
def parse_date(text):
if text is None or text.upper() == 'NULL':
return None
if '-' in text:
text = text.replace('-', '')
if '/' in text:
text = [p.zfill(2) for p in text.split('/')]
text = [text[2], text[0], text[1]]
text = ''.join(text)
return datetime.date(year=int(text[0:4]), month=int(text[4:6]), day=int(text[6:8]))
def unparse_date(date):
return date.strftime('%Y%m%d')
|
7ba6812d8ea22eef0e4c652525f713a33ca92c5e | mariacuracastro/cs114 | /8ball-refactor.py | 1,902 | 3.828125 | 4 | def get_number():
num = int(input('A number between 1 and 99: '))
return num
def get_tens_inwords(num):
tens = num // 10
tens_word = ''
if tens == 9:
tens_word = 'ninety'
elif tens == 8:
tens_word = 'eighty'
elif tens == 7:
tens_word = 'seventy'
elif tens == 6:
tens_word = 'sixty'
elif tens == 5:
tens_word = 'fifty'
elif tens == 4:
tens_word = 'fourty'
elif tens == 3:
tens_word = 'thirty'
elif tens == 2:
tens_word = 'twenty'
return tens_word
def get_ones_inwords(num):
ones = num % 10
if ones == 9:
ones_word = 'nine'
elif ones == 8:
ones_word = 'eight'
elif ones == 7:
ones_word = 'seven'
elif ones == 6:
ones_word = 'six'
elif ones == 5:
ones_word = 'five'
elif ones == 4:
ones_word = 'four'
elif ones == 3:
ones_word = 'three'
elif ones == 2:
ones_word = 'two'
elif ones == 1:
ones_word = 'one'
else:
ones_word = ''
return ones_word
def make_output(num, tens_word, ones_word):
tens = num // 10
ones = num % 10
if int(num) >= 100:
output = 'not valid'
elif int(num) <= 0:
output = 'not valid'
elif tens == 0:
output = ones_word
elif tens == 1:
if ones == 1:
output = 'eleven'
elif ones == 2:
output = 'twelve'
elif ones == 3:
output = 'thirteen'
else:
output = ones_word + 'teen'
else:
output = tens_word + '-' + ones_word
msg = 'Your number is, ' + output
return msg
def main():
num = get_number()
tens_inwords = get_tens_inwords(num)
ones_inwords = get_ones_inwords(num)
output = make_output(num, tens_inwords, ones_inwords)
print(output)
main()
|
e6e067d786750c22548c049f7f6b6e21ea9cf2c7 | donaahasrul/Algoritma_dan_Pemrograman | /Bab 2/28.soal3.py | 174 | 3.8125 | 4 | # Mengubah suhu skala celcius ek skala fahrenheit
C = float(input('Masukkan suhu dalam skala Celcius: '))
F = 9/5*C+32
print('Suhu', C, 'celciuis adalah', F, 'fahrenheit') |
a9b6a41e05bbf15f3984d1759f9de4313eebfe53 | decareano/python_repo | /bicycleApp.py | 2,177 | 4.0625 | 4 | import random
class Bicycle():
"""the bike class"""
def __init__(self, model, weight, cost):
self.model = model
self.weight = float(weight)
self.cost = round(float(cost), 2)
class BikeShop():
"""the shop class"""
def __init__(self, name):
self.name = name
self.inventory = ()
self.profit = 0
def sell_bike(self, inventory_index, retail_margin):
del self.inventory_index[inventory_index]
self.profit += retail_margin * self.profit
def return_profit(self):
return self.profit
class Customer():
""" customer is sacred """
def __init__(self, name, cash):
self.name = name
self.cash = round(float(cash), 2)
self.bikes = []
def print_customer_list(customers, shop):
inventory ={}
for bike in shop.inventory:
inventory[bike.model] = bike.cost
print("list inventory: ", inventory)
print("customers and bikes at %s. " % (shop.name))
for names in customers:
for x, y in inventory.items():
if y <= names.cash: print("%s can affors a %s for %i." % (names.name, x, y))
def print_shop_inventory(shop):
inventory = {}
for bike in shop.inventory:
inventory[bike.model] = bike.cost
print("inventory for shop %s: " % (shop.name))
for model, cost in inventory.items():
print("Bike model %s at initial cost of $%i." % (model, cost))
def main():
bikeshop1 = BikeShop('I bike your pardon')
bikeshop1.profit = 1.5
bike_brands = ['Trek', 'Salsa', 'Jamis', 'Specialized', 'Surly', 'Giant', 'Bianchi',
'Cannondale', 'Soma', 'Cervelo']
bikes = []
for x in range(7):
bikebrand = random.choice(bike_brands)
bikeweight =random.randint(19, 23)
bikecost = random.randint(100, 1200)
bikes.append(Bicycle(bikebrand, bikeweight, bikecost))
bikeshop1.inventory = [x for x in bikes]
Mike = Customer('Mike', 200)
Joe = Customer('Joe', 500)
Sam = Customer('Sam', 1000)
customers = [Mike, Joe, Sam]
print_customer_list(customers, bikeshop1)
print_shop_inventory(bikeshop1)
main()
|
c51fde4cd2f474665dfbf2bfeda11001c27e6925 | haikentcode/code | /collegeTime/vector3d.py | 1,055 | 3.828125 | 4 | import math
class Coordinate:
def __init__(self,t):
self.x=t[0]
self.y=t[1]
self.z=t[2]
def ab(self,b):
return (b.x-self.x,b.y-self.y,b.z-self.z)
class Vector:
def __init__(self,v):
self.v=v
def __add__(self,other):
return Vector((self.v[i]+other.v[i] for i in range(3)))
def __sub__(self,other):
return Vector((self.v[i]-other.v[i] for i in range(3)))
def dot(self,other):
return sum(self.v[i]*other.v[i] for i in range(3))
def cros(self,other):
return Vector((self.v[1]*other.v[2]-self.v[2]*other.v[1],self.v[2]*other.v[0]-self.v[0]*other.v[2],self.v[0]*other.v[1]-self.v[1]*other.v[0]))
def length(self):
return math.sqrt(self.dot(self))
def Cinput():
return Coordinate(tuple(map(float,raw_input().split(" "))))
A=Cinput()
B=Cinput()
C=Cinput()
D=Cinput()
AB=Vector(A.ab(B))
BC=Vector(B.ab(C))
CD=Vector(C.ab(D))
X=AB.cros(BC)
Y=BC.cros(CD)
XdotY=X.dot(Y)
xl=X.length()
yl=Y.length()
phi=XdotY/(xl*yl)
print phi
|
fc42f911be2f0e51c695326fd2f4cd396250a36d | belenmoreno/ejercicios_programacionFuncional | /ej 5.py | 730 | 3.984375 | 4 | def alumno(diccionario):
diccionario_mayusculas = {}
for key in diccionario:
aux = key.upper()
diccionario_mayusculas[aux] = diccionario[key]
return diccionario_mayusculas
def main():
estudiante = {}
while 1:
asignatura = input("introduce la asignatura: ")
nota = float(input("introduce la nota: "))
estudiante[asignatura] = nota
salir = input("Introduce salir para salir para no añadir más asignatuas.")
salir = salir.upper()
if salir == 'SALIR':
resultado = alumno(estudiante)
break #break sale del bucle y return sale de la funcion
print(resultado)
[1,3]
[2,3]
[6,15]
if __name__ == "__main__":
main() |
7894f0fa8aa9a192f78fc16419b8b1b803490eee | shulmanm/TicTacToe | /Server.py | 4,007 | 3.78125 | 4 | ''' File to create a local server for Tic-Tac-Toe. Best way to run: in terminal,
navigate to this file and call "python3 Server.py" You should see
"STARTING SERVER ON LOCALHOST Host:Port (localhost:8000):".
You can choose the server attributes or just press enter for a default of localhost:8000.'''
import PodSixNet.Channel
import PodSixNet.Server
from time import sleep
from enum import Enum
# enum for turns
class Turn(Enum):
PLAYER0 = 0
PLAYER1 = 1
class ClientChannel(PodSixNet.Channel.Channel):
# receive data
def Network(self, data):
print(data)
# get all of the data from the dictionary
def Network_place(self, data):
#x of placed piece
x = data["x"]
#y of placed piece
y = data["y"]
#player number (1 or 0)
num = data["num"]
#id of game given by server at start of game
self.gameid = data["gameid"]
#tells server to place line
self._server.placePiece(x, y, data, self.gameid, num)
# receive close
def Close(self):
self._server.close(self.gameid)
class TicServer(PodSixNet.Server.Server):
channelClass = ClientChannel
def __init__(self, *args, **kwargs):
# call PodSixNet init, pass args through
PodSixNet.Server.Server.__init__(self, *args, **kwargs)
self.games = []
self.queue = None
# keeps track of existing games
self.currentIndex = 0
def Connected(self, channel, addr):
print('new connection:', channel)
#check if theres a game in queue, else make one, connect new clients to it
if self.queue == None:
self.currentIndex += 1
channel.gameid = self.currentIndex
self.queue = Game(channel, self.currentIndex)
else:
channel.gameid = self.currentIndex
self.queue.player1 = channel
self.queue.player0.Send({"action": "startgame","player": 0, "gameid": self.queue.gameid})
self.queue.player1.Send({"action": "startgame","player": 1, "gameid": self.queue.gameid})
self.games.append(self.queue)
self.queue = None
# find game with right gameid then placeLine
def placePiece(self, x, y, data, gameid, num):
# find game with correct gameid
game = [a for a in self.games if a.gameid == gameid]
game[0].placePiece(x, y, data, num)
# close game for both if one closes
def close(self, gameid):
try:
game = [a for a in self.games if a.gameid == gameid][0]
game.player0.Send({"action":"close"})
game.player1.Send({"action":"close"})
except:
pass
# server Game state
class Game:
def __init__(self, player0, currentIndex):
# whose turn (1 or 0)
self.turn = Turn.PLAYER0
#owner map
self.owner = [[False for x in range(3)] for y in range(3)]
# Seven lines in each direction to make a six by six grid.
self.board = [[False for x in range(3)] for y in range(3)]
#initialize the players including the one who started the game
self.player0 = player0
self.player1 = None
#gameid of game
self.gameid = currentIndex
# if you can place piece, do so for for both clients and send data
def placePiece(self, x, y, data, num):
# make sure it's their turn
if num == self.turn.value:
if self.turn == Turn.PLAYER1:
self.player1.Send({"action": "win", "x": x, "y": y})
self.player0.Send({"action": "lose", "x": x, "y": y})
else:
self.player0.Send({"action": "win", "x": x, "y": y})
self.player1.Send({"action": "lose", "x": x, "y": y})
self.turn = Turn.PLAYER0 if self.turn.value else Turn.PLAYER1
self.owner[y][x] = num
self.player1.Send({"action": "yourturn", "torf": True if self.turn == Turn.PLAYER1 else False})
self.player0.Send({"action": "yourturn", "torf": True if self.turn == Turn.PLAYER0 else False})
#place line in game
self.board[y][x] = True
#send data and turn data to each player
self.player0.Send(data)
self.player1.Send(data)
print("STARTING SERVER ON LOCALHOST")
# try:
address = input("Host:Port (localhost:8000): ")
if not address:
host, port="localhost", 8000
else:
host,port=address.split(":")
ticServe = TicServer(localaddr=(host, int(port)))
while True:
ticServe.Pump()
sleep(0.01)
|
e2c6ff8c4b3a13b26d9d36d03b41d67be7ff8a41 | HammadAhmedSherazi/Python-Assignment-5 | /Question6.py | 169 | 3.828125 | 4 | def shoppingList(*items):
print("-------Brought Items List----------")
for item in items:
print(item)
shoppingList("Past","Rice","Bread","Butter", "Oil")
|
3596976e36893fc034921b98db53f3d2e81cac20 | nightangelblade/python_practice | /practice.py | 1,160 | 4.125 | 4 | # Practice declaring various objects as variables
test_variable = "This is a test variable"
test_boolean = True
test_integer = 1000
test_float = 3.14
test_array = ["this", "is", "a", "test", "array"]
test_hash = {'a': 1, 'b': 2, 'c': 3}
print(test_variable)
print(test_boolean)
print(test_integer)
print(test_float)
print(test_array)
print(test_hash)
print(1 == 1)
print(1 == 2)
# Practice declaring if statement
if (test_integer > test_float):
print("Integer is greater")
else:
print("Float is greater")
# Practice declaring a method/function that requires no arguments
def Hello():
print("Hello!")
Hello()
# Practice declaring a method/function with arguments
def Sum(a, b):
method_return = a + b
print(method_return)
Sum(test_integer,test_float)
# Practice using while loop
i = 0
while (i < 5):
print("You are at increment " + str(i))
i = i+1
# Practice using foreach loop
test_array2 = [0, 1, 2, 3, 4, 5]
test_sum = 0
for x in test_array2:
test_sum = test_sum+x
print(test_sum)
# Personal Note: Python doesn't declare an explicit end. Requires a line break as well as a left indent to declare end of loop
print(str(test_sum) + " from loop") |
bea111c3af29804dc9e492175bc8fd5e31b5ff71 | akyl0221/Euler | /Task_2/test.py | 288 | 3.515625 | 4 | from .task import fibonacci_sum
import unittest
class Test(unittest.TestCase):
def test_is_int(self):
self.assertEqual(fibonacci_sum(1.1), 'Number must be Integer!')
def test_positive_number(self):
self.assertEqual(fibonacci_sum(-1), 'Number must be positive')
|
a6fbd82f50ce4243269180553baea89245d2037a | KunalGehlot/Python | /05.py | 210 | 3.640625 | 4 | name = "Zack"
password = "12345"
uname = input("Enter user name")
upass = input("Enter password")
if(uname == name) and (upass == password):
print("login successful")
else:
print("Invalid input")
|
ef8c2db243cf931e748d1f028bdd72bd6d374416 | Tulsit/Let-s-Learn-Python | /Python Fundamentals/9. _Strings.py | 1,399 | 4.0625 | 4 | '''
Topic 9 : Strings :
--> Strings in python are surrounded by either single quotation marks, or double quotation marks
Syntax :
print("value")
print('value')
'''
print("Hii")
# Both are valid ways
print('Hii')
# Assign String to a Variable
a = "Good Morning"
print(a)
# Multiline String
# By using three quotes
s = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(s)
# Three single quotes
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
# Strings are Arrays
a = "Hello"
print(a[3])
# Python does not have a character data type, a single character is simply a string with a length of 1
# String Length
# --> To get the length of a string, use the len() function.
a = "Shyam"
print(len(a))
# Check String
# --> To check if a certain phrase or character is present in a string, we can use the keyword in
s = "This is a string."
print("string" in s) #Check if "string" is present in the following text
# Check if NOT
# --> To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
s = "This is a string."
print("the" not in s) # Check if "the" is NOT present in the following text |
3ee306d27db9359872ef2f10ebc4052111eaf1b2 | Subikesh/Data-Structures-and-algorithms | /Programs/3SumClosest.py | 1,120 | 3.71875 | 4 | import sys
def threeSumClosest(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
min_diff = sys.maxsize
for i in range(len(nums)-2):
left = i+1
right = len(nums)-1
while left < right:
if abs(target - (nums[i] + nums[left]+ nums[right])) < min_diff:
min_diff = abs(target - (nums[i] + nums[left]+ nums[right]))
near = nums[i] + nums[left]+ nums[right]
if min_diff == 0:
return near
if (nums[i] + nums[left]+ nums[right]) <= target:
left += 1
elif (nums[i] + nums[left]+ nums[right]) > target:
right -= 1
print()
return near
def stringToIntegerList(input):
return json.loads(input)
def stringToInt(input):
return int(input)
def intToString(input):
if input is None:
input = 0
return str(input)
def main():
a = list(map(int, input().strip().split()))
target = int(input())
threeSumClosest(a, target)
if __name__ == '__main__':
main() |
0815238d813e81d2cd03b405cfc3e08c04886f44 | asadashfaq/FlowTracing | /functions.py | 1,789 | 3.609375 | 4 | from __future__ import division
import numpy as np
from numpy import matrix
"""
A collection of commonly used functions.
"""
def isMatrix(M):
"""
Check if input is matrix, if not convert to matrix.
"""
if type(M) == matrix:
return M
elif type(M) == np.ndarray:
return matrix(M)
else:
raise Exception('Unknown input format. Should be matrix or numpy array')
def identity(n):
"""
Create an identity matrix.
"""
I = np.zeros((n, n))
diag = np.ones(n)
np.fill_diagonal(I, diag)
return matrix(I)
def invert(M):
"""
Invert matrix if possible.
Need check of inverse and possibly implementation of pseudo inverse.
"""
M = isMatrix(M)
return M.I
def diagM(l):
"""
Return input list as diagonal matrix.
"""
dim = len(l)
M = np.zeros((dim, dim))
np.fill_diagonal(M, l)
return matrix(M)
def posM(M):
"""
Return matrix with negative values set to zero.
"""
M[np.where(M < 0)] = 0
return M
def negM(M):
"""
Return matrix with negative values set to zero.
"""
M[np.where(M > 0)] = 0
return M
def normCols(M):
"""
Return matrix with normalised column vectors.
"""
M.dtype = 'float'
if len(M.shape) < 3:
rows, cols = M.shape
for col in xrange(cols):
colSum = M[:, col].sum()
if colSum != 0:
M[:, col] /= colSum
else:
dims, rows, cols = M.shape
for dim in xrange(dims):
for col in xrange(cols):
colSum = M[dim, :, col].sum()
if colSum != 0:
M[dim, :, col] /= colSum
return M
|
c36b76cfa2cfd8130180408f4a112ca1d5327a88 | asifabdullah/100DaysOfPython | /oop-coffee-machine-start/main.py | 792 | 3.546875 | 4 | from menu import Menu
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
is_machine_on = True
coffee_maker = CoffeeMaker()
money_machine = MoneyMachine()
menu = Menu()
# menu_item = MenuItem(menu)
while is_machine_on:
choice = input(f"\tWhat would you like? ({menu.get_items()}): ").lower()
# print(choice)
if choice == "off":
is_machine_on = False
elif choice == "report":
coffee_maker.report()
money_machine.report()
elif choice == "espresso" or choice == "latte" or choice == "cappuccino":
drink = menu.find_drink(choice)
# print(drink.cost)
if coffee_maker.is_resource_sufficient(drink):
if money_machine.make_payment(drink.cost):
coffee_maker.make_coffee(drink)
|
16f8d9c0ff6767d16f71485f379efa8e8a9b33d6 | agustakatrin/tiletraveller | /TileTraveller/tiletraveller.py | 2,347 | 3.984375 | 4 | # Player starts in tile [1,1]
# Player selects moves (n/N, e/E, s/S, w/W) and the program should print the player's travel options
#this is a change
x_start, y_start = 1, 1
n, s, e, w = 1, -1, 1, -1
def start_tile(x_hnit, y_hnit):
victory = False
if x_hnit == 1 and y_hnit ==1: #1,1
dir_map = "(N)orth."
valid_input = "n"
elif x_hnit == 1 and y_hnit == 2: #1,2
dir_map = "(N)orth or (E)ast or (S)outh."
valid_input = "s", "e", "n"
elif x_hnit == 1 and y_hnit == 3: #1,3
dir_map = "(E)ast or (S)outh."
valid_input = "s", "e"
elif x_hnit == 2 and y_hnit == 3: #2,3
dir_map = "(E)ast or (W)est."
valid_input = "w", "e"
elif x_hnit == 2 and y_hnit == 2: #2,2
dir_map = "(S)outh or (W)est."
valid_input = "w", "s"
elif x_hnit == 2 and y_hnit == 1: #2,1
dir_map = "(N)orth."
valid_input = "n"
elif x_hnit == 3 and y_hnit == 1: #3,1
dir_map = "(N)orth."
valid_input = "n"
victory = True
elif x_hnit == 3 and y_hnit == 2: #3,2
dir_map = "(N)orth or (S)outh."
valid_input = "n", "s"
elif x_hnit == 3 and y_hnit == 3: #3,3
dir_map = "(S)outh or (W)est."
valid_input = "w", "s"
return dir_map, valid_input, victory
def dir_invalid():
print("Not a valid direction!")
return print("You can travel: " + dir_map)
def mover(my_dir, valid_dir, x, y):
if(my_dir in valid_dir):
if my_dir == "s" or my_dir == "n":
y += eval(my_dir)
else:
x += eval(my_dir)
else:
dir_invalid
return x, y
def input_letter(valid_dir):
direction = input("Direction: ").lower()
while direction not in valid_dir:
dir_invalid()
direction = input("Direction: ").lower()
return direction
def guide(possible_dir, victory):
if victory != True:
print("You can travel: " + possible_dir)
else:
print("Victory!")
while 1:
dir_map, valid_input, victory = start_tile(x_start, y_start)
guide(dir_map, victory)
if victory == True:
break
direction = input_letter(valid_input)
x_start, y_start = mover(direction, valid_input, x_start, y_start) |
c24683225b3455fa927147585e9e4a5a07f43c78 | iasharief/PythonLearning | /far_to_cel_v1.py | 605 | 4.09375 | 4 | import sys
starting_which_one = str(input("Type 'c' if you want to convert Celsius to Fahrenheit, and type 'f' if you want to convert Fahrenheit to Celsius:"))
if starting_which_one != 'c' or starting_which_one != 'f':
print ("You are not paying attention, you knucklehead!!!")
sys.exit()
if starting_which_one == 'f':
far = float(input('Fahrenheit number: ' ))
cel = 5 / 9 * (far - 32)
print('The number in celsius is {:.2f}.'.format(cel))
if starting_which_one == 'c':
far2 = float(input('Celsius number:'))
cel2 = (far2 * 1.8) + 32
print('The number in fahrenheit is: {:.2f}.'.format(cel2)) |
035a732ba3f0574b3c587d3f0b3b028de42d86a1 | higor-gomes93/curso_programacao_python_udemy | /Sessão 7.2 - Exercícios/ex1.py | 716 | 3.734375 | 4 | '''
Leia uma matriz 4 x 4, conte e escreva quantos valores maiores que 10 ela possui.
'''
matriz = []
vetor = []
linhas = 4
colunas = 4
cont = 0
for i in range(linhas):
for j in range(colunas):
num = int(input(f'Digite o {j+1}º elemento da {i+1}ª linha: '))
vetor.append(num)
matriz.append(vetor)
vetor = []
for i in range(linhas):
for j in range(colunas):
if matriz[i][j] == 10:
cont += 1
print(f'[{matriz[i][j]:^5}]', end = '')
print()
if cont == 0:
print(f'A matriz não tem nenhum elemento iguai a 10.')
elif cont == 1:
print(f'A matriz tem {cont} elemento igual a 10.')
else:
print(f'A matriz tem {cont} elementos iguais a 10.')
|
7ffd19a42a5d0bb2e76686dcfe9981b71f273db2 | lees/sundaram | /Arch/sundaram_spoiled2.py | 1,648 | 3.640625 | 4 |
import itertools
def take(n, iterable):
"""Return first n items of the iterable as a list"""
return list(itertools.islice(iterable, n))
def func(i):
return 2*(i+1)*(i+2), 2*(i+1)+1
def func_next(struct):
(current_value, step) = struct
return current_value + step, step
def next_data():
data = [func(0)]
while True:
res = min(enumerate(data), key=lambda x: x[1][0])
if res[0] == len(data) - 1:
data.append(func(res[0] + 1))
data[res[0]] = func_next(data[res[0]])
yield res[1][0]
def exclude_repeat(iterable):
last_el = iterable.next()
yield last_el
while True:
next_el = iterable.next()
if next_el != last_el:
yield next_el
last_el = next_el
def primes_generator():
yield 1
yield 2
ex_generator = exclude_repeat(next_data())
to_exclude = ex_generator.next()
to_return = 1
while True:
to_return += 1
if to_return < to_exclude:
yield 2 * to_return + 1
else:
to_exclude = ex_generator.next()
def take(n, iterable):
return list(itertools.islice(iterable, n))
def xprint(n, iterable):
for x in xrange(1, n):
print iterable.next()
def compare(n):
t1 = take(n, primes_generator())
t2 = take(n, sundaram.Primes())
return t1 == t2
def ithprime(n):
primes = primes_generator()
for i in xrange(n - 1):
primes.next()
return primes.next()
if __name__ == '__main__':
take(30000, exclude_repeat(next_data()))
|
1fbb3132c3d39ec0848ec1c3fbfc54864df20df9 | CodeMechanix/Grooming-Python | /stack.py | 294 | 3.828125 | 4 | # Push and Pop
books = []
books.append("Learn C")
books.append("Learn C++")
books.append("Learn Java")
print(books) # ['Learn C', 'Learn C++', 'Learn Java']
books.pop()
print("Now the top book is : ", books[-1]) # Now the top book is : Learn C++
print(books) # ['Learn C', 'Learn C++']
|
aa906617f7f5818014e4402c364397237bb99ea9 | Beichen365/Python | /Syntax/chap14/chap14.py | 327 | 3.734375 | 4 | class Bank:
def __init__(self,username,number,amount):
self.username = username
self.number = number
self.amount = amount
myBank = Bank("Sun Beichen", "12345678", "1265.90")
print("There is ",myBank.amount," in my bank.")
print("The password is ",myBank.number)
print("My username is ",myBank.username) |
b8626e0691bf4ab6c2e73eee748dc201e1762b95 | rozuur/ptvsd | /tests/helpers/counter.py | 1,481 | 3.578125 | 4 | import sys
class Counter(object):
"""An introspectable, dynamic alternative to itertools.count()."""
def __init__(self, start=0, step=1):
self._start = int(start)
self._step = int(step)
def __repr__(self):
return '{}(start={}, step={})'.format(
type(self).__name__,
self.peek(),
self._step,
)
def __iter__(self):
return self
def __next__(self):
try:
self._last += self._step
except AttributeError:
self._last = self._start
return self._last
if sys.version_info[0] == 2:
next = __next__
@property
def start(self):
return self._start
@property
def step(self):
return self._step
@property
def last(self):
try:
return self._last
except AttributeError:
return None
def peek(self, iterations=1):
"""Return the value that will be used next."""
try:
last = self._last
except AttributeError:
last = self._start - self._step
return last + self._step * iterations
def reset(self, start=None):
"""Set the next value to the given one.
If no value is provided then the previous start value is used.
"""
if start is not None:
self._start = int(start)
try:
del self._last
except AttributeError:
pass
|
7089b7457c25c0ce7fb8e1326e424779d085e4cc | CaizhiXu/LeetCode-Python-Solutions | /114. Flatten Binary Tree to Linked List _ Tree.py | 1,363 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
## in-order traversal
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return
stack = [root]
while stack:
node = stack.pop()
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
node.left = None
if stack:
node.right = stack[-1]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
## time - O(n), space - O(1)
class Solution2:
def flatten(self, root: TreeNode) -> None:
self.helper(root)
def helper(self, node):
if not node:
return None
if not node.left and not node.right:
return node
lefttail = self.helper(node.left)
righttail = self.helper(node.right)
if lefttail:
lefttail.right = node.right
node.right = node.left
node.left = None
return righttail if righttail else lefttail
|
a84dfd587e69d5d5c1d26dc89c9239ea5221e59c | Velugoti2/python | /practiecebick.py | 1,654 | 3.96875 | 4 | class Bikerent:
def __init__(self,stock=0):
self.stock=stock
def Display(self):
print("we have avalable only {} bikes to rent".format(self.stock))
def rentBikeonhourlybase(self,bikes,hours):
if bikes<=0:
print("number of bikes should be positive")
return None
elif bikes>self.stock:
print("sorry! we have only {} bikes are avalable".format(self.stock))
else:
print("we have rented {} bikes on {} hours ".format(bikes,hours))
self.stock=self.stock-bikes
print("per hour bike rent is 3rupees")
print("your paying amount is=",bikes*hours*3)
def rentBikeondaywise(self,bike,days):
if bike<=0:
print("no of Bikes should be positive")
elif bike>self.stock:
print("sorry! we have only {} bikes are avalable".format(self.stock))
else:
print("we have rented {} bikes on {} days".format(bike,days))
self.stock=self.stock-bike
print("per day bike rent is 30rupees")
print("your paying amount is=",bike*days*30)
a=Bikerent(10)
a.Display()
print("enter your options to bike rent days or hours")
print("D-days\n","h-hours")
options=input("choose your options=")
if options=="d" or options=="D":
bike=int(input("enter your required bikes= "))
days=int(input("enter your required days="))
a.rentBikeondaywise(bike,days)
elif options=="h" or options=="H":
bike = int(input("enter your required bikes= "))
hours = int(input("enter your required hours="))
a.rentBikeonhourlybase(bike,hours)
# sreekanth reddy
|
3653e54c92433c81cd50593c0205665ce9f6af0c | shahad-mahmud/learning_python | /day_5/python_list.py | 1,251 | 4.25 | 4 | # bangla_mark_saba = 89
# bangla_mark_shafin = 50
# bangla_mark_pinki = 85
# bangla_mark_fahim = 82
# bangla_mark_shahad = 33
# meutable
# write a code to-
# a. create a list to store the age of at least 5 people
# b. Check the type of your created list
# c. Print the 3rd and 4th element
# d. Change the value of the 3rd element and print it.
# e. Add a new student's number at the end of the list
# f. Print the lenght of the current list.
# g. Print the number of the last student
# h. Print the number of 3rd, 4th and 5th students.
# creating list
mark = [89, 50, 85, 82, 33, 56, 9, 87, 56]
print(mark[7])
# changing element
mark[7] = -89
print(mark[7])
# adding at the end
mark.append(45)
print(mark)
# lenght of a list
list_lenght = len(mark)
print(list_lenght)
# negative indexing
print('Last element with positive indexing: ', mark[list_lenght -1])
print('Last element with negative indexing: ', mark[-1])
print('second last element: ', mark[-2])
# slicing
print(mark[2:4])
# inserting
print('Before inserting: ', mark)
mark.insert(4, 91)
print('After inserting: ', mark)
# removing an elemnet
# remove(element)
mark.remove(-89)
print(mark)
# del variable
del mark[4]
print(mark)
# sorting
mark.sort(reverse=True)
print(mark)
|
5210f83e90819a5122040cc740ea6e43eb44d541 | kks4866/pyworks | /gui/button_cmd1.py | 316 | 3.734375 | 4 | from tkinter import *
def click():
print("Hello~Python!!")
root = Tk()
root.title("Hello~")
frame = Frame(root)
frame.pack()
Button(frame, text="확인",command=click).grid(row=0,column=0)
#() 생략한 이류는 버튼 누를때만 함수 작동,() 있으면 함수 생성시점에서 동작
root.mainloop() |
a3d6ea59ae2c1adf3d650d234da4d0a91e9419d1 | pandabb3356/pygame-tetris | /tetris/helper.py | 1,486 | 3.578125 | 4 | from typing import NamedTuple, Union
class Position(NamedTuple):
x: Union[int, float]
y: Union[int, float]
def __add__(self, vector: "Vector") -> "Position": # type: ignore
return Position(self.x + vector.x, self.y + vector.y)
def __sub__(self, vector: "Vector") -> "Position":
return Position(self.x - vector.x, self.y - vector.y)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Position):
return False
return self.x == other.x and self.y == other.y
class Vector(NamedTuple):
x: Union[int, float]
y: Union[int, float]
def __add__(self, vector: "Vector") -> "Vector": # type: ignore
return Vector(self.x + vector.x, self.y + vector.y)
def __sub__(self, vector: "Vector") -> "Vector":
return Vector(self.x - vector.x, self.y - vector.y)
def __mul__(self, value: int) -> "Vector":
return Vector(self.x * value, self.y * value)
def __bool__(self) -> bool:
return False if (not self.x and not self.y) else True
def __eq__(self, other: object) -> bool:
if not isinstance(other, Vector):
return False
return self.x == other.x and self.y == other.y
def clone(self) -> "Vector":
return Vector(*self)
class RGB(NamedTuple):
r: int
g: int
b: int
class Factor(NamedTuple):
a: float = 1.0
b: float = 1.0
c: float = 1.0
|
ca5a0b742a2c16de2acdde817b6d01f7414d68f5 | gistable/gistable | /dockerized-gists/56369a90d03953e370f3964c826ed4b0/snippet.py | 3,850 | 3.578125 | 4 | """
Author: Awni Hannun
This is an example CTC decoder written in Python. The code is
intended to be a simple example and is not designed to be
especially efficient.
The algorithm is a prefix beam search for a model trained
with the CTC loss function.
For more details checkout either of these references:
https://distill.pub/2017/ctc/#inference
https://arxiv.org/abs/1408.2873
"""
import numpy as np
import math
import collections
NEG_INF = -float("inf")
def make_new_beam():
fn = lambda : (NEG_INF, NEG_INF)
return collections.defaultdict(fn)
def logsumexp(*args):
"""
Stable log sum exp.
"""
if all(a == NEG_INF for a in args):
return NEG_INF
a_max = max(args)
lsp = math.log(sum(math.exp(a - a_max)
for a in args))
return a_max + lsp
def decode(probs, beam_size=100, blank=0):
"""
Performs inference for the given output probabilities.
Arguments:
probs: The output probabilities (e.g. post-softmax) for each
time step. Should be an array of shape (time x output dim).
beam_size (int): Size of the beam to use during inference.
blank (int): Index of the CTC blank label.
Returns the output label sequence and the corresponding negative
log-likelihood estimated by the decoder.
"""
T, S = probs.shape
probs = np.log(probs)
# Elements in the beam are (prefix, (p_blank, p_no_blank))
# Initialize the beam with the empty sequence, a probability of
# 1 for ending in blank and zero for ending in non-blank
# (in log space).
beam = [(tuple(), (0.0, NEG_INF))]
for t in range(T): # Loop over time
# A default dictionary to store the next step candidates.
next_beam = make_new_beam()
for s in range(S): # Loop over vocab
p = probs[t, s]
# The variables p_b and p_nb are respectively the
# probabilities for the prefix given that it ends in a
# blank and does not end in a blank at this time step.
for prefix, (p_b, p_nb) in beam: # Loop over beam
# If we propose a blank the prefix doesn't change.
# Only the probability of ending in blank gets updated.
if s == blank:
n_p_b, n_p_nb = next_beam[prefix]
n_p_b = logsumexp(n_p_b, p_b + p, p_nb + p)
next_beam[prefix] = (n_p_b, n_p_nb)
continue
# Extend the prefix by the new character s and add it to
# the beam. Only the probability of not ending in blank
# gets updated.
end_t = prefix[-1] if prefix else None
n_prefix = prefix + (s,)
n_p_b, n_p_nb = next_beam[n_prefix]
if s != end_t:
n_p_nb = logsumexp(n_p_nb, p_b + p, p_nb + p)
else:
# We don't include the previous probability of not ending
# in blank (p_nb) if s is repeated at the end. The CTC
# algorithm merges characters not separated by a blank.
n_p_nb = logsumexp(n_p_nb, p_b + p)
# *NB* this would be a good place to include an LM score.
next_beam[n_prefix] = (n_p_b, n_p_nb)
# If s is repeated at the end we also update the unchanged
# prefix. This is the merging case.
if s == end_t:
n_p_b, n_p_nb = next_beam[prefix]
n_p_nb = logsumexp(n_p_nb, p_nb + p)
next_beam[prefix] = (n_p_b, n_p_nb)
# Sort and trim the beam before moving on to the
# next time-step.
beam = sorted(next_beam.items(),
key=lambda x : logsumexp(*x[1]),
reverse=True)
beam = beam[:beam_size]
best = beam[0]
return best[0], -logsumexp(*best[1])
if __name__ == "__main__":
np.random.seed(3)
time = 50
output_dim = 20
probs = np.random.rand(time, output_dim)
probs = probs / np.sum(probs, axis=1, keepdims=True)
labels, score = decode(probs)
print("Score {:.3f}".format(score)) |
36a75d7306a65b925b3b5eade569d205a764e16e | alicesilva/P1-Python-Problemas | /decisao6.py | 276 | 4.09375 | 4 | #coding: utf-8
numero1 = float(raw_input())
numero2 = float(raw_input())
numero3 = float(raw_input())
maior = numero1
if maior < numero2 and numero2 > numero3:
maior = numero2
elif maior < numero3 and numero3 > numero2:
maior = numero3
else:
maior = numero1
print maior
|
fc1633638e1ad8cd4910b317cc5fd875d52502b6 | alchupin/CodeAbbey | /abbey_pythagorean_theorem.py | 388 | 3.734375 | 4 | import math
f = open('pythagorean_theorem', 'r')
N = int(f.readline())
for i in range(N):
arr = [int(ch) for ch in f.readline().split()]
a = arr[0]
b = arr[1]
c = arr[2]
length = math.sqrt((a*a) + (b*b))
if length < c:
print('O', end=' ')
elif length > c:
print('A', end=' ')
else:
print('R', end=' ')
f.close()
|
ecf284bbeb075a81106a4f61eab24ce8a5919d57 | bullethammer07/Python_Tkinter_tutorial_repository | /Generic_Config_GUI_window/updated_window_scroll.py | 2,088 | 3.875 | 4 | # import tkinter as tk
# root = tk.Tk()
# root.title("Updated Frame scroll")
# root.geometry("500x200")
# frames = []
# def del_frame():
# if frames:
# pop = frames.pop()
# pop.destroy()
# print(len(frames))
# def create_frame():
# fr=tk.Frame(root, borderwidth=2, bg="white", highlightbackground="green", highlightthickness=2)
# fr.pack(sid=tk.TOP,fill="x")
# b0 = tk.Button(fr, text="Add", command=create_frame).pack(side=tk.RIGHT)
# b1 = tk.Button(fr, text="Remove", command=del_frame).pack(side=tk.RIGHT)
# frames.append(fr)
# print(len(frames))
# create_frame()
# root.mainloop()
#-----------------------------------------------------------------------
import tkinter as tk
root = tk.Tk()
root.title("Updated Frame scroll")
root.geometry("500x200")
frames = []
# Set the height of the containers and main window
container_height = 50
window_height = 500
# Create a canvas inside the main window
canvas = tk.Canvas(root, height=window_height)
canvas.pack(side="left", fill="both", expand=True)
# Create a scrollbar and attach it to the canvas
scrollbar = tk.Scrollbar(root, command=canvas.yview)
scrollbar.pack(side="left", fill="y")
canvas.config(yscrollcommand=scrollbar.set)
# Create a frame inside the canvas to hold other frames
canvas_frame = tk.Frame(canvas)
canvas.create_window((0, 0), window=canvas_frame, anchor="nw")
def del_frame():
if frames:
pop = frames.pop()
pop.destroy()
print(len(frames))
def create_frame(container):
fr=tk.Frame(root, borderwidth=2, bg="white", highlightbackground="green", highlightthickness=2)
fr.pack(sid=tk.TOP,fill="x")
b0 = tk.Button(fr, text="Add", command=create_frame(container)).pack(side=tk.RIGHT)
b1 = tk.Button(fr, text="Remove", command=del_frame).pack(side=tk.RIGHT)
frames.append(fr)
print(len(frames))
create_frame(canvas_frame)
# Update the scroll region after the main loop executed, to take initial frame into account
canvas.after(100, lambda: canvas.config(scrollregion=canvas.bbox("all")))
root.mainloop() |
292992c6e41dd3247ea73a29e223f23188ff48a5 | SafonovMikhail/python_000577 | /001133SelfeduPy/Selfedu001133PyBegin_v11_list_TASKmy03_20200621.py | 602 | 3.984375 | 4 | '''
Selfedu001133PyBegin_v11_list_TASKmy03_20200621.py
вывести в консоль последовательно сходящиеся элементы списка (построчно) [дать пример вывода]
использовать только прямую нумерацию элементов
'''
n = int(input("Количество элементов списка: "))
list1 = []
for i in range(n):
list1.append(i)
# построчный вывод сходящихся элементов
print(list1)
for i in range(len(list1) // 2):
print(list1[i], list1[n - 1 - i])
|
d538e8ea24fcb026cf0d2410d855f894a10f8c2f | LeiLu199/assignment6 | /ml4713/assignment6.py | 1,632 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
This is Programming for Data Science Homework6 script file.
Mengfei Li (ml4713)
"""
import sys
import re
from interval_functions import *
def main():
"""In the main function, the user is asked to input a series of intervals which are automatically
coverted to a list. After the initial input, the user is asked to input a new interval and the program
will merge the interval to the list that is created before if mergeable. Otherwise, the program will update
the list with new input interval. The program keeps going until the user hit "quit".
"""
while True:
try:
listofint=raw_input('List of intervals? ')
if listofint!='quit':
try:
listofint=[interval(x) for x in re.split('(?<=[\]\)])\s*,\s*', listofint)]
break
except (Invalid_Interval_list_input, ValueError):
print "invalid interval list"
elif listofint=='quit':
sys.exit()
except KeyboardInterrupt:
sys.exit()
while True:
try:
newinput=raw_input('Interval? ')
if newinput=='quit':
sys.exit()
else:
try:
listofint=insert(listofint,interval(newinput))
print listofint
except (Invalid_Interval_input,ValueError):
print 'Invalid Interval'
continue
except KeyboardInterrupt:
sys.exit()
if __name__=='__main__':
main()
|
a2c109f2b9da90e5a2841864d48bf5adf60dab47 | doraemon1293/Leetcode | /archive/406QueueReconstructionbyHeight.py | 600 | 3.515625 | 4 | # coding=utf-8
'''
Created on 2016?11?16?
@author: Administrator
'''
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
max = -1 * float("inf")
d = {}
for i, j in people:
d.setdefault(i, [])
d[i].append(j)
ans = []
for k in sorted(d.keys(), reverse = True):
for x in sorted(d[k]):
ans.insert(x, [k, x])
return ans
people = [[7, 0]]
print Solution().reconstructQueue(people)
|
c4fe5f04ebd06e34c6111a0373a085dca74e79ea | marcinkrolik/ComputerScience | /ProblemSet6/genPrimes.py | 518 | 3.765625 | 4 | def genPrimes():
primes = [2]
candidate = primes[-1]
while True:
flag = True
candidate += 1
for prime in primes:
if (candidate % prime) == 0:
flag = False
if flag == True:
yield primes[-1]
primes.append(candidate)
g = genPrimes()
'''while True:
print g.next()
aa = raw_input()
'''
import string
print string.punctuation
tt = "a'b"
for c in tt:
print c in string.punctuation
|
60371bbb3b9e5c3eda0f809e47b6089990cb23f9 | KobiShashs/Python | /8_Tuples/7_mult_tuple.py | 635 | 3.890625 | 4 | def mult_tuple(tuple1, tuple2):
res = []
len1 = len(tuple1)
for i in range(0, len1, 1):
len2 = len(tuple2)
for j in range(0, len2, 1):
my_tuple = tuple1[i], tuple2[j]
res.append(my_tuple)
len1 = len(tuple2)
for i in range(0, len1, 1):
len2 = len(tuple1)
for j in range(0, len2, 1):
my_tuple = tuple2[i], tuple1[j]
res.append(my_tuple)
return res
first_tuple = (1, 2)
second_tuple = (4, 5)
print(mult_tuple(first_tuple, second_tuple))
first_tuple = (1, 2, 3)
second_tuple = (4, 5, 6)
print(mult_tuple(first_tuple, second_tuple))
|
bd8db68aff23606b6b7aa8b707cf44ce520a55f1 | shumilin88/multiphase-flow-simulator | /src/correlations.py | 20,103 | 3.640625 | 4 | """
Correlations
"""
import math
def gas_solubility_in_oil(_pressure,
_bubble_point,
_temperature,
_gas_specific_gravity,
_oil_api_gravity):
"""
Calculates gas solubility in oil (Rso) using Standing correlation. If
pressure is higher than the mixture's bubble point, returns the Rso at
bubble point.
Args:
_gas_specific_gravity: Gas' specific gravity (doesn't have an unit).
_pressure: Pressure at which the gas is (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_bubble_point: Mixture's bubble point (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_temperature: Temperature at which the gas is (fahrenheit degrees).
_oil_api_gravity: Oil's API gravity (API degrees).
Returns:
The gas solubility in oil, Rso (scf/stb).
"""
if _pressure > _bubble_point:
_pressure = _bubble_point
exponent = 0.0125 * _oil_api_gravity - 0.00091 * _temperature
first_term = (_pressure + 14.7)/18.2 + 1.4
return _gas_specific_gravity * (first_term * 10 ** exponent) ** 1.2048
def gas_solubility_in_water(_pressure, _bubble_point, _temperature):
"""
Calculates gas solubility in water (Rsw) using Culberson and Maketta
correlation. If pressure is higher than the mixture's bubble point, returns
the Rso at bubble point.
Args:
_pressure: Pressure at which the gas is (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_bubble_point: Mixture's bubble point (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_temperature: Temperature at which the gas is (fahrenheit degrees).
Returns:
The gas solubility in water, Rsw (scf/stb).
"""
term_a = (8.15839 -
6.12265e-2 * _temperature +
1.91663e-4 * (_temperature ** 2) -
2.1654e-7 * (_temperature ** 3))
term_b = (1.01021e-2 -
7.44241e-5 * _temperature +
3.05553e-7 * (_temperature ** 2) -
2.94883e-10 * (_temperature ** 3))
term_c = (-9.02505 +
0.130237 * _temperature -
8.53425e-4 * (_temperature ** 2) +
2.34122e-6 * (_temperature ** 3) -
2.37049e-9 * (_temperature ** 4)) * (10 ** -7)
if _pressure > _bubble_point:
_pressure = _bubble_point
abs_pressure = _pressure + 14.7
return term_a + term_b * (abs_pressure) + term_c * (abs_pressure) ** 2
def mixture_bubble_point(_temperature,
_gas_specific_gravity,
_oil_api_gravity,
_water_cut,
_production_gas_liquid_ratio):
"""
Calculates the mixture's bubble point based on the water cut and the
prouction gas liquid ratio.
Args:
_water_cut: Water cut, WC.
_production_gas_liquid_ratio: Production gas liquid ratio, GLR_p (in
the same unit as Rso and Rsw, suggestion:
scf/stb).
Returns:
The mixture's bubble point Pb (psi).
"""
pressure_low = 0.0
pressure_high = 100000.0
bubble_point = 0.0
error = 1.0
while abs(error) > 1e-10:
bubble_point = (pressure_low + pressure_high)/2
rso = gas_solubility_in_oil(bubble_point,
pressure_high,
_temperature,
_gas_specific_gravity,
_oil_api_gravity)
rsw = gas_solubility_in_water(bubble_point,
pressure_high,
_temperature)
error = (_production_gas_liquid_ratio -
(1 - _water_cut) * rso - _water_cut * rsw)
if error > 0.0:
pressure_low = bubble_point
else:
pressure_high = bubble_point
return bubble_point
def oil_compressibility(_pressure,
_bubble_point,
_temperature,
_gas_solubility_in_oil_at_bp,
_gas_specific_gravity,
_oil_api_gravity):
"""
Calculates the isothermal oil compressibility using Vasquez correlation.
This is the compressibility of the oil as a single-phase liquid with a
certain amount of gas in solution. It is valid above the bubble point
only (Vasquez-Beggs Correlation).
Args:
_pressure: Pressure at which the oil is (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure, and
must be above bubble point.
_bubble_point: Mixture's bubble point (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_temperature: Temperature (fahrenheit degrees).
_gas_solubility_in_oil_at_bp: Gas solubility in oil at bubble point,
Rsob (in scf/stb).
_gas_specific_gravity: Gas' specific gravity (doesn't have an unit).
_oil_api_gravity: Oil's API gravity (API degrees).
Returns:
The compressibility of the oil as a single-phase liquid with a certain
amount of gas in solution in psi-1.
"""
if _pressure < _bubble_point:
raise ValueError('Pressure must be below bubble point.')
numerator = (-1433 +
5 * _gas_solubility_in_oil_at_bp +
17.2 * _temperature -
1180 * _gas_specific_gravity +
12.61 * _oil_api_gravity)
denominator = (_pressure + 14.7) * (10 ** 5)
return numerator/denominator
def oil_formation_volume_factor(_pressure,
_bubble_point,
_temperature,
_gas_solubility_in_oil,
_gas_specific_gravity,
_oil_specific_gravity,
_oil_compressibility=0.0):
"""
Calculates the oil formation volume factor (:math:`B_o`) using Standing's
correlation. The bubble point is necessary because a different correlation
must be used below and above it. Also, it is important to remember that if
pressure is above bubble point, the gas solubility in oil supplied must be
the one at the bubble point (:math:`R_{sob}`). Finally, the oil
compressibility (:math:`c_o`) is only needed if pressure is above bubble
point.
Args:
_pressure (double): Pressure at which the oil is (:math:`psig`). Note
that this value is relative to the atmospheric pressure.
_bubble_point (double): Mixture's bubble point (:math:`psig`). Note
that this value is relative to the atmospheric pressure.
_temperature (double): Temperature (fahrenheit degrees).
_gas_solubility_in_oil_ (double): Gas solubility in oil, :math:`R_{so}`
(in :math:`scf/stb`). **If pressure is above bubble point, the gas
solubility in oil supplied must be the one at the bubble point
(:math:`R_{sob}`).**
_gas_specific_gravity (double): Gas' specific gravity (no unit).
_oil_specific_gravity (double): Oil's specific gravity (no unit).
_oil_api_gravity (double): Oil's API gravity (API degrees).
_oil_compressibility (double, optional): Oil's compressibility
(:math:`psi^{-1}`). Value can be omitted if pressure is below
bubble point.
Returns:
The oil formation volume factor, in :math:`bbl/stb`.
"""
result = (0.9759 + 12e-5 * (
_gas_solubility_in_oil *
math.sqrt(_gas_specific_gravity/_oil_specific_gravity) +
1.25 * _temperature
) ** 1.2)
if _pressure > _bubble_point:
result = (result *
math.exp(_oil_compressibility * (_bubble_point - _pressure)))
return result
def water_compressibility(_pressure,
_bubble_point,
_temperature,
_gas_solubility_in_water_at_bp):
"""
Calculates the isothermal water compressibility using Dodson and Standing
correlation. This is the compressibility of the water as a single-phase
liquid with a certain amount of gas in solution. It is valid above the
bubble point only.
Args:
_pressure: Pressure at which the water is (psig). Note that this value
is in psig, so it is relative to the atmospheric pressure,
and must be above bubble point.
_bubble_point: Mixture's bubble point (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_temperature: Temperature (fahrenheit degrees).
_gas_solubility_in_water_at_bp: Gas solubility in water at bubble point
Rswb (in scf/stb).
Returns:
The compressibility of the water as a single-phase liquid with a
certain amount of gas in solution in psi-1.
"""
if _pressure < _bubble_point:
raise ValueError('Pressure must be below bubble point.')
term_a = 3.8546 - 1.34e-4 * (_pressure + 14.7)
term_b = -0.01052 + 4.77e-7 * (_pressure + 14.7)
term_c = 3.9267e-5 - 8.8e-10 * (_pressure + 14.7)
result = ((term_a + term_b * _temperature + term_c * (_temperature ** 2)) *
(1 + 8.9e-3 * _gas_solubility_in_water_at_bp) / 1e6)
return result
def water_formation_volume_factor(_pressure,
_bubble_point,
_temperature,
_water_compressibility):
"""
Calculates the water formation volume factor (B_w) using Gould's
correlation. The bubble point is necessary because a different correlation
must be used below and above it and the water compressibility (c_w)
is only needed if pressure is above bubble point.
Args:
_pressure: Pressure at which the oil is (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_bubble_point: Mixture's bubble point (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_temperature: Temperature (fahrenheit degrees).
_water_compressibility: Waters compressibility (psi-1). Value doesn't
matter if pressure is below bubble point.
Returns:
The water formation volume factor, in bbl/stb.
"""
result = (1.0 +
1.2e-4 * (_temperature - 60) +
1.0e-6 * (_temperature - 60) ** 2)
if _pressure >= _bubble_point:
result = result - 3.33e-6 * (_bubble_point + 14.7)
result = (result * math.exp(_water_compressibility *
(_bubble_point - _pressure)))
else:
result = result - 3.33e-6 * (_pressure + 14.7)
return result
def gas_deviation_factor(_pressure,
_temperature,
_gas_specific_gravity):
"""
Calculates the gas deviation factor or compressibility factor Z using Papay
correlation.
Args:
_pressure: Pressure at which the gas is (psig). Note that this value is
in psig, so it is relative to the atmospheric pressure.
_temperature: Temperature (fahrenheit degrees).
_gas_specific_gravity: Gas' specific gravity (doesn't have an unit).
Returns:
The gas deviation factor.
"""
pseudo_critical_temperature = (168. +
325. * _gas_specific_gravity -
12.5 * _gas_specific_gravity ** 2)
pseudo_critical_pressure = (677. +
15.0 * _gas_specific_gravity -
37.5 * _gas_specific_gravity ** 2)
pseudo_reduced_temperature = ((_temperature + 460) /
pseudo_critical_temperature)
pseudo_reduced_pressure = ((_pressure + 14.7) /
pseudo_critical_pressure)
pseudo_reduced_ratio = pseudo_reduced_pressure/pseudo_reduced_temperature
deviation_factor = (1 - pseudo_reduced_ratio *
(0.3675 - 0.04188423 * pseudo_reduced_ratio))
return deviation_factor
def gas_formation_volume_factor(_pressure,
_temperature,
_gas_specific_gravity,
_in_cubic_feet=True):
"""
Calculates the gas formation volume factor. This is a convenience method
that uses the gas specific gravity to calculate the gas deviation factor
under the supplied pressure and temperature and under standard conditions.
Args:
_pressure (double): Pressure at which the gas is (psig). Note that this
value is in psig, so it is relative to the atmospheric pressure.
_temperature (double): Temperature (fahrenheit degrees).
_gas_specific_gravity (double): Gas' specific gravity (doesn't have an
unit).
_in_cubic_feet (boolean, optional): If ``true``, result will be in
:math:`ft^3/scf`. If set to ``false``, result will be in
:math:`bbl/scf`.
Returns:
The gas formation volume factor.
"""
_gas_deviation_factor = gas_deviation_factor(_pressure,
_temperature,
_gas_specific_gravity)
_gas_deviation_factor_std = gas_deviation_factor(0,
60.0,
_gas_specific_gravity)
conversion_factor = 0.028269
if not _in_cubic_feet:
conversion_factor = 0.00503475
_gas_formation_volume_factor = (
conversion_factor *
(_temperature + 460) / (_pressure + 14.7) *
_gas_deviation_factor / _gas_deviation_factor_std
)
return _gas_formation_volume_factor
def dead_oil_viscosity(_temperature, _oil_api_gravity):
"""
Calculates the dead oil viscosity using the Beggs and Robinson correlation.
Args:
_temperature (double): Temperature (fahrenheit degrees).
_oil_api_gravity (double): Oil's API gravity (API degrees).
Returns:
The dead oil viscosity in :math:`cp`.
"""
term_x = (10 ** (3.0324 - 0.02023 * _oil_api_gravity) /
(_temperature ** 1.163))
_dead_oil_viscosity = 10 ** term_x - 1
return _dead_oil_viscosity
def live_oil_viscosity(_pressure,
_bubble_point,
_temperature,
_gas_solubility_in_oil,
_oil_api_gravity):
"""
Calculates the live oil viscosity. If pressure is below bubble point, the
Beggs and Robinson correlation will be used. Instead, if it is above bubble
point, the Beggs and Velasquez correlation will be used.
Args:
_pressure (double): Pressure at which the oil is (:math:`psig`). Note
that this value is relative to the atmospheric pressure.
_bubble_point (double): Mixture's bubble point (:math:`psig`). Note
that this value is relative to the atmospheric pressure.
_temperature (double): Temperature (fahrenheit degrees).
_gas_solubility_in_oil_ (double): Gas solubility in oil, :math:`R_{so}`
(in :math:`scf/stb`). **If pressure is above bubble point, the gas
solubility in oil supplied must be the one at the bubble point
(:math:`R_{sob}`)**.
_oil_api_gravity (double): Oil's API gravity (API degrees).
Returns:
The live oil viscosity in :math:`cp`.
"""
_dead_oil_viscosity = dead_oil_viscosity(_temperature, _oil_api_gravity)
_live_oil_viscosity = (10.715 *
(_gas_solubility_in_oil + 100) ** (-0.515) *
_dead_oil_viscosity **
(5.44 * (_gas_solubility_in_oil + 150) ** (-0.338)))
if _pressure > _bubble_point:
_live_oil_viscosity = (
_live_oil_viscosity *
((_pressure + 14.7) / (_bubble_point + 14.7)) ** (
2.6 * (_pressure + 14.7) ** 1.187 * math.exp(
-11.513 - 8.98e-5 * (_pressure + 14.7)
)
)
)
return _live_oil_viscosity
def gas_viscosity(_temperature, _gas_specific_gravity, _gas_density):
"""
Calculates the gas viscosity using the Lee et al. correlation.
Args:
_temperature (double): Temperature (fahrenheit degrees).
_gas_specific_gravity (double): Gas' specific gravity (doesn't have an
unit).
Returns:
The gas viscosity in :math:`cp`.
"""
molecular_weight = 28.97 * _gas_specific_gravity
x_exponent = 3.5 + 986 / (_temperature + 460) + 0.01 * molecular_weight
y_exponent = 2.4 - 0.2 * x_exponent
_gas_viscosity = (
(9.4 + 0.02 * molecular_weight) * ((_temperature + 460.) ** 1.5) /
(209. + 19. * molecular_weight + _temperature + 460) *
10 ** (-4) * math.exp(
x_exponent * (_gas_density / 62.4) ** y_exponent
)
)
return _gas_viscosity
def water_viscosity(_pressure, _temperature):
"""
Calculates the water viscosity using the Kestin, Khalifa and Correa
correlation.
Args:
_pressure (double): Pressure at which the oil is (:math:`psig`). Note
that this value is relative to the atmospheric pressure.
_temperature (double): Temperature (fahrenheit degrees).
Returns:
The water viscosity in :math:`cp`.
"""
viscosity = (
109.574 * _temperature ** (-1.12166) * (
0.9994 + 4.0295e-5 * (_pressure + 14.7) +
3.1062e-9 * (_pressure + 14.7) ** 2
)
)
return viscosity
def dead_oil_gas_surface_tension(_temperature, _oil_api_gravity):
"""
Calculates the dead oil - gas surface tension using Abdul-Majeed
correlation (an update to Baker and Swerdloff's correlation). Source:
http://petrowiki.org/Interfacial_tension#Water-hydrocarbon_surface_tension
Args:
_temperature (double): Temperature (fahrenheit degrees).
_oil_api_gravity: Oil's API gravity (API degrees).
Returns:
The dead oil - gas surface tension in :math:`dina/cm`
"""
return (
(1.17013 - 1.694e-3 * _temperature) *
(38.085 - 0.259 * _oil_api_gravity)
)
def live_oil_gas_surface_tension(_dead_oil_surface_tension,
_gas_solubility_in_oil):
"""
Corrects the dead oil - gas surface tension using Abdul-Majeed proposed
method to obtain the surface tension between live oil and gas. Source:
http://petrowiki.org/Interfacial_tension#Water-hydrocarbon_surface_tension
Args:
_dead_oil_surface_tension (double): Dead oil surface tension in
:math:`dina/cm`
_gas_solubility_in_oil_ (double): Gas solubility in oil, :math:`R_{so}`
(in :math:`scf/stb`).
Returns:
The oil - gas surface tension in :math:`dina/cm`
"""
return _dead_oil_surface_tension * (
0.056379 +
0.94362 * math.exp(
-3.8491e-3 * _gas_solubility_in_oil
)
)
def water_gas_surface_tension():
"""
Returns the water - gas surface tension. Currently there is no correlation
implemented for this property.
Returns:
The water - gas surface tension in :math:`dina/cm`
"""
return 90.359630470339
|
fe6a4d685fe560b9f49066c034798bd3a86cf5af | Prashant47/algorithms | /tree/kth_largest_element_in_bst.py | 877 | 4.0625 | 4 | # Introducing binary tree
class Node:
def __init__(self,val):
self.left = None
self.right = None
self.val = val
# logic is to traverse inorder node
# and keep track of no of nodes visited
# The code first traverses down to the rightmost node which takes O(h) time, then traverses k elements in O(k) time.
# Therefore overall time complexity is O(h + k).
class Solution:
count = 0
def klargestNode(self,root,k):
if root == None:
return
self.klargestNode(root.right,k)
self.count += 1
if self.count == k:
print(root.val)
return
self.klargestNode(root.left,k)
# Create a root node
root = Node(5)
root.left = Node(3)
root.right = Node(8)
root.left.left = Node(1)
root.right.right = Node(11)
obj = Solution()
obj.klargestNode(root,2)
|
c64b3fdfe335a2d02c0c763fcf7dd0e26cfbd4fe | aosbornee/DevOps-Work | /Notes/Week3-Python/PythonFiles/using_builtin_libraries.py | 474 | 4.125 | 4 |
# # Math and Random are builtin modules
# import math
# from random import random
#
# num = 24.8
#
# # Rounds the number up
# print(math.ceil(num))
# # Rounds the number down
# print(math.floor(num))
# # Returns a random number
# print(random())
# Calculating inches to Centimetres
def inches_to_cm():
inches = int(input("What is the length of the object in inches?: "))
print("In centimetres, your object is:")
return inches * 2.54
print(inches_to_cm())
|
f8ec8e5119a8b6a9d5d10bdf9354720ecef19cd3 | beestaicu/CS1028_Programming_for_Sciences_and_Engineering | /lecture/lecture1-4/intops.py | 1,268 | 3.59375 | 4 | #-----------------------------------------------------------------------
# intops.py
#-----------------------------------------------------------------------
import stdio
import sys
# Accept int command-line arguments a and b. Use them to illustrate
# integer operators. Write the results to standard output.
a = int(sys.argv[1])
b = int(sys.argv[2])
total = a + b
diff = a - b
prod = a * b
quot = a // b
# In Python 2.x, / does classic division and // does floor division
# In Python 3.x, / does true division and // does floor division
# It's wise to use // to divide integers, and / to divide floats.
rem = a % b
exp = a ** b
stdio.writeln(str(a) + ' + ' + str(b) + ' = ' + str(total))
stdio.writeln(str(a) + ' - ' + str(b) + ' = ' + str(diff))
stdio.writeln(str(a) + ' * ' + str(b) + ' = ' + str(prod))
stdio.writeln(str(a) + ' // ' + str(b) + ' = ' + str(quot))
stdio.writeln(str(a) + ' % ' + str(b) + ' = ' + str(rem))
stdio.writeln(str(a) + ' ** ' + str(b) + ' = ' + str(exp))
#-----------------------------------------------------------------------
# python intops.py 1234 5
# 1234 + 5 = 1239
# 1234 - 5 = 1229
# 1234 * 5 = 6170
# 1234 // 5 = 246
# 1234 % 5 = 4
# 1234 ** 5 = 2861381721051424 |
9d13ac60e85d1e368271233b72ae19e470f9d218 | Robinpig/Pythonista | /pyplot/20-03-07.py | 549 | 3.640625 | 4 | import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-6,6,0.1)
y=np.sin(x)
plt.plot(x,y)
plt.xlabel("x")
plt.ylabel("y")
#plt.show()
#sigmoid function
def sigmoid(x):
return 1.0 / (1 + np.exp(-x))
sigmoid_inputs = np.arange(-10, 10, 0.1)
sigmoid_outputs = sigmoid(sigmoid_inputs)
print("Sigmoid Function Input :: {}".format(sigmoid_inputs))
print("Sigmoid Function Output :: {}".format(sigmoid_outputs))
plt.plot(sigmoid_inputs, sigmoid_outputs)
plt.xlabel("Sigmoid Inputs")
plt.ylabel("Sigmoid Outputs")
plt.legend()
plt.show() |
30e8137ebc111e36534f310e48128a824161360c | JeevanMahesha/python_program | /college/frequency_of_words.py | 429 | 3.53125 | 4 | import collections as c
data = 'New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.'
data = data.split()
sapreted_data = c.Counter(data)
sapreted_data = dict(sapreted_data)
for k,v in sorted (sapreted_data.items()):
print(k,':',v)
"""
----------- OUTPUT -------------
2 : 2
3. : 1
3? : 1
New : 1
Python : 5
Read : 1
and : 1
between : 1
choosing : 1
or : 2
to : 1
""" |
5b2b583d6d2e020298f320d85c27060d9afe1c06 | huchangchun/learn-python3 | /practice/exam.py | 9,392 | 3.9375 | 4 | <<<<<<< HEAD
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# print('mm333'.
# dic ={"a":1,"b":2}
# print(dic.get("c"))
# print([1,3] in [1,2,3,4])
# print([5,2,8].sort())
#有一堆士力架,第一天吃一半加1个,后面每天都吃一半加1个,直达第6天时只剩下1个
# 问有多少个
d = 6
n = 0
while d>=1:
if d == 6:
n = 1
else:
n = 2*(n+1)
print('the %d day:last n:%d' % (d,n))
d -= 1
print('共:%d个'%(n))
def fun01(day):
if day == 6:
sum =1
else:
sum = 2*(fun01(day + 1) +1)
return sum
print("共买了:%d个士力架"%fun01(1))
# the 6 day:last n:1
# the 5 day:last n:4
# the 4 day:last n:10
# the 3 day:last n:22
# the 2 day:last n:46
# the 1 day:last n:94
# 共:94个
#一次性输入任意不少于5个数字(数字以逗号分界)保存在列表中并且对输入的数字进行排序
# 封装成函数
def sortlist(list):
listlen =len(list)
for i in range(listlen):
for j in range(i + 1, listlen):
if list[j] < list[i]:
list[i], list[j] = list[j], list[i]
# 1,2,3,2,2,2,12,321,12,23,31,1231
str = input("输入不少于5个数:")
list01 = str.split(',')
newlist=[]
for i in range(len(list01)):
newlist.append(int(list01[i]))
print(newlist)
sortlist(newlist)
print(newlist)
# 输入不少于5个数:1,4,3,2,7,8
# ['1', '2', '3', '4', '7','8']
#写一个程序,可任意输入一个文件名打开该文件,如果文件不存在则创建
#然后开始写入内容,可重复输入追加到文件中,若写入失败则退出程序
# 当输入#时结束输入,并打印文件的所有内容,将程序封装成函数
def writefile():
filename = input("输入一个文件名:")
try:
with open(filename,'a+') as fw:
while True:
content = input('输入')
if content == '#':
break;
fw.write(content)
except BaseException :
return
with open(filename,'r') as fr:
content = fr.read()
print(content)
# writefile()
#time操作
# 1)将字符串的时间 "2017-12-31 23:40:00" 转换为时间戳和时间元组
# 2)字符串格式更改,如time = "2017-12-31 23:40:00" 改为time = "2017/12/31 23-40-00"
# 3)获取两天前的当前时间并以可读的字符串形式(格式如1题)
# 4)通过time输出时间'今天是2018年1月1日 08点08分08秒'
import time
t1 = "2017-12-31 23:40:00"
t1_tuple = time.strptime(t1,"%Y-%m-%d %H:%M:%S")
# print(t1_tuple)
t1_stamp = time.mktime(t1_tuple)
# print(t1_stamp)
t1_fmt = time.strftime("%Y/%m/%d %H-%M-%S",t1_tuple)
# print(t1_fmt)
#返回当前时间的时间戳
now = time.time()
twodayago = now - 60*60*24*2
twodayago_tuple = time.localtime(twodayago)
twodayago_fmt = time.strftime("%Y/%m/%d %H-%M-%S",twodayago_tuple)
# print("twodayago:%s" %twodayago_fmt)
nowfmt = time.localtime(now)
# print("今天是%s年%s月%s日 %s点%s分%s秒"%(time.strftime('%Y',nowfmt),
# time.strftime('%m',nowfmt),
# time.strftime('%d',nowfmt),
# time.strftime('%H',nowfmt),
# time.strftime('%M',nowfmt),
# time.strftime('%S',nowfmt)))
"""
将
[5,5,1,1,2,3,2,2,32,2,2,3,2,2,32,2,3,3,3,3,2]
转变为
[[5, 5], [1, 1], [2], [3], [2, 2], [32], [2, 2], [3], [2, 2], [32], [2], [3, 3, 3, 3], [3]]
"""
lst =[5,5,1,1,2,3,2,2,32,2,2,3,2,2,32,2,3,3,3,3,2]
def group_list(list):
new_lst = [[]]
count = len(list)
for i in range(count-1):
if list[i]==list[i+1]:
new_lst[-1].append(list[i])
else:
new_lst[-1].append(list[i])
new_lst.append([])
new_lst[-1].append(list[i])
return new_lst
nlst = group_list(lst)
print(nlst)
"""
将
[5,5,1,1,2,3,2,2,32,2,2,3,2,2,32,2,3,3,3,3,2]
转变为
[[5, 5], [1, 1], 2, 3, [2, 2], 32, [2, 2], 3, [2, 2], 32, 2, [3, 3, 3, 3], 2]
append和extend都仅只可以接收一个参数
append 任意,甚至是tuple
extend 只能是一个列表
"""
def group_listtwo(list):
new_lst = []
templist=[]
count = len(list)
for i in range(count-1):
if list[i]==list[i+1]:
templist.append(list[i])
else:
templist.append(list[i])
if len(templist) >1:
new_lst.append([])
for j in templist:
new_lst[-1].append(j)
else:
new_lst.extend(templist)
templist.clear()
if list[i+1] == new_lst[-1]:
new_lst[-1].append(list[i+1])
else:
new_lst.append(list[i+1])
return new_lst
nlst = group_listtwo(lst)
print(nlst)
def fun01(a, *tup_args, **dict_args):
print(a)
print(tup_args)
print(dict_args)
fun01("a1", "a2", name='joe', age=18)
=======
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# print('mm333'.isalpha())
# print([1,3,3].count(3))
# dic ={"a":1,"b":2}
# print(dic.get("c"))
# print([1,3] in [1,2,3,4])
# print([5,2,8].sort())
#有一堆士力架,第一天吃一半加1个,后面每天都吃一半加1个,直达第6天时只剩下1个
# 问有多少个
d = 6
n = 0
while d>=1:
if d == 6:
n = 1
else:
n = 2*(n+1)
print('the %d day:last n:%d' % (d,n))
d -= 1
sum = 2*(n+1)
print('sum:%d'%(sum))
# the 6 day:last n:1
# the 5 day:last n:4
# the 4 day:last n:10
# the 3 day:last n:22
# the 2 day:last n:46
# the 1 day:last n:94
# sum:190
#一次性输入任意不少于5个数字(数字以逗号未分界)保存在列表中并且对输入的数字进行排序
# 封装成函数
def sortlist(list):
for i in range(len(list)):
for j in range(i):
if list[j] > list[j+1]:
list[j],list[j+1] = list[j+1],list[j]
# str = input("输入5个数:")
# list = str.split(',')
# sortlist(list)
# print(list)
# 输入5个数:1,4,3,2,7
# ['1', '2', '3', '4', '7']
#写一个程序,可任意输入一个文件名打开该文件,如果文件不存在则创建
#然后开始写入内容,可重复输入追加到文件中,若写入失败则退出程序
# 当输入#时结束输入,并打印文件的所有内容,将程序封装成函数
def writefile():
try:
filename = input("输入一个文件名:")
with open(filename,'a+') as fw:
while True:
content = input('输入')
if content == '#':
break;
fw.write(content)
except Exception :
return
with open(filename,'r') as fr:
content = fr.read()
print(content)
# writefile()
#time操作
# 1)将字符串的时间 "2017-12-31 23:40:00" 转换为时间戳和时间元组
# 2)字符串格式更改,如time = "2017-12-31 23:40:00" 改为time = "2017/12/31 23-40-00"
# 3)获取两天前的当前时间并以可读的字符串形式(格式如1题)
# 4)通过time输出时间'今天是2018年1月1日 08点08分08秒'
import time
t1 = "2017-12-31 23:40:00"
t1_tuple = time.strptime(t1,"%Y-%m-%d %H:%M:%S")
# print(t1_tuple)
t1_stamp = time.mktime(t1_tuple)
# print(t1_stamp)
t1_fmt = time.strftime("%Y/%m/%d %H-%M-%S",t1_tuple)
# print(t1_fmt)
#返回当前时间的时间戳
now = time.time()
twodayago = now - 60*60*24*2
twodayago_tuple = time.localtime(twodayago)
twodayago_fmt = time.strftime("%Y/%m/%d %H-%M-%S",twodayago_tuple)
# print("twodayago:%s" %twodayago_fmt)
nowfmt = time.localtime(now)
# print("今天是%s年%s月%s日 %s点%s分%s秒"%(time.strftime('%Y',nowfmt),
# time.strftime('%m',nowfmt),
# time.strftime('%d',nowfmt),
# time.strftime('%H',nowfmt),
# time.strftime('%M',nowfmt),
# time.strftime('%S',nowfmt)))
"""
将
[5,5,1,1,2,3,2,2,32,2,2,3,2,2,32,2,3,3,3,3,2]
转变为
[[5, 5], [1, 1], [2], [3], [2, 2], [32], [2, 2], [3], [2, 2], [32], [2], [3, 3, 3, 3], [3]]
"""
lst =[5,5,1,1,2,3,2,2,32,2,2,3,2,2,32,2,3,3,3,3,2]
def group_list(list):
new_lst = [[]]
count = len(list)
for i in range(count-1):
if list[i]==list[i+1]:
new_lst[-1].append(list[i])
else:
new_lst[-1].append(list[i])
new_lst.append([])
new_lst[-1].append(list[i])
return new_lst
nlst = group_list(lst)
# print(nlst)
"""
将
[5,5,1,1,2,3,2,2,32,2,2,3,2,2,32,2,3,3,3,3,2]
转变为
[[5, 5], [1, 1], 2, 3, [2, 2], 32, [2, 2], 3, [2, 2], 32, 2, [3, 3, 3, 3], 2]
append和extend都仅只可以接收一个参数
append 任意,甚至是tuple
extend 只能是一个列表
"""
def group_listtwo(list):
new_lst = []
templist=[]
count = len(list)
for i in range(count-1):
if list[i]==list[i+1]:
templist.append(list[i])
else:
templist.append(list[i])
if len(templist) >1:
new_lst.append([])
for j in templist:
new_lst[-1].append(j)
else:
new_lst.extend(templist)
templist.clear()
if list[i+1] == new_lst[-1]:
new_lst[-1].append(list[i+1])
else:
new_lst.append(list[i+1])
return new_lst
nlst = group_listtwo(lst)
# print(nlst)
>>>>>>> c352954ac35edc7aa2593da2f426884a7948709d
|
81da4889207a36ebf298ae2e06279f1382fdf4f0 | atanas-bg/SoftUni | /Python3/Lecture_01/task07_chess_board.py | 483 | 3.90625 | 4 | """
Draw a chess board
"""
import turtle
side = 40
turtle.speed('fastest')
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
for row in range(8):
for col in range(8):
if (col + row) % 2 == 0:
turtle.begin_fill()
for a in range(4):
turtle.forward(side)
turtle.left(90)
turtle.end_fill()
turtle.forward(side)
turtle.penup()
turtle.goto(0, (row + 1) * side)
turtle.pendown()
turtle.exitonclick()
|
16a6bd354de51b798f54064545e1833add6a45a0 | cskanani/codechef_prepare | /sorting/MRGSRT.py | 691 | 3.796875 | 4 | from math import ceil
def print_merge_calls(start, end, req_ind, depth):
if start == req_ind and end == req_ind:
return depth
num_ele = end - start + 1
mid = start + ceil(num_ele / 2) - 1
if start <= req_ind <= mid:
print(start, mid)
return print_merge_calls(start, mid, req_ind, depth+1)
else:
print(mid+1, end)
return print_merge_calls(mid+1, end, req_ind, depth+1)
for _ in range(int(input())):
start, end, req_ind = map(int, input().split())
depth_count = False
if req_ind < start or req_ind > end:
print(-1)
else:
print(start, end)
print(print_merge_calls(start, end, req_ind, 1))
|
812e3914562c40f6f587bda5bca00f3c4aee63ac | Joldiazch/holbertonschool-higher_level_programming | /0x05-python-exceptions/4-list_division.py | 535 | 3.84375 | 4 | #!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
list_to_return = []
for idx in range(list_length):
try:
resul = my_list_1[idx] / my_list_2[idx]
except TypeError:
print("wrong type")
resul = 0
except IndexError:
print("out of range")
resul = 0
except ZeroDivisionError:
print("division by 0")
resul = 0
finally:
list_to_return.append(resul)
return list_to_return
|
51b3d27c0673119bf6df3e139c6bc11492824b78 | jeffnuss/project-euler | /python/prob1.py | 113 | 3.515625 | 4 | a = 1000
b = 3
c = 5
sum = 0
for i in range(a):
if i % b == 0 or i % c == 0:
sum += i
print sum |
0c9994ff41c9a62b19afdf383152134ae1df7efb | SapphieByte/Are-you-happy-jolly- | /Plot.py | 476 | 3.65625 | 4 | from matplotlib import pyplot as plt
def plot(d):
plt.plot(d[0], label="Employed (100s)", color="#2489FF")
plt.plot(d[1], label="Average Money", color="#FFCC12")
plt.plot(d[2], label="People alive (100s)", color="#23FF44")
plt.plot(d[3], label="People alive all-time (100s)", color="#119911")
plt.plot(d[4], label="People died all-time (100s)", color="#dd0000")
plt.xlabel("Time")
plt.ylabel("Higher Value")
plt.legend()
plt.show()
|
ea54580c8b2926d7177078a788e99e34da3894b9 | MartynJJ/Public | /OOP_demo.py | 971 | 3.84375 | 4 | import math
class Point:
def __init__(self, x=None, y=None):
if (x == None):
self.m_x = 0.0
self.m_y = 0.0
elif (y == None):
self.m_x = x
self.m_x = y
else:
self.m_x = x
self.m_y = y
def X(self, new_x = None):
if (new_x == None):
return self.m_x
else:
self.m_x = new_x
def Y(self, new_y = None):
if (new_y == None):
return self.m_y
else:
self.m_y = new_y
def Distance(self,Point):
return math.sqrt((self.m_x - Point.m_x)**2 + (self.m_y-Point.m_y) ** 2)
class Line:
def __init__(self, P1=Point(), P2=Point()):
self.m_P1 = P1
self.m_P2 = P2
def Length(self):
return (self.m_P1.Distance(self.m_P2))
my_Point = Point(3.0, 4.0)
Origin = Point()
my_Line = Line(my_Point)
print(my_Line.Length())
my_Point.X(10.0)
print(my_Point.X())
|
c360248dd880c702d36862e55befcbaa68ac4989 | gabriellaec/desoft-analise-exercicios | /backup/user_071/ch138_2020_04_01_19_08_21_714638.py | 403 | 4 | 4 | pergunta = input ('O código está funcionando?')
if pergunta == 'n':
print ('Corrija o código e tente de novo')
print (pergunta)
elif pergunta == 's':
pergunta2 = input ('Produz o resultado correto?')
if pergunta2 == 'n':
print ('Corrija o código e tente de novo e volte para o começo de tudo')
print (pergunta)
elif pergunta2 == 's':
print ('Parabéns!') |
de5fbe5c2464887adfc82365582b173a1db682b4 | PureSin/euler | /python/five.py | 868 | 3.9375 | 4 | from three import is_prime
from primes import getPrimes
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
#TODO speed up
def prime_factors(n):
"""returns all prime factors of n"""
l = {}
listOfPrimes = getPrimes(n)
for p in listOfPrimes:
while n % p == 0:
n = n / p
l[p] = l.get(p, 0) + 1
return l
if __name__=="__main__":
x = xrange(1,21)
all_factors = {}
for i in x:
factors = prime_factors(i)
for key in factors.keys():
if factors[key] > all_factors.get(key, 0):
all_factors[key] = factors[key]
num = 1
for key in all_factors.keys():
num *= key**all_factors[key]
print num |
80520ff8a8300f3ad9e6bb0db14b40f82f76be77 | Eduardo-Lucas/PasswordValidation | /password_validation/password.py | 1,984 | 3.71875 | 4 | from password_validation.calculate import calculate_entropy
from password_validation.character_pool import CharacterPool
class Password:
"""
A password.
Once instantiated, the password can't be recovered. Only metadata about the
password can be recovered.
"""
def __init__(self, password: str, character_pool: CharacterPool = None):
# set character pool
if character_pool is None:
self.pool = CharacterPool()
else:
self.pool = character_pool
assert all(
i in self.pool.all for i in password
), "A password can only use characters from the character_pool provided"
# set password
self.password = password
# set the number of lowercase in the password
self.lowercase = len(
[character for character in password if character in self.pool.lowercase]
)
# set the uppercase of lowercase in the password
self.uppercase = len(
[character for character in password if character in self.pool.uppercase]
)
# set the symbols of lowercase in the password
self.symbols = len(
[character for character in password if character in self.pool.symbols]
)
# set the numbers of lowercase in the password
self.numbers = len(
[character for character in password if character in self.pool.numbers]
)
# set the numbers of whitespace in the password
self.whitespace = len(
[character for character in password if character in self.pool.whitespace]
)
# set the other of lowercase in the password
self.other = len(
[character for character in password if character in self.pool.other]
)
# set the length of the password
self.length = len(password)
# set entropy
self.entropy = calculate_entropy(password, character_pool=self.pool)
|
1f0887375d166c263c8b92ece476323c9302deac | sumitkumar0711/GUVI1 | /IsomorphicStrings.py | 400 | 3.578125 | 4 | var1 = input().split(" ")
string1 = var1[0]
string2 = var1[1]
counter1 = 0
counter2 = 0
for i in range(1,len(string1)):
if(string1[i-1]==string1[i]):
counter1+=1
else:
counter1-=1
for j in range(1,len(string2)):
if(string2[j-1]==string2[j]):
counter2+=1
else:
counter2-=1
if(counter2==counter1):
print("yes")
else:
print("no") |
39be4bdc19a80dba0c4967d71aa5c734d161e1af | IncredibleDevHQ/incredible-dev-videos | /archive/Python101/ep4-Operators-part-1.py | 378 | 4.25 | 4 | # Operators in Python - Part 1
# Arithmetic
print(6 + 9) # result : 15
print(7 - 2) # result : 5
print(8 * 8) # result : 64
print(17 / 4) # result : 4.25
print(9 % 2) # result : 1
print(2 ** 8) # result : 256
print(17 // 4) # result : 4
# Assignment
x = 5
# Shorthand Assignment
x += 3 # same as x = x + 3
x -= 3 # same as x = x - 3
x *= 3 # same as x = x * 3
...
|
fda6effae5c8046159852416eae8dc23b91e151c | JpryHyrd/python_2.0 | /Lesson_1/6.py | 678 | 4.21875 | 4 | # 6. Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
alpha = "abcdefghijklmnopqrstuvwxyz"
print("Для определения позиции буквы АНГЛИЙСКОГО алфавита необходимо ввести некоторое значенеие...")
#Запрос данных у пользователя
answer = int(input("Введите номер буквы АНГЛИЙСКОГО алфавита: "))
#Вывод позиции буквы
print("Под {} номером алфавита распологается буква '{}'" .format(answer, alpha[answer - 1])) |
b3258b7991b00544843ee43a4db73ddb4d65f9ab | shangxiwu/services | /Module_04_Line Bot 前置作業/Lab_4-2.py | 693 | 3.90625 | 4 |
import sqlite3
# 連結資料表
connect = sqlite3.connect('Lab_4-2.db')
cursor = connect.cursor()
# 建立資料表
cursor.execute(" ") # write your code here
connect.commit()
# ----------------------------------------------------------
# 插入資料至資料表中
cursor.execute(" ") # write your code here
cursor.execute(" ") # write your code here
cursor.execute(" ") # write your code here
connect.commit()
print('插入多筆資料')
# ----------------------------------------------------------
# 印出目前資料表中資料
print('印出目前表中內容')
grades_list = cursor.execute(" ") # write your code here
for grade in grades_list:
print(grade) |
ad987e3b253b46753d726ddea1a6b4b973d370e8 | Ford-z/LeetCode | /108 将有序数组转换为二叉搜索树.py | 789 | 3.8125 | 4 | #将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
#本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums:
return None
else:
mid=len(nums)//2
root=TreeNode(nums[mid])
nums1=nums[0:mid]
nums2=nums[mid+1:len(nums)]
root.left=self.sortedArrayToBST(nums1)
root.right=self.sortedArrayToBST(nums2)
return root
|
c236aec650a76608f88af19fe6a633bf542c51bf | amymhaddad/test_driven_development | /pangram/pangram.py | 252 | 3.78125 | 4 | from string import ascii_lowercase as alphabet
def pangram(sentence):
sentence_letters_in_alphabet = set(
letter for letter in sentence.lower() if letter in alphabet
)
return set(alphabet).issubset(sentence_letters_in_alphabet)
|
876fa88d9aea09b3d27201026b9a3951ea632ddb | JJong-Min/Baekjoon-Online-Judge-Algorithm | /Breadth_first_search(BFS)/Breadth_first_search_2번.py | 765 | 3.5 | 4 | def dfs(graph, v, visited):
visited[v] = True
print(v, end =' ')
for i in range (1, n+1):
if not visited[i] and graph[v][i] == 1:
dfs(graph, i, visited)
def bfs(graph, v, visited):
queue = [v]
visited[v] = False
while queue:
v = queue.pop(0)
print(v, end = ' ')
for i in range(1, n+1):
if visited[i] and graph[v][i] == 1:
queue.append(i)
visited[i] = False
n, m, v = input().split()
n = int(n)
m = int(m)
v = int(v)
graph =[[0]*(n+1) for _ in range (n+1)]
for i in range (m):
a, b = map(int, input().split())
graph[a][b] = 1
graph[b][a] = 1
visited = [False] * len(graph)
#dfs, bfs
dfs(graph, v, visited)
print()
bfs(graph, v, visited)
|
df7a85ca80164f06b3e7e8766a5b1072ea5f5143 | shamsaraj/windows | /auto-shutdown.py | 1,653 | 3.671875 | 4 | #python 3.2.2, 2.5
import time
import os
hour = 25
while hour > 23 or hour < 0:
hour = int(raw_input("Enter hour (00-23): "))
minute=60
while minute > 59 or minute < 0:
minute = int (raw_input ("Enter min (00-59): "))
operatingsystem = "null"
while operatingsystem <> "win7" and operatingsystem <> "winxp":
operatingsystem = raw_input("Enter your operating system type: (win7 or winxp):")
events = "null"
while events <> "shutdown" and events <> "hybernate" and events <> "restart":
events = raw_input("Enter your desired event: (shutdown, hybernate or restart):")
print "The time to go is " , hour , ":" , minute
timeob = time.localtime()
hh = timeob.tm_hour
while hh <> hour :
timeob = time.localtime()
hh = timeob.tm_hour
mm = timeob.tm_min
while mm <> minute :
timeob = time.localtime()
mm = timeob.tm_min
print "It is time to go home"
print "."
print "."
print "."
s=11
for i in range (1, 12):
time.sleep(1)
s=s-1
print s
if operatingsystem == "win7" and events == "hybernate" :
os.system ("%windir%\system32\shutdown /h")
if operatingsystem == "win7" and events == "shutdown" :
os.system ("%windir%\system32\shutdown /s")
if operatingsystem == "win7" and events == "restart" :
os.system ("%windir%\system32\shutdown /r")
if operatingsystem == "winxp" and events == "hybernate" :
os.system ("%windir%\System32\rundll32.exe powrprof.dll,SetSuspendState ")
if operatingsystem == "winxp" and events == "shutdown" :
os.system ("%windir%\System32\shutdown -s")
if operatingsystem == "winxp" and events == "restart" :
os.system ("%windir%\System32\shutdown -r") |
0fbd497a0b2db850680157679c0fc1f9cbf9ec3a | Ankush-Chander/euler-project | /problem1.py | 559 | 4.1875 | 4 | '''If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
import sys
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path+'/util')
import numbers_lib
if len(sys.argv) !=2:
print("Usage: python " + sys.argv[0] + " max_limit")
else:
max = int(sys.argv[1])
sum = 0
for i in range(3,max):
if numbers_lib.is_multiple(i,3) or numbers_lib.is_multiple(i,5):
sum = sum + i
print(sum)
|
297a4b026ec29e478ad93d0c47594200ad2340c0 | EtienneLa/Python_Exercises | /LearningBasics/Sets.py | 251 | 4.09375 | 4 | # sets contain every item just once
groceries = {"cereal", "milk", "cornflakes", "beer", "duct tape", "lotion", "beer"}
print(groceries)
if "milk" in groceries:
print("You already have milk added.")
else:
print("You need to add milk, bud.")
|
564045f13f76237db87e46e9c5cd04e78c607c69 | martinezga/jetbrains-academy-hangman | /hangman.py | 2,498 | 3.796875 | 4 | import random
class HangmanGame:
def __init__(self):
self.game_words = 'python', 'java', 'kotlin', 'javascript'
self.random_word = ''
self.hint = ''
self.lives = 8
self.letters_guessed = []
self.last_input = ''
def get_word(self):
self.random_word = self.game_words[random.randrange(len(self.game_words))]
self.hint = '-' * len(self.random_word)
def catch_errors(self, user_input):
if (len(user_input) > 1) or (len(user_input) == 0):
print('You should input a single letter')
return -1
if not(user_input.isalpha()) or user_input.isupper():
print('Please enter a lowercase English letter')
return -1
self.last_input = user_input
return 0
def is_guessed(self):
for letter in self.letters_guessed:
if self.last_input == letter:
print("You've already guessed this letter")
return 1
return 0
def search_letter(self):
hint = list(self.hint)
flag = 0
for i in range(len(self.random_word)):
if self.last_input == self.random_word[i]:
flag += 1
hint[i] = self.last_input
if flag == 0:
print("That letter doesn't appear in the word")
self.count_lives(-1)
self.letters_guessed.append(self.last_input)
self.list_to_str(hint)
def count_lives(self, number):
self.lives += number
if self.lives <= 0:
print('You lost!')
def list_to_str(self, list_):
str_ = ''
for letter in list_:
str_ += letter
self.hint = str_
def compare_hint(self):
if self.hint == self.random_word:
self.lives = -1
print(f'You guessed the word {self.random_word}!')
print('You survived!')
def play(self):
if not(self.is_guessed()):
self.search_letter()
self.compare_hint()
def main():
game = HangmanGame()
game.get_word()
print('H A N G M A N')
option = input('Type "play" to play the game, "exit" to quit: ')
if option != 'exit':
while game.lives > 0:
print('\n' + game.hint)
user_letter = input('Input a letter: ')
if game.catch_errors(user_letter) != -1:
game.play()
option = input('\nType "play" to play the game, "exit" to quit: ')
main()
|
c8448c7d9da50f7982c97c8af4eeac0d5f057c95 | davidhwayne/project-euler | /prob29.py | 397 | 3.53125 | 4 | import time
def distinctnums(maxnum):
nums=[4]
for a in range(2,maxnum+1):
for b in range(2,maxnum+1):
n=a**b
nums.append(n)
return len(set(nums))
def main():
start=time.time()
answer=distinctnums(100)
elapsed=time.time()-start
print answer
print 'Completed in {elapsed} seconds'.format(elapsed=elapsed)
return True
main() |
66d43a0f5abfec78c890f81746843bde22707d9a | Diptiman1999/264725_DailyPractice_Python | /file_operations/read_readlines.py | 206 | 3.75 | 4 | file=open("text.txt","r")
print(type(file))
# print(file)
# for line in file:
# # print(type(line))
# print(line)
# print(file.readline())
# print(file.readlines())
print(len(file.readlines()[1])) |
2a9856951f88756d6689c1170a262d7da7286c50 | mertozzz/programlama | /444444.py | 773 | 3.6875 | 4 | def performans():
x=int(input('standart çevrim giriniz:'))
y=int(input('üretim miktarı:'))
z=int(input('planlanmış üretim süresi:'))
e=int(input('plansız duruş:'))
performansH=((x*y)/(z-e))
print (performansH)
def kullan():
x=int(input('planlanmış üretim süresi:'))
y=int(input('Plansız Duruş:'))
z=int(input('Planlanmış Üretim Süresi :'))
kulH=((x-y)/z)
print (kulH)
def kalite():
x=int(input('Sağlam Ürün Miktarı:'))
y=int(input('Toplam Üretim Mitarı:'))
kaliteH=x/y
return kaliteH
def oee():
x=int(input('Kullanılabilirlik :'))
y=int(input('Performans:'))
z=int(input('kalite:'))
oeeH=x*y*z
print (oeeH)
|
9b4d4b45b812c16456e2a991971a38468d5e62b6 | giorgioGunawan/jenga-vs | /catkin_ws/src/baldor/src/baldor/quaternion.py | 9,756 | 4.125 | 4 | #!/usr/bin/env python
"""
Functions to operate quaternions.
.. important:: Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
"""
import math
import numpy as np
# Local modules
import baldor as br
def are_equal(q1, q2, rtol=1e-5, atol=1e-8):
"""
Returns True if two quaternions are equal within a tolerance.
Parameters
----------
q1: array_like
First input quaternion (4 element sequence)
q2: array_like
Second input quaternion (4 element sequence)
rtol: float
The relative tolerance parameter.
atol: float
The absolute tolerance parameter.
Returns
-------
equal : bool
True if `q1` and `q2` are `almost` equal, False otherwise
See Also
--------
numpy.allclose: Contains the details about the tolerance parameters
Notes
-----
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
Examples
--------
>>> import baldor as br
>>> q1 = [1, 0, 0, 0]
>>> br.quaternion.are_equal(q1, [0, 1, 0, 0])
False
>>> br.quaternion.are_equal(q1, [1, 0, 0, 0])
True
>>> br.quaternion.are_equal(q1, [-1, 0, 0, 0])
True
"""
if np.allclose(q1, q2, rtol, atol):
return True
return np.allclose(np.array(q1)*-1, q2, rtol, atol)
def conjugate(q):
"""
Compute the conjugate of a quaternion.
Parameters
----------
q: array_like
Input quaternion (4 element sequence)
Returns
-------
qconj: ndarray
The conjugate of the input quaternion.
Notes
-----
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
Examples
--------
>>> import baldor as br
>>> q0 = br.quaternion.random()
>>> q1 = br.quaternion.conjugate(q0)
>>> q1[0] == q0[0] and all(q1[1:] == -q0[1:])
True
"""
qconj = np.array(q, dtype=np.float64, copy=True)
np.negative(qconj[1:], qconj[1:])
return qconj
def dual_to_transform(qr, qt):
"""
Return a homogeneous transformation from the given dual quaternion.
Parameters
----------
qr: array_like
Input quaternion for the rotation component (4 element sequence)
qt: array_like
Input quaternion for the translation component (4 element sequence)
Returns
-------
T: array_like
Homogeneous transformation (4x4)
Notes
-----
Some literature prefers to use :math:`q` for the rotation component and
:math:`q'` for the translation component
"""
T = np.eye(4)
R = br.quaternion.to_transform(qr)[:3, :3]
t = 2*br.quaternion.multiply(qt, br.quaternion.conjugate(qr))
T[:3, :3] = R
T[:3, 3] = t[1:]
return T
def inverse(q):
"""
Return multiplicative inverse of a quaternion
Parameters
----------
q: array_like
Input quaternion (4 element sequence)
Returns
-------
qinv : ndarray
The inverse of the input quaternion.
Notes
-----
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
"""
return conjugate(q) / norm(q)
def multiply(q1, q2):
"""
Multiply two quaternions
Parameters
----------
q1: array_like
First input quaternion (4 element sequence)
q2: array_like
Second input quaternion (4 element sequence)
Returns
-------
result: ndarray
The resulting quaternion
Notes
-----
`Hamilton product of quaternions
<http://en.wikipedia.org/wiki/Quaternions#Hamilton_product>`_
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> q = br.quaternion.multiply([4, 1, -2, 3], [8, -5, 6, 7])
>>> np.allclose(q, [28, -44, -14, 48])
True
"""
w1, x1, y1, z1 = q1
w2, x2, y2, z2 = q2
return np.array([-x1*x2 - y1*y2 - z1*z2 + w1*w2,
x1*w2 + y1*z2 - z1*y2 + w1*x2,
-x1*z2 + y1*w2 + z1*x2 + w1*y2,
x1*y2 - y1*x2 + z1*w2 + w1*z2], dtype=np.float64)
def norm(q):
"""
Compute quaternion norm
Parameters
----------
q : array_like
Input quaternion (4 element sequence)
Returns
-------
n : float
quaternion norm
Notes
-----
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
"""
return np.dot(q, q)
def random(rand=None):
"""
Generate an uniform random unit quaternion.
Parameters
----------
rand: array_like or None
Three independent random variables that are uniformly distributed
between 0 and 1.
Returns
-------
qrand: array_like
The random quaternion
Notes
-----
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> q = br.quaternion.random()
>>> np.allclose(1, np.linalg.norm(q))
True
"""
if rand is None:
rand = np.random.rand(3)
else:
assert len(rand) == 3
r1 = np.sqrt(1.0 - rand[0])
r2 = np.sqrt(rand[0])
pi2 = math.pi * 2.0
t1 = pi2 * rand[1]
t2 = pi2 * rand[2]
return np.array([np.cos(t2)*r2, np.sin(t1)*r1, np.cos(t1)*r1, np.sin(t2)*r2])
def to_axis_angle(quaternion, identity_thresh=None):
"""
Return axis-angle rotation from a quaternion
Parameters
----------
quaternion: array_like
Input quaternion (4 element sequence)
identity_thresh : None or scalar, optional
Threshold below which the norm of the vector part of the quaternion (x,
y, z) is deemed to be 0, leading to the identity rotation. None (the
default) leads to a threshold estimated based on the precision of the
input.
Returns
----------
axis: array_like
axis around which rotation occurs
angle: float
angle of rotation
Notes
-----
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
A quaternion for which x, y, z are all equal to 0, is an identity rotation.
In this case we return a `angle=0` and `axis=[1, 0, 0]``. This is an arbitrary
vector.
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> axis, angle = br.euler.to_axis_angle(0, 1.5, 0, 'szyx')
>>> np.allclose(axis, [0, 1, 0])
True
>>> angle
1.5
"""
w, x, y, z = quaternion
Nq = norm(quaternion)
if not np.isfinite(Nq):
return np.array([1.0, 0, 0]), float('nan')
if identity_thresh is None:
try:
identity_thresh = np.finfo(Nq.type).eps * 3
except (AttributeError, ValueError): # Not a numpy type or not float
identity_thresh = br._FLOAT_EPS * 3
if Nq < br._FLOAT_EPS ** 2: # Results unreliable after normalization
return np.array([1.0, 0, 0]), 0.0
if not np.isclose(Nq, 1): # Normalize if not normalized
s = math.sqrt(Nq)
w, x, y, z = w / s, x / s, y / s, z / s
len2 = x*x + y*y + z*z
if len2 < identity_thresh**2:
# if vec is nearly 0,0,0, this is an identity rotation
return np.array([1.0, 0, 0]), 0.0
# Make sure w is not slightly above 1 or below -1
theta = 2 * math.acos(max(min(w, 1), -1))
return np.array([x, y, z]) / math.sqrt(len2), theta
def to_euler(quaternion, axes='sxyz'):
"""
Return Euler angles from a quaternion using the specified axis sequence.
Parameters
----------
q : array_like
Input quaternion (4 element sequence)
axes: str, optional
Axis specification; one of 24 axis sequences as string or encoded tuple
Returns
-------
ai: float
First rotation angle (according to axes).
aj: float
Second rotation angle (according to axes).
ak: float
Third rotation angle (according to axes).
Notes
-----
Many Euler angle triplets can describe the same rotation matrix
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> ai, aj, ak = br.quaternion.to_euler([0.99810947, 0.06146124, 0, 0])
>>> np.allclose([ai, aj, ak], [0.123, 0, 0])
True
"""
return br.transform.to_euler(to_transform(quaternion), axes)
def to_transform(quaternion):
"""
Return homogeneous transformation from a quaternion.
Parameters
----------
quaternion: array_like
Input quaternion (4 element sequence)
axes: str, optional
Axis specification; one of 24 axis sequences as string or encoded tuple
Returns
-------
T: array_like
Homogeneous transformation (4x4)
Notes
-----
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> T0 = br.quaternion.to_transform([1, 0, 0, 0]) # Identity quaternion
>>> np.allclose(T0, np.eye(4))
True
>>> T1 = br.quaternion.to_transform([0, 1, 0, 0]) # 180 degree rot around X
>>> np.allclose(T1, np.diag([1, -1, -1, 1]))
True
"""
q = np.array(quaternion, dtype=np.float64, copy=True)
n = np.dot(q, q)
if n < br._EPS:
return np.identity(4)
q *= math.sqrt(2.0 / n)
q = np.outer(q, q)
return np.array([
[1.0-q[2, 2]-q[3, 3], q[1, 2]-q[3, 0], q[1, 3]+q[2, 0], 0.0],
[q[1, 2]+q[3, 0], 1.0-q[1, 1]-q[3, 3], q[2, 3]-q[1, 0], 0.0],
[q[1, 3]-q[2, 0], q[2, 3]+q[1, 0], 1.0-q[1, 1]-q[2, 2], 0.0],
[0.0, 0.0, 0.0, 1.0]])
|
88de967874612b3dfe900694e10ea950c70811f4 | makrandp/python-practice | /Other/Daily/LongestCommonWord.py | 2,565 | 4.1875 | 4 | '''
Given a list of strings, find the longest common word that occurs at least twice.
["Echo", "Alexa", "Kindle", "Echo Show", "Amazon"] -> "Echo"
["Echo Show", "Echo Show 8"] -> "Echo Show"
'''
from typing import List
class Trie:
def __init__(self, value):
self.value = value
self.children = {}
# Using count to track the number of occurences for this word.
self.count = 0
class Solution:
def longestCommonWord(self, words: List[str]) -> str:
# The idea is that we will insert all words into a trie, and before every space / end of the entire word we check if we have a maximal length such that our values are still greater than 1.
t = Trie('')
for word in words:
# Building our trie
currentTrie = t
for c in word:
if c not in currentTrie.children:
currentTrie.children[c] = Trie(c)
currentTrie.children[c].count += 1
currentTrie = currentTrie.children[c]
# Now we simply perform a DFS search.
o = list()
def dfs(t: Trie, o: list=list(), w: str='', d: int=0) -> None:
if len(t.children) == 0 and t.count > 1:
# We've reached the end of our search. This implies that we've hit the end of a word. Check if this word is bigger.
if len(o) == 0 or d > len(o[0]):
del o[:]
o.append(w)
return
elif d == len(o[0]):
o.append(w)
return
# Iterating over all children and searching deeper on all children that have a count greater than zero
for child in t.children.keys():
if t.children[child].count > 1:
newW = w + child
dfs(t.children[child], o, newW, d + 1)
# We've explored all our children, but we will also check if we are the terminating best value.
if ' ' in t.children and t.count > 1:
if len(o) == 0 or d > len(o[0]):
del o[:]
o.append(w)
elif d == len(o[0]):
o.append(w)
# Performing our DFS search.
dfs(t, o)
if len(o) != 1:
return 'None'
return o[0]
s = Solution()
print(s.longestCommonWord(['Echo','Alexa','Kindle','Echo Show','Amazon']))
print(s.longestCommonWord(["Echo Show", "Echo Show 8"]))
print(s.longestCommonWord(["Eat Show", "Fat Show 8"])) |
74d93c959eaebcf6bbc947a83603a7a1ed263a1e | ksledge/python | /tshirt.py | 234 | 3.75 | 4 | def make_tshirt( message , size = 'large'):
'''Input size of shirt and message to print'''
print("\nThis shirt is a " + size.title() + '.')
print("\n" + message.title())
make_tshirt(message= 'i love python!')
|
49c1393c904b43d632c54702c8d6390cac690cee | mekar4306/python_ST | /solutions/while-demo-2.py | 805 | 4.21875 | 4 | # Kullanıcıdan alacağınız sınırsız ürün bilgisini urunler listesi içinde saklayınız.
# ** ürün sayısını kullanıcıya sorun.
# ** dictionary listesi yapısı (urunAdi, fiyat) şeklinde olsun.
# ** ürün ekleme işlemi bittiğinde ürünleri ekranda while ile listeleyin.
i = 0
adet = int(input('kaç adet ürün eklemek istiyorsunuz: '))
urunler = []
while (i < adet):
urunAdi = input('ürün adı: ')
fiyat = input('ürün fiyatı: ')
urunler.append({
'urunAdi': urunAdi,
'fiyat': fiyat
})
i += 1
# for urun in urunler:
# print(f"ürün adı: {urun['urunAdi']} ürün fiyatı: {urun['fiyat']}")
a = 0
while (a < len(urunler)):
print(f"ürün adı: {urunler[a]['urunAdi']} ürün fiyatı: {urunler[a]['fiyat']}")
a += 1
|
3ca56a0fc9c4521c52cf66444be7b8c8c4cdfa1a | crawler-john/StudyNote | /3code/Python/cainiaoPython/7TimeDate/3Calendar.py | 2,067 | 3.609375 | 4 | #! /usr/bin/python
# -*- coding:UTF-8 -*-
'''
日历(Calendar)模块
此模块的函数都是日历相关的,例如打印某月的字符月历。
星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。模块包含了以下内置函数:
序号 函数及描述
1 calendar.calendar(year,w=2,l=1,c=6)
返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。 每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。
2 calendar.firstweekday( )
返回当前每周起始日期的设置。默认情况下,首次载入caendar模块时返回0,即星期一。
3 calendar.isleap(year)
是闰年返回True,否则为false。
4 calendar.leapdays(y1,y2)
返回在Y1,Y2两年之间的闰年总数。
5 calendar.month(year,month,w=2,l=1)
返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。
6 calendar.monthcalendar(year,month)
返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。
7 calendar.monthrange(year,month)
返回两个整数。第一个是该月的星期几的日期码,第二个是该月的日期码。日从0(星期一)到6(星期日);月从1到12。
8 calendar.prcal(year,w=2,l=1,c=6)
相当于 print calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1)
相当于 print calendar.calendar(year,w,l,c)。
10 calendar.setfirstweekday(weekday)
设置每周的起始日期码。0(星期一)到6(星期日)。
11 calendar.timegm(tupletime)
和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍(1970纪元后经过的浮点秒数)。
12 calendar.weekday(year,month,day)
返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。
''' |
1f90ef3a626f8d82745953665fb2cc26245fe6f1 | Ods25/Python_Cybersecurity_Course | /project1.py | 8,883 | 4.15625 | 4 | import sys
import math
import random
import threading
import time
from functools import reduce
#We will start with variables.
'''
Variables in programming are memory locations that hold a value.
Much like in mathematics, where 'X' is primarily the variable of choice, we can make 'X' equal anything.
'''
a = None #nonetype, has no type.
b = 3 #integer, a whole number with no decimal point.
c = 9.45 #float or double, a number with a decimal point.
d = 4
e = "Hello, world!" #string
f = 'f' #char
#In python, variables are 'weakly typed', meaning the programming langauge declares the variable's type upon value assignment.
#As a more long-term fact, In a 'strongly typed' language, in order to declare an integer you would go "int x = 5", declaring the datatype, the variable name, and then the value.
'''
A function is a command, in the form
name(argument1, argument2, argument3, argumentX, argumentY, argumentZ)
^ Parentheses| ^ Arguments seperated by commas ^close parentheses
^ Function name |
Functions are commands that go through a series of steps in order to attain a certain goal.
print() | Does not print a piece of paper, instead it displays text inside a terminal.
'''
def sumVargAndVarv(varg,varv):
return varg + varv
#We will go more in-depth in them later.
print( sumVargAndVarv(1,2) ) #Will print 3
print("Hello, world!") #prints "Hello, world!"
print(e) #Also prints "Hello, world!"
print("Hello, world!" + e) #prints "Hello, world!Hello, world!"
print("Hello, world!", e) #gives us a tuple of value ('hello world', 'hello world')
# The arithmetic operators +, -, *, /, %, **, //
# ** Exponential calculation
# // Floor Division
print("5 + 2 ="+ str(5+2)) #prints 7
print("5 - 2 ="+ str(5-2)) #prints 3
print("5 * 2 ="+ str(5*2)) #prints 10
print("5 / 2 ="+ str(5/2)) #2 goes into 5 only 2 times (4). Therefore, prints 2
print("5 % 2 ="+ str(5%2)) #Since 2 goes into 5 2 times, 2*2 = 4, the remainder is 1. This prints 1.
print("5 ** 2 ="+ str(5**2)) #5^2 = 25
print("10//3.0="+ str(10//3.0))# In math, 10/3 = 3.333333. By using floor division, 10//3 = 3, floor division rounds down to the lower integer.
print("-10//3.0=", str(-10//3.0))# This also means that since -4.0 < -3.33333333 < -3.0, -10//3.0 = -4.0
#if you want to extend a statement to multiple lines, you can use parenthesis, or \
v1 = (
1+2
+5
)
print(v1) #returns 8 as an int
print(
1+2
+5
)#Still returns 8 as an int
#This is nice and all, but what about the max integer or float we can practically return?
#Well, in python this is rather huge.
print(sys.maxsize) #Returns the max size for integer
print(sys.float_info.max) #Returns the max size for float
#HOWEVER, a float is only accurate up to 15 digits
f1 = 1.1111111111111111
f2 = 1.1111111111111111
f3 = f1+f2
print(1234567890123456)
print(f3)
#complex numbers are in the form [real part]+[imaginary part]
cn1 = 5+6j
#booleans are either True or False
bl = True
bl = False
#Strings are surrounded by ' or "
str1 = "Escape Sequences \' \t \" \\ and \n"
print(str1)
str2 = ''' Triple quoted strings can contain ' and " '''
print(str2)
# Math Functions, we'll just skim over this
print("abs(-1) ", abs(-1))
print("max(5, 4) ", max(5, 4))
print("min(5, 4) ", min(5, 4))
print("pow(2, 2) ", pow(2, 2))
print("ceil(4.5) ", math.ceil(4.5))
print("floor(4.5) ", math.floor(4.5))
print("round(4.5) ", round(4.5))
print("exp(1) ", math.exp(1)) # e**x
print("log(e) ", math.log(math.exp(1)))
print("log(100) ", math.log(100, 10)) # Base 10 Log
print("sqrt(100) ", math.sqrt(100))
print("sin(0) ", math.sin(0))
print("cos(0) ", math.cos(0))
print("tan(0) ", math.tan(0))
print("asin(0) ", math.asin(0))
print("acos(0) ", math.acos(0))
print("atan(0) ", math.atan(0))
print("sinh(0) ", math.sinh(0))
print("cosh(0) ", math.cosh(0))
print("tanh(0) ", math.tanh(0))
print("asinh(0) ", math.asinh(0))
print("acosh(pi) ", math.acosh(math.pi))
print("atanh(0) ", math.atanh(0))
print("hypot(0) ", math.hypot(10, 10)) # sqrt(x*x + y*y)
print("radians(0) ", math.radians(0))
print("degrees(pi) ", math.degrees(math.pi))
# You can cast to different types with int, float,
# str, chr
print("Cast ", type(int(5.4))) # to int
print("Cast 2 ", type(str(5.4))) # to string
print("Cast 3 ", type(chr(97))) # to string
print("Cast 4 ", type(ord('a'))) # to int
# ----- CONDITIONALS -----
# Comparison Operators : < > <= >= == !=
# if, else & elif execute different code depending
# on conditions
age = 30
if age > 21:
# Python uses indentation to define all the
# code that executes if the above is true
print("You can drive a tractor trailer")
elif age >= 16:
print("You can drive a car")
else:
print("You can't drive")
# Make more complex conditionals with logical operators
# Logical Operators : and or not
if age < 5:
print("Baby or Preschool")
elif (age >= 5) and (age <= 6):
print("Kindergarten")
elif (age > 6) and (age <= 17):
print("Grade %d", (age - 5))
else:
print("College")
# Ternary operator in Python
# condition_true if condition else condition_false
canVote = True if age >= 18 else False
print(canVote)
# Combine strings with +
print("Hello " + "You")
# Get string length
str3 = "Hello You"
print("Length ", len(str3))
# Character at index
print("1st ", str3[0])
# Last character
print("Last ", str3[len(str3)-1])
# 1st 3 chrs
print("1st 3 ", str3[0:3]) # Start, up to not including
# Get every other character
print("Every Other ", str3[0:-1:2]) # Last is a step
# You can't change an index value like this
# str3[0] = "a" because strings are immutable
# (Can't Change)
# You could do this
str3 = str3.replace("Hello", "Goodbye")
print(str3)
#----------LISTS------------
#A list is a sequence of data, whose placement is defined by a number.
#Said number is a placement, or index.
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
#Lists can be printed in their entirety
print(list1)
#Or specific elements can be printed. Elements start at 0 and end n-1, where n= the length of the list.
print("The length of list1 is = " +str(len(list1)))
print("list2[0]="+ str(list1[0]) + " list2[3]=" +str(list1[3]))
#-----------LOOPS-----------
# While : Execute while condition is True
# While : Execute while condition is True
w1 = 1
while w1 < 5:
print(w1)
w1 += 1
w2 = 0
while w2 <= 20:
if w2 % 2 == 0:
print(w2)
elif w2 == 9:
# Forces the loop to end all together
break
else:
# Shorthand for i = i + 1
w2 += 1
# Skips to the next iteration of the loop
continue
w2 += 1
# Cycle through list
l4 = [1, 3.14, "Element 2", True]
while len(l4):
print(l4.pop(0))
# For Loop
# Allows you to perform an action a set number of times
# Range performs the action 10 times 0 - 9
# end="" eliminates newline
for x in range(0, 10):
print(x, ' ', end="")
print('\n')
# Cycle through list
l4 = [1, 3.14, "Element 2", True]
for x in l4:
print(x)
# You can also define a list of numbers to
# cycle through
for x in [2, 4, 6]:
print(x)
# ----- TUPLES -----
# Tuples are just like lists except they are
# immutable
t1 = (1, 3.14, "tuple[2]", False)
# Get length
print("Length ", len(t1))
# Get value / values
print("1st", t1[0])
print("Last", t1[-1])
print("1st 2", t1[0:2])
print("Every Other ", t1[0:-1:2])
print("Reverse ", t1[::-1])
# Everything you can do with lists you can do with
# tuples as long as you don't change values
# ----- FUNCTIONS -----
# Functions provide code reuse, organization
# and much more
# Add 2 values using 1 as default
# You can define the data type using function
# annotations
def get_sum(num1: int = 1, num2: int = 1):
return num1 + num2
print(get_sum(5, 4))
# Accept multiple values
def get_sum2(*args):
sum = 0
for arg in args:
sum += arg
return sum
print(get_sum2(1, 2, 3, 4))
# Return multiple values
def next_2(num):
return num + 1, num + 2
i1, i2 = next_2(5)
print(i1, i2)
# A function that makes a function that
# multiplies by the given value
def mult_by(num):
# You can create anonymous (unnamed functions)
# with lambda
return lambda x: x * num
print("3 * 5 =", (mult_by(3)(5)))
# Pass a function to a function
def mult_list(list, func):
for x in list:
print(func(x))
mult_by_4 = mult_by(4)
mult_list(list(range(0, 5)), mult_by_4)
# Create list of functions
power_list = [lambda x: x ** 2,
lambda x: x ** 3,
lambda x: x ** 4]
'''
Sources: https://www.newthinktank.com/2019/08/learn-python-one-video/
w3schools
'''
|
6311e0ebf1ac60317126f0bd778bea7ae0ec0e3f | ocw11/my-machine-learning | /mnist/全连接神经网络架构和效果.py | 1,941 | 3.671875 | 4 | #全连接神经网络
from keras import models #models即使用网络的模型,分序列模型(The Sequential model)和函数式模型
from keras import layers
from keras.datasets import mnist
from keras.utils import to_categorical #就是将类别向量转换为二进制(只有0和1)的矩阵类型表示
#导入数据并进行预处理
(train_images,train_labels),(test_images,test_labels)=mnist.load_data()
train_images=train_images.reshape(60000,28*28) #修改图片尺寸
train_images=train_images.astype('float32')/255 #将颜色取值的范围缩小至0-1
test_images=test_images.reshape(10000,28*28)
test_images=test_images.astype('float32')/255
'''
将数字转换为(0,1)矩阵是为了和输出层输出的矩阵相匹配
例如标签为7,转换为[0,0,0,0,0,0,0,1,0,0] 这正是这个样本的期望输出值
'''
#print(test_labels[0])
train_labels=to_categorical(train_labels)
test_labels=to_categorical(test_labels)
#print(test_labels[0])
#神经网络搭建
network=models.Sequential() #序列模型
#这是一个两层的神经网络,均为全连接层,第一层神经元个数为512个,第二次神经元个数为10个
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))
#设置神经网络的优化器,损失函数(交叉熵),衡量指标(准确率)
network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])
#network.summary() #共计407050个参数
#拟合训练集,预测测试集
network.fit(train_images,train_labels,epochs=5,batch_size=128)
train_loss,train_acc=network.evaluate(train_images,train_labels)
test_loss,test_acc=network.evaluate(test_images,test_labels)
#输出测试集的训练效果
print("训练集误差:",train_loss)
print("训练集准确率:",train_acc)
print("测试集误差:",test_loss)
print("测试集准确率:",test_acc) |
f59c9d70d97d9e7fe0b4171f3d80f292255a26dd | achillesecos/Coding-Bat | /Python/List-2/centered_average.py | 140 | 3.5 | 4 | def centered_average(nums):
minV = min(nums)
maxV = max(nums)
avg = 0
count = 0
return (sum(nums) - minV - maxV) // (len(nums)-2)
|
6211d288b053de91526a34b2b6b7b4f17fd69c73 | Sranciato/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 244 | 3.921875 | 4 | #!/usr/bin/python3
""" function for returning min operations """
def minOperations(n):
""" returns min operations """
res = 0
for i in range(2, n):
while n % i == 0:
res += i
n = n / i
return res |
0076af8fbe07e8b738a89101362dfd1bc03e14b3 | djlad/qlearn | /tictactoe.py | 2,423 | 3.65625 | 4 | class tictactoe:
def __init__(self):
self.board = [[0,0,0],
[0,0,0],
[0,0,0]]
self.numActions = 18
self.turn = 0
def drawboard(self):
for row in self.board:
for col in row:
print(col, end="")
print('\t', end="")
print("\n", end="")
def validMove(self, row, column, player):
return self.board[row][column] == 0 and player == self.getTurn()
def updateTurn(self):
self.turn += 1
self.turn %= 2
def getTurn(self):
return self.turn + 1
def playMove(self, row, column, player=1):
if not self.validMove(row, column, player):
return False
if player == 1:
self.board[row][column] = player
self.updateTurn()
return True
elif player == 2:
self.board[row][column] = player
self.updateTurn()
return True
return False
def checkThree(self, row, col, down=0, right=0):
if down == 0 and right == 0:
print('error')
return False
length = 3
player = self.board[row][col]
if player == 0:
return player
while True:
row += down
col += right
if row < length and col < length:
if player == self.board[row][col]:
continue
else:
return 0
else:
return player
def detectWin(self):
win = False
for coli, col in enumerate(self.board[0]):
win = self.checkThree(0, coli, down=1)
if win > 0:
return win
for rowi, row in enumerate(self.board):
win = self.checkThree(rowi, 0, right=1)
if win > 0:
return win
win = self.checkThree(0, 0, 1, 1)
if win > 0:
return win
win = self.checkThree(2,0,-1,1)
if win > 0:
return win
return win
def hashState(self):
state = self.getTurn()
for row in self.board:
for piece in row:
state *= 10
state += piece
print(state)
return state
if __name__ == "__main__":
t = tictactoe()
t.drawboard()
|
c73527136ba752e3f72dd5ea591a5feaa0bc7594 | jmilhomem/movie_registration_challenge | /utils/databases.py | 12,656 | 4.03125 | 4 | import sys
import json
import sqlite3
import pandas as pd
import pprint
if __name__ == "__main__":
import file_operations
import database_connection
else:
from utils import file_operations
from utils.database_connection import DatabaseConnection
# commands to see the "Python interpreter location"
# import pprint
# pprint.pprint(sys.path)
"""
Concerned with storing and retrieving books from a list.
"""
class Movies:
def __init__(self) -> None:
# paths where the files live
self.path_filename = sys.path[0] + "/utils/files/"
self.path_db = sys.path[0] + "/utils/data.db"
def add_movie(self, store_type='db') -> bool:
"""
Function created to add new registers of movies into a json file or into the database
:param store_type: db (database) or f (file). By default it considers db (database).
:return: True of False
"""
self.add_another_movie = "yes"
while self.add_another_movie == "yes":
try:
# request each information of the new movies and store them on variables
movie_name = input("\nMovie Name: ")
director_name = input("Director Name: ")
movie_year = int(input("Year of the production: "))
name_main_actor_actress = input("Main actor / Actress: ")
# create a dictionary variable that will be used to store new movies
new_movie = {
"movie_name": movie_name
, "director_name": director_name
, "movie_year": movie_year
, "name_main_actor_actress": name_main_actor_actress
, "read": 0
}
if store_type == "f":
result_insert_file = self._write_movie_file(new_movie, "a")
else:
result_insert_file = self._add_movie_db(new_movie)
if result_insert_file:
# check if another movie will be inserted by user
self.add_another_movie = input("\nDo you want insert other movie (yes/no): ").lower()
if self.add_another_movie == "no":
return True
except ValueError as e_value:
print(f"\nDefinition of an object is not set properly.\nError description: {str(e_value)}")
return False
except Exception as e:
print(f"\nOccurred an error during this process.\nError description: {str(e)}")
return False
def delete_movie(self, movie_name, store_type="db") -> bool:
"""
Function created to delete registers of movies from a json file or from database
:param movie_name, store_type: movie_name desired to be deleted.
store_type: db (database) or f (file). By default it considers db (database).
:return: True of False
"""
if store_type.lower() == "f":
result_delete_file = self._delete_movie_file(movie_name)
else:
result_delete_file = self._delete_movie_db(movie_name)
return result_delete_file
def read_movie(self, movie_name, store_type="db") -> bool:
"""
Function created to read movies from a json file or from database
:param movie_name, store_type: movie_name desired to be deleted.
store_type: db (database) or f (file). By default it considers db (database).
:return: True of False
"""
if store_type.lower() == "f":
result_read_file = self._apply_read_movie_file(movie_name)
else:
result_read_file = self._apply_read_movie_db(movie_name)
return result_read_file
def list_movies(self, store_type="f"):
"""
Function created to delete registers of movies from a json file or from database
:param store_type: store_type: db (database) or f (file). By default it considers db (database).
:return: True of False
"""
if store_type.lower() == "f":
file = file_operations.read_file("Movie_Registration.json")
result_list = self._create_dataframe_list(file)
else:
with DatabaseConnection(self.path_db) as cursor:
cursor.execute("select * from tb_movies")
movies = cursor.fetchall()
# creates the same structure that the json file has and create the dataframe
list_movies = []
for row in movies:
row_dict = {}
row_dict["movie_name"] = row[0]
row_dict["director_name"] = row[1]
row_dict["movie_year"] = row[2]
row_dict["name_main_actor_actress"] = row[3]
row_dict["read"] = row[4]
list_movies.append(row_dict)
result_list = self._create_dataframe_list(list_movies)
return result_list
def _write_movie_file(self, content, type_operation, filename="Movie_Registration.json"):
"""
Private function created to write into a Movie's json file
:param content, type_operation, filename: Content is a dataset with Movie's data
type_operation is the type of operation: "a" (to add data) or other to overwrite.
filename by default considers "Movie_Registration.json".
:return: True of False
"""
file = file_operations.read_file(filename)
if type_operation.lower() == "a":
file.append(content)
else:
file = content
if file == []:
return False
else:
check_save_file = file_operations.save_to_file(file, filename, "o")
return check_save_file
def _delete_movie_file(self, movie_name, filename="Movie_Registration.json"):
"""
Private function created to write into a Movie's json file
:param movie_name, filename: movie_name desired to be deleted.
filename by default considers "Movie_Registration.json".
:return: True of False
"""
file = file_operations.read_file(filename)
movie_found = 0
for row in file:
if row["movie_name"].lower() == movie_name.lower():
file.remove(row)
movie_found = 1
if movie_found == 1:
result = self._write_movie_file(file, "o")
else:
result = False
return result
def _apply_read_movie_file(self, movie_name, filename="Movie_Registration.json") -> bool:
"""
Private function created to read from Movie's json file
:param movie_name, filename: movie_name desired to be deleted.
filename by default considers "Movie_Registration.json".
:return: True of False
"""
file = file_operations.read_file(filename)
row_position = 0
movie_found = 0
for row in file:
if row["movie_name"].lower() == movie_name.lower():
file[row_position]["read"] = 1
movie_found = 1
row_position += 1
if movie_found == 1:
result = self._write_movie_file(file, "r")
else:
result = False
return result
def _create_dataframe_list(self, content):
"""
Private Function created to create a dataframe using the movies set into a list
:param filename: filename by default considers "Movie_Registration.json".
:return: dataset
"""
if content == []:
return []
else:
# define the lists that will receive the lists of information
list_movies = []
list_director = []
list_year = []
list_main = []
list_read_books = []
try:
for row in content:
list_movies.append(row["movie_name"])
list_director.append(row["director_name"])
list_year.append(row["movie_year"])
list_main.append(row["name_main_actor_actress"])
list_read_books.append(row["read"])
# create the dictionary containing the filter aplied
dict_movies_filter = {
"movie_name": list_movies,
"director_name": list_director,
"year": list_year,
"main_actor": list_main,
"read": list_read_books
}
# create the dataframe with the dictionary values
df_movies = pd.DataFrame(dict_movies_filter)
# return the dataframe with the movies filtered
return df_movies
except json.JSONDecodeError as e_json:
print(f"\nYour settings file(s) contains invalid JSON syntax. {str(e_json)}")
return []
except ValueError as e_value:
print(f"\nDefinition of an object is not set properly. {str(e_value)}")
return []
except Exception as e:
print(f"\nOccurred an error during reading listing operation.\nError description: {str(e)}")
return []
def _add_movie_db(self, content) -> bool:
"""
Private function created to insert new movies into a Movie's table inside a database
:param content: dictionary with all movies' information.
:return: True of False
"""
movie_name = content["movie_name"].upper()
director_name = content["director_name"].upper()
year = content["movie_year"]
main_actor = content["name_main_actor_actress"].upper()
read = content["read"]
with DatabaseConnection(self.path_db) as cursor:
try:
cursor.execute("Create table if not exists tb_movies("
" movie_name varchar(100)"
", director_name varchar(100)"
", year int"
", main_actor varchar(100)"
", read boolean)")
cursor.execute("insert into tb_movies (movie_name, director_name, year, main_actor, read)"
"values (?, ?, ?, ?, ?)",
(movie_name, director_name, year, main_actor, read))
return True
except ValueError as e_value:
print(f"\nDefinition of an object is not set properly. {str(e_value)}")
return False
except Exception as e:
print(f"\nOccurred an error during the adding operation. Error description: {str(e)}")
return False
def _delete_movie_db(self, movie_name) -> bool:
"""
Private function created to delete movies into a Movie's table inside a database
:param content: movie_name.
:return: True of False
"""
with DatabaseConnection(self.path_db) as cursor:
cursor.execute("Create table if not exists tb_movies("
" movie_name varchar(100)"
", director_name varchar(100)"
", year int"
", main_actor varchar(100)"
", read boolean)")
cursor.execute("delete from tb_movies where upper(movie_name) = ?", (movie_name.upper(),))
return True
def _apply_read_movie_db(self, movie_name) -> bool:
"""
Private function created to update the movies to be read into a Movie's table inside a database
:param content: movie_name.
:return: True of False
"""
with DatabaseConnection(self.path_db) as cursor:
cursor.execute("Create table if not exists tb_movies("
" movie_name varchar(100)"
", director_name varchar(100)"
", year int"
", main_actor varchar(100)"
", read boolean)")
cursor.execute("update tb_movies"
" set read = 1"
" where upper(movie_name) = ?", (movie_name.upper(),))
return True
|
2bf2dc7495b8438036e7ce099d4eab487ea6afb1 | rafaeltorrese/slides_programming-lecture | /03_executing-programs/06_dynamic/exercise53.py | 546 | 3.609375 | 4 | import time
stored_results = {}
def sum_to_n(n):
start_time = time.perf_counter()
result = 0
for i in reversed(range(1, n + 1)):
if i in stored_results:
print(f"Stopping sum at {i} because we have previously computed it")
result += stored_results[i]
break
else:
result += i
stored_results[n] = result
print(time.perf_counter() - start_time, "seconds")
return result
if __name__ == '__main__':
print(sum_to_n(1_000_000))
print(sum_to_n(1_000_000))
|
257e0fbdbccd13116387b0b29065bf5810626ee5 | lflxp/leetcode | /ai/matplotlibed/figures.py | 292 | 3.765625 | 4 | # -*- coding: utf-8 -*
#!/usr/local/bin/python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.show() |
fd9ae0c58432bf87c881a865cf60b95000d56979 | ekant1999/HackerRank | /Python/Built-Ins/ginorts.py | 407 | 3.765625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
word = sorted(raw_input())
low = list(filter(str.islower, word))
upper = list(filter(str.isupper, word))
number = list(filter(str.isdigit, word))
odd = list(filter(lambda x : int(x)%2 == 1, number))
even = list(filter(lambda x : int(x)%2 == 0, number))
word = low + upper + odd + even
print reduce(lambda x,y: x+y, word) |
bb522d88b3b0c937d81b6e8e7f4312070fd4a273 | Seancheey/tensorflow-practice | /demo5_add_layer.py | 1,239 | 3.78125 | 4 | import tensorflow as tf
import numpy as np
### 训练多层神经网络的例子
# function that adds one layer of neuron
def add_layer(inputs, in_size, out_size, activation_function=lambda _: _):
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
Biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + Biases
return activation_function(Wx_plus_b)
# create a x-y relationship of y = x**2 - 0.5 with some noise
x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise
# add the first layer
layer1 = add_layer(x_data, 1, 10, activation_function=tf.nn.relu)
# add the second layer, with layer1 as input
prediction = add_layer(layer1, 10, 1)
# estimate loss
loss = tf.reduce_mean(tf.reduce_sum(tf.square(y_data - prediction), reduction_indices=[1]))
# train to minimize loss
train_step = tf.train.GradientDescentOptimizer(0.03).minimize(loss)
# start session
if __name__ == "__main__":
with tf.Session() as session:
session.run(tf.global_variables_initializer())
for i in range(1000):
session.run(train_step)
if i % 10 == 0:
print(session.run(loss))
|
76a587944f228f2f46ffb343808aeedee079f246 | uppuluriaditya/python_ds_a | /chapters/chapter6/simple_deque.py | 3,447 | 3.765625 | 4 | import sys
sys.path.append('../')
from utils import Empty
class ArrayDeque:
DEFAULT_CAPACITY = 10
def __init__(self):
self._data = [None] * self.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
""" Returns the number of elements """
return len(self._data)
def is_empty(self):
""" Returns True if empty"""
return len(self._data) == 0
def add_first(self, item):
""" Add element to the front of the deque """
self._front = (self._front - 1) % len(self._data)
self._data[self._front] = item
self._size += 1
def add_last(self, item):
""" Add element to the back of the deque """
if self._size == len(self._data):
self._resize(2 * len(self._data))
index = (self._front + self._size) % len(self._data)
self._data[index] = item
self._size += 1
def delete_first(self):
""" Removes and returns the element from the front of the deque
Raises Empty exception if the deque is empty
"""
if self.is_empty():
raise Empty("Deque is Empty")
front_val = self._data[self._front]
self._data[self._front] = None
self._front = (self._front + 1) % len(self._data)
self._size -= 1
# Reduce the size of the queue to half if 1/4 th of the list is free
if 0 < self._size < len(self._data) // 4:
self._resize(len(self._data) // 2)
return front_val
def delete_last(self):
""" Removes and returns the element from the back of the deque
Raises Empty exception id the deque is empty
"""
if self.is_empty():
raise Empty("Deque is empty")
back = (self._front - 1 + self._size) % len(self._data)
val = self._data[back]
self._data[back] = None
self._size -= 1
if 0 < self._size < len(self._data) // 4:
self._resize(len(self._data) // 2)
return val
def first(self):
""" Returns the first element of the deque.
Raises Empty exception if the deque is empty
"""
if self.is_empty():
raise Empty("deque is empty")
return self._data[self._front]
def last(self):
""" Returns the last element of the deque
Raises Empty exception if the deque is empty
"""
if self.is_empty():
raise Empty("deque is empty")
back = (self._front - 1 + self._size) % len(self._data)
return self._data[back]
def _resize(self, capacity):
""" Resizes the deque with the specified capacity """
old_data = self._data
self._data = [None] * capacity
front = self._front
for val in range(self._size):
self._data[val] = old_data[front]
front = (front + 1) % len(old_data)
self._front = 0
if __name__ == "__main__":
D = ArrayDeque()
for i in range(5):
D.add_last(i+1)
assert D.last() == 5
assert D.first() == 1
assert D.delete_first() == 1
assert D.delete_last() == 5
D.add_last(11)
assert D.last() == 11
assert D.first() == 2
D.add_first(12)
assert D.first() == 12
assert D.first() == 12
assert D.last() == 11
assert D.delete_first() == 12
assert D.delete_last() == 11
assert D.first() == 2 |
59c1ba1a7eaca1d052a194ea336f527e30d1225e | Braitiner/Exercicios-wiki.python | /EstruturaSequencial_Exercicio11.py | 703 | 4.34375 | 4 | # Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
# o produto do dobro do primeiro com metade do segundo .
# a soma do triplo do primeiro com o terceiro.
# o terceiro elevado ao cubo.
n1 = int(input('Informe um número inteiro: '))
n2 = int(input('Informe um número inteiro: '))
n3 = float(input('Informe um número real: '))
equac1 = (n1**2) + (n2/2)
equac2 = (n1*3)+n3
equac3 = n3**3
print('O produto do dobro do primeiro número com metade do segundo número ={equac1}'
'\nA soma do triplo do primeiro número com o terceiro número ={equac2}'
'\nO terceiro número elevado ao cubo ={equac3}.'.format(equac1=equac1,equac2=equac2,equac3=equac3))
|
63c5efa2123aceb48bc3d8f17801e1caa632d5a1 | bskari/park-stamper | /parks/scripts/initialize_db/fix_spelling.py | 5,292 | 3.78125 | 4 | #!/bin/python
"""Fixes some common spelling errors. Might I add that this is one of the
reasons why having a website is useful?
"""
import os
import sys
def levenshtein_ratio(s1, s2, cutoff=None):
max_len = max(len(s1), len(s2))
if cutoff is not None:
cutoff = int(math.ceil((1.0 - cutoff) * max_len) + .1)
return 1.0 - (
float(levenshtein(s1, s2, cutoff=cutoff))
/ max_len
)
def levenshtein(s1, s2, cutoff=None):
"""Compute the Levenshtein edit distance between two strings. If the
minimum distance will be greater than cutoff, then quit early and return
at least cutoff.
"""
if len(s1) < len(s2):
return levenshtein(s2, s1, cutoff)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
current_row_min = sys.maxint
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
min_all_three = min(
insertions,
deletions,
substitutions
)
current_row.append(min_all_three)
current_row_min = min(current_row_min, min_all_three)
if cutoff is not None and current_row_min > cutoff:
return current_row_min
previous_row = current_row
return previous_row[-1]
def fix_misspellings(test=None):
if test is None:
test = False
words = (
'Anniversary',
'Bonus',
'Cemetery',
'Heritage',
'Historic',
'Historical',
'Monument',
'Memorial',
'National',
'Park',
'Preserve',
'Recreation',
'Recreational',
'Scenic',
)
ok_words = (
'Hermitage',
'History',
'Presence',
'Reception',
'Reservation',
'Renovation',
'Parks',
'Part',
)
for word in words:
command = r"grep -i -P -o '\b[{first_letter}][a-z]{{{length_minus_one},{length_plus_one}}}\b' master_list.csv | sort -u".format(
first_letter=word[0],
length_minus_one=(len(word[1:]) - 1),
length_plus_one=(len(word[1:]) + 1),
)
if test:
print('Running {command}'.format(command=command))
maybe_misspellings = os.popen(command).readlines()
# Trim newlines
maybe_misspellings = [m[:-1] for m in maybe_misspellings]
# Ignore the correct spelling
for j in (word, word.lower(), word.upper()):
if j in maybe_misspellings:
maybe_misspellings.remove(j)
# Ignore ok words
for i in ok_words:
for j in (i, i.lower(), i.upper()):
if j in maybe_misspellings:
maybe_misspellings.remove(j)
# 'Recreationa' => 'Recreational', not 'Recreation'
removals = []
for mm in maybe_misspellings:
if word == 'Historic' or word == 'Recreation':
if 'a' in mm[-3:].lower() or 'l' in mm[-3:].lower():
removals.append(mm)
for r in removals:
maybe_misspellings.remove(r)
# Misspellings must have most of the letters from the word
misspellings = [mm for mm in maybe_misspellings if levenshtein_ratio(mm[1:].lower(), word[1:].lower()) >= .65]
for misspelling in misspellings:
if misspelling == misspelling.upper():
replacement = word.upper()
elif misspelling == misspelling.lower():
replacement = word.lower()
else:
replacement = word
if test:
print(
'{word} found {times} times'.format(
word=misspelling,
times=os.popen(
r"grep -c -P '\b{word}\b' list.csv".format(
word=misspelling,
)
).readlines()[0][:-1],
)
)
print(
'Replacing {word} with {replacement}'.format(
word=misspelling,
replacement=replacement,
)
)
else:
os.system(
r"sed -i -r 's/\b{misspelling}\b/{replacement}/g' list.csv".format(
misspelling=misspelling,
replacement=replacement,
)
)
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: {program} [--test|--run]'.format(program=sys.argv[0]))
sys.exit(1)
elif sys.argv[1] == '--test':
fix_misspellings(test=True)
elif sys.argv[1] == '--run':
fix_misspellings(test=False)
# Fix whte space too
os.system(r"sed -i -r 's/\s+$//' list.csv")
else:
print('Usage: {program} [--test|--run]'.format(program=sys.argv[0]))
sys.exit(1)
|
8d002273f95b08e2c7327a1e0c7859c80817f5a4 | magotheinnocent/Simple_Chatty_Bot | /Problems/Good rest on vacation/main.py | 250 | 3.765625 | 4 | # put your python code here
days = int(input())
food_cost_daily = int(input()) * days
flight_return = int(input()) * 2
hotel_cost_nightly = int(input()) * (days - 1)
total_cost = food_cost_daily + flight_return + hotel_cost_nightly
print(total_cost) |
ea752d4d2ddcd0bdf72c0148e0bab3ad2d55f3f1 | inhyebaik/ratings | /correlation.py | 1,882 | 3.71875 | 4 | """Pearson correlation."""
from math import sqrt
# from server import app
def pearson(pairs):
"""Return Pearson correlation for pairs.
Using a set of pairwise ratings, produces a Pearson similarity rating.
"""
series_1 = [float(pair[0]) for pair in pairs]
series_2 = [float(pair[1]) for pair in pairs]
sum_1 = sum(series_1)
sum_2 = sum(series_2)
squares_1 = sum([n * n for n in series_1])
squares_2 = sum([n * n for n in series_2])
product_sum = sum([n * m for n, m in pairs])
size = len(pairs)
numerator = product_sum - ((sum_1 * sum_2) / size)
denominator = sqrt(
(squares_1 - (sum_1 * sum_1) / size) *
(squares_2 - (sum_2 * sum_2) / size)
)
if denominator == 0:
return 0
return numerator / denominator
#def judgement(user_id, title):
# def judgement(user_id, title):
# m = Movie.query.filter_by(title=title).one()
# u = User.query.get(user_id)
# other_ratings = Rating.query.filter(Rating.movie_id == m.movie_id).all()
# other_users = [r.user for r in other_ratings]
# o = other_users[0]
# u_ratings = {}
# #for each rating in the user's ratings, add to dictionary the movie_id as
# #a key, and rating as the value
# for r in u.ratings:
# u_ratings[r.movie_id] = r
# paired_ratings = []
# # go through other user's ratings
# for o_rating in o.ratings:
# # see if the user (u) rated the movie. If they did, create tuple;
# # add to list
# u_rating = u_ratings.get(o_rating.movie_id)
# if u_rating is not None:
# pair = (u_rating.score, o_rating.score)
# paired_ratings.append(pair)
# return paired_ratings
# if __name__ == "__main__":
# connect_to_db(app)
# pairs = judgement(945, "Beauty and the Beast")
# corr = pearson(pairs)
# print corr |
c050dbe0e9b320d57b139249837a18867067e3b2 | baorie/dsa_goodrich | /chapter_2/creativity/c_2_27.py | 2,269 | 3.625 | 4 | # Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class Range:
"""A class that mimic's the built-in range class."""
def __init__(self, start, stop=None, step=1):
"""Initialize a Range instance.
Semantics is similar to built-in range class.
"""
if step == 0:
raise ValueError('step cannot be 0')
if stop is None: # special case of range(n)
start, stop = 0, start # should be treated as if range(0,n)
# calculate the effective length once
self._length = max(0, (stop - start + step - 1) // step)
# need knowledge of start and step (but not stop) to support __getitem__
self._start = start
self._step = step
self._stop = stop
def __len__(self):
"""Return number of entries in the range."""
return self._length
def __getitem__(self, k):
"""Return entry at index k (using standard interpretation if negative)."""
if k < 0:
k += len(self) # attempt to convert negative index
if not 0 <= k < self._length:
raise IndexError('index out of range')
return self._start + k * self._step
def __contains__(self, val):
""" Return if Range contains k """
# we should use _length, _start, and _step
# don't use an iterator, use math!
if val >= self._start and val < self._stop and (val - self._start) % self._step == 0:
return True
return False
if __name__ == "__main__":
r = Range(1, 11, 2)
test1 = 2 in r
test2 = 3 in r
print(test1, test2)
|
6dab016d2ff06acf32e1af9bc602cb89b5d04167 | candi955/Set_List_LinkedList_Practice | /LinkedListPractice.py | 804 | 4.125 | 4 | # A little look at linked lists: below is inserting a tail of a linked list from HackerRank
# reference: https://stackoverflow.com/questions/35559632/insert-a-node-at-the-tail-of-a-linked-list-python-hackerrank
# The code immediately below is a verbatim copy, so this disclaimer is being placed here in attempt to avoid
# copyright issues; the reference mentioned above is where the information came from.
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def Insert(head, data):
if (head == None):
head = Node(data)
else:
current = head
while (current.next != None):
current = current.next
current.next = Node(data)
return head
|
89ce2df4cb998d85d0f69a668489e09e49c17f7a | B-Rich/MATLAB | /PhysModMatlab02.py | 1,703 | 3.734375 | 4 | # Physical Modeling in MATLAB by Allen B. Downey
# Chapter 2: Scripts
# MATLAB script refactored into Python (via R)
from math import *
import myscript
# 2.1 M-files
myscript
#my script # comment out so script completes without (intentional) error
# 2.2 Why scripts?
# No code in section 2.2
# 2.3 The workspace
x = 5
y = 7
z = 9
# "who" in MATLAB or objects() in R
# http://www.gossamer-threads.com/lists/python/python/565579
print "Your variables are:"
print [var for var in dir() if not (var.startswith('_') or var == 'var')]
print ""
# http://grokbase.com/t/python/tutor/07adweedqr/variables-in-workspace
del y # "clear y" in MATLAB or rm(y) in R
print "Your variables are:"
print [var for var in dir() if not (var.startswith('_') or var == 'var')]
print ""
print ">> z = ", z # "disp(z)" in MATLAB
print ""
# 2.4 More errors
# "fibanocci1" from Exercise 2.1
#fibanocci1 # comment out so script completes without (intentional) error
n = 10
# http://stackoverflow.com/questions/5788891/execfile-with-argument-in-python-shell
import sys
sys.argv = ['fibanocci1.py','n']
execfile('fibanocci1.py')
# 2.5 Pre- and post-conditions
#help("fibanocci1.R") # comment out - 'help' is for commands or packages in R
#doc fibanocci1 # comment out - 'doc' is for internal fucntions in Python
# 2.6 Assignment and equality
y = 1
x = y + 1
print ">> x = ", x
print ""
#y + 1 = x % comment out so script completes without (intentional) error
y = 1
y = y + 1
print ">> y = ", y
print ""
# 2.7 Incremental development
# No code in section 2.7
# 2.8 Unit testing
print ">> asin(0) = ", asin(0.0)
print ""
print ">> asin(1) = ", asin(1.0)
print ""
print ">> asin(1) / pi = ", asin(1.0) / pi
print ""
|
d80ab87ecf35d9b3c7f45cffc204c8e028c8b11d | enextus/python_learnstuff | /input_decorator_rev.2.py | 716 | 4.03125 | 4 | # Eduard
# input
import math
# endlose Schleife
while True:
r = input ("Enter the radius of the circle : ")
try:
r = float(r)
break
except ValueError:
print("No.. the input string is not a number. It's a string")
# decorator Funktion
def my_decorator(func):
def wrapper():
if r < 0:
print('Falsche Eingabe!')
else:
print(func())
return wrapper
# decoration
@my_decorator
def input_func():
# input
while True:
try:
temperatur = input ("Gebe das Temperatur ein. (Float): ")
temperatur = float(temperatur)
break
except ValueError:
print("No.. the input string is not a number. It's a string")
return area
# start der Funktion
input_func() |
56bfc99a533bc876905b476e8d1aa1fd404b8582 | kowshik448/python-practice | /python codes/itertols.py | 142 | 3.53125 | 4 | from itertools import permutations
word,r=input().split()
for i in list(permutations(sorted(word),int(r))):
print(''.join(i))
|
ec9ecf80f5eb5cc1f9956a62ffa072281e453ff4 | colo6299/CS-2.1-Trees-Sorting | /Code/sorting_random_test.py | 1,920 | 3.5 | 4 | import sorting_iterative as SortIter
import sorting_recursive as SortRecur
import sorting_integer as SortInt
from unittest import TestCase
from random import randint
def _generate_testcase(length=10, rnge=None):
if rnge is None:
rnge = (0, length*10)
random_list = []
for _ in range(length):
random_list.append(randint(rnge[0], rnge[1]))
sorted_list = sorted(random_list)
return random_list, sorted_list
class RandomSortTest(TestCase):
def test_bubble_sort(self):
for _ in range(100):
random_and_sorted = _generate_testcase()
SortIter.bubble_sort(random_and_sorted[0])
assert random_and_sorted[0] == random_and_sorted[1]
def test_selection_sort(self):
for _ in range(100):
random_and_sorted = _generate_testcase()
SortIter.selection_sort(random_and_sorted[0])
assert random_and_sorted[0] == random_and_sorted[1]
def test_insertion_sort(self):
for _ in range(100):
random_and_sorted = _generate_testcase()
SortIter.insertion_sort(random_and_sorted[0])
assert random_and_sorted[0] == random_and_sorted[1]
def test_merge_sort(self):
for _ in range(100):
random_and_sorted = _generate_testcase()
SortRecur.merge_sort(random_and_sorted[0])
assert random_and_sorted[0] == random_and_sorted[1]
def test_counting_sort(self):
for _ in range(100):
random_and_sorted = _generate_testcase()
SortInt.counting_sort(random_and_sorted[0])
assert random_and_sorted[0] == random_and_sorted[1]
def test_bucket_sort(self):
for _ in range(100):
random_and_sorted = _generate_testcase()
SortInt.bucket_sort(random_and_sorted[0])
assert random_and_sorted[0] == random_and_sorted[1]
|
d37010214edcbee92bb6b09b6078e3750df27f62 | cindyanorris/cs5450-prog3 | /HTTPServer.py | 933 | 3.734375 | 4 | #!/usr/local/bin/python
import threading
import socket
#This is the simple starting TCP Server from the second programming assignment.
#You can start out with this code or you can start with your
#own code from that assignment.
#You'll need to make it threaded.
serverPort = 15080 #modify this port to your port number
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#These options should cause the port to become available
#soon after the server terminates
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind((socket.gethostname(), serverPort))
serverSocket.listen(1)
print("The server is ready to receive.")
while 1:
(connectionSocket, addr) = serverSocket.accept()
expression = connectionSocket.recv(1024)
#need to modify this code so that the connection is handled
#in a thread
connectionSocket.send("42".encode('utf-8'));
connectionSocket.close()
|
c19a22028cb110fb81cdb6284227c9142079a2e4 | liamfisher8/beginner-projects | /tip-calculator.py | 365 | 4.125 | 4 | print("Welcome to the tip calculator")
bill = input("What was the total bill? $")
percent = input("What percentage tip would you like to give 10, 12 or 15?")
people = input("How many people split the bill?")
no_tip = float(bill) / float(people)
with_tip = round(no_tip * (1+ (float(percent)/ 100)), 2)
print(f"Each person should pay: ${with_tip}")
|
e309eec615a394eaa8d64fbc408332f6679b3f9c | Bininin/python | /Урок2/2.3.1.py | 522 | 3.75 | 4 | a = int(input("Введите номер месяца: "))
d = {1: "Январь", 2: "Февраль", 12: "Декабрь", 3: "Март", 4: "Апрель", 5: "Май", 6: "Июнь", 7: "Июль", 8: "Август",
9: "Сентябрь", 10: "Октябрь", 11: "Ноябрь"}
l = ["Зима", "Зима", "Весна", "Весна", "Весна", "Лето", "Лето", "Лето", "Осень", "Осень", "Осень", "Зима"]
print("Месяц: ", d.get(a), "\nВремя года: ", l[a - 1])
|
cb3d5ff8066553129ed176a908c15dc2c63b6713 | Awesome-Kirill/edu | /codeWars/Stop_gninnipS.py | 272 | 3.53125 | 4 | #https://www.codewars.com/kata/5264d2b162488dc400000001
def spin_words(sentence):
test_list = []
for x in sentence.split(' '):
if len(x)>=5:
test_list.append(x[::-1])
else:
test_list.append(x)
return ' '.join(test_list)
|
ce124bee7036c4a466d5881f0b78f6985e909252 | Aasthaengg/IBMdataset | /Python_codes/p03854/s221859774.py | 526 | 3.84375 | 4 | def main(S):
while len(S) > 0:
if S[-1] == "m":
if S[-5:] == "dream":
S = S[:-5]
else:
print("NO")
return 0
elif S[-1] == "e":
if S[-5:] == "erase":
S = S[:-5]
else:
print("NO")
return 0
elif S[-1] == "r":
if S[-6:] == "eraser":
S = S[:-6]
elif S[-7:] == "dreamer":
S = S[:-7]
else:
print("NO")
return 0
else:
print("NO")
return 0
else:
print("YES")
main(input()) |
4c461b61a5b19250abad03e399c8933aececf20c | acirulis/SmartNinjaWebDev_02 | /python/funkcijas.py | 743 | 3.515625 | 4 | def paragrafs(text):
rezultats = '<span>{}</span>'.format(text)
return rezultats
zina = ['Pirmais paragrafs', 'Otrais paragrafs', 'Tresais paragrafs']
### PIRMAIS VARIANTS BEZ FUNKCIJAS
print('<H1>Virsraksts</H1>')
print('<p>{}</p>'.format(zina[0]))
print('<p>{}</p>'.format(zina[1]))
print('<p>{}</p>'.format(zina[2]))
print('<p>Nobeiguma teksts</p>')
### OTRAIS VARIANTS AR FUNKCIJU
print('<H1>ALTERNATIVA</H1>')
print(paragrafs(zina[0]))
print(paragrafs(zina[1]))
print(paragrafs(zina[2]))
print(paragrafs('Cits teksts nobeiguma'))
### CITA FUNKCIJA
def summa(a, b):
rezultats = (a + b) * 2
return rezultats
skaitlisA = 10
skaitlisB = 20
skaitlisC = summa(skaitlisA, skaitlisB)
print(skaitlisC)
print(summa(4, 5))
|
67b08bccced928570caccde8c7811308248948aa | snowmantw/pyarraywindow | /window.py | 3,405 | 3.859375 | 4 |
class IndexOverflow(Exception):
pass
class IndexUnderflow(Exception):
pass
class InvalidIndex(Exception):
pass
# Rules: Window and Index only accept integer as the init index,
# while methods of Window always return Index, not plain int.
class Index():
def __init__(self, window, index):
if index < window.minx:
raise IndexUnderflow("Index underflow: %d < %d" % (index, window.minx))
if index > window.maxx:
raise IndexOverflow("Index overflow: %d > %d" % (index, window.maxx))
self.index = index
self.window = window
def __sub__(self, offset):
if self.index - offset < self.window.minx:
raise IndexUnderflow("Index expression underflow: %d - %d < %d" % (index, offset, window.minx))
return Index(self.window, self.index - offset)
def __add__(self, offset):
# Well python support infinite long number but still get used to do this (from addition to substraction)
if self.index < self.window.maxx - offset:
raise IndexOverflow("Index expression underflow: %d + %d > %d" % (index, offset, window.maxx))
# And if we really need to check overflow, put it here
#
# So that this line don't need to check it again.
return Index(self.window, self.index + offset)
class Window():
def __init__(self, origin, min_index, max_index):
if len(origin) == 0:
raise InvalidIndex("Cannot make a window from zero-sized origin")
if min_index < 0:
raise IndexUnderflow("Min index < 0: %d" % min_index)
if max_index < 0:
raise IndexUnderflow("Max index < 0: %d" % max_index)
if max_index >= len(origin):
raise IndexOverflow("Max index out of range: %d > %d" % (max_index, len(origin)))
if max_index < min_index:
raise InvalidIndex("Max index < min index: %d < %d" % (max_index, min_index))
self.minx = min_index
self.maxx = max_index
self.lenx = max_index - min_index + 1
self.origin = origin
self.iterx = min_index
def __iter__(self):
return self
def __next__(self):
if (self.iterx == self.maxx+1):
raise StopIteration
result = self.origin[self.iterx]
self.iterx += 1
return result
def to_array(self):
return [ self.origin[i] for i in range(self.minx, self.maxx+1) ]
# For even number, it will be [pivot+1]
def pivot(self):
olen = len(self.origin)
if olen == 0:
return None
if olen == 1:
return Index(self, self.minx)
# index: 3,4,5,6,7 -> 3 + 5 // 2 = 3 + 2 = 5, pivot at index 5
# index: 3,4,5,6 -> 3 + 4 // 2 = 3 + 2 = 5, pivot at index 5
# index: 3,4 -> 3 + 2 // 2 = 3 + 1 = 4, pivot at index 4
return Index(self, self.minx + self.lenx // 2)
# return (minx -> [pivot - 1], [pivot] -> maxx)
def split(self, pindex=None):
if pindex == None:
# half-half
pindex = self.pivot()
if self.lenx == 0:
return None
if self.lenx == 1:
return (None, Window(self.origin, self.minx, self.maxx))
lpart = Window(self.origin, self.minx, (pindex - 1).index)
rpart = Window(self.origin, pindex.index, self.maxx)
return (lpart, rpart)
|
9e937171a482e02587fe284113478729f3e41baa | OldDreamHunter/Leetcode | /Math/ExcelSheetNumber.py | 633 | 3.796875 | 4 | """
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
"""
class solution(object):
def titleNumber(self,s):
if s == '': return 0
tn = 0
for i in range(len(s)):
tn += pow(26,len(s)-i-1) * (ord(s[i])-ord('A')+1)
return tn
def titleToNumber(self,s):
return sum([pow(26, len(s) - i - 1) * (ord(s[i]) - ord('A') + 1) for i in range(len(s))])
if __name__ == '__main__':
problem1 = solution()
print(problem1.titleNumber('AB'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.