blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
38b2eb41aff9813fd70eed0c6a12de2f097049fa | liuhatry/python_tools | /Search/blockSearch.py | 1,404 | 3.90625 | 4 | #!/usr/bin/env python
listIndex = [9,19,25,100,200,321]
mylist = [[],[],[],[],[],[],[]]
def findIndex(index,data):
min = 0
max = len(index) -1
while(min <= max):
mid = (max + min) // 2
if data > index[mid]:
min = mid + 1
else:
max = mid -1
return max + 1
def searchBlock(mylist,data):
for i in range(0,len(mylist)):
if data == mylist[i]:
return i
return -1
def insert(index,value):
item = findIndex(index,value)
if searchBlock(mylist[item],value) >= 0:
print value, 'is already exist in list',item
return False
else:
mylist[item].append(value)
return True
def search(index,value):
item = findIndex(index,value)
location = searchBlock(mylist[item],value)
if location >= 0:
print value,'is in block',item,'location:',location
else:
print 'can not find',value
if __name__=='__main__':
data = [0,2,3,201,1,3,4,14,14,23,34,56,78,90,100,198,340,324,67,890,0,-123,45,67,89,3,5,90,45,67]
for i in range(0,len(data)):
insert(listIndex,data[i])
print mylist[0]
print mylist[1]
print mylist[2]
print mylist[3]
print mylist[4]
print mylist[5]
print mylist[6]
search(listIndex, 0)
search(listIndex, 7)
search(listIndex, 56)
search(listIndex, 11)
search(listIndex, 324)
|
2acb0005b760b130fc4c553b8f9595c91b828c0e | tainagdcoleman/sharkid | /helpers.py | 2,892 | 4.125 | 4 | from typing import Tuple, List, Dict, TypeVar, Union
import scipy.ndimage
import numpy as np
import math
Num = TypeVar('Num', float, int)
Point = Tuple[Num, Num]
def angle(point: Point,
point0: Point,
point1: Point) -> float:
"""Calculates angles between three points
Args:
point: midpoint
point0: first endpoint
point1: second endpoint
Returns:
angle between three points in radians
"""
a = (point[0] - point0[0], point[1] - point0[1])
b = (point[0] - point1[0], point[1] - point1[1])
adotb = (a[0] * b[0] + a[1] * b[1])
return math.acos(adotb / (magnitude(a) * magnitude(b)))
def find_angles(points: List[Point])-> List[float]:
"""Finds angles between all points in sequence of points
Args:
points: sequential list of points
Returns:
angles in radians
"""
return angle(points[len(points) // 2], points[0], points[-1])
def magnitude(point: Point) -> float:
"""Finds the magnitude of a point, as if it were a vector originating at 0, 0
Args:
point: Point (x, y)
Returns:
magnitude of point
"""
return math.sqrt(point[0]**2 + point[1]**2)
def dist_to_line(start: Point, end: Point, *points: Point, signed=False) -> Union[float, List[float]]:
"""Finds the distance between points and a line given by two points
Args:
start: first point for line
end: second point for line
points: points to find distance of.
Returns:
A single distance if only one point is provided, otherwise a list of distances.
"""
start_x, start_y = start
end_x, end_y = end
dy = end_y - start_y
dx = end_x - start_x
m_dif = end_x*start_y - end_y*start_x
denom = math.sqrt(dy**2 + dx**2)
_dist = lambda point: (dy*point[0] - dx*point[1] + m_dif) / denom
dist = _dist if signed else lambda point: abs(_dist(point))
if len(points) == 1:
return dist(points[0])
else:
return list(map(dist, points))
def gaussian_filter(points:List[Point], sigma=0.3):
return scipy.ndimage.gaussian_filter(np.asarray(points), sigma)
def distance(point1: Point, point2: Point):
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def coord_transform(points: List[Tuple[int, int]])-> float:
start_x, start_y = points[0]
end_x, end_y = points[-1]
inner = points[1:-1]
perp_point_x = start_x - (end_y - start_y)
perp_point_y = start_y + (end_x - start_x)
ys = dist_to_line((start_x, start_y), (end_x, end_y), *inner, signed=True)
xs = dist_to_line((start_x, start_y), (perp_point_x, perp_point_y), *inner, signed=True)
return xs, ys
def remove_decreasing(xs, ys):
maxx = xs[0]
for x, y in zip(xs, ys):
if x > maxx:
yield x, y
maxx = x
|
20912df66b41ae5dd0ff66d24b09d713333cd187 | eglrp/point-cloud-clustering | /analysis/visualize_histograms_for_object_clouds.py | 1,778 | 3.640625 | 4 | import os
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
# This python file is used to plot a histogram of the number of points in object PCD files.
# This is useful to see the distribution of the number of points/PCD for different objects
# To run this file you have to download out_10_transformed folder from link below
# https://drive.google.com/drive/u/0/folders/1lnVNuEFTcJpKi0eY2Fex6Js69cw0nApt
# getting files from directory and reading from files
files = os.listdir('out_10_transformed')
os.chdir('out_10_transformed')
print(len(files))
object_dictionary = dict()
#Printing file name and size
for file in files:
print(file)
file_text = open(file, 'r').readlines() #opening file in read mode
for line in file_text:
# serching for "POINTS" in each line in PCD
if 'POINTS' in line:
print(line.strip().split(' ')[1])
# getting points size and giving to value
value = int(line.strip().split(' ')[1])
# getting the object name from file name and giving to key value
key = file.split('-')[0]
# Adding key and value to object dictionary
if key in object_dictionary:
object_dictionary[key].append(value)
else:
object_dictionary[key] = [value]
break
#printing each object with points in each Cloud file
print(object_dictionary)
#Plotting Histogram for objects
for object in object_dictionary.keys():
dataframe = pd.DataFrame(object_dictionary[object], columns=[object])
print(dataframe)
ax = dataframe.plot.hist(bins=100, legend=False, title=object)
plt.xlabel('Number of points')
plt.ylabel('Number of clouds')
plt.show()
fig = ax.get_figure()
|
7aaa877e60eff4a1000e505eefa770912e3bf0a8 | KartikJha/code-quiver | /python/comp-coding/flatten-binary-tree-linked-list.py | 935 | 3.796875 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
l = TreeNode(-1, None, None)
self.preOrderFlatten(root, l)
while (l.right != None):
print(l.val + " ")
l = l.right
root = l
def preOrderFlatten(self, t, l):
if (t != None):
l = TreeNode(t.val, None, None)
nl = l
if (t.left != None):
nl = self.preOrderFlatten(t.left, nl.right)
if (t.right != None):
nl = self.preOrderFlatten(t.right, nl.right)
return nl
s = Solution()
s.flatten(TreeNode(1, TreeNode(2, TreeNode(3, None, None), TreeNode(4, None, None)), TreeNode(5, TreeNode(9, None, None), None)))
|
30463e25c78ae51d99a5ddc06a58c1f7d17127ea | sharannyobasu/Hacker-Blocks | /gcd.py | 166 | 3.859375 | 4 | def gcd(a,b):
if(b>a):
if(b%a==0):
print(a)
else:
gcd(b-a,a)
else:
if(a%b==0):
print(b)
else:
gcd(a-b,b)
a=int(input())
b=int(input())
gcd(a,b)
|
3dca2e4f3597cf59d199e95e0b74536c828d26b4 | I-will-miss-you/CodePython | /Curso em Video/Exercicios/ex031.py | 560 | 4 | 4 | # Desenvolva um programa que pergunte a distância de uma viagem em Km.
# Calcule o preço da passagem, cobrando R$050 por Km para viagens
# de até 200km e R$0.45 para viagens mais longas.
distância = float(input('Qual é a distância da sua viagem? '))
print('Você está prestes a começar uma viagem de {}Km.')
'''if distância <= 200:
preço = distância * 0.50
else:
preço = distância * 0.45'''
#ou
preço = distância * 0.50 if distância <= 200 else distância * 0.45
print('E o preço da sua passagem será de R${:.2f}'.format(preço))
|
2858240db931d531fefc1e55824438f36ca22bad | LukasNickel/aoc | /07/solution.py | 2,272 | 3.703125 | 4 | from collections import defaultdict
def part1(puzzle, target='shiny gold bag'):
contains = containment_rules(puzzle)
result = set()
check = [target]
finished_searching = set()
while True:
try:
target = check.pop()
except IndexError:
break
if target in finished_searching:
continue
containing = find_containing(contains, target)
check += containing
finished_searching.update([target])
result.update(containing)
return len(result)
def part2(puzzle):
rules = containment_with_numbers(puzzle)
r = count_inner(rules, [1, "shiny gold bag"])
return r-1 # 1 for the start bag
def find_containing(rules, target):
result = []
for outer, inner in rules.items():
if target in inner:
# Whitespace messes search up
result.append(outer.strip())
return result
def containment_rules(puzzle):
contains = {}
for line in puzzle:
bag, content = line.split('contain')
contains[bag.replace('bags', 'bag')] = content.replace('bags', 'bag')
return contains
def containment_with_numbers(puzzle):
contains = defaultdict(list)
for line in puzzle:
bag, content = line.replace('no', '0').replace('.', '').split(
'contain'
)
for inner in content.split(','):
contains[bag.replace('bags', 'bag').strip()].append(
inner.replace('bags', 'bag').strip().split(" ", 1)
)
return contains
def count_inner(rules, target):
if target[0] == '0':
return 0
n, bag = target
n = int(n)
new_bags = rules[bag]
n_total = n
for inner_target in new_bags:
n_inside = count_inner(rules, inner_target)
n_total += n*int(n_inside)
return n_total
def main():
with open('example') as f:
example = f.readlines()
with open('example2') as f:
example2 = f.readlines()
with open('input') as f:
puzzle = f.readlines()
assert part1(example) == 4
print('Solution Part 1:', part1(puzzle))
assert part2(example) == 32
assert part2(example2) == 126
print('Solution Part 2:', part2(puzzle))
if __name__ == '__main__':
main()
|
6a2c08824866a7fcc4fefb60974a2051bf0913c4 | hubert-wojtowicz/learn-python-syntax | /module-2/16-for-loops.py | 114 | 3.796875 | 4 | for x in "Python":
print(x)
for x in ['a', 'b', 'c']:
print(x)
for x in range(1,5):
print(x) |
df0c0e1a0fe2c0a997ce32d3d4dd251ca4abbdcd | MrWifeRespecter/TECHNOLOGY | /U12-6/U12-6/U12_6.py | 570 | 3.640625 | 4 | from turtle import *
from random import *
from math import *
setworldcoordinates(-20, -20, 20, 20)
speed(0)
ht()
def draw(x,y):
pu()
setpos(x,0)
pd()
goto(0,y)
#Man gör bara förra uppgiften fast åt olika håll
#Första kvadrant
x=0
y=20
for i in range(21):
draw(x,y)
x+=1
y-=1
#Andra kvadrant
x=0
y=20
for i in range(21):
draw(x,y)
x-=1
y-=1
#Tredje kvadrant
x=0
y=-20
for i in range(21):
draw(x,y)
x-=1
y+=1
#Fjärde kvadrant
x=0
y=-20
for i in range(21):
draw(x,y)
x+=1
y+=1
exitonclick()
input() |
2e3663ca0bbdc7252f9bc7a4c453708a20be1cdb | gar19421/lab03 | /lab3_GUI_Serial.py | 3,072 | 3.59375 | 4 | #Codigo para comunicacion serial GUI lab03
#Brandon Garrido -19421
#Digital 2 seccion 20
#LIBRERÍAS
from tkinter import *
from tkinter.font import Font
from time import sleep
import serial
import time
import sys
import tkinter as tk
#CREAR PUERTO SERIAL PARA LA COMUNICACION USANDO PYTHON
puerto= serial.Serial()
#DEFINIR VELOCIDAD EN BAUDIOS
puerto.baudrate=9600
puerto.timeout=3#tiempo hasta recibir un caracterer de fin de linea
#DEFINIR PUERTO COM DEL FTDI232
puerto.port='COM3'
#ABRIR UNA CONEXION SERIAL
puerto.open()
print('PUERTO SERIAL LISTO PARA LA COMUNICAICON')
#Crear un objeto Tk()
vent=Tk()
#TITULO DE LA INTERFAZ
vent.title(" COMUNICACION SERIAL Y SPI ")
#DIMENSIONES DE LA INTERFAZ
vent.geometry('400x400')
def button1():#CUANDO SE PRESIONA EL BOTON DE CONECTAR
global vent
var1 = []
n=0
flag = False
flag1=False
while(flag == False):
var = puerto.read().decode('ascii')
if var == '\r':
flag = True
if (flag):
while(n<9):
var = puerto.read().decode('ascii')
var_temp = var
var1.append(var_temp)
n = n+1
flag = False
flag1 = True
#RENDERIZAR VALORES DE USART A INTERFAZ
label_pots1=tk.Label(vent, text=var1[0])
label_pots1.place(x=120, y=250)
label_pots2=tk.Label(vent, text=var1[1])
label_pots2.place(x=140, y=250)
label_pots3=tk.Label(vent, text=var1[2])
label_pots3.place(x=160, y=250)
label_pots4=tk.Label(vent, text=var1[3])
label_pots4.place(x=180, y=250)
label_pots5=tk.Label(vent, text=var1[4])
label_pots5.place(x=200, y=250)
label_pots6=tk.Label(vent, text=var1[5])
label_pots6.place(x=220, y=250)
label_pots7=tk.Label(vent, text=var1[6])
label_pots7.place(x=240, y=250)
label_pots7=tk.Label(vent, text=var1[7])
label_pots7.place(x=260, y=250)
label_pots7=tk.Label(vent, text=var1[8])
label_pots7.place(x=280, y=250)
def button3():#CUANDO SE PRESIONA EL BOTON DE ENVIAR DATOS A CONTADOR
global vent
mystring=tex.get(1.0,END)
b = mystring.encode('utf-8')
puerto.write(b)
tex.delete(1.0,END)
tex.insert(1.0,"")
#CREACIÓN DE BOTONES
l1=Button(vent,text= 'Conectar', command=button1 ,cursor='arrow')
l3=Button(vent,text='ENVIAR CONTADOR',command=button3,cursor='arrow')
#CREACION DE ETIQUETAS
lab1=Label(vent,text=' ',width=15,height=3)
lb2=Label(vent,text=' GUI LAB 3',width=38,height=4)
#CREACION DE TEXTO
pot1= tk.Label(vent, text="POT1:")
pot1.place(x=150, y=230)
pot2 = tk.Label(vent, text="POT2:")
pot2.place(x=240, y=230)
tex= Text(vent,width=20,height=2)
#ESTABLECER POSICIONES DE LOS BOTONES EN LA INTERFAZ GRAFICA
l1.place(x=180,y=200)
l3.place(x=150,y=300)
#ESTABLECER POSICIONES DE LAS ETQIUETAS Y TEXTOS EN LA INTERFAZ GRAFICA
lab1.place(x=150,y=100)
lb2.place(x=48,y=40)
tex.place(x=125,y=140)
vent.mainloop()
#CERRAR EL PUERTO SERIAL
puerto.close()
print('PUERTO BLOQUEADO')
sys.exit(0) |
055444edb77a8cf4e79c6e1a57f7c9d4d00ba699 | Javacream/org.javacream.training.python | /org.javacream.training.python/src/3-Einfache Anwendungen/types_control_loop.py | 351 | 3.96875 | 4 | even_message = "an even number: "
odd_message = "an odd number: "
numbers = range(1, 10)
finished = False
for i in numbers:
print ("processing number " , i, ", finished: ", finished)
if i % 2 == 0:
print (even_message, i)
else:
print (odd_message, i)
finished = True
print ("all numbers processed, finished: ", finished)
|
4637c58e87c1e1be51f96bf19ccbfe586be4201a | AbdurrahimBalta/ProjectEuler-AlgorithmQuestion-in-Python | /Question2.py | 936 | 3.65625 | 4 | #Soru 2
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms
Ilk_Fibon_Deger: int = 1
Ortanca_Fibon_Deger: int = 1
Son_Fibon_Deger : int = 0
i : int = 0
# 4 milyondan küçük tüm çift fibon değerler
while (Ilk_Fibon_Deger <4000000 and Ortanca_Fibon_Deger < 4000000):
Son_Fibon_Deger = Ilk_Fibon_Deger + Ortanca_Fibon_Deger
Ortanca_Fibon_Deger = Son_Fibon_Deger
Ilk_Fibon_Deger = Ortanca_Fibon_Deger + Ilk_Fibon_Deger
if Ilk_Fibon_Deger % 2 == 0 and Ortanca_Fibon_Deger % 2 == 0:
i += Ilk_Fibon_Deger
elif Ilk_Fibon_Deger % 2 == 0:
i += Ilk_Fibon_Deger
elif Ortanca_Fibon_Deger % 2 == 0:
i += Ortanca_Fibon_Deger
print(i)
|
68cebde8659110abe925da3d6ab5189095dd9a1e | FelipeSenco/PokemonMaster | /pokemon.py | 8,755 | 3.765625 | 4 |
class Pokemon:
def __init__(self, name, level, type):
self.name = name
self.level = level
types = ["normal", "fighting", "flying", "electric"]
if (type.lower() in types):
self.type = type.lower()
else:
print("Warning: invalid type! This will cause errors!")
self.max_health = level * 10
self.current_health = self.max_health
self.is_knocked_out = False
#string representation method for print():
def __repr__(self):
return (f'{self.name} is level {self.level} and it is of {self.type} type. It has {self.max_health} health points')
#lose_health method
def lose_health(self, damage):
#first check if the pokemon is already knocked_out:
if (self.is_knocked_out == True):
print(f'{self.name} is already knocked out and cannot be damaged.')
#now we update the health and call knock out in case the health points reachs 0:
else:
self.current_health -= damage
if (self.current_health <= 0):
self.knock_out()
print(f'{self.name} took {damage} points of damage and was knocked out')
else:
print(f'{self.name} took {damage} points of damage! He has {self.current_health} points of health now.')
#gain_health method
def gain_health(self, health):
#first check if the pokemon is knocked out:
if (self.is_knocked_out == True):
print(f'{self.name} is knocked out and cannot be healed.')
#update the health points and make sure it cannot be higher than max health:
else:
self.current_health += health
if (self.current_health > self.max_health):
self.current_health = self.max_health
print(f'{self.name} was healed for {health} points of health! He has {self.current_health} points of health now.')
#knock_out method
def knock_out(self):
self.is_knocked_out = True
#revive method
def revive(self):
if (self.is_knocked_out == True):
self.is_knocked_out = False
self.current_health = self.level * 5
print(f'{self.name} was revived with {self.current_health} points of health!')
else:
print(f'{self.name} is not knocked out, therefore revive does not work...')
#attack method
def attack(self, opponent):
damage = self.level * 2
#check if the attacking pokemon is not knocked out:
if (self.is_knocked_out == False):
#checking the types to define if it will be super effective or not very effective:
#normal will do the regular damage to all other types:
if (self.type == "normal"):
print(f'{self.name} used Headbutt!')
opponent.lose_health(damage)
#fighting pokemons will do double damage to electric and reduced damage to flying pokemons:
elif(self.type == "fighting"):
print(f'{self.name} used Mega Punch!')
if (opponent.type == "electric"):
print("It is super effective!")
opponent.lose_health(damage * 2)
elif(opponent.type == "flying"):
print("It is not very effective!")
opponent.lose_health(damage * 1/2)
else:
opponent.lose_health(damage)
#flying pokemons will do double damage to fighting and regular damage to the other types:
elif(self.type == "flying"):
print(f'{self.name} used Sky Attack!')
if (opponent.type == "fighting"):
print("It is super effective!")
opponent.lose_health(damage * 2)
else:
opponent.lose_health(damage)
#electric pokemons will do double damage to flying pokemons and regular to the other types:
elif(self.type == "electric"):
print(f'{self.name} used Thunderbolt!')
if (opponent.type == "flying"):
print("It is super effective!")
opponent.lose_health(damage * 2)
else:
opponent.lose_health(damage)
else:
print(f'{self.name} is knocked out and cannot attack!')
class Trainer:
#Trainer initializer:
def __init__(self, name, pokemons, potions, revives, currently_active):
self.name = name
if (len(pokemons) > 6 or len(pokemons) < 1):
print("Warning! You can't have more than six or less than 1 pokemons, this will cause errors!")
else:
self.pokemons = pokemons
self.potions = potions
self.revives = revives
self.currently_active = currently_active
#Trainer string represantion for print():
def __repr__(self):
return f'{self.name} has {len(self.pokemons)} pokemons and {self.potions} potions. He is currently using {self.pokemons[self.currently_active - 1].name}.'
#use_potion method:
def use_potion(self):
print(f'{self.name} tries to use potion...')
active_pokemon = self.pokemons[self.currently_active - 1]
#check if there are potions avaiable and than update the health and number of potions left:
if (self.potions < 1):
print(f'{self.name} is out of potions, no way to heal {active_pokemon.name}')
else:
active_pokemon.gain_health(30)
self.potions -= 1
print(f'{self.name} have {self.potions} left...')
#revive method:
def revive(self, chosen):
print(f'{self.name} tries to use revive...')
#define the pokemon to use revive:
pokemon_chosen = self.pokemons[chosen - 1]
#check if there are revives avaiable and than update the health and number of revives left:
if (self.revives < 1):
print(f'{self.name} is out of revives, no way to revive {pokemon_chosen.name}')
else:
pokemon_chosen.revive()
self.revives -= 1
print(f'{self.name} have {self.revives} revives left...')
#attack method:
def attack(self, opponent):
active_pokemon = self.pokemons[self.currently_active - 1]
print(f'{self.name} commands {active_pokemon.name} to attack:')
opponent_active_pokemon = opponent.pokemons[opponent.currently_active - 1]
#after defining the current pokemons, call the pokemon attack method using the opponent pokemon as argument:
active_pokemon.attack(opponent_active_pokemon)
#switch_pokemon method:
def switch_pokemon(self, pokemon_chosen):
#pokemon chosen will be the number of the pokemon in the rolster
#example ["pikachu", "machop", "farfet"] pikachu is the 1, machop is 2, farfet is 3
if (pokemon_chosen > (len(self.pokemons) + 1) or pokemon_chosen < 1):
print("Invalid Pokemon choice!")
else:
print(f'{self.name} retreats {self.pokemons[self.currently_active - 1].name}...')
if (self.pokemons[pokemon_chosen - 1].is_knocked_out == False):
self.currently_active = pokemon_chosen
pokemon_to_switch = self.pokemons[self.currently_active - 1]
print(f'{self.name} chooses {pokemon_to_switch.name} to battle!')
else:
print(f'{self.pokemons[pokemon_chosen - 1].name} is knocked out, try again using another choice of pokemon!')
#blue rolster:
pikachu = Pokemon("Pikachu", 20, "electric")
cleffairy = Pokemon("Cleffairy", 11, "normal")
pidgeot = Pokemon("Pidgeot", 36, "flying")
hitmonchan = Pokemon("Hitmonchan", 22, "fighting")
#red_rolster
electabuzz = Pokemon("Electabuzz", 25, "electric")
primeape = Pokemon("Primeape", 40, "fighting")
fearow = Pokemon("Fearow", 34, "flying")
jigglypuff = Pokemon("Jigglypuff", 16, "normal")
blue_rolster = [pikachu, cleffairy, pidgeot, hitmonchan]
red_rolster = [electabuzz, primeape, fearow, jigglypuff]
#create trainers
blue = Trainer("Blue", blue_rolster, 4, 2, 3)
red = Trainer("Red", red_rolster, 3, 2, 2)
#testing the classes in action!
print(blue)
print("")
print(red)
print("")
red.switch_pokemon(4)
print("")
blue.attack(red)
print("")
blue.attack(red)
print("")
blue.attack(red)
print("")
red.attack(blue)
print("")
red.switch_pokemon(1)
print("")
red.switch_pokemon(4)
print("")
red.revive(4)
print("")
red.switch_pokemon(4)
print("")
print("")
|
462b0a6faa51e5a389bdd47b81d7879a303dc8b1 | damyac/working-days | /workingdays.py | 2,471 | 3.578125 | 4 | #Author: Da'Mya Campbell (damycamp@cisco.com)
#File: workingdays.py
#Date: May 2018 (c) Cisco Systems
#Description: Calculates the number of working days between two dates, excluding weekends and holidays.
import time
from dateutil import rrule
from datetime import datetime
from datetime import date
def workingdays(startdate, enddate):
# Business days (working days) between the start date and end date
days = list(rrule.rrule(rrule.DAILY, byweekday = range(0,5), dtstart = startdate, until = enddate))
# List of company holidays, Memorial Day, Independence Day, Labor Day, Thanksgiving, Company Shutdown, MLK Birthday
holidays = list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 5, byweekday = rrule.MO(-1))) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 7, bymonthday = 4)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 9, byweekday = rrule.MO(1))) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 11, byweekday = rrule.TH(4))) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 11, byweekday = rrule.FR(4))) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 12, bymonthday = 25)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 12, bymonthday = 26)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 12, bymonthday = 27)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 12, bymonthday = 28)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 12, bymonthday = 29)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 12, bymonthday = 30)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 12, bymonthday = 31)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 1, bymonthday = 1)) +\
list(rrule.rrule(rrule.YEARLY, dtstart = startdate, until = enddate, bymonth = 1, byweekday = rrule.MO(3)))
# Total number of working days
totaldays = len(set(days) - set(holidays))
return totaldays
#Example input
unit_test = 1
if unit_test :
startdate = date(2018, 1, 1)
enddate = date(2019, 1, 2)
r = workingdays(startdate, enddate)
print('The number of workingdays is', r) |
f3d150018213352f079d38699361ec144302b336 | Sceluswe/pyNutrition | /myJson.py | 893 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Save jsonObj to json file.
"""
import json
def loadJSON(filename):
"""
Load a JSON file.
Return JSON object.
"""
returnObj = None
# Try to create the file, if it exists just move on.
try:
with open(filename, "x") as JSONfile:
json.dump({}, JSONfile, indent=4)
except FileExistsError:
pass
# Load the JSON file.
with open(filename, "r") as JSONfile:
returnObj = json.load(JSONfile)
return returnObj
def saveJSON(filename, JSONobject):
"""
Take a sequence and save it as JSON.
"""
# Try to create the file, if it exists just move on.
try:
open(filename, "x")
except FileExistsError:
pass
# Save the sequence to the file.
with open(filename, "w") as JSONfile:
json.dump(JSONobject, JSONfile, indent=4)
|
605e5fea818e882f1ee11c8962ce5db5e9a591af | iamserda/cuny-ttp-algo-summer2021 | /AdrianBarros/assignments/fastSlow/lc202/lc202.py | 2,631 | 4.15625 | 4 | # Problem Statement #
# Any number will be called a happy number if, after repeatedly replacing it with a number equal to the sum of the square of all of its digits, leads us to number 1. All other (not-happy) numbers will never reach 1. Instead, they will be stuck in a cycle of numbers which does not include 1.
'''
Using the slow , fast pointer approach we are going to start looking at two numbers
after that we are going to take the sum of the squre of each digit
we are going to be using a helper funcion for that
Conditional
IF both of their digit sums are the same we found a cycle
'''
def find_happy_number(num):
# TODO: Write your code here
slow = fast = num
while True: # will run unti we find a cycle
slow = square_sum(slow)
fast = square_sum(square_sum(fast))
# IF both of their digit sums are the same we found a cycle
if slow == fast:
break
return slow == 1
def square_sum(num):
sq_sum = 0
while num > 0:
dig = num % 10 # until the number is 0 well take each digit and add it to the sum
sq_sum += dig * dig # they need to be squared
num /= 10
return sq_sum
def main():
print(find_happy_number(23))
print(find_happy_number(12))
main()
# Solution
# -----
# def find_happy_number(num):
# slow, fast = num, num
# while True:
# slow = find_square_sum(slow) # move one step
# fast = find_square_sum(find_square_sum(fast)) # move two steps
# if slow == fast: # found the cycle
# break
# return slow == 1 # see if the cycle is stuck on the number 1
# def find_square_sum(num):
# _sum = 0
# while (num > 0):
# digit = num % 10
# _sum += digit * digit
# num //= 10
# return _sum
# -----
# Time Complexity #
# The time complexity of the algorithm is difficult to determine. However we know the fact that all unhappy numbers eventually get stuck in the cycle: 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4
# This sequence behavior tells us two things:
# 1. If the number N is less than or equal to 1000, then we reach the cycle or 1 in at most 1001 steps.
# 2. For N > 1000, suppose the number has M digits and the next number is N1. From the above Wikipedia link, we know that the sum of the squares of the digits of N is at most 9^2M, or 81M (this will happen when all digits of N are 9).
# This means:
# 1. N1 < 81M
# 2. As we know M = log(N+1)
# 3. Therefore: N1 < 81 * log(N+1) => N1 = O(logN)
# This concludes that the above algorithm will have a time complexity of O(logN).
# Space Complexity #
# The algorithm runs in constant space O(1).
|
6134445a05970921338e0027413584a4905eebc4 | sitxseek/AdventOfCode2019 | /day1/puzzle.py | 324 | 3.515625 | 4 | def parse(lines):
return list(map(int, lines))
def solvePartOne(data):
sum = 0
for n in data:
sum += (n // 3 - 2)
return sum
def solvePartTwo(data):
sum = 0
for n in data:
while True:
n = (n // 3 - 2)
if n > 0: sum += n
else: break
return sum |
676b23fefba2422c3d7fef3abda3cd74336b2e49 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/eyrros001/question2.py | 594 | 3.984375 | 4 | """ recursive function to count the number of pairs of repeated characters in a string
Ross Eyre
05/05/2014"""
def main():
msg = input("Enter a message:\n")
n = pairs(msg)
print("Number of pairs:", n)
# count pairs of characters
def pairs(string):
if(len(string)==0): #if string contains nothing, we are done
return 0
elif(string[0:1]==string[1:2]): #if char equals char next to it, return 1 and move on, cutting off both characters to prevent overlap
return 1 + pairs(string[2::])
else: #
return pairs(string[1::])
main() |
e91f3dfee2b0eb94123d11b7c8dd0f9775055d8c | alemarlo1992/accounting_summary- | /accounting.py | 1,524 | 4.4375 | 4 |
# To Do
# Read through accounting.py and understand what it’s doing.
# Create a function that takes in a text file of customer orders and parses it to produce similar output.
# Add comments explaining what your code is doing.
# Read over the solution and see how it compairs to your answer.
def underpaid_melons(path):
#Create a fucntion that takes the file as an argument
melon_cost = 1.00
#represent the price of the melon
file = open(path)
#set variable to open the file
for line in file:
# create a for loop to iterate through each line
line = line.rstrip()
#delete any empty spaces
line = line.split('|')
#Create a list so we can access desired info through indices
customer_name = line[1]
customer_melons = float(line[2])
customer_paid = float(line[3])
#access the index that we want for our statement
#add float to eliminate the string
customer_expected = customer_melons * melon_cost
#create equation for the amount of money that is expected from each customer
print("{} paid ${},expected ${}".format(customer_name, customer_paid, customer_expected))
#print that number
if customer_expected < customer_paid:
print("{} has underpaid".format(customer_name))
elif customer_expected > customer_paid:
print("{} has overpaid".format(customer_name))
#create an if and elif to know who underpaid or overpaid for melons
file.close()
#close file
underpaid_melons('customer-orders.txt')
#call fucntion so that our fuction is able to run |
564518af54b7bfe9c0d90fe887df4fa918fa4e0d | sherms77/Calculator-app | /Calculator.py | 1,887 | 4.03125 | 4 | import math
print('This is a calculator app. \nIt lets you do basic arithmitic operations.')
menChoice = ''
def mainMenu():
global menChoice
menChoice = input('\nEnter the type of operation you want to do by entering the number next to one of the four options below or enter q to quit: \n1.Add \n2.Subtract \n3.Multiply \n4.Divide \n')
print('')
if menChoice == '1':
Add()
elif menChoice == '2':
Sub()
elif menChoice == '3':
Mult()
elif menChoice == '4':
Div()
elif menChoice == 'q':
quit()
def Add():
num1=()
num2=()
print('You have selected 1.Addition')
if menChoice == '1':
num1 = input('\n1.Enter the first number:')
num2 = input('2.Enter the second number:')
addResult = int(num1) + int(num2)
print('\nThe result is', addResult)
def Sub():
num1=()
num2=()
print('You have selected 2.Subtraction')
if menChoice == '2':
num1 = input('\n1.Enter the first number:')
num2 = input('2.Enter the second number:')
addResult = int(num1) - int(num2)
print('\nThe result is', addResult)
def Mult():
num1=()
num2=()
print('You have selecred 3.Multiplication.')
if menChoice == '3':
num1 = input('\n1.Enter the fist number:')
num2 = input('2.Enter the second number:')
addResult = int(num1) * int(num2)
print('\nThe result is:', addResult)
def Div():
num1=()
num2=()
print('You have selecred 4.Division.')
if menChoice == '4':
num1 = input('\n1.Enter the first number:')
num2 = input('2.Enter the second number:')
addResult = float(num1) / float(num2)
print('\nThe result is:', addResult)
while menChoice != 'q':
menChoice = mainMenu()
|
0a3ae986420c3d891e3c7c09aba183ee8b76ef3f | daniel-reich/ubiquitous-fiesta | /JBTLDxvdzpjyJA4Nv_3.py | 197 | 3.65625 | 4 |
def super_reduced_string(s):
stack=[]
for x in s:
if stack==[] or stack[-1]!=x:
stack.append(x)
else:
stack.pop()
return ''.join(stack) if stack!=[] else 'Empty String'
|
d302dcd5b705246a9e1ce966e9af1066484737da | IgorNikolin/python | /Задачи по функциям 2.py | 623 | 3.96875 | 4 | i = int(input("1) Круг 2)прямоугольник 3)треугольник"))
if i==1:
A = int(input("введите значение Радиуса"))
B = 3.14
s = ((A*B)**2)
print(round(s, 2));
elif i==2:
A = int(input("Введите значение высоты"))
B = int(input("Введите значение ширины"))
s = (A*B)
print(s)
elif i==3:
A = int(input("Введите значение основания"))
B = int(input("Введите значение высоты"))
s=(A*B)/2
print(s)
else:
print("error999999999999")
|
45ac246159a1cc4d8212be4bab16e8c4259b2ee2 | msbuddhu/PythonBasics | /q135.py | 115 | 3.671875 | 4 | def add(x, y):
return x + y
result = add(10, 20)
print("The sum is", result)
print("The sum is", add(100, 200)) |
377c6b4c8fb04e5bf0148992eaf8fa10be37e939 | Nostromo-04/python | /lesson02/Zadanie2_4.py | 557 | 4 | 4 | # Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
my_str = input('Введите строку из нескольких слов: ')
split_str = my_str.split()
for i in range(0, len(split_str)):
print(i + 1, split_str[i][:10]) |
ae2440c591c9aedd06971ddf6507c86543856008 | Pythones/MITx_6.00.1x | /ProblemSet6/borra.py | 181 | 3.5625 | 4 |
list = ['6.00.1x', 'is', 'pretty', 'fun']
ListLen = len(list)
wordLenInList = []
for i in range (ListLen):
wordLenInList.append (len(list[i]))
print ListLen
print wordLenInList |
f91af59a5266d355adc790d03b98a93230eac0ed | ShinCheung/LeetCode | /66.加一.py | 708 | 3.703125 | 4 | # 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一
# 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字
# 你可以假设除了整数 0 之外,这个整数不会以零开头
# 示例 1:
# 输入: [1,2,3]
# 输出: [1,2,4]
# 解释: 输入数组表示数字 123
# 示例 2:
# 输入: [4,3,2,1]
# 输出: [4,3,2,2]
# 解释: 输入数组表示数字 4321
# 注意,9+1=10,会进位
class Solution:
def plusOne(self, digits):
num_int = 0
for num in digits:
num_int = num_int * 10 + num
num_int += 1
return [int(i) for i in str(num_int)]
print(Solution().plusOne([4,3,2,9]))
|
9cbbd97635854b3532a20e3410a9fddd874b9538 | MDGSF/JustCoding | /python-leetcode/it_08.06.py | 480 | 3.625 | 4 | from typing import List
class Solution:
def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
"""
Do not return anything, modify C in-place instead.
"""
def dfs(n, A, B, C):
if n == 0:
return
if n == 1:
C.append(A.pop())
return
dfs(n - 1, A, C, B)
C.append(A.pop())
dfs(n - 1, B, A, C)
dfs(len(A), A, B, C)
A = [2, 1, 0]
B = []
C = []
s = Solution()
s.hanota(A, B, C)
print(A, B, C)
|
1654c8235aa45abf509d82f418234e366cb5f1e2 | duongyen24/python-master | /tik tak toe.py | 474 | 3.6875 | 4 | board = ["-","-","-",
"-","-","-",
"-","-","-",]
def display_board():
print(board[0],board[1],board[2])
print(board[3],board[4],board[5])
print(board[5],board[6],board[7])
display_board()
def play_game():
display_board()
handle_turn()
def handle_turn():
position= input("choose from 1 to 9")
#board
#display board
#play
#handle return
#check win
#check row
#check columns
#check diagonals
#check tie
#flip player
|
5350fb6bb4df26529187d8b83bead510f9954938 | juanmbraga/CS50-2021-Seminars | /Taste of Python/11.scores.py | 294 | 3.921875 | 4 | def main():
score1 = int(input("Score 1: "))
score2 = int(input("Score 2: "))
score3 = int(input("Score 3: "))
printScore(score1)
printScore(score2)
printScore(score3)
def printScore(n):
for i in range(n):
print("#", end="")
print()
main() |
75f9f740ab41b9ddafaa229f4b5e4b4963983148 | MasumTech/URI-Online-Judge-Solution-in-Python | /URI-1074.py | 357 | 3.875 | 4 | n = int(input())
for i in range(n):
a = int(input())
if a == int(0):
print('NULL')
elif a%int(2)!=int(0):
if a<int(0):
print('ODD NEGATIVE')
else:
print('ODD POSITIVE')
elif a%int(2)==int(0):
if a<int(0):
print('EVEN NEGATIVE')
else:
print('EVEN POSITIVE')
|
03636fdb1ea03d3e264dafb4ef30cf7cef476876 | Baha/tuenti-challenge-4 | /challenge-1/challenge-1.py | 1,694 | 3.609375 | 4 | #! /usr/bin/env python
import sys
class Student:
name = ""
gender = ""
age = 0
studies = ""
academic_year = 0
def __init__(self, line):
fields = [x for x in line.split(',')]
if len(fields) > 4 :
self.name = fields[0]
self.gender = fields[1]
self.age = int(fields[2])
self.studies = fields[3]
self.academic_year = int(fields[4])
else:
self.gender = fields[0]
self.age = int(fields[1])
self.studies = fields[2]
self.academic_year = int(fields[3])
def __eq__(self, other):
if self.gender == other.gender and \
self.age == other.age and \
self.studies == other.studies and \
self.academic_year == other.academic_year:
return True
return False
class StudentManager:
student_list = []
def addStudent(self, student):
self.student_list.append(student)
def loadStudents(self, filename):
student_file = open(filename, 'r')
student_lines = student_file.readlines()
for line in student_lines:
self.addStudent(Student(line))
student_file.close()
def getMatches(self, student):
matches_list = []
for st in self.student_list:
if st == student:
matches_list.append(st)
matches_list = sorted([x.name for x in matches_list])
return matches_list
manager = StudentManager()
manager.loadStudents("students")
num_cases = int(sys.stdin.readline())
for i in range(num_cases):
line = sys.stdin.readline()
new_student = Student(line)
matches = manager.getMatches(new_student)
case_string = "Case #{0}: ".format(i + 1)
if len(matches) > 0 :
print case_string + ",".join(matches)
else:
print case_string + "NONE"
|
9708a128e871da39e7eabecec0e1ab59fe098a69 | DenisZun/flunet_python | /chapter_01/mulit_vecttor.py | 1,757 | 3.921875 | 4 | # -*- coding:utf-8 -*-
# 二维数组表示向量
"""
len(x) 的速度会非
常快。背后的原因是 CPython 会直接从一个 C 结构体里读取对象的长度,完全不会调用任
何方法。获取一个集合中元素的数量是一个很常见的操作,在 str、list、memoryview
等类型上,这个操作必须高效。
"""
from math import hypot
class Vector(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
"""
这就是“字符串表示形式”。repr 就是通过 __repr__ 这个特殊方法来得到一个对象的字
如果没有实现 __repr__,当我们在控制台里打印一个向量的实例时,
得到的字符串可能会是 <Vector object at 0x10e100070>。
__repr__ 和 __str__ 的区别在于,后者是在 str() 函数被使用,或是在用 print 函数
打印一个对象的时候才被调用的,并且它返回的字符串对终端用户更友好。
__repr__前者方便我们调试和记录日志,
__str__后者则是给终端用户看的。
这就是数据模型中存在特殊方法 __repr__ 和 __str__ 的原因。
"""
return 'Vector(%r, %r)' % (self.x, self.y)
def __abs__(self):
return hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
if __name__ == '__main__':
# v1 = Vector(2, 4)
# v2 = Vector(2, 1)
#
# print(v1 + v2)
v = Vector(3, 4)
print(abs(v))
print(v * 3)
print(abs(v * 3))
|
ac7dcbab0f3a540ec01bf762ca80eb12ceb1bddc | tenten0113/python_practice | /5/str7_1.py | 240 | 3.53125 | 4 | msg = 'にわにはにわにわとりがいる'
print(msg.replace('にわ', 'ニワ')) # 結果:ニワにはニワニワとりがいる
print(msg.replace('にわ', 'ニワ', 2)) # 結果:ニワにはニワにわとりがいる
|
ea0e631ee3d6b1b9491bf780462673946804efd0 | ConlinLee/homework-python-github | /prime.py | 369 | 3.578125 | 4 | #!-_-coding;utf-8 !-_-
from time import clock
def SuShu(num):
ss=[2]
for x in range(3,num,2):
for y in ss:
if x % y == 0:
break
elif y > int(num**0.5):
ss.append(x)
else:
ss.append(x)
return ss
c = clock()
print(SuShu(1000000))
print(len(SuShu(1000000)))
print(clock() -c) |
ed6e26cc6741238d5eb044a15d9d72a46cec78ae | RoslinErla/AllAssignments | /assignments/functions/prime_number.py | 954 | 4.4375 | 4 | # A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
# Write a function named is_prime that takes an integer argument and returns True if the number is prime and False otherwise. (Assume that the argument is an integer greater than 1, i.e. no need to check for erroneous input.)
# Also write code that calls the function and prints out a message saying that the given number is a prime or not.
# Example input/output:
# Input an integer greater than 1: 7
# 7 is a prime
# Input an integer greater than 1: 6
# 6 is not a prime
def is_prime(number):
prime=True
count=2
while count < number:
if number%count == 0:
prime = False
count +=1
if prime==True:
result= "is a prime"
else:
result= "is not a prime"
return result
num = int(input("Input an integer greater than 1: "))
is_it_prime = is_prime(num)
print(num,is_it_prime)
|
3b553ac4247327297074a8075d52c8f6e2f0a108 | Yuvaraj421/object_oriented_programs | /stack.py | 1,189 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def isEmpty(self):
# this block check the linked list
if self.top == None:
return True
else:
return False
def push(self, data):
# this block add the element into stack
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
# this block pop the element one by one
if self.top is None:
return "Stack empty"
element = self.top
self.top = self.top.next
return element.data
def size(self):
# this block check the size of the linked list
temp = self.top
count = 0
while temp != None:
count += 1
temp = temp.next
return count
def print(self):
# this block print the element
if self.top is None:
print("Stack is empty!!!")
return
current = self.top
while current != None:
print(current.data)
current = current.next
|
b4e7995de611dad194e05521710f98abaed8a7ed | rssbrrw/PythonProgrammingPuzzles | /generators/trivial_inverse.py | 20,862 | 4.25 | 4 | """Trivial problems. Typically for any function, you can construct a trivial example.
For instance, for the len function you can ask for a string of len(s)==100 etc.
"""
from puzzle_generator import PuzzleGenerator
from typing import List
# See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles
class HelloWorld(PuzzleGenerator):
"""Trivial example, no solutions provided"""
@staticmethod
def sat(s: str):
"""Find a string that when concatenated onto 'world' gives 'Hello world'."""
return s + 'world' == 'Hello world'
class BackWorlds(PuzzleGenerator):
"""We provide two solutions"""
@staticmethod
def sat(s: str):
"""Find a string that when reversed and concatenated onto 'world' gives 'Hello world'."""
return s[::-1] + 'world' == 'Hello world'
@staticmethod
def sol():
return ' olleH'
@staticmethod
def sol2(): # solution methods must begin with 'sol'
return 'Hello '[::-1]
class StrAdd(PuzzleGenerator):
@staticmethod
def sat(st: str, a='world', b='Hello world'):
"""Solve simple string addition problem."""
return st + a == b
@staticmethod
def sol(a, b):
return b[:len(b) - len(a)]
def gen_random(self):
b = self.random.pseudo_word()
a = b[self.random.randrange(len(b) + 1):]
self.add({"a": a, "b": b})
class StrSetLen(PuzzleGenerator):
@staticmethod
def sat(s: str, dups=2021):
"""Find a string with dups duplicate chars"""
return len(set(s)) == len(s) - dups
@staticmethod
def sol(dups):
return "a" * (dups + 1)
def gen(self, target_num_instances):
for dups in range(target_num_instances):
if len(self.instances) == target_num_instances:
return
self.add(dict(dups=dups))
class StrMul(PuzzleGenerator):
@staticmethod
def sat(s: str, target='foofoofoofoo', n=2):
"""Find a string which when repeated n times gives target"""
return s * n == target
@staticmethod
def sol(target, n):
if n == 0:
return ''
return target[:len(target) // n]
def gen_random(self):
s = self.random.pseudo_word() * self.random.randint(1, 3)
n = self.random.randrange(10)
target = s * n
self.add(dict(target=target, n=n))
class StrMul2(PuzzleGenerator):
@staticmethod
def sat(n: int, target='foofoofoofoo', s='foofoo'):
"""Find n such that s repeated n times gives target"""
return s * n == target
@staticmethod
def sol(target, s):
if len(s) == 0:
return 1
return len(target) // len(s)
def gen_random(self):
s = self.random.pseudo_word() * self.random.randint(1, 3)
n = self.random.randrange(10)
target = s * n
self.add(dict(target=target, s=s))
class StrLen(PuzzleGenerator):
@staticmethod
def sat(s: str, n=1000):
"""Find a string of length n"""
return len(s) == n
@staticmethod
def sol(n):
return 'a' * n
def gen_random(self):
n = self.random.randrange(self.random.choice([10, 100, 1000, 10000]))
self.add(dict(n=n))
class StrAt(PuzzleGenerator):
@staticmethod
def sat(i: int, s="cat", target="a"):
"""Find the index of target in string s"""
return s[i] == target
@staticmethod
def sol(s, target):
return s.index(target)
def gen_random(self):
s = self.random.pseudo_word() * self.random.randint(1, 3)
target = self.random.choice(s)
self.add(dict(s=s, target=target))
class StrNegAt(PuzzleGenerator):
@staticmethod
def sat(i: int, s="cat", target="a"):
"""Find the index of target in s using a negative index."""
return s[i] == target and i < 0
@staticmethod
def sol(s, target):
return - (len(s) - s.index(target))
def gen_random(self):
s = self.random.pseudo_word() * self.random.randint(1, 3)
target = self.random.choice(s)
self.add(dict(s=s, target=target))
class StrSlice(PuzzleGenerator):
@staticmethod
def sat(inds: List[int], s="hello world", target="do"):
"""Find the three slice indices that give the specific target in string s"""
i, j, k = inds
return s[i:j:k] == target
@staticmethod
def sol(s, target):
from itertools import product
for i, j, k in product(range(-len(s) - 1, len(s) + 1), repeat=3):
try:
if s[i:j:k] == target:
return [i, j, k]
except (IndexError, ValueError):
pass
def gen_random(self):
s = self.random.pseudo_word() * self.random.randint(1, 3)
i, j, k = [self.random.randrange(-len(s) - 1, len(s) + 1) for _ in range(3)]
try:
target = s[i:j:k]
self.add(dict(s=s, target=target))
except (IndexError, ValueError):
pass
class StrIndex(PuzzleGenerator):
@staticmethod
def sat(s: str, big_str="foobar", index=2):
"""Find a string whose *first* index in big_str is index"""
return big_str.index(s) == index
@staticmethod
def sol(big_str, index):
return big_str[index:]
def gen_random(self):
big_str = self.random.pseudo_word(max_len=50)
i = self.random.randrange(len(big_str))
index = big_str.index(big_str[i:])
self.add(dict(big_str=big_str, index=index))
class StrIndex2(PuzzleGenerator):
@staticmethod
def sat(big_str: str, sub_str="foobar", index=2):
"""Find a string whose *first* index of sub_str is index"""
return big_str.index(sub_str) == index
@staticmethod
def sol(sub_str, index):
i = ord('A')
while chr(i) in sub_str:
i += 1
return chr(i) * index + sub_str
def gen_random(self):
sub_str = self.random.pseudo_word(max_len=50)
index = self.random.randrange(1000)
self.add(dict(sub_str=sub_str, index=index))
class StrIn(PuzzleGenerator):
@staticmethod
def sat(s: str, a="hello", b="yellow", length=4):
"""Find a string of length length that is in both strings a and b"""
return len(s) == length and s in a and s in b
@staticmethod
def sol(a, b, length):
for i in range(len(a) - length + 1):
if a[i:i + length] in b:
return a[i:i + length]
def gen_random(self):
sub_str = self.random.pseudo_word()
a = self.random.pseudo_word() + sub_str + self.random.pseudo_word()
b = self.random.pseudo_word() + sub_str + self.random.pseudo_word()
length = len(sub_str)
self.add(dict(a=a, b=b, length=length))
class StrIn2(PuzzleGenerator):
@staticmethod
def sat(substrings: List[str], s="hello", count=15):
"""Find a list of >= count distinct strings that are all contained in s"""
return len(substrings) == len(set(substrings)) >= count and all(sub in s for sub in substrings)
@staticmethod
def sol(s, count):
return [""] + sorted({s[j:i] for i in range(len(s) + 1) for j in range(i)})
def gen_random(self):
s = self.random.pseudo_word(max_len=50)
count = len(self.sol(s, None))
self.add(dict(s=s, count=count))
class StrCount(PuzzleGenerator):
@staticmethod
def sat(string: str, substring="a", count=10, length=100):
"""Find a string with a certain number of copies of a given substring and of a given length"""
return string.count(substring) == count and len(string) == length
@staticmethod
def sol(substring, count, length):
c = chr(1 + max(ord(c) for c in (substring or "a"))) # a character not in substring
return substring * count + (length - len(substring) * count) * '^'
def gen_random(self):
substring = self.random.pseudo_word(max_len=self.random.randrange(1, 11))
count = self.random.randrange(100)
length = len(substring) * count + self.random.randrange(1000)
self.add(dict(substring=substring, count=count, length=length))
class StrSplit(PuzzleGenerator):
@staticmethod
def sat(x: str, parts=["I", "love", "dumplings", "!"], length=100):
"""Find a string of a given length with a certain split"""
return len(x) == length and x.split() == parts
@staticmethod
def sol(parts, length):
joined = " ".join(parts)
return joined + " " * (length - len(joined))
def gen_random(self):
parts = [self.random.pseudo_word() for _ in range(self.random.randrange(1, 6))]
length = len(" ".join(parts)) + self.random.randrange(100)
self.add(dict(parts=parts, length=length))
class StrSplitter(PuzzleGenerator):
@staticmethod
def sat(x: str, parts=["I", "love", "dumplings", "!", ""], string="I_love_dumplings_!_"):
"""Find a separator that when used to split a given string gives a certain result"""
return string.split(x) == parts
@staticmethod
def sol(parts, string):
if len(parts) <= 1:
return string * 2
length = (len(string) - len("".join(parts))) // (len(parts) - 1)
start = len(parts[0])
return string[start:start + length]
def gen_random(self):
x = self.random.pseudo_word()
parts = [self.random.pseudo_word(min_len=0) for _ in range(1, self.random.randrange(6))]
parts = [p for p in parts if x not in p]
if not any(parts):
return
string = x.join(parts)
self.add(dict(parts=parts, string=string))
class StrJoiner(PuzzleGenerator):
@staticmethod
def sat(x: str, parts=["I!!", "!love", "dumplings", "!", ""], string="I!!!!!love!!dumplings!!!!!"):
"""
Find a separator that when used to join a given string gives a certain result.
This is related to the previous problem but there are some edge cases that differ.
"""
return x.join(parts) == string
@staticmethod
def sol(parts, string):
if len(parts) <= 1:
return ""
length = (len(string) - len("".join(parts))) // (len(parts) - 1)
start = len(parts[0])
return string[start:start + length]
def gen_random(self):
x = self.random.pseudo_word()
parts = [self.random.pseudo_word(min_len=0) for _ in range(1, self.random.randrange(6))]
string = x.join(parts)
self.add(dict(parts=parts, string=string))
class StrParts(PuzzleGenerator):
@staticmethod
def sat(parts: List[str], sep="!!", string="I!!!!!love!!dumplings!!!!!"):
"""Find parts that when joined give a specific string."""
return sep.join(parts) == string and all(sep not in p for p in parts)
@staticmethod
def sol(sep, string):
return string.split(sep)
def gen_random(self):
sep = self.random.pseudo_word()
parts = [self.random.pseudo_word(min_len=0) for _ in range(1, self.random.randrange(6))]
parts = [p for p in parts if sep not in p]
string = sep.join(parts)
self.add(dict(sep=sep, string=string))
########################################
# List problems
########################################
class ListSetLen(PuzzleGenerator):
@staticmethod
def sat(li: List[int], dups=42155):
"""Find a list with a certain number of duplicate items"""
return len(set(li)) == len(li) - dups
@staticmethod
def sol(dups):
return [1] * (dups + 1)
def gen_random(self):
self.add(dict(dups=self.random.randrange(10 ** 5)))
class ListMul(PuzzleGenerator):
@staticmethod
def sat(li: List[int], target=[17, 9, -1, 17, 9, -1], n=2):
"""Find a list that when multiplied n times gives the target list"""
return li * n == target
@staticmethod
def sol(target, n):
if n == 0:
return []
return target[:len(target) // n]
def gen_random(self):
li = [self.random.randrange(-10 ** 5, 10 ** 5) for _ in
range(self.random.randrange(1, 10))] * self.random.randint(1, 3)
n = self.random.randrange(10)
target = li * n
self.add(dict(target=target, n=n))
class ListLen(PuzzleGenerator):
@staticmethod
def sat(li: List[int], n=85012):
"""Find a list of a given length n"""
return len(li) == n
@staticmethod
def sol(n):
return [1] * n
def gen_random(self):
n = self.random.randrange(self.random.choice([10, 100, 1000, 10000]))
self.add(dict(n=n))
class ListAt(PuzzleGenerator):
@staticmethod
def sat(i: int, li=[17, 31, 91, 18, 42, 1, 9], target=18):
"""Find the index of an item in a list. Any such index is fine."""
return li[i] == target
@staticmethod
def sol(li, target):
return li.index(target)
def gen_random(self):
li = [self.random.randrange(-10 ** 2, 10 ** 2) for _ in range(self.random.randrange(1, 20))]
target = self.random.choice(li)
self.add(dict(li=li, target=target))
class ListNegAt(PuzzleGenerator):
@staticmethod
def sat(i: int, li=[17, 31, 91, 18, 42, 1, 9], target=91):
"""Find the index of an item in a list using negative indexing."""
return li[i] == target and i < 0
@staticmethod
def sol(li, target):
return li.index(target) - len(li)
def gen_random(self):
li = [self.random.randrange(-10 ** 2, 10 ** 2) for _ in range(self.random.randrange(1, 20))]
target = self.random.choice(li)
self.add(dict(li=li, target=target))
class ListSlice(PuzzleGenerator):
@staticmethod
def sat(inds: List[int], li=[42, 18, 21, 103, -2, 11], target=[-2, 21, 42]):
"""Find three slice indices to achieve a given list slice"""
i, j, k = inds
return li[i:j:k] == target
@staticmethod
def sol(li, target):
from itertools import product
for i, j, k in product(range(-len(li) - 1, len(li) + 1), repeat=3):
try:
if li[i:j:k] == target:
return [i, j, k]
except (IndexError, ValueError):
pass
def gen_random(self):
li = [self.random.randrange(-10 ** 2, 10 ** 2) for _ in range(self.random.randrange(1, 20))]
i, j, k = [self.random.randrange(-len(li) - 1, len(li) + 1) for _ in range(3)]
try:
target = li[i:j:k]
if (target != [] and target != li) or self.random.randrange(50) == 0:
self.add(dict(li=li, target=target))
except (IndexError, ValueError):
pass
class ListIndex(PuzzleGenerator):
@staticmethod
def sat(item: int, li=[17, 2, 3, 9, 11, 11], index=4):
"""Find the item whose first index in li is index"""
return li.index(item) == index
@staticmethod
def sol(li, index):
return li[index]
def gen_random(self):
li = [self.random.randrange(-10 ** 2, 10 ** 2) for _ in range(self.random.randrange(1, 20))]
i = self.random.randrange(len(li))
index = li.index(li[i])
self.add(dict(li=li, index=index))
class ListIndex2(PuzzleGenerator):
@staticmethod
def sat(li: List[int], i=29, index=10412):
"""Find a list that contains i first at index index"""
return li.index(i) == index
@staticmethod
def sol(i, index):
return [i - 1] * index + [i]
def gen_random(self):
i = self.random.randrange(-10 ** 5, 10 ** 5)
index = self.random.randrange(10 ** 5)
self.add(dict(i=i, index=index))
class ListIn(PuzzleGenerator):
@staticmethod
def sat(s: str, a=['cat', 'dot', 'bird'], b=['tree', 'fly', 'dot']):
"""Find an item that is in both lists a and b"""
return s in a and s in b
@staticmethod
def sol(a, b):
return next(s for s in b if s in a)
def gen_random(self):
a = [self.random.pseudo_word() for _ in range(self.random.randrange(1, 100))]
b = [self.random.pseudo_word() for _ in range(self.random.randrange(1, 100))]
b.insert(self.random.randrange(len(b)), self.random.choice(a))
self.add(dict(a=a, b=b))
########################################
# int problems
########################################
class IntNeg(PuzzleGenerator):
@staticmethod
def sat(x: int, a=93252338):
"""Solve a unary negation problem"""
return -x == a
@staticmethod
def sol(a):
return - a
def gen_random(self):
a = self.random.randint(-10 ** 16, 10 ** 16)
self.add(dict(a=a))
class IntSum(PuzzleGenerator):
@staticmethod
def sat(x: int, a=1073258, b=72352549):
"""Solve a sum problem"""
return a + x == b
@staticmethod
def sol(a, b):
return b - a
def gen_random(self):
a = self.random.randint(-10 ** 16, 10 ** 16)
b = self.random.randint(-10 ** 16, 10 ** 16)
self.add(dict(a=a, b=b))
class IntSub(PuzzleGenerator):
@staticmethod
def sat(x: int, a=-382, b=14546310):
"""Solve a subtraction problem"""
return x - a == b
@staticmethod
def sol(a, b):
return a + b
def gen_random(self):
m = 10 ** 16
a = self.random.randint(-m, m)
b = self.random.randint(-m, m)
self.add(dict(a=a, b=b))
class IntSub2(PuzzleGenerator):
@staticmethod
def sat(x: int, a=8665464, b=-93206):
"""Solve a subtraction problem"""
return a - x == b
@staticmethod
def sol(a, b):
return a - b
def gen_random(self):
m = 10 ** 16
a = self.random.randint(-m, m)
b = self.random.randint(-m, m)
self.add(dict(a=a, b=b))
class IntMul(PuzzleGenerator):
@staticmethod
def sat(n: int, a=14302, b=5):
"""Solve a multiplication problem"""
return b * n + (a % b) == a
@staticmethod
def sol(a, b):
return a // b
def gen_random(self):
m = 10 ** 6
a = self.random.randint(-m, m)
b = self.random.randint(-100, 100)
if b != 0:
self.add(dict(a=a, b=b))
class IntDiv(PuzzleGenerator):
@staticmethod
def sat(n: int, a=3, b=23463462):
"""Solve a division problem"""
return b // n == a
@staticmethod
def sol(a, b):
if a == 0:
return 2 * b
for n in [b // a, b // a - 1, b // a + 1]:
if b // n == a:
return n
def gen_random(self):
m = 10 ** 16
n = self.random.randint(-m, m)
b = self.random.randint(-m, m)
if n != 0:
a = b // n
self.add(dict(a=a, b=b))
class IntDiv2(PuzzleGenerator):
@staticmethod
def sat(n: int, a=345346363, b=10):
"""Find n that when divided by b is a"""
return n // b == a
@staticmethod
def sol(a, b):
return a * b
def gen_random(self):
m = 10 ** 16
a = self.random.randint(-m, m)
b = self.random.randint(-m, m)
if b != 0:
self.add(dict(a=a, b=b))
class IntSquareRoot(PuzzleGenerator):
@staticmethod
def sat(x: int, a=10201202001):
"""Compute an integer that when squared equals perfect-square a."""
return x ** 2 == a
@staticmethod
def sol(a):
return int(a ** 0.5)
def gen_random(self):
z = self.random.randint(0, 2 ** 31) # so square < 2 **64
a = z ** 2
self.add(dict(a=a))
class IntNegSquareRoot(PuzzleGenerator):
@staticmethod
def sat(n: int, a=10000200001):
"""Find a negative integer that when squared equals perfect-square a."""
return a == n * n and n < 0
@staticmethod
def sol(a):
return -int(a ** 0.5)
def gen_random(self):
z = self.random.randint(0, 2 ** 31)
a = z ** 2
self.add(dict(a=a))
class FloatSquareRoot(PuzzleGenerator):
@staticmethod
def sat(x: float, a=1020):
"""Find a number that when squared is close to a."""
return abs(x ** 2 - a) < 10 ** -3
@staticmethod
def sol(a):
return a ** 0.5
def gen_random(self):
a = self.random.randint(0, 10 ** 10)
self.add(dict(a=a))
class FloatNegSquareRoot(PuzzleGenerator):
@staticmethod
def sat(x: float, a=1020):
"""Find a negative number that when squared is close to a."""
return abs(x ** 2 - a) < 10 ** -3 and x < 0
@staticmethod
def sol(a):
return -a ** 0.5
def gen_random(self):
a = self.random.randint(0, 10 ** 10)
self.add(dict(a=a))
if __name__ == "__main__":
PuzzleGenerator.debug_problems()
|
47b3b6b94781b8cf6108feaab7dd83ba91a348da | xavier/KidsCode | /puissance4/pyssance4.py | 4,962 | 3.625 | 4 | # -*- coding: UTF-8 -*-
VIDE = " "
ROUGE = 'R'
JAUNE = 'J'
class Erreur(Exception):
pass
class ErreurDePosition(Erreur):
pass
class Grille:
"""
Grille de Puissance 4
Le système de coordonées de la grille est compris dans l'intervalle [0;7] pour les colonnes et [0;6] pour les lignes.
Les colonnes son numérotées de gauche à droite, les lignes sont numérotées de bas en haut.
"""
COLONNES = 7
LIGNES = 6
def __init__(self):
self.grille = [[] for col in range(self.COLONNES)]
def ajouter_pion(self, numero_colonne, couleur_pion):
""" Ajoute le pion de la couleur donnée dans la colonne. Retourne la ligne à laquelle se trouve le pion ajouté """
self.__assert_numero_colonne(numero_colonne)
if len(self.grille[numero_colonne]) < self.LIGNES:
self.grille[numero_colonne].append(couleur_pion)
return len(self.grille[numero_colonne])-1
else:
raise Erreur("Maximum " + str(self.LIGNES) + " pions par colonne")
def pion(self, numero_colonne, numero_ligne):
""" Retourne la couleur du pion à la position donnée """
self.__assert_numero_colonne(numero_colonne)
self.__assert_numero_ligne(numero_ligne)
colonne = self.grille[numero_colonne]
if numero_ligne < len(colonne):
return colonne[numero_ligne]
else:
return VIDE
def pion_gagnant(self, numero_colonne, numero_ligne):
""" Retourne True si le pion à la position indiquée fait partie d'une série de 4 """
self.__assert_numero_colonne(numero_colonne)
self.__assert_numero_ligne(numero_ligne)
couleur_pion = self.pion(numero_colonne, numero_ligne)
if couleur_pion == VIDE:
return False
if self.__compte_pions_de_meme_couleur_horizontalement(couleur_pion, numero_colonne, numero_ligne) > 3:
return True
if self.__compte_pions_de_meme_couleur_verticalement(couleur_pion, numero_colonne, numero_ligne) > 3:
return True
if self.__compte_pions_de_meme_couleur_diagonalement_so_ne(couleur_pion, numero_colonne, numero_ligne) > 3:
return True
if self.__compte_pions_de_meme_couleur_diagonalement_no_se(couleur_pion, numero_colonne, numero_ligne) > 3:
return True
return False
def __str__(self):
""" Retourne la grille formattée dans une chaîne """
output = " " + " ".join(map(str, range(self.COLONNES))) +"\n"
for ligne in range(self.LIGNES, 0, -1):
output += "|"
for col in range(self.COLONNES):
output += self.pion(col, ligne-1) or " "
output += "|"
output += "\n"
output += "-" * ((self.COLONNES*2)+1)
return output
#
# API privée
#
def __assert_numero_colonne(self, numero_colonne):
if (numero_colonne < 0) or (numero_colonne >= self.COLONNES):
raise ErreurDePosition("Le numero de colonne doit etre compris entre 0 et " + str(self.COLONNES-1))
def __assert_numero_ligne(self, numero_ligne):
if (numero_ligne < 0) or (numero_ligne >= self.LIGNES):
raise ErreurDePosition("Le numero de ligne doit etre compris entre 0 et " + str(self.LIGNES-1))
def __compte_pions_de_meme_couleur_horizontalement(self, couleur_pion, numero_colonne, numero_ligne):
compteur_horizontal = self.__compte_pions_de_meme_couleur(couleur_pion, numero_colonne, numero_ligne, 1, 0)
compteur_horizontal += self.__compte_pions_de_meme_couleur(couleur_pion, numero_colonne, numero_ligne, -1, 0)-1
return compteur_horizontal
def __compte_pions_de_meme_couleur_verticalement(self, couleur_pion, numero_colonne, numero_ligne):
compteur_vertical = self.__compte_pions_de_meme_couleur(couleur_pion, numero_colonne, numero_ligne, 0, 1)
compteur_vertical += self.__compte_pions_de_meme_couleur(couleur_pion, numero_colonne, numero_ligne, 0, -1)-1
return compteur_vertical
def __compte_pions_de_meme_couleur_diagonalement_so_ne(self, couleur_pion, numero_colonne, numero_ligne):
compteur_diagonal = self.__compte_pions_de_meme_couleur(couleur_pion, numero_colonne, numero_ligne, 1, 1)
compteur_diagonal += self.__compte_pions_de_meme_couleur(couleur_pion, numero_colonne, numero_ligne, -1, -1)-1
return compteur_diagonal
def __compte_pions_de_meme_couleur_diagonalement_no_se(self, couleur_pion, numero_colonne, numero_ligne):
compteur_diagonal = self.__compte_pions_de_meme_couleur(couleur_pion, numero_colonne, numero_ligne, -1, 1)
compteur_diagonal += self.__compte_pions_de_meme_couleur(couleur_pion, numero_colonne, numero_ligne, 1, -1)-1
return compteur_diagonal
def __compte_pions_de_meme_couleur(self, couleur_pion, numero_colonne, numero_ligne, increment_horizontal, increment_vertical):
compteur = 0
try:
while (self.pion(numero_colonne, numero_ligne) == couleur_pion) and compteur < 4:
compteur += 1
numero_colonne += increment_horizontal
numero_ligne += increment_vertical
except ErreurDePosition:
pass
return compteur |
5dd7ff7017f8bb50f4d14e29de71509f790a3b02 | dawn888/leetcode | /算法/设计链表.py | 6,624 | 4.15625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class MyLinkedList:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head=None
def get(self, index):
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
:type index: int
:rtype: int
"""
if self.head is None:
return -1
if index==0:
return self.head.val
else:
i=1
cur=self.head
while cur.next:
if index==i:
result=cur.next.val
cur = cur.next
return result
else:
cur = cur.next
i=i+1
return -1
def addAtHead(self, val):
"""
Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
:type val: int
:rtype: void
"""
pre=ListNode(val)
pre.next=self.head
self.head=pre
return self.head
def addAtTail(self, val):
"""
Append a node of value val to the last element of the linked list.
:type val: int
:rtype: void
"""
cur=self.head
if self.head is None:
self.head=ListNode(val)
else:
while cur.next:
cur=cur.next
cur.next=ListNode(val)
return self.head
def addAtIndex(self, index, val):
"""
Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
:type index: int
:type val: int
:rtype: void
"""
length=self.length()
if index==0:
self.head=self.addAtHead(val)
return self.head
if index==length:
self.head=self.addAtTail(val)
return self.head
if index>length:
self.head=self.head
else:
i=1
pre=self.head
while pre.next:
if index==i:
addnode=ListNode(val)
addnode.next=pre.next
pre.next = addnode
else:
pre = pre.next
i=i+1
return self.head
def length(self):
if self.head is None:
len=0
else:
cur=self.head
len=0
while cur:
len=len+1
cur=cur.next
return len
def deleteAtIndex(self, index):
"""
Delete the index-th node in the linked list, if the index is valid.
:type index: int
:rtype: void
"""
if index==0:
self.head=self.head.next
length = self.length()
if index!=0 and index<length:
i=1
cur=self.head
while cur:
if index==i:
cur.next=cur.next.next
cur = cur.next
else:
cur=cur.next
i=i+1
return self.head
else:
return '索引无效'
def printnode(self):
cur=self.head
while cur:
print(cur.val)
cur=cur.next
return self.head
def printnode(self):
cur=self.head
while cur:
print(cur.val)
cur=cur.next
return self.head
if __name__ == '__main__':
#["MyLinkedList", "addAtHead", "addAtHead", "deleteAtIndex", "addAtIndex", "addAtTail", "addAtIndex", "addAtTail",
# "addAtHead", "addAtHead", "addAtHead", "addAtTail", "addAtTail", "addAtHead", "addAtTail", "addAtTail",
# "addAtHead", "addAtTail", "deleteAtIndex", "addAtTail", "addAtTail", "get", "addAtIndex", "addAtHead", "get",
# "get", "addAtHead", "get", "addAtIndex", "addAtTail", "addAtIndex", "addAtHead", "addAtHead", "addAtHead", "get",
# "addAtHead", "addAtIndex", "addAtTail", "addAtHead", "addAtIndex", "get", "addAtTail", "addAtTail", "addAtIndex",
# "addAtIndex", "addAtHead", "addAtHead", "get", "addAtTail", "addAtIndex", "addAtIndex", "addAtHead",
# "deleteAtIndex", "addAtIndex", "addAtHead", "deleteAtIndex", "addAtTail", "deleteAtIndex", "addAtTail",
# "addAtHead", "addAtTail", "addAtTail", "addAtHead", "addAtTail", "addAtIndex", "deleteAtIndex", "addAtHead",
# "addAtHead", "addAtHead", "addAtTail", "get", "addAtIndex", "addAtTail", "addAtTail", "addAtTail", "deleteAtIndex",
# "get", "addAtHead", "get", "get", "addAtTail", "deleteAtIndex", "addAtTail", "addAtIndex", "addAtHead",
# "addAtIndex", "addAtTail", "get", "addAtIndex", "addAtIndex", "addAtHead", "addAtHead", "get", "get", "get",
# "addAtIndex", "addAtHead", "addAtIndex", "addAtHead", "addAtTail", "addAtIndex", "get"]
# [[], [38], [45], [2], [1, 24], [36], [3, 72], [76], [7], [36], [34], [91], [69], [37], [38], [4], [66], [38], [14],
# [12], [32], [5], [7, 5], [74], [7], [13], [11], [8], [10, 9], [19], [3, 76], [7], [37], [99], [10], [12], [1, 20],
# [29], [42], [21, 52], [11], [44], [47], [6, 27], [31, 85], [59], [57], [4], [99], [13, 83], [10, 34], [48], [9],
# [22, 64], [69], [33], [5], [18], [87], [42], [1], [35], [31], [67], [36, 46], [23], [64], [81], [29], [50], [23],
# [36, 63], [8], [19], [98], [22], [28], [42], [24], [34], [32], [25], [53], [55, 76], [38], [23, 98], [27], [18],
# [44, 27], [16, 8], [70], [15], [9], [27], [59], [40, 50], [15], [11, 57], [80], [50], [23, 37], [12]]
mylinkedlist=MyLinkedList()
mylinkedlist.addAtHead(38)
mylinkedlist.addAtHead(45)
mylinkedlist.deleteAtIndex(2)
# mylinkedlist.addAtHead(4)
# mylinkedlist.addAtHead(5)
# mylinkedlist.addAtHead(6)
# print('在尾部添加元素---------')
# mylinkedlist.addAtTail(7)
# mylinkedlist.printnode()
# print('长度---------')
# #获取某个索引元素
# #mylinkedlist.get(7)
# print(mylinkedlist.length())
# #插入元素
# print('插入元素---------')
# mylinkedlist.addAtIndex(1,2)
# mylinkedlist.printnode()
# print('删除索引是xx的元素---------')
# mylinkedlist.deleteAtIndex(1)
# mylinkedlist.printnode()
|
326d10133ac2ee0cda40c789e8fb8e0e4a375d82 | rodfmarin/adventofcode | /2022/13/main.py | 4,822 | 4.09375 | 4 | """
--- Day 13: Distress Signal ---
You climb the hill and again try contacting the Elves. However, you instead receive a signal you weren't expecting: a
distress signal.
Your handheld device must still not be working properly; the packets from the distress signal got decoded out of order.
You'll need to re-order the list of received packets (your puzzle input) to decode the message.
Your list consists of pairs of packets; pairs are separated by a blank line. You need to identify how many pairs of
packets are in the right order.
For example:
[1,1,3,1,1]
[1,1,5,1,1]
truncated
"""
from functools import cmp_to_key
def get_input(mode='test'):
input = []
filename = './input.txt'
if mode == 'test':
# use input2 (example input)
filename = './input2.txt'
with open(filename, 'r') as my_file:
for line in my_file:
line = line.replace("\n", "")
input.append(line)
return input
def get_input_2(mode='test'):
filename = './input.txt'
if mode == 'test':
# use input2 (example input)
filename = './input2.txt'
with open(filename, 'r') as my_file:
return my_file.read().strip().replace("\n\n", "\n").split("\n")
def compare(a, b):
# Comparator Functions are Fun :)
# Lesson Learned: Try not to use Booleans but integers for the result of a compare
# This way you can return -1, 0, 1 etc.
if isinstance(a, list) and isinstance(b, int):
b = [b]
if isinstance(a, int) and isinstance(b, list):
a = [a]
if isinstance(a, int) and isinstance(b, int):
if a < b:
return 1
if a == b:
return 0
return -1
if isinstance(a, list) and isinstance(b, list):
i = 0
while i < len(a) and i < len(b):
x = compare(a[i], b[i])
if x == 1:
return 1
if x == -1:
return -1
i += 1
if i == len(a):
if len(a) == len(b):
return 0
return 1 # a ended first
# If i didn't hit the end of a, it hit the end of b first
# This means that b is shorter, which is bad
return -1
class Pair:
"""
A Pair represents two lists to seek through and find out if their in the correct order
"""
def __init__(self, left_string: str, right_string: str):
self.left_string = left_string
self.right_string = right_string
self.left = None
self.right = None
self.try_parse()
def try_parse(self):
"""
Try to eval left and right and assign their expressions to left and right
"""
self.left = eval(self.left_string)
self.right = eval(self.right_string)
def __repr__(self):
return f"left:{str(self.left_string)}, right:{str(self.right_string)}"
def parse_input(input: [str]):
"""
Input is a list of lines
Pairs are next to each other separated by a blank line
"""
pairs = []
for i in range(0, len(input), 3):
left = input[i]
right = input[i + 1]
p = Pair(left, right)
pairs.append(p)
return pairs
def parse_input_part_two(input: [str]):
"""
Disregard the lines just get all the packets
"""
lines = []
lines.append([[2]])
lines.append([[6]])
for line in input:
if str.isprintable(line):
lines.append(line)
return lines
def do_part_one():
input = get_input(mode='real')
pairs = parse_input(input)
sum = 0
for index, p in enumerate(pairs):
if compare(p.left, p.right) == 1:
sum += index + 1
print(sum)
def do_part_two():
"""
--- Part Two ---
Now, you just need to put all of the packets in the right order. Disregard the blank lines in your list of received
packets.
The distress signal protocol also requires that you include two additional divider packets:
[[2]]
[[6]]
Using the same rules as before, organize all packets - the ones in your list of received packets as well as the two
divider packets - into the correct order.
For the example above, the result of putting the packets in the correct order is:
truncated
"""
input = get_input_2(mode='real')
packets = list(map(eval, input))
packets.append([[2]])
packets.append([[6]])
# Super neat cmp_to_key function in functools
packets = sorted(packets, key=cmp_to_key(compare), reverse=True)
a = 0
b = 0
# We just want to multiply the index of divider packets in the sorted list
for i, li in enumerate(packets):
if li == [[2]]:
a = i + 1
if li == [[6]]:
b = i + 1
print(a*b)
if __name__ == "__main__":
do_part_one()
do_part_two()
|
2a545ca3926075d6f6a7e0fdbbfc484aec780ffd | ramsandhya/Python | /ex13-argv.py | 1,154 | 4.21875 | 4 | from sys import argv
# script, first, second, third = argv
# print "The script is called", script
# print "The first variable is called ",first
# print "The second variable is called", second
# print "The third variable is called", third
# argv needs these arguments from the command line. The first argument will be the name of the script. nachos, sandwich, fries are all variables.
# Command line will take 1st argument as the script.py which is ex13.py and the other 4 arguments as there are 4 other arguments.
# The command line returns string so if we need to add the arguments convert themto integer by int method
# From the book - "Take whatever is in argv, unpack it, and assign it to all of these variables on the left in order."
# script, nachos, sandwich, fries, dessert = argv
# print script
# print nachos
# print sandwich
# print fries
# print dessert
#
# # same as print nachos
# print raw_input(nachos)
# concatenates
# print nachos + sandwich
# prints added values
# print (int(nachos) + int(sandwich))
# prints input we give in command line after it runs
print raw_input()
# argv takes inputs at command line not after it runs
|
64109eff0291d32e3cb457603fff1fc6ef0b8f0b | Iwontbecreative/Positive-tweets | /positive.py | 2,321 | 3.703125 | 4 | """
Those are functions that use REST api to check users timelines and add
them and check whether text is positive or negative about a topic.
"""
from __future__ import division
from string import punctuation
import tweepy
import credentials as c
from credentials import our_id
with open("positive.txt", "r") as pos:
positive_words = pos.read().splitlines()
with open("negative.txt", "r") as neg:
negative_words = neg.read().splitlines()
def preprocess(tweet):
"""
Takes a tweet and preprocesses it so as to enhance detection rate.
"""
tweet = tweet.lower()
for p in punctuation:
tweet = tweet.replace(p, "")
return tweet
def check_topic(tweet, keywords):
"""
Checks whether some text is on the right topic
"""
return any(True for k in keywords if k in preprocess(tweet))
def check_pos(tweet):
"""Checks whether a tweet is positive or not."""
positive_counter, negative_counter = 0, 0
for word in tweet.split(' '):
if word in positive_words:
positive_counter += 1
elif word in negative_words:
negative_counter += 1
if positive_counter > negative_counter:
return True
def setup_auth():
"""
Dummy function to avoid importing credentials everytime
"""
auth = tweepy.OAuthHandler(c.consumer_key, c.consumer_secret)
auth.set_access_token(c.access_token, c.access_token_secret)
return auth
def is_prospect(author, topic, about_topic=0.15):
"""
Checks whether enough (about_topic) of author tweets are about topic.
"""
if author == our_id:
return False
api = tweepy.API(setup_auth())
try:
tweets = [t.text for t in api.user_timeline(user_id=author, count=50)]
except tweepy.error.TweepError:
print("Too many requests")
return
# This is quite stringent, only about 5% of users pass the test with our
# default keywords. We add minimum tweets length to make sure we don't add
# people whose first tweet is randomly about big data.
return len([True for t in tweets if check_topic(t, topic)]) > about_topic * len(tweets) and len(tweets) > 5
def follow(author_id):
"""
Follows the id user on Twitter.
"""
api = tweepy.API(setup_auth())
api.create_friendship(user_id=author_id)
|
fb096545a310598d29d222842bb229e90324d67d | HamishBB/zomvennia | /typeclasses/rooms.py | 3,646 | 3.578125 | 4 | """
Room
Rooms are simple containers that has no location of their own.
"""
from evennia import DefaultRoom
from evennia import utils
from evennia import create_object
from characters import Character
class Room(DefaultRoom):
"""
Rooms are like any Object, except their location is None
(which is default). They also use basetype_setup() to
add locks so they cannot be puppeted or picked up.
(to change that, use at_object_creation instead)
See examples/object.py for a list of
properties and methods available on all Objects.
"""
def at_object_creation(self):
"""
Called only at initial creation. This is a rather silly
example since ability scores should vary from Character to
Character and is usually set during some character
generation step instead.
"""
# 1 2 3 small medium large
self.db.roomSize = 0
# Our rooms will have a title
self.db.roomTitle = ""
# eventual modifier for coverage when sneaking/hiding
self.db.roomCover = 0
# movement modifier i.e. tarmac v swap for running/driving
self.db.movementMod = 0
# Encounter % for zombies
self.db.zombieEncounter = 10
# items on searching
self.db.findItemsChance = 1
# is the room inside or outside
self.db.roomInside = 0
def return_appearance(self, looker):
"""
This is called when e.g. the look command wants to retrieve
the description of this object.
Args:
looker (Object): The object looking at us.
Returns:
description (str): Our description.
"""
if not looker:
return ""
# get and identify all objects
visible = (con for con in self.contents if con != looker and
con.access(looker, "view"))
exits, users, things = [], [], []
for con in visible:
key = con.get_display_name(looker)
if con.destination:
exits.append(key)
elif con.has_account:
users.append("%s" % key)
else:
things.append(key)
# get description, build string
string = "|c%s|n\n" % self.get_display_name(looker)
desc = self.db.desc
if desc:
string += "%s" % desc
if things:
string += "\n|cYou notice: " + ", ".join(things) + "|n"
if users:
string += "\n|MAlso here:|m " + ", ".join(users) + "|n"
if exits:
string += "\n|GExits: " + ", ".join(exits)
return string
def get_roominfo(self):
"""
Simple access method to return room abilities
scores as a tuple (roomSize, roomTitle, roomCover, movementMod, zombieEncounter, findItemsChance)
"""
return self.db.roomSize, self.db.roomTitle, self.db.roomCover, self.db.movementMod, self.db.zombieEncounter, \
self.db.findItemsChance
def at_object_receive(self, obj, source_location):
if utils.inherits_from(obj, Character):
# A PC has entered, NPC is caught above.
# Cause the character to look around
#
self.db.findItemsChance = self.db.findItemsChance + 1
# demonstration
if self.db.findItemsChance > 10:
rock = create_object(key="Rock", location=self)
rock.db.desc = "An ordinary rock."
rock.db.weight = 20
rock.db.cost = 0
rock.db.size = 5
self.db.findItemsChance = 1
|
d63239b74444d9f366ed6c273a1b098f9e8b80f0 | albinjohn366/AI_Minesweeper_Game | /my_minesweeper.py | 2,739 | 3.875 | 4 | # MINESWEEPER GAME OUTLOOK
import random
class Minesweeper:
mine_number = None
def __init__(self, height=8, width=8, mines=15):
self.mine_number = dict()
self.full_set = set()
self.height = height
self.width = width
self.mines = set()
self.board = []
self.mine_length = mines
def board_setting(self):
# Considering there are no mines in the board
for i in range(self.height):
row = []
for j in range(self.width):
row.append(False)
self.full_set.add((i, j))
self.board.append(row)
# Putting in mines in random spaces
while True:
if len(self.mines) == self.mine_length:
break
x = random.randint(0, self.height - 1)
y = random.randint(0, self.width - 1)
self.mines.add((x, y))
self.board[x][y] = True
# Numbering the cells with respect to mines
for i in range(self.height):
for j in range(self.width):
if (i, j) in self.mines:
continue
mine_count = 0
for i1 in range(i - 1, i + 2):
for j1 in range(j - 1, j + 2):
try:
if (i1, j1) == (i, j):
continue
elif i1 < 0 or j1 < 0:
continue
if self.board[i1][j1]:
mine_count += 1
except IndexError:
pass
self.mine_number[(i, j)] = mine_count
# Printing the board with numbers
def print_board_with_num(self):
for i in range(self.height):
print('--' * self.width + '-')
for j in range(self.width):
if self.board[i][j]:
print('|X', end='')
else:
print('|{}'.format(self.mine_number[(i, j)]), end='')
print('|')
print('--' * self.width + '-')
# Printing the board without numbers
def print_board(self, cells=None, mine_cell=None):
if mine_cell is None:
mine_cell = []
for i in range(self.height):
print('--' * self.width + '-')
for j in range(self.width):
if (i, j) in mine_cell:
print('|X', end='')
elif (i, j) in cells:
print('|{}'.format(self.mine_number[(i, j)]), end='')
else:
print('| ', end='')
print('|')
print('--' * self.width + '-')
|
c40fdf6704940586bb8273a134458c04559e9a7d | mgoldey/hackerrank | /programming_interview_questions/fizzbuzz.py | 171 | 3.65625 | 4 | for i in range(1,1+int(input())):
ret_str=""
if i%3==0:
ret_str+="Fizz"
if i%5==0:
ret_str+="Buzz"
if ret_str=="":
print(i)
else:
print(ret_str)
|
6dee50a062a8efd25cd1a8eea0d470cb3048951f | clcsar/python-examples | /sum_of_squares.py | 208 | 3.53125 | 4 | square = (i*i for i in range(1000000))
#add the squares
total = 0
for i in square:
total += i
print total
#add the squares
total = 0
for i in (i*i for i in range(1000000)):
total += i
print total
|
5a89f63c90d9a791230a9cdeed72f9921642c008 | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/278/67409/submittedfiles/testes.py | 114 | 3.703125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
medida = float(input("medida: ")
print('centimetros eh medida*100') |
5e89bc180f370be3b5603300f1984a5cbb73fd05 | adyadyat/pyprojects | /lw/day12/day12_lw3.py | 506 | 4 | 4 | for i in range(8,0,-1):
for x in range(8,i,-1):
print(" ",end="")
for j in range(i,0,-1):
print(j,end="")
print(" ",end="")
print()
for i in range(8,0,-1):
for x in range(0,i-1):
print(" ",end="")
for j in range(8,i-1,-1):
print(j,end="")
print(" ",end="")
print()
"""
8 7 6 5 4 3 2 1
7 6 5 4 3 2 1
6 5 4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
8
8 7
8 7 6
8 7 6 5
8 7 6 5 4
8 7 6 5 4 3
8 7 6 5 4 3 2
8 7 6 5 4 3 2 1
""" |
e504e23de74b1e4bad0341b877f1095385a31754 | Adib234/Leetcode | /binary_tree_inorder_traversal.py | 1,090 | 3.921875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# res, stack = [], []
# cur = root
# while cur or stack:
# while cur: # travel to each node's left child, till reach the left leaf
# stack.append(cur)
# cur = cur.left
# cur = stack.pop() # this node has no left child
# res.append(cur.val) # so let's append the node value
# cur = cur.right # visit its right child --> if it has left child ? append left and left.val, otherwise append node.val, then visit right child again... cur = node.right
# return res
output= []
self.dfs(output,root)
return output
def dfs (self,output,root):
if root:
self.dfs(output,root.left)
output.append(root.val)
self.dfs(output,root.right)
|
76ab412292521cd218ebf6d26c3bd3fe8c8ca893 | kuangbiaodewoniu/calc_wage | /deal_csv.py | 861 | 3.609375 | 4 | # !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:dandan.zheng
@file: deal_csv.py
@time: 2018/03/20
"""
import csv
class CSV(object):
def __init__(self, value):
self.file_path = value
def get_data(self):
try:
result = {}
with open(self.file_path, 'r') as file:
file_content = csv.reader(file)
for line in file_content:
result[line[0]] = float(line[-1])
return result
except:
print('need config file')
exit(-1)
def write_list_to_file(self, data):
try:
with open(self.file_path, 'a', newline="") as file:
writer = csv.writer(file, dialect="excel")
writer.writerows(data)
except:
print('file not exist')
exit(-1) |
118115215f5fbd91d7e85287bcc46d8c787e3f18 | liviaerxin/zipline | /dual_moving_average.py | 3,869 | 3.515625 | 4 | #dual_moving_average.py
#!/usr/bin/env python
#
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dual Moving Average Crossover algorithm.
This algorithm buys apple once its short moving average crosses
its long moving average (indicating upwards momentum) and sells
its shares once the averages cross again (indicating downwards
momentum).
"""
from zipline.api import order_target, record, symbol, history, add_history,order
from zipline import TradingAlgorithm
import matplotlib.pyplot as plt
import pandas as pd
def initialize(context):
# Register 2 histories that track daily prices,
# one with a 100 window and one with a 300 day window
#add_history(100, '1m', 'price')
#add_history(300, '1m', 'price')
context.i = 0
context.sym = 'Close'
def handle_data(context, data):
# Skip first 300 days to get full windows
#print data['Close'].dt
#context.i += 1
#if context.i < 300:
# return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
sym = symbol('Close')
if data['short_mavg'].price > data['long_mavg'].price:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(context.sym, 1000)
elif data['short_mavg'].price < data['long_mavg'].price:
order_target(context.sym, 0)
# Save values for later inspection
record(Close=data[context.sym].price,
short_mavg=data['short_mavg'].price,
long_mavg=data['long_mavg'].price)
def analyze(context, perf):
fig = plt.figure()
ax1 = fig.add_subplot(211)
perf.portfolio_value.plot(ax=ax1)
ax1.set_ylabel('portfolio value in $')
ax2 = fig.add_subplot(212)
perf['AAPL'].plot(ax=ax2)
perf[['short_mavg', 'long_mavg']].plot(ax=ax2)
perf_trans = perf.ix[[t != [] for t in perf.transactions]]
buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]]
sells = perf_trans.ix[
[t[0]['amount'] < 0 for t in perf_trans.transactions]]
ax2.plot(buys.index, perf.short_mavg.ix[buys.index],
'^', markersize=10, color='m')
ax2.plot(sells.index, perf.short_mavg.ix[sells.index],
'v', markersize=10, color='k')
ax2.set_ylabel('price in $')
plt.legend(loc=0)
plt.show()
if __name__ == '__main__':
import pylab as pl
# Read data from yahoo website
#start = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
#end = datetime(2010, 1, 1, 0, 0, 0, 0, pytz.utc)
#data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,end=end)
#data = data.dropna()
# Read data from csv
data = pd.read_csv('EURUSD.csv') # DataFrame
data = data.dropna()
data.set_index('Date', inplace=True) # set the Date as index
data.index = pd.to_datetime(data.index, utc=True) # convert to datetime format
print data.head()
# Or directly
#data = pd.DataFrame.from_csv('AAPL.csv')
data['short_mavg'] = pd.rolling_mean(data['Close'], 100)
data['long_mavg'] = pd.rolling_mean(data['Close'], 300)
algo = TradingAlgorithm(initialize=initialize,
handle_data=handle_data)
#identifiers=['AAPL'])
results = algo.run(data)
results.to_csv('EURUSD_DMA.csv') |
ab49dcf192d10b4a3a07bffb23c022c43a19f09b | airtonsiqueira/python-safaribooks-exercises | /Introduction to Python/Exercises/WebCrawler/scraper.py | 1,207 | 3.609375 | 4 | import os
import urllib.request
from urllib.parse import urljoin
from bs4 import BeautifulSoup
# Para cada arquivo, siga cada link, encontre a imagem e faça download
# Download fotos: urllib
# Parse e tratamento HTML: BeautifulSoup
# Links
index_page = 'https://apod.nasa.gov/apod/archivepix.html'
pasta_downloads = 'Exercises/WebCrawler/apod_pictures'
print("Index: " + index_page)
# Traz todo o HTML
conteudo = urllib.request.urlopen(index_page).read()
# Cria objeto bs4 que contem todos as tags a
for link in BeautifulSoup(conteudo, "html.parser").findAll("a"):
# Converter url relativa para absoluta
href = urljoin(index_page, link['href'])
# Traz o conteudo do novo link, para extrair a imagem
conteudo = urllib.request.urlopen(href).read()
for img in BeautifulSoup(conteudo, "html.parser").findAll("img"):
img_href = urljoin(href, img["src"])
# Download Imagens
print("Downloading image: " + img_href)
image_name = img_href.split("/")[-1]
# print(image_name)
caminho = os.path.join(pasta_downloads, image_name)
# print(caminho)
urllib.request.urlretrieve(img_href, caminho)
|
2c58096eb133997121873eaa74584b72ae64a5b5 | SinanTang/MIT600 | /Lec5_in-class-exercise.py | 4,701 | 4.0625 | 4 | ## using bisection to approximate the square root of input number
def squareRootBi(x, epsilon):
"""
:param x: number to be squared
:param epsilon: the precision the square root expects to be
:return: the approximate square root of input x
"""
assert x >= 0, "x must be non-negative, not " + str(x)
assert epsilon > 0, "epsilon must be positive, not " + str(epsilon)
# ? the bug: when there's a perfect square, the function doesn't give the integer. --> its not a bug
# for i in range(x):
# if i**2 == x:
# return i
# else: pass
# REAL BUG: cant compute the square root of number less than 1
#==== my solution: not very elegant
# if x >= 1.0 :
# low = 0
# high = x
# guess = (low + high)/2.0
# count = 1
# while abs(guess**2 - x) > epsilon and count <= 100:
# print "High: ", high, ", Low: ", low, ", Guess: ", guess
# if guess**2 < x:
# low = guess
# else:
# high = guess
# guess = (low + high)/2.0
# count += 1
# if x < 1.0 :
# low = x
# high = 1.0
# guess = (low + high)/2.0
# count = 1
# while abs(guess**2 - x) > epsilon and count <= 100:
# print "High: ", high, ", Low: ", low, ", Guess: ", guess
# if guess**2 < x:
# low = guess
# else:
# high = guess
# guess = (low + high)/2.0
# count += 1
#=== Prof's solution, much better
low = 0
high = max(x, 1.0) ## when you need to evaluate
guess = (low + high)/2.0
count = 1
while abs(guess**2 - x) > epsilon and count <= 100:
# print "High: ", high, ", Low: ", low, ", Guess: ", guess
if guess**2 < x:
low = guess
else:
high = guess
guess = (low + high)/2.0
count += 1
assert count <= 100, "Iteration count exceeded"
print "Bi method. Num iteration: ", count, "Estimate: ", guess
return guess
# print squareRootBi(0.125, 0.0001), "\n", squareRootBi(16, 0.0001)
## better way to do testing - regression testing: make sure that things used to work will still work later
def testBi():
print "squareRootBi(4, 0.0001)"
squareRootBi(4, 0.0001)
print "squareRootBi(8, 0.0001)"
squareRootBi(8, 0.0001)
print "squareRootBi(16, 0.0001)"
squareRootBi(16, 0.0001)
print "squareRootBi(0.25, 0.0001)"
squareRootBi(0.25, 0.0001)
# testBi()
### Lecture 6
# speed of convergence (of bisection methods)
# Newton/Raphson method
def squareRootNR(x, epsilon):
"""Assume x >= 0 and epsilon > 0
Return y s.t. y*y is within epsilon of x"""
assert x>= 0, "x must be non-negative, not" + str(x)
assert epsilon > 0, "epsilon must be positive, not" + str(epsilon)
x = float(x)
guess = x/2.0 # experimenting with different guesses
# guess = 0.001
diff = guess**2 - x
ctr = 1
while abs(diff) > epsilon and ctr <= 100:
# print 'Error:', diff, 'guess:' guess
guess = guess - diff/(2.0*guess)
diff = guess**2 - x
ctr += 1
assert ctr <= 100, "Iteration count exceeded"
print "NR method. Num. iteration:", ctr, "Estimate:", guess
return guess
def compareMethods():
print "squareRoot(2, 0.01)"
squareRootBi(2, 0.01)
squareRootNR(2, 0.01)
raw_input()
print "squareRoot(2, 0.001)"
squareRootBi(2, 0.001)
squareRootNR(2, 0.001)
raw_input()
print "squareRoot(2, 0.0001)"
squareRootBi(2, 0.0001)
squareRootNR(2, 0.0001)
raw_input()
print "squareRoot(123456789, 0.0001)"
squareRootBi(123456789, 0.0001)
squareRootNR(123456789, 0.0001)
raw_input()
print "squareRoot(123456789, 0.000001)"
squareRootBi(123456789, 0.000001)
squareRootNR(123456789, 0.000001)
raw_input()
print "squareRoot(2736336100, 0.0001)"
squareRootBi(2736336100, 0.0001)
squareRootNR(2736336100, 0.0001)
raw_input()
# as the problem gets more complex, the difference between good and bad methods get bigger
# compareMethods()
# Answers can be WRONG: when you get an answer from the computer, ask yourself: why do I believe it
### Non-scalar types: tuples, strings -> immutable
# mutable -> Lists
Techs = ['MIT', 'Cal Tech'] # points to a list (object)
Ivys = ['Harvard', 'Yale', 'Brown']
Univs = []
Univs.append(Techs)
Univs.append(Ivys) # method
# print Univs
# for e in Univs:
# print e
# for c in e: print c
# Flattening the list
Univs = Techs + Ivys # concatenation
# print Univs
Ivys.remove('Harvard') # changed the original list
print Univs |
31fa244890654355ae00b4089c14014c8a4241b4 | pkovarsky/artem_p | /examples/_01_Python_Basics/_22_string_strip.py | 395 | 4.0625 | 4 | """String Manipulation"""
phrase = " Monty Python's Flying Circus "
print(phrase.strip()) # 'strip' removes whitespaces from both ends
# Monty Python's Flying Circus
print(phrase.lstrip()) # 'lstrip' removes leading characters (Left-strip)
# Monty Python's Flying Circus
print(phrase.rstrip()) # 'lstrip' removes trailing characters (Right-strip)
# Monty Python's Flying Circus
|
ca679ffe84f7fed14407e4736ad210bf3b6b2b37 | vla3089/adventofcode | /2018/3.py | 1,441 | 3.546875 | 4 | #!/usr/bin/env python
import collections
fname = "input3.txt"
with open(fname) as f:
content = f.readlines()
content = [line.strip() for line in content]
# claim contract
# #1 @ 432,394: 29x14
def parse_claim(claim):
claim = claim[1:]
claim_id, rest = claim.split('@', 1)
left, rest = rest.split(',', 1)
top, rest = rest.split(':', 1)
w, h = rest.split('x', 1)
return (int(claim_id), int(left), int(top), int(w), int(h))
def inflate_claims(claims):
grouped = collections.defaultdict(int)
for claim in claims:
claim_id, left, top, w, h = claim
for i in range(left, left + w):
for j in range(top, top + h):
grouped[i, j] += 1
return grouped
def overlaps_count(inflated_claims):
return sum(1 for count in inflated_claims.values() if count > 1)
def has_no_overlaps(claim, inflated):
claim_id, left, top, w, h = claim
for i in range(left, left + w):
for j in range(top, top + h):
if inflated[i, j] != 1:
return False
return True
def first_no_overlap_claim(claims, inflated):
for claim in claims:
if has_no_overlaps(claim, inflated):
return claim
return None
claims = [parse_claim(claim) for claim in content]
inflated = inflate_claims(claims)
print overlaps_count(inflated)
not_overlapped = first_no_overlap_claim(claims, inflated)
print not_overlapped[0]
|
5d7dca2b51494a3dd1574f52a992a8897fa097d3 | baby5/HackerRank | /DataStructures/LinkedList/TailInsert.py | 359 | 3.578125 | 4 | #coding:utf-8
#stupid
def Insert(head, data):
if head:
node = head
while node.next:
node = node.next
node.next = Node(data)
else:
head = Node(data)
return head
#smart
def Insert(head, data):
node = head
while node.next:
node = node.next
node.next = Node(data)
return head
|
a1e6219338ed0855e54e871bb365582d973c78a5 | GabrielYLT/DPL5211Tri2110-1 | /Lab 4/Lab 4.3.py | 230 | 3.734375 | 4 | # Create a while loop that displays I love Python 7 times
#Student ID: 1201200039
#Student Name: Tan Jiue Hong
word = 1
while (word <= 7 ):
print("I love phyton")
word = word + 1
for num in range(10):
print(num) |
fddd5224060a3a5fbb63b33f0a5a7c932f1d75b0 | ATinyLearner/PythonPractice | /test.py | 1,072 | 4.125 | 4 | #create a program for merge sort
user_input=input("Enter the elements of array:").split(",")
alist=[int(i) for i in user_input]
print("Given array is:")
print(alist)
le=len(alist)-1
def merge(a:list,start:int,mid:int,end:int):
n1=mid-start+1
n2=end-mid
l=[None]*n1
r=[None]*n2
k=0
# making temp list to store two sorted list
for i in range(n1):
l[i]=a[start+i]
for j in range(n2):
r[j]=a[mid+1+j]
while(i<=mid and j<=end):
if l[i]<=r[j]:
a[k]=l[i]
i+=1
else:
a[k]=r[j]
j+=1
k+=1
if (i>mid):
while(j<=end):
a[k]=r[j]
j+=1
k+=1
else:
while(i<=mid):
a[k]=l[i]
i+=1
k+=1
a=b.copy()
return a
def mergeSort(a:list,start:int,end:int):
if(start<end):
mid=(start+end)//2
mergeSort(a,start,mid)
mergeSort(a,mid+1,end)
merge(a,start,mid,end)
return a
print(mergeSort(alist,0,le)) |
9140cfe246e5c9f09e0049a21716a82b04a03819 | eriickluu/pywombat | /Mis ejercicios/Factorial/factorial.py | 132 | 3.703125 | 4 | def factorial(valor):
if valor == 1:
return valor
else:
return valor * factorial(valor-1)
print(factorial(4))
|
a0ae3027a1cf8816049b90ef74df57bb1757f9a5 | muman613/bookshelf | /python/sandbox/test_obj.py | 377 | 3.6875 | 4 |
class Book:
data = {}
def __init__(self, value1: str, value2: int):
self.data = {}
self.data["value"] = value1
self.data["int"] = value2
def __repr__(self):
return "{{ {}, {} }}".format(self.data["value"], self.data["int"])
myBook_1 = Book("stringvalue", 10)
myBook_2 = Book("anothervalue", 20)
print(myBook_1)
print(myBook_2)
|
e0ec6c235042de5a30abcdeabc175aac1d0c8e8b | mguomanila/programming_tests | /lesson5/countdiv.py | 1,178 | 3.9375 | 4 | '''
Task
Write a function:
def solution(A, B, K)
that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
{ i : A ≤ i ≤ B, i mod K = 0 }
For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
Write an efficient algorithm for the following assumptions:
A and B are integers within the range [0..2,000,000,000];
K is an integer within the range [1..2,000,000,000];
A ≤ B.
'''
from timeit import timeit
from random import randrange as r
from array import array
def soln1(A, B, K):
# write your code in Python 3.6
count = 0
for i in range(A,B+1):
if i % K == 0:
count += 1
return count
def soln2(A,B,K):
ar = array('L',(a for a in range(A,B+1)))
for count
if __name__ == '__main__':
n_min = 0
n_max = 2*10**9
v_min = 1
A = r(n_min,(n_max/2)-1)
B = r(n_max/2,n_max)
K = r(A,B)
#a = timeit('soln1(A, B, K)',number=10**1,globals=globals())
#print(a)
b = timeit('soln2(A, B, K)',number=10**1,globals=globals())
|
6ef96375c12d962aef6b7472846de7f9bbf5b0d1 | ricklixo/estudos | /DSA_Break.py | 761 | 3.875 | 4 | # Utilizando BREAK e PASS para interromper ou continuar o loop.
counter = 0
while counter < 100:
if counter == 4:
break
else:
pass
print(counter)
counter += 1
# Utilizando continue para pular a letra H e dar prosseguimento a verificação
for verificador in 'Python':
if verificador == 'h':
continue
print(verificador)
# Utilizando os loops While e For juntos para verificar numeros primos:
for i in range (2, 30):
j = 2
counter = 0
while j < i:
if i % j == 0:
counter = 1
j += 1
else:
j += 1
if counter == 0:
print('{} é um número primo'.format(i))
counter = 0
else:
counter = 0
|
272bca04a591ae32d58f18c7ea86eb45d390897a | youaresherlock/PythonPractice | /python核心技术与实战/16/函数参数传递.py | 1,046 | 4.28125 | 4 | #!usr/bin/python
# -*- coding:utf8 -*-
"""
python里的参数传递: 共享传参(对象的引用传递)
"""
if __name__ == "__main__":
# 变量及赋值
a = 1
b = a
a = a + 1
print(a, b)
# 列表赋值
l1 = [1,2,3]
l2 = l1
l1.append(4)
print(l1)
print(l2)
# 函数参数传递
def my_func1(b):
b = 2
a = 1
my_func1(a)
print(a)
# 传入可变对象
def my_func3(l2):
l2.append(4)
l1 = [1, 2, 3]
my_func3(l1)
print(l1)
# 参数原值不变
def my_func4(l2):
l2 = l2 + [4]
l1 = [1, 2, 3]
my_func4(l1)
print(l1)
# 要改变参数原值的做法
def my_func5(l2):
l2 = l2 + [4]
return l2
l1 = [1, 2, 3]
l1 = my_func5(l1)
print(l1)
# 思考题1
l1 = [1, 2, 3, 4]
l2 = [1, 2, 3, 4]
l3 = l2
print(id(l1), id(l2), id(l3))
# 思考题2
def func(d):
d["a"] = 10
d["b"] = 20
d = {"a": 1, "b": 2}
func(d)
print(d)
|
bf8807a56c9d5f4af11300ced17cee53788928b2 | mattfeng/rosalind | /hamm/hamm.py | 574 | 3.546875 | 4 | #!/usr/bin/env python
"""
hamm.py
Counting point mutations
========================
"""
import argparse
def hamming(s, t):
dist = 0
for a, b in zip(s, t):
if a != b:
dist += 1
return dist
def main(fname):
with open(fname) as f:
seq1 = f.readline().strip()
seq2 = f.readline().strip()
print(hamming(seq1, seq2))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("fname",
help="path to input file",
)
args = parser.parse_args()
main(args.fname)
|
4829a6af35b0305f21d81c46aad8aae6ac611d3f | shanksms/python-algo-problems | /arrays/add_two_numbers.py | 535 | 3.734375 | 4 | def add_two_arrays(A, B):
if len(A) > len(B):
B = [0] * (len(A) - len(B)) + B
else:
A = [0] * (len(B) - len(A)) + A
#this will hold the result
C = [0]*len(A)
#carry
c = 0
for i in reversed(range(len(A))):
sum = A[i] + B[i] + c
c = 0
if sum >= 10:
C[i] = sum % 10
c = sum // 10
else:
C[i] = sum
if c is not 0:
C = [c] + C
return C
if __name__ == '__main__':
print(add_two_arrays([9, 0, 0], [1, 0, 1]))
|
0b3340ecacdb60aae18a17a3bfa5ad7f1380dc6a | fancy84machine/Python | /Projects/Cleaning Data in Python/Ebola+Melt%2C+Split%2C+Assert.py | 1,816 | 3.65625 | 4 |
# coding: utf-8
# In[1]:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
ebola = pd.read_csv ('ebola.csv', header=0)
# In[2]:
ebola.columns
# In[3]:
#Splitting a column with .split() and .get()
# Melt ebola: ebola_melt
ebola_melt = pd.melt(ebola, id_vars=['Date', 'Day'], var_name='type_country', value_name='counts')
# Create the 'str_split' column
ebola_melt['str_split'] = ebola_melt.type_country.str.split('_')
# Create the 'type' column
ebola_melt['type'] = ebola_melt['str_split'].str.get(0)
# Create the 'country' column
ebola_melt['country'] = ebola_melt['str_split'].str.get(1)
# Print the head of ebola_melt
print(ebola_melt.head())
# In[6]:
'''
# Concatenate ebola_melt and status_country column-wise: ebola_tidy
ebola_tidy = pd.concat ([ebola_melt, status_country], axis = 1)
# Print the shape of ebola_tidy
print(ebola_tidy.shape)
# Print the head of ebola_tidy
print(ebola_tidy.head())
'''
# In[9]:
'''
all() method together with the .notnull() DataFrame method to check for missing values in a column.
The .all() method returns True if all values are True. When used on a DataFrame, it returns a Series of Booleans -
one for each column in the DataFrame. So if you are using it on a DataFrame, like in this exercise, you need to chain
another .all() method so that you return only one True or False value. When using these within an assert statement,
nothing will be returned if the assert statement is true: This is how you can confirm that the data you are checking are valid.
Note: You can use pd.notnull(df) as an alternative to df.notnull().
# Assert that there are no missing values
assert pd.notnull (ebola).all().all()
# Assert that all values are >= 0
assert (ebola>=0).all().all()
'''
|
f8b54b4dc408b8d7a4480c50a908c6538a76dc22 | LockeShots/Learning-Code | /training_task_9_-_fibonacci_sequence.py | 378 | 4.1875 | 4 | #Generate the fibonacci sequence
def fibseq(limit):
"""
>>> fibseq('10')
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
"""
fiblist = list()
fiblist.append(i+(i+1) for i in range(0, (limit)))
return(fiblist)
if __name__ == '__main__':
limit = int(input("To how many digits would you like to determine the fibonacci sequence?: "))
print(f"{fibseq(limit)}") |
57d465357b45b1ef37ba49ac257158a2b463779b | engtim/Python2021-Introduction | /Assignment2.py | 1,051 | 4.28125 | 4 | # Enter your first and last names
print("Enter First and Last Name: ")
first_name = input("First name: ")
last_name = input("Last name: ")
fullnames = first_name + " " + last_name
# Enter your country of origin
print("Enter your country of origin: ")
country = input("Country: ")
# Enter the nature of your current job
print("Enter the nature of your current job: ")
profession = input("Profession: ")
# Enter your email address
print("Enter your email address: ")
email = input("Email: ")
# Enter your phone number
print("Enter your phone number: ")
phone_number = input("Phone number: ")
# Enter your current city of residence
print("Enter your current city of residence: ")
city = input("City: ")
# Enter your Mailing address/ Physical address
print("Enter your Mailing address/Physical address: ")
address = input("Address: ")
print()
print(f"Full Names:", fullnames)
print(f"Country: ", country)
print(f"Profession: ", profession)
print(f"Email: ", email)
print(f"Phone: ", phone_number)
print(f"City: ", city)
print(f"Address: ", address) |
9e1c327ab5ba2c58b106897c78eb3e580dca9de5 | Harshad-Chavan/Python_OOPS | /mar_exploration.py | 404 | 3.609375 | 4 | s = 'SOSOOSOSOSOSOSSOSOSOSOSOSOS'
n = 3
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def marsExploration(s):
count = 0
for part in list(divide_chunks(s, n)):
if part[0] != 'S':
count += 1
if part[1] != 'O':
count += 1
if part[2] != 'S':
count += 1
return(count)
marsExploration(s) |
921ca99f41d6d2d5b9700ec0c0c60547984bcd81 | pdefusco/Python | /app_development/lpth/ex40.py | 206 | 3.5 | 4 | #practice classes:
class MyClass():
def __init__(self):
self.var1 = "var1"
def method(self):
print("this method prints this text")
obj1 = MyClass()
obj1.method()
print(obj1.var1)
|
b8ea6a78dbb3d0ba8253e2b0c8c2dacb037a84d0 | xiaodchen/NomNomNow | /Problem1/payment_api.py | 620 | 3.609375 | 4 | # Use this mock API as-is for charging an amount.
# No code in this file should be changed.
import random
class Error(Exception):
"""Base exception class."""
class ChargeFailedError(Error):
"""Raised when a charge fails for whatever reason. Who knows? Not me."""
def Charge(amount):
"""Attempts to charge an amount.
Args:
amount: Float USD amount to be charged.
Returns:
Float USD amount if charge attempt succeeded.
Raises:
ChargeFailedError: Raised if charge attempt fails.
"""
if random.randint(0, 3):
raise ChargeFailedError('Charge attempt failed.')
return amount
|
ce688de3fa16d6a4660e947af1663abedc1ede0d | Okemp-1/geekbrains-ai-python1 | /Lesson_2/GeekBrains_AI_Strzhelinsky_Python_2-2.py | 1,374 | 4.25 | 4 | '''
2. Для списка реализовать обмен значений соседних элементов,
т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте.
Для заполнения списка элементов необходимо использовать функцию input().
'''
el_count = int(input("Введите количество элементов списка "))
my_list = []
# my_list_orig = my_list ## пытался сохранить оригинальный список
i = 0
el = 0
while i < el_count:
my_list.append(input("Введите значение списка "))
i += 1
for elem in range(int(len(my_list)/2)):
my_list[el], my_list[el + 1] = my_list [el + 1], my_list[el]
el += 2
# print(f'Ваш список из {el_count} элементов выглядел как {my_list_orig}')
# print(f'Программа поменяла их местами согласно заданным условиям и теперь список выглядит так: {my_list}')
print(f'Программа перемешала значения в парах и ваш список выгляит так: {my_list}')
|
064c1b2f379e9ab6c44b3d04bce149bcdbeab30d | deanrobertcook/job-scraper | /tools.py | 1,723 | 3.890625 | 4 | def dict_depth(d):
"""Return the depth of a dictionary"""
if type(d) is dict:
return 1 + (max(map(dict_depth, d.values())) if d else 0)
return 0
def flatten_json(nested_json, exclude=[''], drop_lone_keys=False):
"""Flatten json object with nested keys into a single level.
Credit: https://stackoverflow.com/a/57334325/1751834
Args:
nested_json: A nested json object.
exclude: Keys to exclude from output.
drop_lone_keys: if a dict key has no siblings, don't add it to the flattened key
Returns:
The flattened json object if successful, None otherwise.
"""
out = {}
def flatten(x, name='', exclude=exclude):
if type(x) is dict:
for a in x:
#if drop_lone_keys and len(x.keys()) == 1 and dict_depth(x.values()) > 1: continue
if a not in exclude: flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(nested_json)
return out
## Tests
import unittest
class TestModule(unittest.TestCase):
def test_dict_depth(self):
self.assertEqual(dict_depth({'a': 'a_val'}), 1)
def test_dict_depth(self):
self.assertEqual(dict_depth({'a': {'b': 'b_val'}}), 2)
def test_flatten_json(self):
self.assertEqual(flatten_json({'a': {'b': 'b_val'}}), {'a_b': 'b_val'})
def test_flatten_json_drop_lone_keys(self):
self.assertEqual(flatten_json({'a': {'b': 'b_val'}}, drop_lone_keys=True), {'b': 'b_val'})
if __name__ == "__main__":
unittest.main()
|
49d18c3a615ed7d8024faf8e2d3d98196a390af3 | sash7410/coding | /OOPS.py | 4,907 | 4.46875 | 4 | #OOPS
#%%%
#the class Person has 2 attributes - name and the method say_hi
#an object p is created by calling the class
#every method/func in the class passes the object as the first argument
#the object p is passed as the 1st arg to the say_hi method
class Person:
name = "abc"
def say_hi(self):
print("hello, my name is", self.name)
p = Person()
p.say_hi()
#Methods inside the class can be directly used too
Person.say_hi(p)
#%%%
# __init__ func is called whenever an object is created (its a dunder)
# the init func has the reference to the object (self means object)
# the argument name is being accepted by init and name is being stored as an
# attribute of the object. so name need not be defined in the class
#the name passed to the init method while initiating the object p will be
#stored as an attribute of that object by init
class Person :
def __init__(self,name):
self.name = name
def say_hi(self):
print("hello, my name is", self.name)
p = Person("xyz")
p.say_hi()
Person.say_hi(p)
#%%%
# Dunders or magic funcs - used for operator overloading
# init stores model and mileage info in the object's attributes
#__str__ is used to give string representation
#__repr__ is used by print func to get the string and print it
# __eq__ takes the self obj and another obj and compares for equality,
#__add__ adds them both
class Car:
def __init__(self,model,mileage):
self.model= model
self.mileage= mileage
def __str__(self):
print ("{} , {}".format(self.model, self.mileage))
def __repr__(self):
print ("{}".format(self.model))
def __eq__(self, other):
print (self.mileage == other.mileage)
def __add__(self,other):
print (self.mileage + other.mileage)
c1 = Car('a', 10)
c2 = Car('b', 20)
print (c1 + c2)
print (c1==c2)
#%%%
## How attributes of a class is copied to an object
#when an object is created, all the attributes of the class is copied into
#the object before the __init__ func is executed
class Car:
mileage = 10
def __init__(self, model):
self.model = model
a = Car('honda')
print (a.mileage) #obj a has a mileage of 10 as defined in the class
b = Car('civic')
b.mileage = 20 #the attribute is specifically changed for this object
print (b.mileage)
class Dog:
tricks = []
def __init__(self, name):
self.name = name
def add_trick(self,trick):
self.tricks.append(trick)
a = Dog('bruno')
#every trick added will get appended to the tricks list
a.add_trick('fetch')
a.add_trick('roll')
print (a.tricks)
b = Dog('max')
print (b.tricks)
#b also has the same tricks as a even though it wasnt appended for b
#this is because a list is mutable. that means the object b also points
#to the same memory for tricks
#immutable data strc like strings and tuples will create an alias rather
#than point to the same memory address
#list can be used if tricks is defined in the init. a new list of tricks
#will be created every time an object is initiated
class Dog:
def __init__(self, name):
self.name = name
self.tricks=[]
def add_trick(self,trick):
self.tricks.append(trick)
a = Dog('bruno')
#every trick added will get appended to the tricks list
a.add_trick('fetch')
a.add_trick('roll')
print (a.tricks)
b = Dog('max')
print (b.tricks)
#%%%
## Inheritance
class Nig:
def __init__(self, name, age):
self.name = name
self.age = age
def tell(self):
print("Name: {} Age:{}".format(self.name, self.age), end= ' ')
class BigNig(Nig): #The above class is inherited into this class
def __init__(self, name, age, salary):
#super method calls init from super class and takes name and age
super().__init__(name, age)
self.salary = salary
def tell(self):
super().tell()
print("Salary: {}".format(self.salary))
class LilNig(Nig):
def __init__(self, name, age, cred):
super().__init__(name, age)
self.cred = cred
def tell(self):
super().tell()
print ("Cred: {}".format(self.cred))
a = BigNig ("abc", 40, 50000)
a.tell()
b = LilNig ("xyz", 15, 2000)
b.tell()
#%%%
# MRO (Method Resolution Order)
class A:
x = 10
class B(A):
pass
class C(A):
x= 5
class D(C):
x = 15
class E(B, D):
pass
print (E.x)
# __mro__ gives the order in which methods & their attributes are traversed
print (E.__mro__)
#%%%
# Modules in Python
# import module_name
# OR
# import module_name as custom_name
# OR
# from module_name import (method_names,variables,etc)
# OR
# from module_name import (method_name as custom_name, etc)
|
5366b770e6281f7222a95492a2fb28c9b699562f | jonahswift/pythonStudy1 | /firstDay/studySanYuanBiaoDaShi.py | 93 | 3.78125 | 4 | #三元表达式
a=1
b=2
if a>b:
c=a
else:
c=b
print(c)
c=a if a>b else b
print(c) |
464e043185de062b640576a21a16cda902927633 | Moeyinoluwa/tip-calculator | /main.py | 674 | 4.3125 | 4 | print("Welcome to the tip calculator!")
# ask for the total bill
total_bill = float(input("What was the total bill? \n$"))
# ask for the % tip
tip = int(input("What percentage tip would you like to give? \n"))
percentage_tip = tip / 100
# multiply total bill by % tip, add the result to the total bill
final_bill = (total_bill * percentage_tip) + total_bill
# ask for the number of people splitting the bill
no_of_people = float(input("How many people are splitting this bill? \n"))
# divide the final bill by the number of people, round up the result to 2 decimal places
each_bill = "{:.2f}".format(final_bill / no_of_people)
print(f"Each person should pay: ${each_bill}")
|
caed6ffa1ea3ec0c81470b7c162b46ba5ddc2285 | genemalkin/geneveo_utils | /wave_freq.py | 5,959 | 3.578125 | 4 | #
# Simple calculator from wavelengths and frequencies of electromagnetic waves
# This calculator is used among other things for the work for the Standards Committee.
#
import argparse
import sys
supported_units_wave = ['nm', 'um', 'mm', 'm']
supported_units_freq = ['Hz', 'kHz', 'MHz', 'GHz', 'THz']
class EMConverter:
def __init__(self):
# Speed of light in m/sec
self.speed = 3.0 * pow(10, 8)
@staticmethod
def frequnits_to_value(str_unit):
"""
Converts supported units into actual coefficients
@param str_unit: units as text: HZ, kHz, etc.
@return: floating point coefficient: 1.0, 1000.0 etc.
"""
if str_unit == 'Hz':
return 1.0
elif str_unit == 'kHz':
return 1000.0
elif str_unit == 'MHz':
return pow(10, 6)
elif str_unit == 'GHz':
return pow(10, 9)
elif str_unit == 'THz':
return pow(10, 12)
else:
return None
@staticmethod
def waveunits_to_value(str_unit):
"""
Converts supported units into actual coefficients
@param str_unit: units as text: m, mm, etc.
@return: floating point coefficient: 1.0, 0.001 etc.
"""
if str_unit == 'm':
return 1.0
elif str_unit == 'mm':
return pow(10.0, -3)
elif str_unit == 'um':
return pow(10.0, -6)
elif str_unit == 'nm':
return pow(10.0, -9)
else:
return None
@staticmethod
def freq2str(fr):
if fr < 1000.0:
return f"{fr:0.2f} Hz"
elif fr < 1e06:
return f"{(fr/1000.):0.2f} kHz"
elif fr < 1e09:
return f"{(fr/1e06):0.2f} MHz"
elif fr < 1e12:
return f"{(fr/1e09):0.2f} GHz"
else:
return f"{(fr/1e12):0.2f} THz"
@staticmethod
def wave2str(w):
if w > 1.0:
return f"{w:0.2f} m"
elif w > 1e-03:
return f"{(w * 1000.):0.2f} mm"
elif w > 1e-06:
return f"{(w * 1e06):0.2f} um"
elif w > 1e-09:
return f"{(w * 1e09):0.2f} nm"
else:
return f"{(w * 1e09)} nm"
def wave_to_freq(self, wave):
"""
@param wave: wavelength in meters
@return frequency in Hz
"""
freq = self.speed / wave
return freq
def freq_to_wave(self, freq):
"""
@param freq: frequency in Hz
@return wavelength in meters
"""
wave = self.speed / freq
return wave
def convert2freq(self, wavel, u):
w = wavel * self.waveunits_to_value(u)
f = self.wave_to_freq(w)
fs = self.freq2str(f)
return fs
def convert2wave(self, freq, u):
f = freq * self.frequnits_to_value(u)
w = self.freq_to_wave(f)
ws = self.wave2str(w)
return ws
def run(self, wv, fr, u):
"""
@param wv: wavelength value as string, may be None
@param fr: frequency value as string, may be None
@param u: units, will fit either wavelength or frequency
@return: text string for the conversion result
"""
if wv is not None:
return self.convert2freq(float(wv), u)
if fr is not None:
return self.convert2wave(float(fr), u)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-w",
"--wavelength",
help="define wavelength [only one: either frequency or wavelength]",
)
parser.add_argument(
"-f",
"--frequency",
help="define frequency [only one: either frequency or wavelength]",
)
parser.add_argument(
"-u",
"--units",
help=f"define units for wavelength or frequency; wavelengths supports:"
f" {supported_units_wave} and"
f" frequency supports: {supported_units_freq}"
)
args = parser.parse_args()
if args.wavelength is None and args.frequency is None:
print("You have not defined wavelength or frequency"
" some value for conversion has to be provided.")
sys.exit(-1)
if args.wavelength is not None and args.frequency is not None:
print("You have defined both wavelength and frequency"
f" (wv = {args.wavelength}, freq = {args.frequency}),"
" only one of them is supported at a time.")
sys.exit(-1)
units = None
if args.wavelength is not None:
units = 'm'
if args.units is not None:
if args.units in supported_units_freq:
print("Error: you have defined input as wavelength, but provided"
" units for frequency:"
f" (wv = {args.wavelength}, units = {args.units}).")
sys.exit(-1)
if args.units not in supported_units_wave:
print("Error: you have provided not supported units:"
f" {args.units}); we support: {supported_units_wave}.")
sys.exit(-1)
units = args.units
if args.frequency is not None:
units = 'Hz'
if args.units is not None:
if args.units in supported_units_wave:
print("Error: you have defined input as frequency, but provided"
" units for wavelength:"
f" (freq = {args.frequency}, units = {args.units}).")
sys.exit(-1)
if args.units not in supported_units_freq:
print("Error: you have provided not supported units:"
f" {args.units}); we support: {supported_units_freq}.")
sys.exit(-1)
units = args.units
converter = EMConverter()
res = converter.run(args.wavelength, args.frequency, units)
print(f"RESULT = {res}")
sys.exit(0)
|
f4132a22dafcd5de091efcdf571355260a1613f8 | doraeball22/Python-for-kids | /1.data_type.py | 3,544 | 4.1875 | 4 | # ชนิดข้อมูล
# 1.Number แบ่งออกเป็น 1.1 จำนวนเต็ม 1.2 จำนวนจริง
integerNumber = 102 # จำนวนเต็ม (integer)
flotingPointNumber = 10.5 # จำนวนจริง เป็นทศนิยม (Floating point)
# + - * / % //
num1 = 9
num2 = 2
print("num1 + num2 = {}".format(num1+num2))
print("num1 - num2 = {}".format(num1-num2))
print("num1 * num2 = {}".format(num1*num2))
print("num1 / num2 = {}".format(num1/num2))
print("num1 % num2 = {}".format(num1%num2))
print("num1 // num2 = {}".format(num1//num2))
# 2. String คือ สายอักขระ หรือประโยค ก็คือข้อความนั่นแหละ
myString = 'hello world'
# การจัดการ string
firstName = "Sorawut"
lastName = "Wichahong"
# 2.1 เอา String มาต่อกันได้ด้วยการ +
fullName = firstName + ' ' + lastName
# My fullname: Sorawut Wichahong
print("My fullname: {} {}".format(firstName, lastName))
num1 = "1"
num2 = "2"
num3 = num1+num2
print(num3)
# การ casting คือการแปลงชนิดข้อมูล
num3 = int(num1)+int(num2)
print(num3)
myBirthYear = "2548"
current = "2561"
age = int(current) - int(myBirthYear)
# my birth year is 2548, current year is 2561 so my age is 13
print(age)
print("my birth year is {}; current tear is {} so my age is {}".format(myBirthYear,current,age))
# 2.2 ต้องการส่วนหนึ่งของ string
myString = "hello world"
print("ตัดสตริง: {}".format(myString[4:9])) # o wor เอาต้งแต่ตำแหน่งที่ 4 แต่ไม่ถึง 9
# 2.3 นับความยาวของ string
print("{} มี {} ตัวอักษร".format(myString, len(myString)))
# 3. ชนิดข้อมูล List
myList = [] # การประกาศลิส
myGameList = ['minecraft', 'ROV', 'APB']
print("my first game: {}".format(myGameList[1:3]))
# 3.1 การเพิ่มของเข้าไปใน List เราจะใช้คำสั่งว่า append()
myGameList.append('DECEIT')
print(myGameList)
# 3.2 การเอา List มารวมกัน
fahGameList = ['APB','the sims','DECEIT']
sumList = myGameList + fahGameList
print(sumList)
# 3.3 การเอาของออกจาก List จะใช้วิธี เช่น ต้องการเอาเกมแรกออกจากลิส myGameList = myGameList[1:3] หรือใช้คำสั่ง remove()
myGameList.remove('minecraft')
print("new list after remove first item: {}".format(myGameList))
# Assignment 1
# 1.ให้สร้างไฟล์ 1.bmi.py
# 2. สร้างตัวแปร น้ำหนัก(กิโลกรัม) กับ ส่วนสูง(เมตร)
# 3. bmi = น้ำหนัก/ส่วนสูง ยกกำลังสอง
# Assignment 2
# 1. องศาฟาเรนไฮต์ °F = (1.8 × °C) + 32 ให้องศาเซลเซียสมา แล้วแปลงไปเป็นองศาฟาเรนไฮ เช่น 0 เซลเซียส = 32 ฟาเรนไฮ
# 2. องศาเซลเซียส °C = (F - 32) x 5/9 ให้องศาฟาเรนไฮมา แล้วแปลงเป็นองศาเซลเซียส เช่น 32 ฟาเรนไฮ = 0 เซลเซียส
|
7390c61245dd220d6047e3ec5d7e9600c008a003 | aharri64/python_scripting | /Recursion/pretty_print.py | 700 | 4.46875 | 4 | # Pretty print a dictionary structure
# Input: A dictionary and a string
# Output:
# Purpose: Pretty print a dictionary structure
def pretty_print(dictionary, indent=""):
# iterate through every key in the dictionary
for key in dictionary:
# get the value associated with the key
val = dictionary[key]
# check the type of the key to see if it's another dict
if isinstance(val, dict):
print(f"{indent}{key}:")
pretty_print(dictionary[key], indent + " ")
else:
# it's the val isn't a dict then just print out they key and val
print(f"{indent}{key}: {val}")
o1 = {"a": 1, "b": 2}
print(pretty_print(o1))
|
a4958b9bb1e0eb6b727842106ab917848b342bfb | lizzzcai/leetcode | /python/backtracking/0051_N-Queens.py | 5,574 | 4.09375 | 4 | '''
26/03/2020
51. N-Queens - Hard
Tag: Backtracking
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
'''
from typing import List
# Solution
class Solution1:
def solveNQueens(self, n: int) -> List[List[str]]:
# if can put queen in board[row][col]
def is_valid(board, row, col):
# check upper
i = row-1
while i >= 0:
if board[i][col] == 'Q':
return False
i -= 1
# check up left
i, j = row-1, col-1
while i >=0 and j >= 0:
if board[i][j] == 'Q':
return False
i -= 1
j -= 1
# check up right
i, j = row-1, col+1
while i >=0 and j < len(board[0]):
if board[i][j] == 'Q':
return False
i -= 1
j += 1
return True
def backtrack(board, row):
# terminate if row reach the end
if row == len(board):
res.append([''.join(row) for row in board])
return
for c in range(len(board[0])):
# if valid, no two queens attach each other
if is_valid(board, row, c):
# make selection, each col in ROW
board[row][c] = 'Q'
# go to next row
backtrack(board, row + 1)
# revoke selection
board[row][c] = '.'
board = [['.' for _ in range(n)] for _ in range(n)]
res = []
backtrack(board, 0)
return res
class Solution2:
def solveNQueens(self, n: int) -> List[List[str]]:
'''
Time:O(N!)
Space: O(N)
'''
def is_valid(board, row):
for i in range(row):
# check if queen in same colum or diagonal
if board[i] == board[row] or abs(board[i]-board[row]) == row-i:
return False
return True
def backtrack(board, row):
# terminate if row reach the end
if row == len(board):
tmp = "."*len(board)
res.append([tmp[:i]+"Q"+tmp[i+1:] for i in board])
return
for col in range(len(board)):
# make selection, each col in ROW
board[row] = col
# if valid, no two queens attach each other
if is_valid(board, row):
# go to next row
backtrack(board, row + 1)
board = [-1]*n
res = []
backtrack(board, 0)
return res
class Solution3:
def solveNQueens(self, n: int) -> List[List[str]]:
'''
Time:O(N!)
Space: O(N)
diags (row_idx - col_idx):
3 | 3 2 1 0
2 | 2 1 0 -1
1 | 1 0 -1 -2
0 | 0 -1 -2 -3
r ------------
c 0 1 2 3
off_diags (row_idx + col_idx):
3 | 3 4 5 6
2 | 2 3 4 5
1 | 1 2 3 4
0 | 0 1 2 3
r ------------
c 0 1 2 3
'''
def backtrack(board, row):
# terminate if row reach the end
if row == len(board):
res.append([tmp[:i]+"Q"+tmp[i+1:] for i in board])
return
for col in range(len(board)):
# make selection, each col in ROW
board[row] = col
# check if no two queens on the rows or diags
if col not in cols and row-col not in diags and row+col not in off_diags:
# go to next row
cols.append(col)
diags.append(row-col)
off_diags.append(row+col)
backtrack(board, row + 1)
cols.pop()
diags.pop()
off_diags.pop()
board = [-1]*n
tmp = "."*len(board)
cols = []
diags = []
off_diags = []
res = []
backtrack(board, 0)
return res
# Unit Test
import unittest
class TestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_testCase(self):
for Sol in [Solution1(), Solution2(), Solution3()]:
func = Sol.solveNQueens
out = [
[".Q..",
"...Q",
"Q...",
"..Q."],
["..Q.",
"Q...",
"...Q",
".Q.."]
]
self.assertEqual(set(tuple(x) for x in func(4)), set(tuple(x) for x in out))
if __name__ == '__main__':
unittest.main() |
ea2064d4f281bb8cc353af8d43cad0915efba640 | chrisdawww/adventofcode2020 | /9/xmas.py | 1,309 | 3.765625 | 4 | """
Day 9
XMAS "encryption"
Part 1: Find the first number where there aren't two numbers in the previous
25 which sum to it
Part 2: Find a contiguous set of numbers which add to the target found from
the first part
"""
def part1(nums):
for i in range(len(nums)):
preamble = nums[i:i+25]
target = nums[i+25]
if not check_preamble(target, preamble):
return target
return -1
def check_preamble(target, preamble):
for i, num in enumerate(preamble):
need = target - num
if need in preamble:
return i, preamble.index(need)
return False
def part2(target, nums):
# Start at the beginning of the array, then from 2, work our way up until
# we're at or over the target
for i, start_num in enumerate(nums):
for length in range(2, len(nums)-i-1):
contig_set = nums[i:i+length]
contig_sum = sum(contig_set)
if contig_sum == target:
return sum([min(contig_set), max(contig_set)])
if contig_sum > target:
break
return -1
if __name__ == "__main__":
with open('input.txt', 'r') as f:
numbers = [int(l.strip()) for l in f.readlines()]
#ans = part1(numbers)
target = 85848519
print(part2(target, numbers))
|
7c408ca7f0d13764d71d8f6cd1c934a3ef8fd557 | Sukhrobjon/CS-2.1-Trees-Sorting | /Code/prefixtree.py | 9,340 | 4.28125 | 4 | #!python3
from prefixtreenode import PrefixTreeNode
class PrefixTree:
"""
PrefixTree: A multi-way prefix tree that stores strings with efficient
methods to insert a string into the tree, check if it contains a matching
string, and retrieve all strings that start with a given prefix string.
Time complexity of these methods depends only on the number of strings
retrieved and their maximum length (size and height of subtree searched),
but is independent of the number of strings stored in the prefix tree, as
its height depends only on the length of the longest string stored in it.
This makes a prefix tree effective for spell-checking and autocompletion.
Each string is stored as a sequence of characters along a path from the
tree's root node to a terminal node that marks the end of the string.
"""
# Constant for the start character stored in the prefix tree's root node
START_CHARACTER = ''
def __init__(self, strings=None):
"""Initialize this prefix tree and insert the given strings, if any."""
# Create a new root node with the start character
self.root = PrefixTreeNode(PrefixTree.START_CHARACTER)
# Count the number of strings inserted into the tree
self.size = 0
# Insert each string, if any were given
if strings is not None:
for string in strings:
self.insert(string)
def __repr__(self):
"""Return a string representation of this prefix tree."""
return f'PrefixTree({self.strings()!r})'
def is_empty(self):
"""Return True if this prefix tree is empty (contains no strings)."""
return self.size == 0
def insert(self, string):
"""Insert the given string into this prefix tree."""
# check if tree has current string
if not self.contains(string):
# print(f"inserting: {string}")
node = self.root
for char in string:
# check if the current char is already exists, if so skip the char
if char.isalpha():
char = char.upper()
else:
continue
# check if node has child for char
if not node.has_child(char):
# create a child node to be added
child_node = PrefixTreeNode(char)
# add the child node as a child to the current node
node.add_child(char, child_node)
# print(f"node: {node}: new child node: {child_node}")
# child already exists, so we just continue traversing down
else:
child_node = node.get_child(char)
# print(f'child node is there: {child_node}')
# update the current node always
node = child_node
# set the last char in the string as a terminal node
node.terminal = True
# print(f"inserted: {string}")
# increment the size by 1 once we inserted the whole string
self.size += 1
else:
print(f'String: {string} is already in the tree!')
def contains(self, string):
"""
Return True if this prefix tree contains the given string.
Args:
string(str): string to be searched in tree
"""
node, _ = self._find_terminal_node(string)
# print(f"last node in contains: {node}")
return node is not None
def complete(self, prefix=''):
"""
Return a list of all strings stored in this prefix tree that start
with the given prefix string.
"""
node = self._find_prefix(prefix)
if not node:
return []
completions = []
if not self.is_empty():
self._traverse(node, prefix, completions.append)
# print(f"completion in complete: {completions}")
return completions
def _traverse(self, node, prefix, visit):
"""
Traverse this prefix tree with recursive depth-first traversal.
Start at the given node and visit each node with the given function.
"""
# base case.
if node.terminal:
# prefix is now whole word
visit(prefix)
for child in node.children:
if child is not None:
# print(f"prefix+char: {prefix+child.character}")
self._traverse(child, prefix+child.character, visit)
def _find_terminal_node(self, string):
"""
Return a tuple containing the node that terminates the given string
in this prefix tree and the node's depth, or if the given string is not
completely found, return None and the depth of the last matching node.
Search is done iteratively with a loop starting from the root node.
"""
# Match the empty string
if len(string) == 0:
# print(f"string is empty!")
return self.root, 0
# Start with the root node
node = self.root
for index, char in enumerate(string):
# print(f"find node not working! for => {string}")
# check if the node has that child
if node.has_child(char):
child_node = node.get_child(char)
# found last matching node in the tree
else:
# print(f"find the unmatch {node}")
return None, index
# update the child node
node = child_node
# check for if last node is terminal node, to make sure for
# overlapping words e.g. there is string 'ABCD' and if we look for
# 'ABD' even though ABC is part of ABCD and in the tree, 'C' is not
# a terminal node so it is considered it is not in the tree
if node.terminal:
return node, index + 1
else:
return None, index + 1
def strings(self):
"""Return a list of all strings stored in this prefix tree."""
# complete all elements
return self.complete()
def _find_prefix(self, prefix):
"""
Return the node that terminates the given string in this prefix tree
or if the given string is not completely found, return None.
Search is done iteratively with a loop starting from the root node.
"""
# Match the empty string
if len(prefix) == 0:
print(f"prefix is empty!")
return self.root
# Start with the root node
node = self.root
for _, char in enumerate(prefix):
# check if the node has that child for curr char
if node.has_child(char):
child_node = node.get_child(char)
# found first unmatching node in the tree
else:
return None
# update the child node
node = child_node
return node
def create_prefix_tree(strings):
print(f'strings: {strings}')
tree = PrefixTree()
print(f'\ntree: {tree}')
print(f'root: {tree.root}')
print(f'strings: {tree.strings()}')
print('\nInserting strings:')
for string in strings:
tree.insert(string)
print(f'\ntree: {tree}')
print(f'root: {tree.root}')
print('\nSearching for strings in tree:')
for string in sorted(set(strings)):
result = tree.contains(string)
print(f'contains({string!r}): {result}')
print('\nSearching for strings not in tree:')
prefixes = sorted(set(string[:len(string)//2] for string in strings))
# for prefix in prefixes:
# if len(prefix) == 0 or prefix in strings:
# continue
# result = tree.contains(prefix)
# print(f'contains({prefix!r}): {result}')
# print(f'\nFinding the last node of prefix:')
# # prefixes = sorted(set(string[:len(string)//2] for string in strings))
# for prefix in prefixes:
# if len(prefix) == 0 or prefix in strings:
# continue
# result = tree._find_prefix(prefix)
# print(f'_find_prefix({prefix!r}): {result}')
print('\nCompleting prefixes in tree:')
for prefix in prefixes:
completions = tree.complete(prefix)
print(f'complete({prefix!r}): {completions}')
print('\nRetrieving all strings:')
retrieved_strings = tree.strings()
print(f'strings: {retrieved_strings}')
matches = set(retrieved_strings) == set(strings)
print(f'matches? {matches}')
if __name__ == '__main__':
# Create a dictionary of tongue-twisters with similar words to test with
tongue_twisters = {
'Seashells': 'Shelly sells seashells by the sea shore'.upper().split(),
# 'Peppers': 'Peter Piper picked a peck of pickled peppers'.upper().split(),
# 'Woodchuck': ('How much wood would a wood chuck chuck'
# ' if a wood chuck could chuck wood').upper().split()
}
# Create a prefix tree with the similar words in each tongue-twister
for name, strings in tongue_twisters.items():
print('\n' + '='*80 + '\n')
print(f'{name} tongue-twister:')
print(f"strings: {strings}")
create_prefix_tree(strings)
|
57aec935fccd0d5010e033999fe73216b13f2369 | danitrave/BurrowsWheelerTransform | /BURROWS_WHEELER_TRANSFORM/bwt.py | 12,380 | 4.28125 | 4 | ##This algorithm is the implementation of the one for a Burrows-Wheeler transform that allows to convert the genome sequence in a compact string.
##The algorithm must be run on the terminal using python version 3.7 to have a more clear and user-friendly visualization.
##The program asks the user to insert a genome string. Then the algorithm will create the Burrows-Wheeler transform (BWT). In the BWT we see the presence
##of an additional character "$" that is insert by the program, marking the end of the sequence (the character is not insered by the user). Once done that, the program
##will use the BWT to reverse the string and re-obtain the initial string that the user has insert by input. If the messaged visualized is YES, the reverse
##is equal to the initial string. If, otherwise, is NO the reverse is different from the initial string. Then the algorithm will ask the user to insert
##a substring in a way to verify its presence and possibly its number of occurences. If present, the program will report the number of occurencs and its
##range (initial and final index in which the subsequence is found) in the sequence. If, otherwise, the subsequence is not present,
##the program will confirm its absence in the genome sequence.
matrixRot = [] #all these variable are global since they are used and updated by different functions
F = '' #last colum containing the last character of each rotation (so our BWT) used for reverse formation and string matching
L = '' #first colum containing the first character of each rotation used for reverse formation and string maching
lastCol = [] #same as the two previous ones but seen as a list of tuples reporting the character and the position
firstCol = [] #for each kind of character. So if A occurs 3 times, the number associated to each A will be: 0,1,2 or 3
array = tuple() #array reporting offsets
def ranker(volatile,i):
if i == '$': #if the last character is the special one
output = '$' #just report it
return output
else: #if the last character is a string charcter (not the special one)
output = volatile.count(i) - 1 #count the number of that kind of character in the slice selected -1 since indexes start from 0 and not 1
return output
def suffix(M): #this function calculates the offset of each substring of the input string reported as first character from the special charater "$" from each cyclic rotation
global array
for t in M: #select the rotation from the matrix
i = 1
suffix = len(t) #take the length of each rotation
while True:
if t[i-1] == '$': #if the charatcer is the special one
suffix = suffix - i #calculate offset subtracting the current positon to the total length of the cyclic rotation length
array += (suffix,) #add the result to the array
break #stop execution when "$" is found
else:
i += 1 #keep on elongating the offset as the special character is not found
return array #return the array containing all offsets
def cyclicRotations(T): #this funciton use the sequence to build the cyclic rotaions
global matrixRot
TT = T * 2
matrixRot = [TT[i:i+len(T)] for i in range(0,len(T))] #built cyclic rotations
matrixRot = sorted(matrixRot) #sort the rotations in lexycographic order
array = suffix(matrixRot) #use the matrix reporting all cyclic rotations as strings to build an array reporting the offset of each rotation
return matrixRot #Burrows-Wheeler matrix (BWM)
def BWT(T): #this function computes the BWT
global F
global L
T = T + '$' #add special character at the end of the string
rotations = cyclicRotations(T) #build cyclic rotations
for e in rotations: #of each cyclic rotation take the first character and the last one to get
L += e[-1] #the last column of the matrix, so our BWT
F += e[0] #the first column
return L
def firstColRank(F,LL): #this function ranks the characters of the first column of the BWM
global firstCol #use the first column. We can do in this way since characters of a kind of the first column
for y in F: #have the same rank-order of the character of a kind in the last column --> LM-mapping rule
j = 0
while True:
currentCell = tuple() #tuple that will collect the character and the rank
if LL[j][0] == y: #take the first element of the last column-ranked and the first one of the first column not ranked
currentCell = (y,) + (LL[j][1],) #associate the same rank of the first character of a kind of the last column to the first character of the first column of kind
firstCol += (currentCell,) #build up the new character-rank first column
LL.remove(LL[j]) #remove the character of the last column that we have seleced to avoid ambiguos and repetitive ranking of the first column
break #stop while loop
else:
j += 1 #go to the next character
return firstCol
def T_ranking(): #this function builts the ranks of the first and last column of the BWM
global lastCol
ranking_L = [] #collector for the ranks of the last characters
i = 0
for v in matrixRot:
slicer = v.find('$') #find the index of the special character at each rotation
volatile = v[slicer:] #take the section fo each rotation starting from the special charater up to the end of the string
currentRank = ranker(volatile,L[i]) #rank the last character of each cyclic rotation in the matrix
ranking_L += [currentRank,] #add the current
i += 1
i = 0
while i != len(L): #build the list of tuples reporting the character and the rank of that character
currentCell = (L[i],) + (ranking_L[i],) #create the current character-rank tuple
lastCol += (currentCell,) #add it to the the new lst column
i += 1
LL = lastCol[:] #make a copy to avoid unwanted alliasing effects of the last column-rank
firstCol = firstColRank(F,LL) #build rank of the characters of the first column using the last column (character-rank) as reference
return firstCol,lastCol #report the first and the last columns each seen as a list of charcter-rank tuples
def reverseBWT(T): #this function reverse the BWT to get the original strinf
colums = T_ranking() #use first as a sort of guide line and last column to get the reverse
reverse = ''
guard = colums[1][0] #the starting point is the first character of the last column
while guard != ('$','$'): #until you do not have the special character
reverse += guard[0] #add current character of the last character
index = colums[0].index(guard) #use the first column as an array to get the index of the column having the same character of the last column
guard = colums[1][index] #move to the character of the last column at the index that we just found before.
return reverse[::-1] #get reverse
def stringMatch(P): #This functions takes a string as parameter and returns the number of its occurences in the string and the range of the match
global firstCol
global lastCol
global array
i = len(P)-1 #start from the last character of the string i want to match
start = []
suffix = P[i] #the last character of the string i want to match is my new suffix
for x in range(len(firstCol)): #consider all elements in the ranked last column
vol = tuple()
if firstCol[x][0] == suffix: #if the character of the last column-ranked is equal to our suffix
vol = (firstCol[x],) + (x,) #collect it. It will be one of the possible starting points from which i start to match the remainig characters of my string
start += (vol,)
if len(P) == 1: #in the case in which the substring is rapresented by one character only
indexForRange = [] #the occurrences are present in the initials point extrapolated from the first column-ranked
count = 0
if len(start) == 0: #of course i evaluate the occurences of the unique character only if it is present the the string
return count,indexForRange
else:
for char in start: #if it is present at least one time in the string
count += 1 #i collect the number of occurences of it
index = firstCol.index(char[0]) #and i collect the occurence position the the BWM
indexForRange += [index,] #to then use it to extrapolate the range of the occurences
else: #if, otherwise, the substring is made of more then one character
count = 0
indexForRange = [] #initialize a list that will contain the ranges of the occurences of the substring
for e in start: #start form the first possible element that may lead to a complete match of th substring
i = len(P)-1 #set as suffix the slice of the substring: as long as a match is found, the slice is increased un to get the whole sequence when its value is 0
index = e[1] #set the value of the first current colomn-rank
while True:
i = i - 1 #move to the next character of the substring. The current suffix length will be increased
guard = lastCol[index] #select the character of the last column-ranked localized in the same index as the character of the first column-rank
if guard[0] == P[i]: #if the character of the tuple of last column-ranked is equal to the current character of the suffix
index = firstCol.index(guard) #go on to the new character
if i == 0: #when the suffix reaches the max lenth, means that you found a match
indexForRange += [index,] #select the index of the BWM where the last character of the substring has been matched
count += 1 #keep on track of the number of matches you found
break
else:
break #if no match is found, go to next starting point
rangeSub = [] #list that will be filled with lists each reporting the start-end index of each match per substring found
for r in indexForRange:
rank = [] #range of the current match. The range is evaluated as python indexes. So the last charater is index -1
loc = array[r] #use the array to report the offset of a string in a given position
rank = [loc,(loc+len(P)-1)] #select start and end of the occurence
rangeSub += [rank,] #add current range
return count,sorted(rangeSub) #report number of occurences and for each, the range in the string
T = input('Insert the string to get its BWT:')
T = T.upper()
BWT = BWT(T)
print('The BWT obtained is:',BWT)
reverse = reverseBWT(T)
print('Using the BWT, the reverse string obtained is:',reverse)
if reverse == T:
result = True
else:
result = False
if result == True:
print('Is the reverse string that we got equal to the original string? YES')
else:
print('Is the reverse string that we got equal to the original string? NO')
subString = input('Insert the substring for which you want to find the occurence/s:')
subString = subString.upper()
match = stringMatch(subString)
if match[0] != 0:
print('The substring occurs in the string',match[0],'times at index/s',match[1])
else:
print('The substring insered is not present in the string')
|
7bb20b96667672cbe7939d7757e67ca78970bc41 | zhouxinmin/Strip-Packing-Problem | /daily/study/practise/shixi/test.py | 1,795 | 3.5625 | 4 | # ! /usr/bin/env python
# -*- coding: utf-8 --
# ---------------------------
# @Time : 2017/3/10 19:03
# @Site :
# @File : test.py
# @Author : zhouxinmin
# @Email : 1141210649@qq.com
# @Software: PyCharm
import sys
import copy
# num = sys.stdin.readline().strip()
# num_list = list(num)
# real_num = 0
# for index, value in enumerate(num_list):
# real_num += int(value) * pow(7, len(num_list) - index-1)
# print (real_num)
import copy
# def ke_zi(num_list):
# if num_list[0] == num_list[1] == num_list[2]:
# return 1
# else:
# return 0
#
# def shun_zi(num_list):
# if int(num_list[0]) +2 == int(num_list[1]) +1 == int(num_list[2]):
# return 1
# else:
# return 0
#
# def dui_zi(num_list):
# len_list = len(num_list)
# tem = []
# for index, value in enumerate(num_list):
# while index+1 < len_list:
# if num_list[index] == num_list[index+1]:
# duizi = num_list[index: index+2]
# last = num_list.remove(duizi)
# tem.append([duizi, last])
num = sys.stdin.readline().strip()
num_list = list(num)
if len(num_list) == 2:
if num_list[0] == num_list[1]:
print ("yes")
else:
print ("no")
if len(num_list) == 5:
tem_list = copy.deepcopy(num_list)
if len(set(tem_list)) == 5:
print ("no")
else:
b = [x for x in num_list if num_list.count(x) == 1]
c = set(b) ^ set(tem_list)
if len(b) == 0:
print ("yes")
elif len(b) == 1:
print ("no")
elif len(b) == 2:
print ("no")
elif len(b) == 3:
b.sort()
if int(b[0])+2 == int(b[1]) +1 == int(b[2]):
print ("yes")
else:
print ("no")
|
5709a20758e62ec61a63865bfbb1e71afb9a5964 | bong1915016/Introduction-to-Programming-Using-Python | /evennumberedexercise/Exercise11_02.py | 497 | 3.71875 | 4 | def main():
matrix = []
for i in range(4):
s = input("Enter a 4-by-4 matrix row " + str(i) + ": ")
items = s.split() # Extracts items from the string
list = [ eval(x) for x in items ] # Convert items to numbers
matrix.append(list)
print("Sum of the elements in the major diagonal is", sumMajorDiagonal(matrix))
def sumMajorDiagonal(m):
sum = 0
for i in range(len(m)):
sum += m[i][i]
return sum
main()
|
13ff45bda1f369d31a7997dbbca9c5a99bb0e7b5 | DropthaBeatus/Python_GameMaster | /Game_Time/Pieces.py | 822 | 3.625 | 4 | import random
import copy
import json
class Card:
def __init__(self, value, suite, card_name, code, color):
self.value = value
self.suite = suite
self.card_name = card_name
self.code = code
self.color = color
class Deck:
cards = []
def __init__(self):
with open('../JSON/cards.json') as f:
data = json.load(f)
for n in data:
self.cards.append(Card(n["value"], n["suit"], n['card_name'], n['code'], n['color']))
self.shuffle_deck()
def print_cards(self):
for n in self.cards:
print(n.cardName + " of " + n.suite)
def shuffle_deck(self):
random.shuffle(self.cards)
def draw_card(self):
draw = copy.deepcopy(self.cards[0])
self.cards.pop(0)
return draw
|
78a4623a68ac759093d7740ec6bf2ce9cbe37fe7 | ErnestoDibia/Team-Sanger | /Gladys_python.py | 711 | 3.65625 | 4 | #!/usr/bin/env python3
#Defining my variables
#Name
Name = "Gladys Rotich"
#Email address
Email_address = "gladysjerono86@gmail.com"
#Slack username
Slack_username = "@Gladys"
#Preferred biostack
Biostack = "Genomics, Data Science"
#Twitter handle
Twitter="@jerono7_gladys"
#Finding the hamming distance
def hammingDist(Slack_username,Twitter):
i=0
count=0
while (i<len(Slack_username)):
count +=1
i +=1
return count
hammingDistance=hammingDist(Slack_username,Twitter)
#Printing each output on a new line
print("Name: {}\nEmail_address: {}\nSlack_username: {}\nBiostack: {}\nTwitter: {}\nhammingDistance: {}".format(Name, Email_address ,
Slack_username , Biostack , Twitter, hammingDistance))
|
dea54043661a6a0bd7cceb73f427c982965b59eb | kritikyadav/Practise_work_python | /if-else/ifelse6.py | 174 | 4 | 4 | a=int(input('year= '))
if a%4==0 and a%100==0:
print('is a leap year')
elif a%4==0 and a%100!=0:
print('is a leap year')
else:
print('is not a leap year')
|
2e2e5aff1e814d7942bb81d078d932a7f586def6 | GudiedRyan/day_1 | /main.py | 2,225 | 4.21875 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"milk": 0,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0
}
def coffee_machine():
user_input = input("What would you like? (espresso/latte/cappuccino): \n").lower()
if user_input == "off":
print("Shutting off. Goodbye!")
return 0
elif user_input == "report":
print("Water: " + str(resources["water"])+"ml")
print("Milk: " + str(resources["milk"])+"ml")
print("Coffee: " + str(resources["coffee"])+"g")
print("Money: $" + str(resources["money"]))
elif user_input == "latte" or user_input == "espresso" or user_input == "cappuccino":
for ingredient in ["water", "milk", "coffee"]:
if MENU[str(user_input)]["ingredients"][ingredient] > resources[ingredient]:
print("Sorry, there is not enough" + [ingredient])
break
print("Please insert coins")
quarters = int(input("How many quarters? "))
dimes = int(input("How many dimes? "))
nickels = int(input("How many nickels? "))
pennies = int(input("How many pennies? "))
total = .25*quarters + .1*dimes + .05*nickels + .01*pennies
if total < MENU[user_input]["cost"]:
print("Sorry that's not enough money. Money refunded.")
return 0
difference = total - MENU[user_input]["cost"]
resources["money"] += MENU[user_input]["cost"]
if difference > 0:
print("Your change is",difference)
for ingredient in ["water", "milk", "coffee"]:
resources[ingredient] -= MENU[str(user_input)]["ingredients"][ingredient]
print("Here is your " + user_input + " Have a nice day!")
coffee_machine()
coffee_machine()
|
667134240639a296d1ddbeae3b4743684fa6542b | mashpolo/leetcode_ans | /500/leetcode506/ans.py | 845 | 3.546875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
@desc:
@author: Luo.lu
@date: 2018-11-16
"""
class Solution:
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
nums_bak = sorted(nums)
map_rs = {}
for (index, x) in enumerate(nums_bak):
if index + 3 == len(nums_bak):
map_rs[x] = "Bronze Medal"
elif index + 2 == len(nums_bak):
map_rs[x] = "Silver Medal"
elif index + 1 == len(nums_bak):
map_rs[x] = "Gold Medal"
else:
map_rs[x] = str(len(nums) - index)
res = []
for x in nums:
res.append(map_rs[x])
return res
if __name__ == '__main__':
A = Solution()
print(A.findRelativeRanks([5, 4, 3, 2, 1]))
|
11d41b600ae5aaf0d16df22ca822940e80e4f484 | jeen0404/Text-to-speech-python | /entertext.py | 1,387 | 4.03125 | 4 | from gtts import gTTS
from playsound import playsound
import playmp3
#here you can add wellcome sound
'''
wellcome=""
playsound(wellcome)
'''
#this function is use to take input from user
def entertext():
text=str(input("enter the text"))
return text
#this is our main function it convert string into mp3 file
def prosess(name):
a=name #it,s value of we passed from while loop
path=str(a+'.mp3')#here we add to string and .mp3 extention
print(path)
text=entertext()#here we call entertext function and take input from user
t=str("")#here we define empty string
if(text==t): #here we check user text is empty or not if condition is true we call again entertext function
print("enter ext first")
entertext()
else: #if user is write some text then we convert it into voice or mp3 usein gtts here
tts = gTTS(text=text, lang='en')
tts.save(path)
playmp3.speek(path) #here we call the function of other file name is playmp3 where it play and delete
#we defaine a and convert into string because if we use only one name then the gtts will give us error so we change the name of mp3 every time
a=0
while 1 :#we use while loop because we can't open file every time
a=a+1
b=str(a)
prosess(b)#were the value of a passed to prosess function
|
5a515700c6a379d58b4033c64b80b4d3959dcaa1 | wp6530/studypython | /01python基础/进程线程协程/线程04线程同步.py | 1,108 | 3.671875 | 4 | # -*- coding = utf-8 -*-
import threading
import time
import random
# lock = threading.Lock()
# list1 = [0] * 10
#
#
# def task1():
# # lock.acquire()
# for i in range(len(list1)):
# list1[i] = 1
# time.sleep(0.5)
# # lock.release()
#
#
# def task2():
# # lock.acquire()
# for i in range(len(list1)):
# print(list1[i])
# time.sleep(0.5)
# # lock.release()
#
#
# if __name__ == '__main__':
# t1 = threading.Thread(target=task1, name='task1')
# t2 = threading.Thread(target=task2, name='task2')
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# print(list1)
lockA = threading.Lock()
lockB = threading.Lock()
class Mythread(threading.Thread):
def run(self):
if lockA.acquire():
print(self.name + 'get lock A')
time.sleep(1)
if lockB.acquire():
print(self.name + 'get lock B,and also have lock A')
lockA.release()
lockB.release()
if __name__ == '__main__':
t1 = Mythread()
t2 = Mythread()
t1.start()
t2.start()
|
0ab27fcc067c8d104f58fe80f9abb60768921b67 | mauricio-velasco/min-cross-entropy | /optimalTransports.py | 13,959 | 3.765625 | 4 | '''
Created on May 14, 2021
@author: mvelasco
'''
import numpy as np
import pdb
import time
import numpy as np
import matplotlib.pyplot as plt
class Empirical_Measure:
"""
An empirical measure is determined by a list of data points (self.data_vectors)
in some R^n. n=self.dim. Represents the sum of Dirac deltas at these data points.
An empirical measure is capable of:
-Acting on functions by integration (integrate)
-Find the index of nearest data point to a given new point (nearest_data_point_index).
the notion of distance used is specified in self.distance.
-Classify_nearest (for each vector on a list returns the vector in self.data_vectors closest to it)
"""
def __init__(self, data_points_vector):
self.data_vectors = []
self.ndata_vectors = len(data_points_vector)
assert(self.ndata_vectors>0)
#Receives an array of vectors corresponding to the observations x_i
first =True
for vector in data_points_vector:
if first:
first=False
self.dimension = len(vector)
assert(len(vector) == self.dimension)
self.data_vectors.append(np.array(vector))
self.dim = self.dimension
def integrate(self,fn):
Result = []
for vector in self.data_vectors:
Result.append(fn(vector)*(1/self.ndata_vectors))
return np.sum(Result)
class Probability_Measure:
"""
We represent probability measures via black box routine that produces independent samples from
this distribution and an analytic formula for its density wrt Lebesgue.
A probability measure is capable of:
-Producing an independent sample of the random variable.
-Acting on functions by integration (integrate via MonteCarlo)
-evaluate the corresponding probability density function
"""
def __init__(self, sample_q_fn, density_fn):
self.sample_q_fn = sample_q_fn
self.density_fn = density_fn
def sample_q(self, numsamples):
return self.sample_q_fn(numsamples)
def integrate(self, fn):
points = self.sample_q(self.MC_points)
return np.average([fn(p) for p in points])
def evaluate_density_fn(self,vector):
return(self.density_fn(vector))
class Weighted_Voronoi_Diagram:
"""A weighted Voronoi diagram is specified by:
-a collection of centers
-with a corresponding vector of weights, one per center which sum to zero (\lambdas in the article)
-An ambient distance function
It should be capable of:
(1) Given a new vector find the index of the weighted nearest center+
(2) Given a collection of vectors count the fraction of these points in each of the weighted voronoi cells.+
(3) Given a collection of vectors and a (u,v) distortion, count the fraction of these points
in each of the weighted voronoi cells.+
"""
def __init__(self, centers_array, weights_vector, distance_fn):
self.centers = []
self.distance = distance_fn
self.ncenters = len(centers_array)
#Receives an array of vectors corresponding to the centers of the Weighted Voronoi
first =True
for vector in centers_array:
if first:
first=False
self.dim = len(vector)
assert(len(vector) == self.dim)
self.centers.append(np.array(vector))
self.weights = weights_vector
assert(len(self.centers) == len(self.weights))
def index_weighted_cell_of(self, vector):
#Given a new vector find the index of the weighted nearest center
N = self.ncenters
weighted_distances = np.array([self.distance(vector, self.centers[k])-self.weights[k] for k in range(N)])
index = np.where(weighted_distances == np.min(weighted_distances))[0]
return(index[0])
def minimal_weighted_distance_to_data_point(self,vector):
N = self.ncenters
weighted_distances = np.array([self.distance(vector, self.centers[k])-self.weights[k] for k in range(N)])
return(np.min(weighted_distances))
def compute_array_minimal_weighted_distances(self, vectors_array):
distances_vector = np.zeros(len(vectors_array))
for k, vector in enumerate(vectors_array):
distances_vector[k] = self.minimal_weighted_distance_to_data_point(vector)
return(distances_vector)
def compute_array_index_weighted_cell_of(self,vectors_array):
indices_vector = np.zeros(len(vectors_array))
for k, vector in enumerate(vectors_array):
indices_vector[k] = self.index_weighted_cell_of(vector)
return(indices_vector)
def compute_proportions_in_cells(self, vectors_array, gradient=False):
#Given a collection of vectors count the fraction of these points in each of the weighted voronoi cells
region_counts_vector = np.zeros(self.ncenters)
for vector in vectors_array:
idx = self.index_weighted_cell_of(vector)
region_counts_vector[idx]+=1
if gradient:
return (-1)*(region_counts_vector/len(vectors_array)-(1/self.ncenters))
else:
return region_counts_vector/len(vectors_array)
#The distorted weights below are needed for computing Theorem 1.3 b
def uv_distorted_weight(self,vector, UVvector):
N = self.ncenters
weighted_distances = np.array([self.distance(vector, self.centers[k])-self.weights[k] for k in range(N)])
phi_lambda = np.min(weighted_distances)
u=UVvector[0]
v=UVvector[1]
return(np.exp(-1-v*phi_lambda-u))
def compute_array_uv_distorted_weights(self, vectors_array, UVvector):
distorsions_vector = np.zeros(len(vectors_array))
for k, vector in enumerate(vectors_array):
distorsions_vector[k] = self.uv_distorted_weight(vector, UVvector)
return(distorsions_vector)
def compute_gradient_from_distorted_averages_in_cells(self, vectors_array, UVvector):
"""Given a collection of vectors and a u,v pair compute the average of the uv-distorted distribution in each weighted Voronoi cell"""
N_samples=len(vectors_array)
distortions_vector = self.compute_array_uv_distorted_weights(vectors_array, UVvector)#computes the value of exp(-1-v\phi(z)-u) for z in sample
indices_vector = self.compute_array_index_weighted_cell_of(vectors_array)# Finds the nearest center to each sample point
#Next we go compute the average of the values in each region. Results are stored in region_values_vector
region_values_vector = np.zeros(self.ncenters)
for k in range(self.ncenters):
active_indices = np.where(indices_vector==k)
if active_indices[0].size > 0:
region_values_vector[k] = np.sum(distortions_vector[active_indices])/N_samples
#Finally we return the numerically computed gradient.
return ((-1)*region_values_vector +1/self.ncenters)#Compute the gradient vector
def plot_WVD(self, namestring, num_points = 500):
plt.figure(dpi=150)
ax = plt.gca() #you first need to get the axis handle
ax.set_aspect(1.0)
M = num_points
#We will use an MxM grid of points
xvalues = np.linspace(0,1,num=M);
yvalues = np.linspace(0,1,num=M);
xx, yy = np.meshgrid(xvalues, yvalues)
g = lambda a,b: self.index_weighted_cell_of(np.array([a,b]))
Vg = np.vectorize(g)#Vectorization to be able to apply it to a numpy meshgrid
z = Vg(xx,yy)
plt.pcolormesh(xvalues, yvalues, z, cmap="RdYlBu_r")
#Next we plot the centers in black
Xs = [self.centers[k][0] for k in range(self.ncenters)]
Ys = [self.centers[k][1] for k in range(self.ncenters)]
plt.scatter(Xs, Ys, c="black", alpha=0.9)
#Finally we save the image and show it to screen
plt.savefig(namestring)
plt.show()
class Optimal_Transport_Finder:
""" This function finds an optimal transport between
an empirical measure and any probability measure q specified by a sampling function."""
def __init__(self, empirical_measure, probability_measure, distance_fn, num_MC):
#Check the input types:
assert(isinstance(empirical_measure,Empirical_Measure ))
self.empirical_measure = empirical_measure
assert(isinstance(probability_measure,Probability_Measure ))
self.probability_measure = probability_measure
weights = np.zeros(empirical_measure.ndata_vectors)
centers = empirical_measure.data_vectors
self.WVD = Weighted_Voronoi_Diagram(centers,weights,distance_fn)
self.bestLambdas = self.WVD.weights.copy()#Will keeptrack of the best lambdas so far.
self.num_MC = num_MC
self.best_objective_so_far = self.compute_objective()
self.best_weights_so_far = np.zeros(len(self.WVD.weights))
self.best_gradient_norm = 0
def compute_objective(self):
"""Computes the current \Psi(\lambda) with \lambda=self.WVD.weights"""
#Create a sample from our probability measure
sample_vectors_array = self.probability_measure.sample_q(self.num_MC)
#Evaluate the minimum weighted distance of each sampled point to the centers
min_distances = self.WVD.compute_array_minimal_weighted_distances(sample_vectors_array)
#Monte Carlo evaluation of the integral
return(np.average(min_distances))
def compute_gradient(self):
#Create a sample from our probability measure
sample_vectors_array = self.probability_measure.sample_q(self.num_MC)
gradient = self.WVD.compute_proportions_in_cells(sample_vectors_array, gradient=True)
return gradient
def do_gradient_descent(self, NumSteps, StepSize, keep_track_of_best = True, Descending_in_size=True):
#Do a gradient descent for NumSteps steps
for k in range(NumSteps):
weights = self.WVD.weights
gradient = self.compute_gradient()
if Descending_in_size:
CurrStepSize = StepSize/(1+np.sqrt(k))#
else:
CurrStepSize = StepSize
#gradient step
new_weights = weights + CurrStepSize * gradient
self.WVD.weights = new_weights
if keep_track_of_best:
objective = self.compute_objective()
grad_norm = np.linalg.norm(gradient)
print("Optimal transport descent computation step "+str(k)+":\n")
self.print_current_status(objective, grad_norm)
if objective > self.best_objective_so_far:
#if grad_norm < self.best_gradient_norm:# we are looking for points with Voronoi regions of constant uniform area
self.best_objective_so_far = objective
self.best_weights_so_far = new_weights
self.best_gradient_norm = np.linalg.norm(gradient)
#if we keep track of the best then we should set it as the chosen weights
if keep_track_of_best:
self.WVD.weights = self.best_weights_so_far
def print_current_status(self,curr_obj,curr_grad_norm):
print("_____________________________________________________________")
print("Curr_obj: " + str(curr_obj)+ "")
print("Curr_grad_norm: " + str(curr_grad_norm)+ "")
print("Best_obj: " + str(self.best_objective_so_far)+ "")
print("grad_norm_at_best: " + str(self.best_gradient_norm)+ "")
print("_____________________________________________________________")
"""PROTOTYPES FOR DISTANCE FUNCTION AND SAMPLING FUNCTION FOR SPECIFYING A DISTRIBUTION"""
def dist(x,y):
#Prototype for distance functions allowed. For now uses the l2-norm but one can put here any norm
assert(len(x)==2)
assert(len(x)==len(y))
return np.linalg.norm(x-y)
def two_d_uniform_sample_q(numSamples):
#prototype of a sampling function. This is how measures are specified.
"""returns a collection of numSamples many independent vectors unif distributed in [-1,1] x [-1,1]"""
ResultsArray = []
Xs = np.random.uniform(0,1,numSamples)
Ys = np.random.uniform(0,1,numSamples)
for k in range(numSamples):
ResultsArray.append([Xs[k],Ys[k]])
return ResultsArray
def two_d_uniform_density(vector):
#prototype of a density function. This is how measures are specified.
"""returns the density of an independent 2d vector unif distributed in [-1,1] x [-1,1]"""
x = vector[0]
y = vector[1]
if (0<=x) and (x<=1) and (0<=y) and (y<=1):
return 1.0
else:
return 0.0
if __name__ == "__main__":
#0.Weighted Voronoi diagrams:
N=5 #number of centers of the empirical measure
centers_array = [np.random.uniform(-1,1,2) for k in range(N)] #Chosen uniformly in the square [-1,1]x[-1,1]
empirical_measure = Empirical_Measure(centers_array)
#The probability measure is specified by its sampling function
probability_measure = Probability_Measure(two_d_uniform_sample_q,two_d_uniform_density)
#We construct the optimal transport object which carries out the gradient descent
OT = Optimal_Transport_Finder(empirical_measure,probability_measure,dist,num_MC=100000)
OT.do_gradient_descent(NumSteps=30, StepSize=0.5, keep_track_of_best=True, Descending_in_size=True)
WVD = OT.WVD #This is the resulting Weighted Voronoi Diagram, which contains an encoding of the optimal transport
print("Centers: " +str(WVD.centers))
print("Weights: " +str(OT.best_weights_so_far))
print("Distance: " +str(OT.best_objective_so_far))
|
e708a4ff294f9296bbbe05413894c4a96604a106 | cp-helsinge/2020-attack | /common/tech_screen.py | 1,897 | 3.546875 | 4 | """============================================================================
Tech screen
Create a transparent overlay display of internal values usefull for game
development and debuging
Activare in-game with F3
============================================================================"""
import pygame
from common import globals
from game_objects import setting
class TechScreen:
def __init__(self):
self.font = pygame.font.Font(None,30)
self.surface = pygame.Surface((setting.screen_width, setting.screen_height))
self.rect = self.surface.get_rect()
self.text_color = (0,128,0)
self.idle_avarage = 1
def display(self, x, y, format_str, *arguments):
str = format_str.format(*arguments)
text = self.font.render(str, True, self.text_color)
self.surface.blit( text, (x, y) )
def draw(self):
# Paint background as transparent
self.surface.fill((0,0,0))
self.display(10, 10, "Process time: {0} ms", pygame.time.get_ticks() - globals.game.frame_start)
self.display(10, 40, "Game objects: {0}", len(globals.game.object.list))
self.display(10, 70, "Level time: {0} Sec.", (pygame.time.get_ticks() - globals.game.level_time) // 1000)
self.display(10, 100, "Frame rate: {0}/sec. ({1}ms)",
int(setting.frame_rate * globals.game.game_speed),
int(1000 / setting.frame_rate / globals.game.game_speed) )
self.display(10, 130, "Game speed: {0}", globals.game.game_speed )
# Draw box around game objects
for game_obj in globals.game.object.list:
if getattr(game_obj['obj'], 'rect', None):
pygame.draw.rect(self.surface,self.text_color, game_obj['obj'].rect, 2)
# Make surface transparent and copy unto display surface
self.surface.set_colorkey((0,0,0))
self.surface.set_alpha(150)
globals.game.window.blit(self.surface, self.rect)
|
4bc5292f05f9fddcc8b792169b9733040be6a318 | msn322/Python | /Ericsson-Python/decorators2_check.py | 1,101 | 3.65625 | 4 | '''
Write a decorator that decorates functions that take a variable number of numeric values
and returns 4 numeric values.
'''
from __future__ import division
def check(func):
def ifunc(*numbers):
if not all( isinstance(number, (int, float)) for number in numbers):
raise TypeError('all parameters must be numeric')
return_values = func(*numbers)
if len(return_values) != 4:
raise ArithmeticError('must return 4 values')
if not all( isinstance(number, (int, float)) for number in return_values):
raise TypeError('all return values must be numeric')
return return_values
return ifunc
@check
def info(*numbers):
return sum(numbers), sum(numbers)/len(numbers), max(numbers), min(numbers)
assert info(1, 7, 11, 42) == ( 61, 15.25, 42, 1)
try:
info(90, 'joe')
except TypeError:
print 'bad info test passes'
@check
def bad_info(*numbers):
return 1, 2, 3
try:
bad_info(1, 7, 11, 42)
except ArithmeticError:
print 'bad_info call test passes'
print 'all tests pass'
|
333b8016fc41cd485cfd0849140b3554a8141876 | andersontmachado/Python_na_PRATICA | /Ex051-Progressão Aritmetica ou uma PA.py | 201 | 3.75 | 4 | primeiro=int(input('Primeiro Termo: '))
razao=int(input('A razão: '))
decimo=primeiro+(10-1)*razao
for c in range (primeiro,decimo+razao,razao):
print('{}'.format(c),end= '->')
print('ACABOU')
|
ee731b059372d40a750b8f02fe7ced4f0a2036ce | SamShepp/Practicals-2018 | /prac_05/hex_colours.py | 559 | 4.09375 | 4 | """
CP1404 Practical
Hexadecimal colour lookup
"""
COLOUR_CODES = {"AliceBlue": "#f0f8ff", "Blue1": "#0000ff", "BlueViolet": "#8a2be2",
"Brown": "#a52a2a", "CadetBlue1": "#98f5ff", "Chartreuse1": "#7fff00",
"Chocolate": "#d2691e", "Coral": "#ff7f50", "CornFlowerBlue": "#6495ed",
"Cyan1": "#00ffff"}
colour_name = input("Enter a colour name: ")
while colour_name != "":
print("The code for \"{}\" is {}".format(colour_name, COLOUR_CODES.get(colour_name)))
colour_name = input("Enter a colour name: ")
|
93db7022345dfc4903ead4812529a98e10e2397e | qiaozhi827/leetcode-1 | /04-栈_队列_优先队列/4-队列和广度优先遍历/01-102.py | 1,105 | 3.796875 | 4 | # 二叉树的层次遍历
# 使用队列
from leetcode.tree_node import TreeNode, get_binary_tree
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
res = []
queue = [root]
while queue:
cur = []
length = len(queue)
# 遍历层
for i in range(length):
node = queue.pop(0)
cur.append(node.val)
left = node.left
right = node.right
if left:
queue.append(left)
if right:
queue.append(right)
res.append(cur)
return res
if __name__ == '__main__':
obj = Solution()
while True:
nums_str = input().strip().split()
node_list = [int(n) if n != 'null' else None for n in nums_str]
root = get_binary_tree(node_list)
res = obj.levelOrder(root)
print(res)
|
8d5cc3d56604c2915b441de5df2fb56f580ca0a6 | s-ferdousy/Codeforces19 | /1335A - Candies And Two Sisters.py | 105 | 3.59375 | 4 | import math
t=int(input())
while(t>0):
n=int(input())
print (math.floor((n - 1) / 2))
t=t-1 |
a866463640bf268dc00ece18ea037e28c70cb05c | Manjuguna/pythonpractice | /Q60.py | 69 | 3.59375 | 4 | x=int(input(""))
su=0
for i in range(1,x+1,1):
su=su+i
print(su)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.