blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3c901acff3910976604d2f1f1de853274080ad8a | Huh-jae-won/Study | /PythonAI/Source/W1D3/src/EX_URL/ex_str_byte.py | 721 | 3.53125 | 4 | # str과 byte ---------------------------------
msg='hello' # 일반 문자열
bmsg=b'hello' # b'문자열' => 문자 해당 ASCII code 변환한 값 즉 바이트 형식
# 각 데이터 요소 출력
print('\n===== 데이터 요소 출력 =====')
for i in msg: print(i, end='\t')
print('\n')
for i in bmsg: print(i, end='\t')
for i in bmsg: print('0x%x'%i, end='\t')
print('\n\n===== str타입 => bytes타입 변경 : encode() =====')
strData='Good Luck'
byteData = strData.encode()
print('byteData =>', byteData)
print('strData =>', strData)
print('\n===== bytes타입 => str타입 변경 : decode() =====')
strData2=byteData.decode()
print('byteData =>', byteData)
print('strData2 =>', strData2) |
a4b27e4dfbb6e41dd966a902a1ba2be08253bd78 | lucasdiogomartins/curso-em-video | /python/ex022_string_meths.py | 397 | 4.15625 | 4 | nome = input('Digite seu nome: ').strip()
print('\n Nome em maiúsculas:', nome.upper())
print(' Nome em minúsculas:', nome.lower())
print(' Quantidade de letras:', len(nome.replace(' ', '')))
print(' Quantidade de letras:', len(nome)-nome.count(' ')) # 2° opção
print(' Q. de letras primeiro nome:', len(nome.split()[0]))
print(' Q. de letras primeiro nome:', nome.find(' ')) # 2° opção
|
77990194f1b61aeaba91b98c8988865e69b762ea | mohamedhmda/Algorithms | /Easy/bubble_sort/bubble_sort.py | 282 | 4.125 | 4 | def bubble_sort(array):
l = len(array)
sorted = False
while not sorted:
sorted = True
for i in range(l-1):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
sorted = False
return array
|
b92caa9a4cc870552d6fe944e768dc8bca374ac1 | hmutschler15/rpi_git | /cs/300/lab3/switch_blink.py | 692 | 3.75 | 4 | # Name: Hamilton Mutschler
# For: Lab 3 in CS 300 at Calvin University
# Date: February 21, 2020
import RPi.GPIO as GPIO
# set up GPIO pins to BCM
GPIO.setmode(GPIO.BCM)
# set BCM pin 12 to an input
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# set BCM pin 16 to an output
GPIO.setup(16, GPIO.OUT)
# initialize LED to off
GPIO.output(16, 0)
LEDstate = 0
# function to control the status of the LED
def LED_control(channel):
global LEDstate
# change the state of the LED
LEDstate = not LEDstate
GPIO.output(16, LEDstate)
# detect a falling edge on pin 12
GPIO.add_event_detect(12, GPIO.FALLING, callback=LED_control, bouncetime=200)
# main program loop
while(True):
continue |
0997cb31c2f610e64955b6b92144f5e61bf1fbf1 | yinxingyi/Python100day_Learning | /Day6.py | 479 | 3.984375 | 4 | from random import randint
def roll_dice(n = 2): # n=2 is default number, if there is no inputs when you call this function, the n use default number 2
total = 0 # roll the dice, and return total number, duce number origanlly is 2
for _ in range(n):
total += randint(1,6)
return total
def add(a=0, b=0, c=0):
return a+b+c
def main():
print(roll_dice(5))
print(add(1,2,3))
if __name__ == '__main__':
main() |
d1f95632fa1db78ee1667a579e08ee718047299e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2064/60634/269458.py | 602 | 3.609375 | 4 | def tranBit(c):
if c == 'I':
return 1
elif c == 'V':
return 5
elif c == 'X':
return 10
elif c == 'L':
return 50
elif c == 'C':
return 100
elif c == 'D':
return 500
elif c == 'M':
return 1000
def tran(num):
result = 0
i = 0
while i < len(num)-1:
theBit = tranBit(num[i])
aftBit = tranBit(num[i+1])
if theBit < aftBit:
result -= theBit
else:
result += theBit
i += 1
return result + tranBit(num[len(num)-1])
num = input()
print(tran(num))
|
3438b4eb1b69fe6674b952a95fa9c2e181acd8f8 | renancoelhodev/jogo_nim | /jogadas.py | 1,174 | 4.125 | 4 | from time import sleep
def computador_escolhe_jogada(n, m):
if n > 0:
if n <= m: # retira o maior número de peças possíveis se o número de peças no tabuleiro for menor
print() # que o número de peças que podem ser retiradas em uma jogada
sleep(2)
print("O computador tirou", n, "peças.")
return n
elif n == 1:
print()
sleep(2)
print("O computador tirou uma peça.")
return 1
else:
i = m
# procura uma quantidade de peças para retirar de modo
# que reste um número de peças múltiplo de m+1
while i != 1 and (n-i) % (m+1) != 0:
i = - 1
print()
sleep(2)
print("O computador tirou", i, "peças.")
return i
def usuario_escolhe_jogada(n, m):
if n > 0:
print()
jogada_usuario = -1
while jogada_usuario < 1 or jogada_usuario > m:
jogada_usuario = int(input("Quantas peças você vai tirar? "))
print("Você tirou", jogada_usuario, "peças.")
return jogada_usuario
|
e5e45ec12b92c4e4979f63a2d6a8ce84d5028d5d | cielo33456/practice | /main.py | 329 | 3.609375 | 4 | from sort import bubble
list_a = [233,1,453,35,87,400,46,77,35,700]
print(list_a)
bubble(list_a)
#length = len(list_a)
#for times in range(1, length):
# for flag in range(1, length-times+1):
# if list_a[flag-1] > list_a[flag]:
# list_a[flag-1], list_a[flag] = list_a[flag], list_a[flag-1]
print(list_a)
|
1f1ca9e1869593a302abd770f991400b67a1e1a4 | thanhmaikmt/pjl | /PythonPodSim/src/devel/podworld/atttic/podParamEvolver_orig.py | 14,192 | 3.625 | 4 | # demonstration of Evolving pods using a randomish search.
#
# uses the idea of a population selection and mutatation (does not try crossover)
#
# Each pod is controlled with a neural brain.
# Pods have a finite life.
# Pods die when they reach the age limit or crash into a wall
# The fitness of a pod is measured by the distance around track when it dies.
# if it has completed the circuit I also use the age of pod to encourage speed.
# A good_brain_list (Pool) of the best pods is kept.
# When a pod dies its neural brain is added to the pool (if it is good enough)
# it brain is then replaced by a new one created from the pool.
# The Pool creates new neural nets by mutating one of the brains in the pool.
# mutation in this version
# - all the weights are changed by a random amount.
# - I also use a random scaling factor so some new pods are small changes whilst
# others are large changes.
#
# Notes: the initial angle of a pod has got a random pertubation.
# Just because a pod can has achieved a good score does not mean it is the best
# I keep "re-testing" the best pod in case its score was by chance.
#
# A log file is written out which could be used to plot graphs of performance to compare different
# configurations (e.brain. change the size of the POOL)
#
# For more information on the working of this code see in line comments
# and look at the code.
import simulation
import pygame
import random
import copy
from fontmanager import *
import pickle
import time
import pods
import world
import math
# The world
WORLD_FILE="../worlds/carCircuit.world" # world to use
N_SENSORS=8 # number of sensors
# files used by program
RUN_NAME="POX"
#POOL_FILE_NAME=RUN_NAME+"_pool.txt" # file to save/restore the pool
log_file=open("log.txt","w") # keep a record of the performance
nin=N_SENSORS+1 # velocity + sensors are inputs
nout=4 # controls
#paramsRoot=[1.259,200.0,0.01,1.0,-0.0083,1.083,100,80];
paramsInit= [1.0, 200.0, 0.00, 0.5,-0.01, 1.0, 100,100];
paramsScale=[1.259,200.0, 0.01, 1.0,-0.0083,1.083,100,80];
# encapsulate the parameters in a class
class ParamBrain:
def __init__(self):
self.params=copy.deepcopy(paramsInit)
def clone(self):
clone=ParamBrain()
clone.params=copy.deepcopy(self.params)
return clone
def mutate(self):
x=self.params
#i=randrange(len(self.params))
MUTATE_SCALE=0.1
for i in range(len(self.params)):
x[i]=x[i] + (random.random()-0.5)*paramsScale[i]*MUTATE_SCALE*random.random()
# Pool is responsible for keeping track of the fittest solutions
POOL_SIZE=1 # size of pool of best brains
SEED_PROB=0.1 # probability a new thing is created from nothing
class Pool: # use me to store the best brains and create new brains
def __init__(self):
self.list=[]
self.maxMembers=POOL_SIZE
self.touched=True
self.reaping=True
# add a new Gene to the Pool (if better than the worst one in pool)
def add(self,brain):
if len(self.list) >= self.maxMembers:
if brain.fitness < self.list[self.maxMembers-1].fitness:
return
for i in range(len(self.list)):
if brain.fitness >= self.list[i].fitness:
self.touched=True
self.list.insert(i,brain)
if len(self.list) > self.maxMembers:
self.list.pop()
return
if len(self.list) < self.maxMembers:
self.list.append(brain)
self.touched=True
# create a neural brain from the pool or maybe random
# might return best brain to be reproven
def create_new(self):
# if pool is not full create a random brain
if len(self.list) < self.maxMembers or random.random() < SEED_PROB:
#Create a brain
brain=ParamBrain()
return brain
# Otherwise just select a random brain from the pool
clone=self.select()
# mutate the cloned brain by a random amount.
clone.mutate()
return clone
# random selection from the pool
def select(self):
id=random.randint(0,len(self.list)-1)
return self.list[id].clone()
# return the best fitness in the pool
# since I retest the best this value can fall
def best_fitness(self):
if len(self.list) == 0:
return 0
else:
return self.list[0].fitness
# return average fitness
def average_fitness(self):
if len(self.list) == 0:
return 0
else:
sum=0.0
for x in self.list:
sum +=x.fitness
return sum/len(self.list)
# save the pool to a file
# (note reproof count is not saved)
def save(self,file):
n=len(self.list)
pickle.dump(n,file)
for x in self.list:
o=copy.deepcopy(x.fitness)
pickle.dump(o,file)
x.brain.save(file)
print "POOL SAVED"
# load pool from a file
def load(self,file):
self.list=[]
n=pickle.load(file)
print n
for i in range(n):
f=pickle.load(file)
net=loadBrain(file)
net.proof_count=0 # sorry we lost the proof count when we saved it
net.fitness=f
self.add(net)
print "RELOADED POOL"
for pod in pods:
# reset the pod and give it a new brain from the pool
world.init_pod(pod)
pod.ang += random()-0.5 # randomize the intial angle
pod.brain.brain=pool.create_new()
# decide if we want to kill a pod
MAX_AGE=200 # pods life span
MIN_AGE=0.2 # Allow to live this long before reaping for not moving
def reap_pod(state):
if state.collide:
return True
if state.vel < 0:
# print "backwards"
return True
if state.age > MIN_AGE and state.distance_travelled == 0:
return True
if state.age > MAX_AGE:
return True
if state.pos_trips >= N_TRIP:
return True
return False
# calculate the fitness of a pod
def calc_fitness(state):
if state.collide:
return state.pos_trips-state.neg_trips+state.seg_pos
# encourage them to go fast once they get round the path
if state.pos_trips == N_TRIP:
fitness = N_TRIP + MAX_AGE-state.age
else:
# just count the trip wires we have passed
fitness = state.pos_trips-state.neg_trips
return fitness
class MyController:
def __init__(self):
self.brain=pool.create_new()
# normal process called every time step
def process(self,pod,dt):
# If we are trying to evolve and pod dies
if pool.reaping and reap_pod(pod.state):
" here then time to replace the pod"
# save current brain and fitness in the pool
self.brain.fitness=calc_fitness(pod.state)
pool.add(self.brain)
# reset the pod and give it a new brain
world.init_pod(pod)
self.brain=pool.create_new()
return
# normal control stuff
control=pods.Control()
p=self.brain.params
sensor=pod.sensors
state=pod.state
V=p[0]*sensor[0].val
if V>p[1]:
V=p[1]
cont=(V/(abs(state.vel+1e-6)+p[2])) - p[3]
if cont > 0:
control.up = cont
else:
control.down = abs(cont)
diff=(sensor[1].val+sensor[2].val)-(sensor[7].val+sensor[6].val)
turn_compensation=p[4]*sensor[0].val+p[5]
if diff>0.0:
control.left=abs((diff/p[6])**2/p[7])+turn_compensation
else:
control.right=abs((diff/p[6])**2/p[7])+turn_compensation
return control
# create a car and equip it with snesors and a controller
def createCar(nSensor):
control=MyController()
sensors=[]
sensorRange = 2000
for i in range(nSensor):
ang_ref=i*math.pi*2/nSensor
sensors.append(pods.Sensor(ang_ref,sensorRange,"sensor"+str(i)))
# random colours
b=255-(i*167)%256
brain=(i*155)%256
r=255-(i*125)%256
pod = pods.CarPod((r,brain,b))
pod.setController(control)
pod.addSensors(sensors)
return pod
# Define some cosmetic stuff ------------------------------------
class Painter: # use me to display stuff
def __init__(self):
self.preDraw=None # define this function to draw on top!
self.fontMgr = cFontManager(((None, 20), (None, 48), ('arial', 24)))
self.last_time=time.time()
self.last_ticks = 0
def postDraw(self,screen):
Y=20
X=20
tot_ticks=sim.ticks
ticks=tot_ticks-self.last_ticks
tot_time=time.time()
delta=tot_time-self.last_time
ticks_per_sec=ticks/delta
self.last_time=tot_time
self.last_ticks=tot_ticks
avFit="%4.1f" % pool.average_fitness()
tickRate="%8.1f" % ticks_per_sec
str1=RUN_NAME+' pool size:'+ str(POOL_SIZE)+\
' ticks:'+ str(sim.ticks) +\
' best:'+ str(pool.best_fitness())+\
' average:'+ avFit+\
' ticks/sec:'+tickRate+" "
# print str1
self.fontMgr.Draw(screen, None, 20,str1,(X,Y), (0,255,0) )
class Admin: # use me to control the simulation
# see comments to see what key hits do
def process(self,sim):
# this is called just before each time step
# do admin tasks here
global pods
# output to a log file
if pool.reaping and log_file!=None and pool.touched:
log_file.write(str(sim.ticks) +','+ str(pool.best_fitness())+','+str(pool.average_fitness())+'\n')
pool.touched=False
keyinput = pygame.key.get_pressed()
# speed up/down display
if keyinput[pygame.K_KP_PLUS] or keyinput[pygame.K_EQUALS]:
sim.frameskipfactor = sim.frameskipfactor+1
print "skip factor" ,sim.frameskipfactor
if keyinput[pygame.K_MINUS]:
sim.frameskipfactor = max(1,sim.frameskipfactor-1)
print "skip factor" ,sim.frameskipfactor
# display the performance of the best pod in pool
if keyinput[pygame.K_b]:
if pool.reaping: # if reaping copy existing to allow restore
self.pods_copy=copy(pods)
pod=pods[0]
del pods[:]
pods.append(pod)
else:
pod=pods[0]
world.init_pod(pod)
pod.ang += random()-0.5 # randomize the intial angle
pod.control.brain=pool.create_best()
pool.reaping=False
# display the performance of the most proven pod
if keyinput[pygame.K_p]:
if pool.reaping: # if reaping copy existing to allow restore
self.pods_copy=copy(pods)
pod=pods[0]
del pods[:]
pods.append(pod)
else:
pod=pods[0]
world.init_pod(pod)
pod.ang += random()-0.5 # randomize the intial angle
pod.control.brain=pool.create_most_proven()
pool.reaping=False
# go back into evolution mode after looking at best pod
if not pool.reaping and keyinput[pg.K_r]:
del pods[:]
pods.extend(self.pods_copy)
pool.reaping=True
# save the pool to a file
if keyinput[pygame.K_s]:
file=open(POOL_FILE_NAME,"w")
pool.save(file)
file.close()
# reload the pool from a file
if keyinput[pygame.K_l]:
file=open(POOL_FILE_NAME,"r")
pool.load(file)
file.close()
if keyinput[pygame.K_d]:
for brain in pool.list:
print brain.fitness," : ",brain.params
### START OF PROGRAM
dt =.1
pool=Pool() # create a pool for evolving
podlist=[] # pods on the circuit
POP_SIZE=1 # number of pod on circuit
for i in range(POP_SIZE): # create initial population on the circuit
podlist.append(createCar(N_SENSORS))
world = world.World(WORLD_FILE,dt,podlist)
N_TRIP=len(world.trips)*2 # to avoid end wall remove pod after hitting this (last) trip
print "Max trips :",N_TRIP
sim = simulation.Simulation(world,"simple param evolver")
# register the painter to display stuff
sim.painter = Painter()
admin = Admin()
sim.setAdmin(admin)
# go go go ..........
sim.run()
|
6de80be36186ff661cbfb55b2d8451e429c6a991 | qzson/Study | /hamsu/h1_split.py | 767 | 3.765625 | 4 | import numpy as np
# test0602_samsung_review에서 사용
def split_x(seq, size):
aaa = []
for i in range(len(seq) - size + 1):
subset = seq[i:(i+size)]
aaa.append([j for j in subset])
# print(type(aaa))
return np.array(aaa)
size = 6 # 6일치씩 자르겠다?
# test0602_exam에서 사용
def split_xy3(dataset, time_steps, y_column):
x, y = list(), list()
for i in range(len(dataset)):
x_end_number = i + time_steps
y_end_number = x_end_number + y_column
if y_end_number > len(dataset):
break
tmp_x = dataset[i:x_end_number, :]
tmp_y = dataset[x_end_number:y_end_number, 0]
x.append(tmp_x)
y.append(tmp_y)
return np.array(x), np.array(y) |
19ea97b11d097b0f661960b53abbbf34b32e5033 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4351/codes/1649_1054.py | 185 | 3.90625 | 4 | x=float(input("valor de x"))
y=float(input("valor de y"))
reta= (2*x)+y
if (reta == 3):
menssagem="ponto pertence a reta"
else:
menssagem="ponto nao pertence a reta"
print(menssagem) |
8625f2d1d1a04a1b86fc2a28dc2c207b207fefa7 | teberger/cs554-project2 | /ll1_tools.py | 10,129 | 3.625 | 4 | from cfg import Grammar, EOF, EPSILON
def nullable(grammar):
'''
Returns a list of the all non-terminals that are nullable
in the given grammar. A nullable non-terminal is calculated
as a closure using the following rules:
nullable(A -> Epsilon) -> True
nullable(A -> a) -> False
nullable(A -> AB) -> nullable(A) AND nullable(B)
nullable(A -> A1 | A2 | ... | AN) -> nullable(A1) OR .. OR nullable(A_n)
:param Grammar grammar: the set of productions to use and
wrapped in the Grammar object
:return a set of all non-terminals that can be nullable
'''
nullable = set()
productions = grammar.productions
cardinality = -1
while cardinality < len(nullable):
cardinality = len(nullable)
for non_term in productions:
#if epsilon is in the rhs already,
#the production is nullable
if EPSILON in productions[non_term]:
nullable.add(non_term)
else:
isNullable = False
for N in productions[non_term]:
#check to see if this specific production is
# nullable by checking to see if the join set of
# all symbols in the production are nullable.
# If they are not, that production is not nullable
isProductionNullable = True
for symbol in N:
isProductionNullable &= symbol in nullable
# This is the disjoint set of all nullable
# productions the correspond to this lhs
isNullable |= isProductionNullable
# if any of the disjoint productions are nullable,
# then this is true. Therefore, add this production's
# lhs to the nullable set
if isNullable:
nullable.add(non_term)
return nullable
def first(grammar):
'''A first set calucation for a grammar returns a dictionary of all
the first terminals that can proceed the rest of a parse given a
non-termial symbol. First is a closure that is calculated as
follows:
first(Epsilon) -> EmptySet
first(A -> a) -> { a }
first(A -> A B) -> { first(A) U first( B), if nullable(A)
{ first(A), otherwise
first(A -> A1 | A2 | ... | AN) -> first(A1) U first(A2 U ... U first(AN)
:param Grammar grammar: the set of productions to use wrapped in a
Grammar object
:return dict{Non-Terminal : set(Terminal)}: a table of all terminals that
could come from a given
non-terminal
'''
productions = grammar.productions
#define the nullables
nullable_non_terms = nullable(grammar)
#initially set our table to the empty set of terminals
prev_table = {non_term : set() for non_term in grammar.nonTerminals}
#add just the productions of the form:
# non_terminal -> terminal
#to start the algorithm off
for non_term in grammar.nonTerminals:
for rhs in productions[non_term]:
if [] == rhs: continue
if rhs[0] in grammar.terminals or rhs[0] == EPSILON:
prev_table[non_term].add(rhs[0])
has_changed = True
while has_changed:
has_changed = False
#construct the new table so we don't interfere with the
#previous one by adding things we wouldn't add this iteration
new_table = prev_table.copy()
for non_term in grammar.nonTerminals:
for rhs in productions[non_term]:
# if we have an epsilon, add it to the first set of this
if len(rhs) == 0:
if EPSILON not in prev_table[non_term]:
has_changed = True
new_table[non_term] |= set([EPSILON])
continue
# we already handled this above
if rhs[0] in grammar.terminals or rhs[0] == EPSILON:
continue
first = rhs[0]
# Now, we need to check to see if adding anything from
# the first item in the rhs changes the current set of
# terminals we have for this non_term
# this is done by seeing if the rhs's first
# non-terminal's first set can add anything to the
# current set of terminals for non_term
if len(prev_table[first] - prev_table[non_term]) > 0:
new_additions = prev_table[first] - prev_table[non_term]
#skip past all the nullables until we hit the end
#or we find a non-terminal. Add all the first sets
#for the next item in the production as we come
#across them
i = 1
while i+1 < len(rhs) and rhs[i] in nullable_non_terms:
if rhs[i + 1] in grammar.nonTerminals:
new_additions |= prev_table[rhs[i + 1]]
else:
#must list-ify to match the rest in the
#set
new_additions |= set([rhs[i+1]])
break
i += 1
new_table[non_term] |= new_additions
has_changed = True
prev_table = new_table.copy()
return prev_table
def create_first_from_list(first_table, nullables, symbol_list):
if len(symbol_list) == 0: return set([EPSILON])
#if it starts with a terminal, return the singleton set
if symbol_list[0] not in first_table.keys():
return set([symbol_list[0]])
first_set = set().union(first_table[symbol_list[0]])
if symbol_list[0] in nullables:
recursive_set = create_first_from_list(first_table, nullables, symbol_list[1:])
first_set.union(recursive_set)
return first_set
def betas_following(non_terminal, productions):
ret_set = {}
for lhs,all_rhs in productions.iteritems():
for rhs in all_rhs:
if non_terminal in rhs:
symbol_list = rhs
while non_terminal in symbol_list:
idx = symbol_list.index(non_terminal)
beta = []
if idx < len(symbol_list):
beta = symbol_list[idx + 1:]
if lhs in ret_set:
ret_set[lhs].append(beta)
else:
ret_set[lhs] = [beta]
symbol_list = beta
return ret_set
def follows(grammar):
'''Calculates all terminals that can follow a given non terminal.
Follows is a closure calculated by the following rules:
given [M -> ANB] -> follows(N) = follows(N) U first(B)
if nullable(B) then
follows(M) = follows(M) U follows(N)
given [M -> A N B1...A N B2...A N BX]
-> follows(N) = first(B1) U first(B2) U ...
U first(BX)
if nullable(B_i) then
follows(M) = follows(M) U follows(N)
:param Grammar grammar: the set of productions to use as a Grammar
object
:return dict{non-Terminal : set(terminals)}: the set of terminal characters
that can follow any given
non-terminal
'''
first_table = first(grammar)
nullable_set = nullable(grammar)
follows_table = {non_term : set() for non_term in grammar.nonTerminals}
#add EOF to the follows set for the start of the follows table
follows_table[grammar.start] |= set([EOF])
#iterate until there are no changes. Construct the closure.
changed = True
while changed:
changed = False
# We need to construct the follows table for each non-terminal
for non_terminal in grammar.nonTerminals:
#Get all productions of the form X -> a A beta
beta_productions = betas_following(non_terminal, grammar.productions)
#Iterate over all productions of the previous form. LHS refers to X
for lhs in beta_productions:
#This is for each specific 'beta' that could be of the form X -> a A beta
for beta in beta_productions[lhs]:
# if there are no productions following 'A', then do this..
if beta == []:
#Add Follows(X) to Follows(A)
for elem in follows_table[lhs]:
if elem not in follows_table[non_terminal]:
changed = True
follows_table[non_terminal].add(elem)
continue
#Construct First(beta)
first_of_beta = create_first_from_list(first_table, nullable_set, beta)
#Add all elements in First(beta) to Follows(A)
for elem in (first_of_beta - set([EPSILON])):
if elem not in follows_table[non_terminal]:
changed = True
follows_table[non_terminal].add(elem)
#If 'beta' is nullable, then do this...
if EPSILON in first_of_beta:
#Add each element in Follows(X) to Follows(A)
for elem in follows_table[lhs]:
if elem not in follows_table[non_terminal]:
changed = True
follows_table[non_terminal].add(elem)
return follows_table
|
f1d86d652d01d6dddfb4d7c88707ef9b434027d2 | kristenlega/python-challenge | /PyPoll/main.py | 2,434 | 3.765625 | 4 | import os
import csv
electiondata_csv = os.path.join("..","PyPoll", "Resources", "election_data.csv")
# Open the CSV file
with open(electiondata_csv,'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# Skip the header row
next(csvreader, None)
# Set the initial summing variables to 0 and create empty list
totalvotes = 0
election_results = {}
# Iterate through all of the rows to determine each of the candidates
for row in csvreader:
# Count the number of votes
totalvotes = totalvotes + 1
# Set the candidate name as a variable
candidate_name = row[2]
# If the candidate is not in the dictionary, add it
if candidate_name not in election_results:
election_results[candidate_name] = 1
# Otherwise, add 1 to the total votes for that candidate
else:
election_results[candidate_name] += 1
# Create winner votes variable
winner_votes = 0
# Determine the winner
for candidate_name in election_results:
if winner_votes < election_results[candidate_name]:
winner_name = candidate_name
winner_votes = election_results[candidate_name]
# Print the results to the terminal
# Decimal precision citation: https://stackoverflow.com/questions/45310254/fixed-digits-after-decimal-with-f-strings
print("Election Results")
print("--------------------")
print(f'Total Votes: {totalvotes}')
print("--------------------")
for candidate_name in election_results:
print(f'{candidate_name}: {(election_results[candidate_name] / totalvotes):.3%} ({election_results[candidate_name]})')
print("--------------------")
print(f'Winner: {winner_name}')
print("--------------------")
# Create a new text file and print the results there
results = open('analysis/PyPoll_Results.txt', "w")
# Write the results - new line formatting citation: https://www.kite.com/python/answers/how-to-write-to-a-file-in-python#:~:text=Use%20writelines()%20to%20write,be%20in%20a%20single%20line.
results.write(
"Election Results" "\n"
"--------------------" "\n"
f'Total Votes: {totalvotes}' "\n"
"--------------------" "\n")
for candidate_name in election_results:
results.write(
f'{candidate_name}: {(election_results[candidate_name] / totalvotes):.3%} ({election_results[candidate_name]})' "\n")
results.write(
"--------------------" "\n"
f'Winner: {winner_name}' "\n"
"--------------------") |
439853f2a919e95e1ff4d52ddd9b0fc63eb56578 | dantsub/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 316 | 3.96875 | 4 | #!/usr/bin/python3
for first in range(0, 10):
second = first + 1
for second in range(0, 10, 1):
if (first != 8 or second != 9):
if (first != 8 and second > first):
print('{}{}'.format(first, second), end=', ')
else:
print('{}{}'.format(first, second))
|
44067d74ac7aea3cc15b343433fa8c9d5147d2be | mindovermiles262/codecademy-python | /11 Introduction to Classes/18_inheritance.py | 1,072 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 09:59:18 2017
@author: mindovermiles262
Codecademy Python
Create a class named Equilateral that inherits from Triangle.
Inside Equilateral, create a member variable named angle and set it equal to 60.
Create an __init__() function with only the parameter self, and set
self.angle1, self.angle2, and self.angle3 equal to self.angle (since an
equilateral triangle's angles will always be 60˚).
"""
class Triangle(object):
def __init__(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
number_of_sides = 3
def check_angles(self):
if self.angle1+self.angle2+self.angle3==180:
return True
else: return False
my_triangle = Triangle(90, 30, 60)
print(my_triangle.number_of_sides)
print(my_triangle.check_angles())
class Equilateral(Triangle):
angle = 60
def __init__(self):
self.angle1 = self.angle
self.angle2 = self.angle
self.angle3 = self.angle |
a3f24ce27ad6d4d961704e1fb82768be2b64ed3a | chereddybhargav/disc-opt | /knapsack/solver_dp_time_opt.py | 3,215 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from collections import namedtuple
sys.setrecursionlimit(10001)
Item = namedtuple("Item", ['index', 'value', 'weight'])
def solve_it(input_data):
# Modify this code to run your optimization algorithm
# parse the input
lines = input_data.split('\n')
firstLine = lines[0].split()
item_count = int(firstLine[0])
capacity = int(firstLine[1])
items = []
weights=[]
values=[]
for i in range(1, item_count+1):
line = lines[i]
parts = line.split()
items.append(Item(i-1, int(parts[0]), int(parts[1])))
weights+=[int(parts[1])]
values+=[int(parts[0])]
"""
############ Building bottom up dp to reduce time complexity
taken=[0]*item_count
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
# Build table K[][] in bottom up manner
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],K[i-1][w])
else:
K[i][w] = K[i-1][w]
cap=W
i=n
while cap !=0 and i !=0:
if K[i][cap]==K[i-1][cap]:
taken[i-1]=0
i = i-1
else:
taken[i-1]=1
i=i-1
cap=cap-wt[i]
return K[n][W]
value=knapSack(capacity,weights,values,item_count)
"""
#################### Greedy Algorithm for feasible solution
items.sort(key=lambda x:x.density,reverse=True)
value = 0
weight = 0
taken = [0]*len(items)
for item in items:
if weight + item.weight <= capacity:
taken[item.index] = 1
value += item.value
weight += item.weight
"""
################### Naive dp
def knap(k,n):
if k==0 or n==0:
return 0
elif weights[n-1]>k:
taken[n-1]=0
return knap(k,n-1)
else:
if values[n-1]+knap(k-weights[n-1],n-1)>=knap(k,n-1):
taken[n-1]=1
return values[n-1]+knap(k-weights[n-1],n-1)
else:
taken[n-1]=0
return knap(k,n-1)
value=knap(capacity,item_count)
"""
# prepare the solution in the specified output format
output_data = str(value) + ' ' + str(1) + '\n'
output_data += ' '.join(map(str, taken))
return output_data
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
file_location = sys.argv[1].strip()
with open(file_location, 'r') as input_data_file:
input_data = input_data_file.read()
print(solve_it(input_data))
else:
print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)')
file_location='data/ks_500_0'
#file_location='data/ks_lecture_dp_2'
with open(file_location, 'r') as input_data_file:
input_data = input_data_file.read()
print(solve_it(input_data))
|
2f7b72e44d7712613602eae2d920260508efeba7 | EvanJamesMG/Leetcode | /python/Dynamic Programming/264.Ugly Number II.py | 1,977 | 4.3125 | 4 | '''
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
Hint:
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
'''
# coding=utf-8
import sys
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
'''
丑陋数序列可以拆分为下面3个子列表:
(1) 1×2, 2×2, 3×2, 4×2, 5×2, …
(2) 1×3, 2×3, 3×3, 4×3, 5×3, …
(3) 1×5, 2×5, 3×5, 4×5, 5×5, …
我们可以发现每一个子列表都是丑陋数本身(1, 2, 3, 4, 5, …) 乘以 2, 3, 5
接下来我们使用与归并排序相似的合并方法,从3个子列表中获取丑陋数。每一步我们从中选出最小的一个,然后向后移动一步。
'''
class Solution:
# @param {integer} n
# @return {integer}
def nthUglyNumber(self, n):
q = [1]
i2 = i3 = i5 = 0
while len(q) < n:
m2, m3, m5 = q[i2] * 2, q[i3] * 3, q[i5] * 5
m = min(m2, m3, m5)
if m == m2:
i2 += 1
if m == m3:
i3 += 1
if m == m5:
i5 += 1
q += [m]
return q[-1]
# if __name__ == "__main__":
# result = Solution().nthUglyNumber(12)
# print(result)
|
31d2a8ee14e7510d8892b2f5ae5a2d5f653742da | DCWhiteSnake/Data-Structures-and-Algo-Practice | /Chapter 2/Projects/P-2.33.py | 2,926 | 4.21875 | 4 |
def differentiate(expression):
""" Function that finds the first differential of a polynomial expression
expression the polynomial expression
if expression is a constant, the function returns 1.
if expression is a number, the function returns 0.
if the expressionis a polynomial expression the function returns the first differential.
"""
is_number = False
try:
x = int(expression) # try to convert expression to a number, call this number x
if isinstance(x, (int)):
is_number = True # is is
except ValueError:
is_number = False
if len(expression) == 1 and is_number == False:
return str(1) # The differential of a constant is one(1)
elif is_number == True:
return str(0) # The differential of a number is zero(0)
else:
number, constant, power = "", "","" # Create string variables number, constant, and power to hold the similarly named variables.
for x in range(len(expression)):
try:
number += str(int(expression[x])) # concatenate items in the expression to variable number until you meet an unparseable item
# store that item as constant i.e x, and record the positon
except ValueError:
position = x
constant = expression[x]
break
for x in range(position+2, len(expression)): # add two to the location of the constant variable i.e., the positon of the exponent of the expression
# concatenate the remaining variables as power
power += expression[x]
number = int(number)
try:
power = int(power) # if power isn't given i.e in the case if 3x, assign a value of 1 to power
except ValueError:
power = 1
if power != 1 :
soln = str(number * power) + str(constant) + "^" + str(power-1)
elif power == 1: # if power is one, i.e., if we substract one from power it gives us zero,
# and x^0 is one, so we just return the number as solution
soln = str(number)
return soln
if __name__ == '__main__':
user_input = input("Input the polynomial(s), seperate the operators by a single space")
polynomial_eqn = user_input.split()
soln = ""
for x in range(len(polynomial_eqn)):
if polynomial_eqn[x] in ['+', '-']:
soln += str(polynomial_eqn[x]) + " "
else:
soln += differentiate(polynomial_eqn[x]) + " "
print(soln)
|
0768a2ae7c269c71ed59d3ec406db82d3a18b8ab | HeyVoyager/Portfolio-Projects | /ud_graph.py | 14,532 | 3.875 | 4 | # Course: CS261 - Data Structures
# Author: Michael Hilmes
# Assignment: 6
# Description: Undirected Graph Implementation
from collections import deque
class UndirectedGraph:
"""
Class to implement undirected graph
- duplicate edges not allowed
- loops not allowed
- no edge weights
- vertex names are strings
"""
def __init__(self, start_edges=None):
"""
Store graph info as adjacency list
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.adj_list = dict()
# populate graph with initial vertices and edges (if provided)
# before using, implement add_vertex() and add_edge() methods
if start_edges is not None:
for u, v in start_edges:
self.add_edge(u, v)
def __str__(self):
"""
Return content of the graph in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
out = [f'{v}: {self.adj_list[v]}' for v in self.adj_list]
out = '\n '.join(out)
if len(out) < 70:
out = out.replace('\n ', ', ')
return f'GRAPH: {{{out}}}'
return f'GRAPH: {{\n {out}}}'
# ------------------------------------------------------------------ #
def add_vertex(self, v: str) -> None:
"""
Add new vertex to the graph
"""
# If vertex is not already in the adj_list, add empty list to the dictionary
if v not in self.adj_list:
self.adj_list[v] = []
def add_edge(self, u: str, v: str) -> None:
"""
Add edge to the graph
"""
# If the vertices are not equal...
if u != v:
# If vertex u is not in adj_list, add it
if u not in self.adj_list:
self.add_vertex(u)
# If vertex v is not in adj_list, add it
if v not in self.adj_list:
self.add_vertex(v)
# If vertex u does not have an edge to v, add it
if v not in self.adj_list[u]:
self.adj_list[u].append(v)
# If vertex v does not have an edge to u, add it
if u not in self.adj_list[v]:
self.adj_list[v].append(u)
def remove_edge(self, v: str, u: str) -> None:
"""
Remove edge from the graph
"""
# If both vertices v and u exist...
if v in self.adj_list and u in self.adj_list:
# If edge to u exists for vertex v, remove it
if u in self.adj_list[v]:
self.adj_list[v].remove(u)
# If edge to v exists for vertex u, remove it
if v in self.adj_list[u]:
self.adj_list[u].remove(v)
def remove_vertex(self, v: str) -> None:
"""
Remove vertex and all connected edges
"""
# If the vertex exists in adj_list, remove it
self.adj_list.pop(v, None)
# Check each remaining vertex and remove any edges connected to v
for key in self.adj_list:
if v in self.adj_list[key]:
self.adj_list[key].remove(v)
def get_vertices(self) -> []:
"""
Return list of vertices in the graph (any order)
"""
# Initialize empty list of vertices
list_vertices = []
# Iterate through adj_list and add the keys to list_vertices
for key in self.adj_list:
list_vertices.append(key)
# Return the list of vertices
return list_vertices
def get_edges(self) -> []:
"""
Return list of edges in the graph (any order)
"""
# Initialize empty list to store edges
list_edges = []
# Iterate through the adj_list
for key in self.adj_list:
# For each edge associated with the given vertex key, create a sorted tuple representing the edge
for item in self.adj_list[key]:
edge = [key, item]
edge.sort()
edge_tuple = (edge[0], edge[1])
# Add the edge to the list of edges
list_edges.append(edge_tuple)
# If the list of edges is non-empty, regenerate the list by calling set() to remove duplicates
if len(list_edges) > 0:
list_edges = list(set(list_edges))
# Sort the list of edges and return it
list_edges.sort()
return list_edges
def is_valid_path(self, path: []) -> bool:
"""
Return true if provided path is valid, False otherwise
"""
# Initialize a counter and get the length of the path array
count = 1
length = len(path)
# If the path is empty, return True
if length == 0:
return True
# If the path has one vertex and the vertex exists, return True.
# Return False if the vertex doesn't exist
if length == 1:
if path[0] in self.adj_list:
return True
else:
return False
# Check that all path vertices exist. If not, return False
for item in path:
if item not in self.adj_list:
return False
# Iterate through the path checking for valid connections from one vertex
# to the next, returning False if a connection is not valid
while count < length:
if path[count] in self.adj_list[path[count - 1]]:
return_val = True
count += 1
else:
return_val = False
break
return return_val
def dfs(self, v_start, v_end=None) -> []:
"""
Return list of vertices visited during DFS search
Vertices are picked in alphabetical order
"""
# Initialize lists for visited vertices and a stack
visited = []
stack = []
# If starting vertex doesn't exist, return empty list
if v_start not in self.adj_list:
return visited
# If v_end doesn't exist, set v_end to None
if v_end is not None and v_end not in self.adj_list:
v_end = None
# Append the starting vertex to the stack
stack.append(v_start)
# Iterate while the stack is non-empty
while len(stack) > 0:
# Pop the top value off the stack
pop_val = stack.pop()
# Sort the edges in the pop_val vertex in reverse order
temp_list = self.adj_list[pop_val]
temp_list.sort()
temp_list.reverse()
# If pop_val vertex has not been visited, append it to the visited list
if pop_val not in visited:
visited.append(pop_val)
# If we've reached the end specified by v_end, break out of loop
if pop_val == v_end:
break
# For each item in the sorted list of edges to vertices not yet visited, append to stack
for item in temp_list:
if item not in visited:
stack.append(item)
# Return the list of visited vertices
return visited
def bfs(self, v_start, v_end=None) -> []:
"""
Return list of vertices visited during BFS search
Vertices are picked in alphabetical order
"""
# Initialize empty lists for visited vertices and a queue
visited = []
queue = []
# If starting vertex doesn't exist, return empty list
if v_start not in self.adj_list:
return visited
# If v_end doesn't exist, set v_end to None
if v_end is not None and v_end not in self.adj_list:
v_end = None
# Append the starting vertex to the queue and list of visited vertices
queue.append(v_start)
visited.append(v_start)
# If the start and end vertices are the same, return the list
if v_start == v_end:
return visited
# Iterate while the queue is non-empty
while len(queue) > 0:
# Dequeue and sort the list of edges
dequeue = queue.pop(0)
temp_list = self.adj_list[dequeue]
temp_list.sort()
# Iterate through the list of edges adding vertices to the queue and
# visited list if they haven't been visited.
for item in temp_list:
if item not in visited:
visited.append(item)
queue.append(item)
# Break out of the loop if the end has been reached
if v_end in visited:
break
# Break out of the loop if the end has been reached
if v_end in visited:
break
# Return the list of visited vertices
return visited
def count_connected_components(self):
"""
Return number of connected components in the graph
"""
final_list = []
if len(self.adj_list) == 0:
return 0
# For each vertex, run a depth first search to get a list of vertices for
# that component, sort the list of vertices, and store in final_list as a tuple.
for key in self.adj_list:
dfs_list = self.dfs(key)
dfs_list.sort()
dfs_list = tuple(dfs_list)
final_list.append(dfs_list)
# Get the final count by finding the length of the list of unique, sorted dfs search results
final_count = len(set(final_list))
return final_count
def has_cycle(self):
"""
Return True if graph contains a cycle, False otherwise
Receives: Nothing
Returns: bool; True if cycle exists, False otherwise
"""
# Find the length of the adjacency list, and get list of vertices
length = len(self.adj_list)
list_vertices = self.get_vertices()
# Iterate through the range of the length of the adjacency list
for i in range(0, length):
# Initialize the first vertex, an empty list of visited vertices, and append first vertex
vertex = list_vertices[i]
visited = []
visited.append(vertex)
# Initialize empty queue
queue = []
# Append the first vertex and its parent to the queue (first vertex has no parent)
queue.append((vertex, -1))
while len(queue) > 0:
# Dequeue the vertex, parent info from the queue
(v, parent) = queue.pop(0)
# Iterate through the vertices connected to the vertex
for u in self.adj_list[v]:
# Append u to list of visited vertices, add u and its parent to the queue
if u not in visited:
visited.append(u)
queue.append((u, v))
# Return True if u is visited and is not a parent
elif u != parent:
return True
return False
if __name__ == '__main__':
print("\nPDF - method add_vertex() / add_edge example 1")
print("----------------------------------------------")
g = UndirectedGraph()
print(g)
for v in 'ABCDE':
g.add_vertex(v)
print(g)
g.add_vertex('A')
print(g)
for u, v in ['AB', 'AC', 'BC', 'BD', 'CD', 'CE', 'DE', ('B', 'C')]:
g.add_edge(u, v)
print(g)
print("\nPDF - method remove_edge() / remove_vertex example 1")
print("----------------------------------------------------")
g = UndirectedGraph(['AB', 'AC', 'BC', 'BD', 'CD', 'CE', 'DE'])
g.remove_vertex('DOES NOT EXIST')
g.remove_edge('A', 'B')
g.remove_edge('X', 'B')
print(g)
g.remove_vertex('D')
print(g)
#
#
print("\nPDF - method get_vertices() / get_edges() example 1")
print("---------------------------------------------------")
g = UndirectedGraph()
print(g.get_edges(), g.get_vertices(), sep='\n')
g = UndirectedGraph(['AB', 'AC', 'BC', 'BD', 'CD', 'CE'])
print(g.get_edges(), g.get_vertices(), sep='\n')
#
#
print("\nPDF - method is_valid_path() example 1")
print("--------------------------------------")
g = UndirectedGraph(['AB', 'AC', 'BC', 'BD', 'CD', 'CE', 'DE'])
test_cases = ['ABC', 'ADE', 'ECABDCBE', 'ACDECB', '', 'D', 'Z']
for path in test_cases:
print(list(path), g.is_valid_path(list(path)))
#
#
print("\nPDF - method dfs() and bfs() example 1")
print("--------------------------------------")
edges = ['AE', 'AC', 'BE', 'CE', 'CD', 'CB', 'BD', 'ED', 'BH', 'QG', 'FG']
g = UndirectedGraph(edges)
test_cases = 'ABCDEGH'
for case in test_cases:
print(f'{case} DFS:{g.dfs(case)} BFS:{g.bfs(case)}')
print('-----')
for i in range(1, len(test_cases)):
v1, v2 = test_cases[i], test_cases[-1 - i]
print(f'{v1}-{v2} DFS:{g.dfs(v1, v2)} BFS:{g.bfs(v1, v2)}')
#
#
print("\nPDF - method count_connected_components() example 1")
print("---------------------------------------------------")
edges = ['AE', 'AC', 'BE', 'CE', 'CD', 'CB', 'BD', 'ED', 'BH', 'QG', 'FG']
g = UndirectedGraph(edges)
test_cases = (
'add QH', 'remove FG', 'remove GQ', 'remove HQ',
'remove AE', 'remove CA', 'remove EB', 'remove CE', 'remove DE',
'remove BC', 'add EA', 'add EF', 'add GQ', 'add AC', 'add DQ',
'add EG', 'add QH', 'remove CD', 'remove BD', 'remove QG')
for case in test_cases:
command, edge = case.split()
u, v = edge
g.add_edge(u, v) if command == 'add' else g.remove_edge(u, v)
print(g.count_connected_components(), end=' ')
print()
#
#
print("\nPDF - method has_cycle() example 1")
print("----------------------------------")
edges = ['AE', 'AC', 'BE', 'CE', 'CD', 'CB', 'BD', 'ED', 'BH', 'QG', 'FG']
g = UndirectedGraph(edges)
test_cases = (
'add QH', 'remove FG', 'remove GQ', 'remove HQ',
'remove AE', 'remove CA', 'remove EB', 'remove CE', 'remove DE',
'remove BC', 'add EA', 'add EF', 'add GQ', 'add AC', 'add DQ',
'add EG', 'add QH', 'remove CD', 'remove BD', 'remove QG',
'add FG', 'remove GE')
for case in test_cases:
command, edge = case.split()
u, v = edge
g.add_edge(u, v) if command == 'add' else g.remove_edge(u, v)
print('{:<10}'.format(case), g.has_cycle())
|
cfd1fa7811f434c2f9293d8526e06122575c100b | dankeder/xbtarbiter | /xbtarbiter/forex.py | 675 | 3.640625 | 4 | import requests
from decimal import Decimal
def get_eurusd():
""" Return the current EUR/USD exchange rate from Yahho Finance API.
:return: Current EUR/USD exchange rate
"""
# See:
# http://code.google.com/p/yahoo-finance-managed/wiki/csvQuotesDownload
# http://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty
url = 'http://download.finance.yahoo.com/d/quotes.csv'
params = {
'f': 'l1',
's': 'EURUSD=X',
}
response = requests.get(url, params=params)
if response.status_code != 200:
raise Exception('Failed to get EURUSD exchange rate')
return Decimal(response.text)
|
aae8909ba175d168a6d2915e6ff312fca93eeb34 | Ecoste/MouseFlask | /db_manager.py | 2,743 | 3.578125 | 4 | __author__ = 'A pen is a pen'
import sqlite3
from contextlib import closing
import sys
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, self.__class__):
return Point(self.x + other.x, self.y + other.y)
else:
raise TypeError("unsupported operand type(s) for +: '{}' and '{}'").format(self.__class__, type(other))
def __str__(self):
return "{},{}".format(self.x, self.y)
Points = []
db = None
def init():
global db
with closing(connect()) as db:
with open('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def connect():
return sqlite3.connect("C:\\Users\\A pen is a pen\\PycharmProjects\\Flasky\\db\\mouse_data.db")
def close():
if db is not None:
db.close()
def getData(index):
return "C".join([str(Points[i]) for i in range(index, len(Points))]) + "C{}".format(len(Points))
def put(data):
def m(point):
Points.append(Point(*list(map(int, point.split(","))))) #This might be a little too much. Is it?
list(map(m, data.split("C")))
def connectionWrapper(func):
def func_wrapper(*args):
db = connect()
cur = db.cursor()
func(cur, *args)
close()
return func_wrapper
@connectionWrapper
def putIntoDatabase(cur, data):
def m(point):
cur.execute("INSERT INTO points (x, y) VALUES({},{});".format(*point.split(",")))
list(map(m, data.split("C")))
init()
'''Maybe this is better?
if uid is not 0 and index is not 0:
pass
elif uid is not 0 and index is 0:
pass
elif uid is 0 and index is not 0:
pass
elif uid is 0 and index is 0:
pass
'''
#cur = g.db.cursor()
#cur.execute("SELECT x, y FROM points{};".format(uid and " WHERE uid = {}".format(uid) or ""))
#values = cur.fetchall()
#return "C".join([str(Point(*values[i])) for i in range(index, len(values))]) + "C{}".format(len(values)) #pointCpointCpointCpoint...pointCindex
'''
#Tbh I have no idea if the recursive or normal one is better. I think the normal one is way easier to understand, but that might be because I've never written a recursive function before this one.
@app.route('/sendData/<path:data>', methods=['POST'])
def receiveData(data):
return "Derp"
cur = g.db.cursor()
cur.execute("INSERT INTO points (uid, x, y) VALUES({}, {},{});".format(session['uid'] ,*data.split("C",1)[0].split(","))) #Apparently, this is slow. Like, really slow.
g.db.commit()
print("Received data.")
if data.count("C") == 0:
return "Done"
else:
return receiveData(data.split("C",1)[1])
''' |
60e6e9b4d07b2072462161428e6721f8e22fc076 | 2dam-spopov/di | /P12_Sergey.py | 717 | 3.796875 | 4 | def copia(fichero):
"""
Se pasa por parámetro el nombre del fichero.
Crea dos ficheros, uno con nombre del fichero y otro con extensión bak.
Copia del archivo creado el contenido al archivo bak.
"""
fichero1 = open(str(fichero), "w+")
fichero2 = open(str(fichero) + "bak.txt", "w+")
respuesta = ""
while(respuesta != "n"):
respuesta = input("Introduce texto para fichero: ")
fichero1.write(respuesta + "\n")
respuesta = input("¿Otra línea s/n?: ")
print("El fichero y su copia se ha creado.")
fichero1.close()
fichero1 = open(fichero, "r")
for linea in fichero1:
fichero2.write(linea)
fichero1.close()
fichero2.close()
fichero = input("Introduce nombre del fichero: ")
copia(fichero) |
44e79a7adca8d55172f4e94c3644cc507c7dcffc | shivanshsen7/goeduhub | /assignment-1/assignment-1-q14.py | 626 | 4.03125 | 4 | """
Write a Python program to get next day of a given date.
Expected Output:
Input a year: 2016
Input a month [1-12]: 08
Input a day [1-31]: 23
The next date is [yyyy-mm-dd] 2016-8-24
"""
from datetime import date
print('''Input Format:
Year in format YYYY
Month in format MM
Day in format DD
e.g.: 2016 08 23''')
d = list(map(lambda x: int(x), input().strip().split()))
print(d)
d = date(d[0], d[1], d[2])
d += datetime.timedelta(days=1)
print(d)
|
95808b861c32248f3557a3957e39cbe06211f87b | Yifei-Deng/myPython-foundational-level-practice-code | /Woniu ATM version3.0.py | 3,691 | 3.5625 | 4 | '''
WoniuATM
a. 在前面项目的基础上进一步改进,要求使用一个二位列表来保存用户名和密码
b. 添加如下操作主菜单,用户选择对应的菜单选项进行操作,每次操作完成后继续进入主菜单,用户输入3之后可以结束并退出应用
*****************Welcome to Woniu ATM*****************
******Please Choose One of The Following Options******
**************1.Sign Up 2.Log In 3.Exit***************
'''
users = [
['Rey','5P1Wsl'],
['Rose','pPofPI'],
['Finn','FL4J4L']
]
def get_menu():
menu = '''
*****************Welcome to Woniu ATM*****************
******Please Choose One of The Following Options******
**************1.Sign Up 2.Log In 3.Exit***************
'''
while True:
print(menu)
op = input('Please enter your option: ')
if op == '1':
reg()
elif op == '2':
login()
elif op == '3':
print('Thanks for using Woniu ATM, see you next time...')
break
else:
print('Invalid input, please try again!')
def reg():
print("Welcome to Woniu ATM, sign up now!")
while True:
return_flag = True
user = input('Please enter the username for your new account: ')
for record in users:
if record[0] == user:
print('The username has already been taken, try another!')
return_flag = False
break
if return_flag:
break
while True:
pw = input('Please enter the password for your new account: ')
if len(pw) < 6:
print("Your password can't be less then 6 characters long, try another!")
else:
users.append([user,pw])
print('Thanks for signing up with Woniu ATM. Redirecting to the Start menu... ')
return
def login():
return_flag = False
while True:
user = input('Please enter your username: ')
pw = input('Please enter your password: ')
for record in users:
if record[0] == user and record[1] == pw:
print('Hello {}!'.format(user))
return_flag = True
break
if return_flag:
break
else:
print('The username or password you entered is incorrect, please try again!')
if __name__ == '__main__':
get_menu()
'''
Example Outputs:
*****************Welcome to Woniu ATM*****************
******Please Choose One of The Following Options******
**************1.Sign Up 2.Log In 3.Exit***************
Please enter your option: 1
Welcome to Woniu ATM, sign up now!
Please enter the username for your new account: Rey
The username has already been taken, try another!
Please enter the username for your new account: Poe
Please enter the password for your new account: 123
Your password can't be less then 6 characters long, try another!
Please enter the password for your new account: 123456
Thanks for signing up with Woniu ATM. Redirecting to the Start menu...
*****************Welcome to Woniu ATM*****************
******Please Choose One of The Following Options******
**************1.Sign Up 2.Log In 3.Exit***************
Please enter your option: 2
Please enter your username: Poe
Please enter your password: 123456
Hello Poe!
*****************Welcome to Woniu ATM*****************
******Please Choose One of The Following Options******
**************1.Sign Up 2.Log In 3.Exit***************
Please enter your option: 3
Thanks for using Woniu ATM, see you next time...
'''
|
6b722c5fedcd4aa172eb7b85c4470f344d596bcd | YossiBenZaken/Python-Scripts | /1.py | 372 | 3.515625 | 4 | '''
Yossi Ben Zaken ID:315368134
'''
#-------Targil 1----
H=int(input("Enter hours of start:"))
M=int(input("Enter minutes of start:"))
S=int(input("Enter seconds of start:"))
FL=int(input("Enter seconds of flight time:"))
time=FL+S+M*60+H*3600
D=time//86400
H=time%86400//3600
M=time%3600//60
S=time%3600%60
print('Days = {} Hours = {} Minutes = {} Seconds = {}'.format(D,H,M,S))
|
ee76a5f4ac36d3eb1de623cfeb5e4ff5c7b58799 | HMurkute/PythonNumpy | /LearnNumpy3.py | 1,187 | 4.65625 | 5 | import numpy as np
# To perform linespacing we use '.linspace' function. Linespacing means printing
# values between two points divided equally.
a = np.linspace(1, 10, 5) # The syntax is like this '(start,stop,no. of values)'.
print(a)
# For finding the min, max, sum we use functions like below
# Let's define an array
a = np.array([(1, 2, 3), (4, 5, 6)])
# Now for sum
print(a.sum()) # Print the sum of the array
print(a.max()) # Print the max number present in the array
print(a.min()) # Print the min number present in the array
# To print sum of rows or columns
# We refer rows as axis 1 and columns as axis 0.
# To calculate we are using array 'a' from the top.
print(a.sum(axis=0))
print(a.sum(axis=1))
# To print the sqrt of the array 'a' we do like below
print(np.sqrt(a))
# To print the standard deviation we do like below
print(np.std(a))
# To do addition, subtract, multiply, divide. For that we have to define a new array let's take 'a' array only.
# To do follow below
b = np.array([(1, 2, 3), (4, 5, 6)])
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
|
6db8f79a1209cd06ab9c1ba797b22f1c125d3cd8 | Dexton/advent2020 | /d6/d6-p2.py | 682 | 3.546875 | 4 | input = open("input", "r")
groups = []
group = set()
first_in_group = True
for line in input:
person = set()
if line == '\n':
groups.append(group)
group = {}
first_in_group = True
continue
for char in line.strip():
person.add(char)
if first_in_group:
group = person
first_in_group = False
else:
# Set the group as all the yes answers from this person that match the
# yes answers from the previous persons in the group
group = group.intersection(person)
count = 0
for i, group in enumerate(groups):
print(f"{i+1}: {len(group)} {group}")
count += len(group)
print(count) |
49661d5de0169b0c0f3d798f022a4d6c7b3aff87 | pswilson/WordSolver | /python/Dictionary.py | 2,227 | 3.8125 | 4 | # Basic Word Dictionary
# to support a Word Solver and Boggle Solver
DEFAULT_DICTIONARY_FILE = 'twl06.txt'
# Private class to keep track of whether a node is a prefix and/or a word
class _DictionaryNode:
is_prefix = False
is_word = False
# The Dictionary class itself
class Dictionary:
def __init__(self, dictionary_file = DEFAULT_DICTIONARY_FILE):
# Use a map of DictionaryNodes to store each prefix/word
self.data = {}
self.prefix_count = 0
self.word_count = 0
# TODO: Error handling
# TODO: User pkg_resources to get the file path
with open(dictionary_file, 'r') as f:
for line in f:
self.add_word(line.strip())
print('Added {} prefixes and {} words to the dictionary.'.format(self.prefix_count, self.word_count))
def add_word(self, word: str):
if len(word) == 0:
return
# Normalize case before we put things in the dictionary
word = word.upper()
# Build up all of the prefixes for this word
# add to the dictionary if necessary and set the prefix flag
for i in range(1, len(word)):
p = word[:i]
if not p in self.data:
self.data[p] = _DictionaryNode()
if not self.data[p].is_prefix:
self.prefix_count += 1
self.data[p].is_prefix = True
# make sure we add the word itself and set the word flag
if not word in self.data:
self.data[word] = _DictionaryNode()
self.word_count += 1
self.data[word].is_word = True
def remove_word(self, word: str):
print('removing word {}'.format(word))
word = word.upper()
# TODO:
# This is problematic with the flat implementation
# since we won't be able to easily tell if any prefixes
# from this word are also prefixes for other words
def is_prefix(self, word: str) -> bool:
if word in self.data:
return self.data[word].is_prefix
return False
def is_word(self, word: str) -> bool:
if word in self.data:
return self.data[word].is_word
return False
|
0e271b9c239a95d7a589e3d3aedf22f8e60c53bd | sakurasakura1996/Leetcode | /二叉树/problem563_二叉树的坡度.py | 1,312 | 4.09375 | 4 | """
563. 二叉树的坡度
给定一个二叉树,计算整个树的坡度。
一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
整个树的坡度就是其所有节点的坡度之和。
示例:
输入:
1
/ \
2 3
输出:1
解释:
结点 2 的坡度: 0
结点 3 的坡度: 0
结点 1 的坡度: |2-3| = 1
树的坡度 : 0 + 0 + 1 = 1
提示:
任何子树的结点的和不会超过 32 位整数的范围。
坡度的值不会超过 32 位整数的范围。
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumTree(self, root:TreeNode)->int:
# 计算以root为根节点的树的结点之和
if not root:
return 0
left = self.sumTree(root.left)
right = self.sumTree(root.right)
return left + right + root.val
def findTilt(self, root: TreeNode) -> int:
if not root:
return 0
left = self.sumTree(root.left)
right = self.sumTree(root.right)
left_tilt = self.findTilt(root.left)
right_tilt = self.findTilt(root.right)
return left_tilt + right_tilt + abs(left-right)
|
abf8f381154347bc738a45bd00438e18dddaac03 | GourabRoy551/Python_Codes_2 | /Matplotlib/BarChart.py | 603 | 3.78125 | 4 | import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.bar(x_pos, popularity, color='blue')
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("Popularity of Programming Language\n" + "Worldwide, Oct 2017 compared to a year ago")
plt.xticks(x_pos, x)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()
|
a130af5c3ec8cd82ba7b0999c3e2deecb26e2cb6 | LucMc/backup-of-old-projects | /go.py | 3,835 | 3.5 | 4 | import pygame
import numpy as np
pygame.init()
display_width = 600
display_height = 600
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('GO')
clock = pygame.time.Clock()
black = (0,0,0)
white = (255,255,255)
grey = (200,140,70)
points = []
board_size = 9
board = np.zeros((10,10))
positions = []
def __init__():
global positions
temp = []
for y in range(11):
positions.append(temp)
temp = []
for x in range(11):
temp.append((40+x*60, 40+y*60))
positions = positions[1:]
game_loop()
def draw_board():
gameDisplay.fill(grey)
for i in range(40, board_size*60, 60):
pygame.draw.lines(gameDisplay, black, True, [(40, i), (580, i)], 5)
pygame.draw.lines(gameDisplay, black, True, [(i, 40), (i, 580)], 5)
pygame.draw.circle(gameDisplay, black, (160, 160), 10)
pygame.draw.circle(gameDisplay, black, (460, 160), 10)
pygame.draw.circle(gameDisplay, black, (160, 460), 10)
pygame.draw.circle(gameDisplay, black, (460, 460), 10)
pygame.draw.rect(gameDisplay, black, (40, 40, 540, 540), 10)
pygame.display.update()
def update():
# Add 2's to outside to make edges
draw_board()
for x in range(10):
for y in range(10):
if board[y][x] == -1.: #change to -1
pygame.draw.circle(gameDisplay, white, positions[x][y], 17) # can change to pos x,y if I want
elif board[y][x] == 1.:
pygame.draw.circle(gameDisplay, black, positions[x][y], 17)
pygame.display.update()
def check_capture():
for row in range(board_size):
for value in range(board_size):
for i in [-1,1]:
# Normal case
if (board[row][value] == i and board[row-1][value] == -i and board[row+1][value] == -i) and (board[row][value-1] == -i and board[row][value+1] == -i):
board[row][value] = 0
update()
# Still takes go on illegal move, perhaps remove the first argument in this if statement and add a check_if_valid function
# Capturing Multiple
# If its left is also filled
if (board[row][value] == i and board[row-1][value] == i and board[row+1][value] == -i) and (board[row][value-1] == -i and board[row][value+1] == -i):
if (board[row-1][value] == i and # It is filled
board[row-2][value] == -i and # Its left is filled
# removed right
board[row-1][value - 1] == -i and # Its top is filled
board[row-1][value + 1] == -i): # Its bottom is filled
board[row-1][value] = 0
board[row][value] = 0
update()
#print(row, value)
print('\n\n', board)
def game_loop():
gameExit = False
turn = 1
update()
# Main Loop
while not gameExit:
# event handling
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
y = 0
mouse = pygame.mouse.get_pos()
for pos in positions:
y += 1
for x in range(10):
if (int(pos[x][0])-10 <= int(mouse[0]) <= int(pos[x][0])+10) and (int(pos[x][1])-10 <= int(mouse[1]) <= int(pos[x][1])+10) and (board[x][positions.index(pos)] == 0):
board[x][positions.index(pos)] = turn
turn = -turn
update()
check_capture()
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.update()
clock.tick(120)
__init__()
pygame.quit()
quit()
|
b06d55c44206ca9329252496cac69efa6f4a474b | luid95/Python-Django | /python/POO2.py | 828 | 3.90625 | 4 | #INHERITANCE
class Animal():
def __init__(self):
print("Animal created")
def WhoAmI(self):
print("Animal")
def eat(self):
print("Eating")
class Dog(Animal):
def __init__(self):
print("Dog created")
def bark(self):
print("Woof")
myd = Dog()
myd.WhoAmI()
myd.eat()
myd.bark()
#SPECIAL METHODS
class Book():
def __init__(self, tittle, author, pages):
self.tittle = tittle
self.author = author
self.pages = pages
def __str__(self):
return "Tittle: {}, Author: {}, Pages: {}".format(self.tittle, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print("A book is destroyed!")
b = Book("Python", "Luis", 200)
print(b)
print(len(b))
del b
list = [1,2,3,4]
print(list)
|
f60f18fd350cb56f2abf2d670109a397658b5e88 | ComteAgustin/learning-py | /tuples.py | 236 | 3.890625 | 4 | # Tuples can't be modified and are more secure than lists
tuple = (1, 2, 3)
x = tuple((1, 2, 3)) # > (1, 2, 3)
singleTuple = (1)
print(singleTuple) # > class 'int'>
# del, delete all the tuple
del tuple # > error, tuple doesn't exist
|
bfb9b7939d291f9baa3ace1188fa53b3501e362a | WeiS49/Python-Crash-Course | /python_work/ch9/practice/9-5 sign_in_count.py | 1,574 | 4 | 4 |
class User:
""" simulate person. """
def __init__(self, first_name, last_name):
""" Initialize property first_name and last_name. """
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
# 声明的变量不用self的, 只能作用于这个函数
# full_name = self.first_name + self.last_name
def describe_user(self):
""" Print user info. """
# 像这样的变量只有先调用这个函数才能生成, 其他函数与才可用
self.full_name = f"{self.first_name} {self.last_name}"
print(f"\nYour name is {self.full_name.title()}.")
def greet_user(self):
""" Send personalize message to user. """
print(f"\tHello, {self.full_name.title()}!")
def read_login_attempts(self):
""" Print the number of login attempts. """
print(f"\nYou have failed login for {str(self.login_attempts)} times")
def increment_login_attempts(self):
""" Increse the number of login attempts. """
self.login_attempts += 1
def reset_login_attempts(self):
""" Reset the number of login attempts to 0. """
self.login_attempts = 0
user = User("w", "s")
user.describe_user() # 用这条语句生成full_name变量, 下面的函数才可用
user.greet_user()
print("--------------")
user.read_login_attempts()
user.increment_login_attempts()
user.increment_login_attempts()
user.increment_login_attempts()
user.read_login_attempts()
user.reset_login_attempts()
user.read_login_attempts()
|
488355f5922b03b19f82365a0a6462ae0c3cb011 | reddyachyuth/python_devops | /InterPython/1.py | 99 | 3.859375 | 4 | sum = 0
a = input("enter a number for range:")
for i in range(a):
sum = sum +i
print sum
|
7ae31c4b365c7073ed23e6ebaf90d491f082b8a9 | uludag-udl/Python_Beginner | /8_Fonskiyonlar/Rg_first.py | 602 | 3.96875 | 4 | firstNumber=int(input("Bir Sayı Giriniz: "))
secondNumber=int(input("Bir Daha Sayi Giriniz: "))
print("\nfirstNumber : {}\nsecondNumber : {}\n".format(firstNumber,secondNumber))
def calculator(firstNumber,secondNumber,default):
if default=="add":
return firstNumber+secondNumber
if default=="sub":
return firstNumber-secondNumber
if default=="div":
return firstNumber/secondNumber
if default=="mul":
return firstNumber*secondNumber
operation=calculator(firstNumber,secondNumber,"add")
print(f"Yapılan işlemin Sonucu ==> {operation}") #f print ile
|
0ef4199cdaf6ca9dadb3f3651aa1db34683b2b68 | saurav188/python_practice_projects | /largest_no.py | 853 | 3.71875 | 4 | def fact(n):
temp=1
for i in range(1,n+1):
temp*=i
return temp
def get_num(nums,indexes):
temp=''
for index in indexes:
temp+=str(nums[index])
return int(temp)
def largestNum(nums):
largest=0
indexes=[i for i in range(len(nums))]
for each in range(fact(len(nums))):
temp=get_num(nums,indexes)
if largest<temp:
largest=temp
x=0
for i in range(len(indexes)-1,-1,-1):
if indexes[i]>indexes[i-1]:
x=i-1
break
y=0
for i in range(len(indexes)-1,-1,-1):
if indexes[i]>indexes[x]:
y=i
break
indexes[x],indexes[y]=indexes[y],indexes[x]
indexes=indexes[:x+1]+indexes[x+1:][::-1]
return largest
print(largestNum([17, 7, 2, 45, 72]))
# 77245217 |
4680c89c982aa13768fe37f39e121241a308771a | Vijay1126/Interview-Prep | /Amazon/flatten.py | 1,003 | 3.765625 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def (self, head: 'Node') -> 'Node':
if not head:
return head
start = head
stack = [head]
while True:
start = stack.pop()
while start.next or start.child:
if start.child:
if start.next:
stack.append(start.next)
start.next = start.child
start.child.prev = start
start.child = None
start = start.next
if stack:
start.next = stack[-1]
stack[-1].prev = start
else:
break
h = head
while h:
# print(h.child, h.val, h.next)
h = h.next
return head
|
f2559b676347ccef18c87896ad64bfdd57e368bb | IrynaKucherenko/hw_repository | /hw2/leap_year.py | 395 | 4.125 | 4 | """
Вводится год.
Программа выводит количество дней в году, учитывая високосный год.
* високосный год кратный 4, но не кратный 100 или кратный 400
"""
a = int(input("year: "))
if a % 4 != 0 or a % 100 == 0 and a % 400 != 0:
print("365 days")
else:
print("366 days")
|
a6753878ec2386822da3e6e61370f6fcc103e9d3 | Estefa29/Ejercicios_con_Python | /Examen1NT/marceliano.py | 1,498 | 4.0625 | 4 | # La escuela marceliano desea obtener el promedio de notas de un grupo de 25 estudiantes,
# y los 25 se les solicita 5 notas por cada una de las materias (matemática y lenguaje).
# Se debe imprimir el promedio de notas por cada materia, se debe imprimir el promedio de
# notas de las dos asignaturas por estudiante y se debe imprimir el total general del grupo.
# (Ciclos anidados)
# Las 5 notas de los estudiantes
promedio=0
suma=0
estudiantes=int(input("Ingrese numero de estudiantes: "))
while(estudiantes<25):
nombre=input("Ingrese su nombre: ")
print(nombre)
matematicas=0
while(matematicas<5):
notamateria1=float(input("ingrese la nota de matematicas: "))
suma=suma+notamateria1
print (matematicas)
matematicas=matematicas+1
promedio=suma/5
print ("El promedio de matematicas es ",promedio)
promedio2=0
suma2=0
lenguaje=0
while(lenguaje<5):
notamateria2=float(input("ingrese las notas de lenguaje : "))
suma2=suma2+notamateria2
print (lenguaje)
lenguaje=lenguaje+1
promedio2=suma2/5
print ("El promedio de lenguaje es ",promedio2)
promedioA=(promedio+promedio2)/2
estudiantes=estudiantes+1
totGrup=(estudiantes + promedioA)/25
print("El numero de personas es:",estudiantes)
print("El total general del grupo es,",totGrup)
print("El promedio de las dos asignaturas es:" ,promedioA)
|
a44b2b5427baebd95b4607f14573a61fdf1db487 | mustafabinothman/cs50 | /6__Python__/pset6/dna/dna.py | 664 | 3.640625 | 4 | import sys
import csv
if len(sys.argv) != 3:
sys.exit("Usage: python dna.py database.csv sequence.txt")
database = sys.argv[1]
with open(database) as file:
db_data = [row for row in csv.DictReader(file)]
sequence = sys.argv[2]
with open(sequence) as file:
seq_data = file.read()
counts = {}
for key in db_data[0].keys():
if key == 'name':
continue
most = 1
while key * most in seq_data:
most += 1
counts[key] = str(most - 1)
found = False
for row in db_data:
name = row.pop('name')
if row.items() == counts.items():
found = True
print(name)
break
if not found:
print("No match") |
3e9596e0d0f6f692d66665f847af83020f83577c | JapoDeveloper/think-python | /exercises/chapter9/words.py | 358 | 4.25 | 4 | """
Helper functions that will be used in several exercises into the chapter
"""
def list_words():
"""return a list of words"""
fin = open('words.txt')
words = []
for line in fin:
words.append(line.strip())
fin.close()
return words
def is_palindrome(s):
"""check if a string is a palindrome"""
return s == s[::-1]
|
c9cb5b875a347bf40584759abaf6f97fdf4bcdc5 | Remyaaadwik171017/mypythonprograms | /collections/dictionary/advanced python/oops/inheritance/hiarchy.py | 682 | 3.984375 | 4 | #multilevel inheritance/hiarchial inheritance
class Parent:
parentname="Ajith"
def m1(self,age):
self.age=age
print("I am father of adwik.my name is ",Parent.parentname)
class Mom(Parent):
def m2(self,name):
self.name=name
print("I am",self.name,"mother of Aadwik")
print("my husband name",Parent.parentname)
class Child(Mom):
def m3(self,age1):
self.age1=age1
print("my father name is",Parent.parentname)
print("My mom's name is", self.name)
print("My father name",self.age)
print("child age",self.age1)
obj=Child()
obj.m1(23)
obj.m2("Resmi")
obj.m3(3)
a=Mom()
a.m1(23)
a.m2("Remya") |
e7eeb5e3a2f2f82af679a486348df72c89775ac4 | zhiymatt/Leetcode | /Python/30.substring-with-concatenation-of-all-words.131470044.ac.py | 1,698 | 3.8125 | 4 | #
# [30] Substring with Concatenation of All Words
#
# https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/
#
# algorithms
# Hard (22.26%)
# Total Accepted: 95.9K
# Total Submissions: 430.9K
# Testcase Example: '"barfoothefoobarman"\n["foo","bar"]'
#
#
# You are given a string, s, and a list of words, words, that are all of the
# same length. Find all starting indices of substring(s) in s that is a
# concatenation of each word in words exactly once and without any intervening
# characters.
#
#
#
# For example, given:
# s: "barfoothefoobarman"
# words: ["foo", "bar"]
#
#
#
# You should return the indices: [0,9].
# (order does not matter).
#
#
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
wordsDict = {}
wordsNum = len(words)
for word in words:
if word not in wordsDict:
wordsDict[word] = 1
else:
wordsDict[word] += 1
wordLen = len(words[0])
res = []
for i in range(len(s) + 1 - wordLen * wordsNum):
curr = {}
j = 0
while j < wordsNum:
word = s[i + j * wordLen : i + j * wordLen + wordLen]
if word not in wordsDict:
break
if word not in curr:
curr[word] = 1
else:
curr[word] += 1
if curr[word] > wordsDict[word]:
break
j += 1
if j == wordsNum:
res.append(i)
return res
|
e7817ae275899c458e618af2d22c865bc11cc39b | Neha-kumari200/python-Project2 | /wordsgreterthank.py | 290 | 4.375 | 4 | #Find words which are greater than given length k
def stringLength(k, str):
string = []
text = str.split(" ")
for x in text:
if len(x) > k:
string.append(x)
res = ' '.join(string)
return res
k = 3
str = "Neha is Nehas"
print(stringLength(k, str))
|
8353db478540285ef3e745d7ed465299faed716d | Daniyal963/Programming-LAB-04 | /Question no.5.py | 363 | 3.96875 | 4 | print("Daniyal Ali - 18b-096-CS(A)")
print("Lab-4 - 09/Nov/2018")
print("Question no.5")
#Code
initial_value = eval(input("Enter the initial value for the range :"))
final_value = eval(input("Enter the final value for the range :"))
numbers = range(initial_value,final_value)
sum = 0
for value in numbers:
sum = sum + value
print("The sum is", sum)
|
256539a03c1dec74130e0c616f4da6951aa9d7c8 | Jinny-s/ddit_python_backUp | /HELLOPYTHON/day02/exer02.py | 316 | 3.796875 | 4 | #Exer 02
#첫 숫자를 입력하시오 : 1
#끝 숫자를 입력하시오 : 3
#모든 수의 합은 '6'입니다 (1~3 덧셈)
a = int(input("첫 숫자를 입력하시오"))
b = int(input("끝 숫자를 입력하시오"))
c = 0
for i in range(a, b+1):
c += i
print("모든 수의 합은 {}입니다".format(c)) |
a3bcf6842e7cf5082adde20e5745197925eaabd9 | japarker02446/BUProjects | /CS521 Data Structures with Python/Homework2/japarker_hw_2_3.py | 526 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
japarker_hw_2_3.py
Jefferson Parker
Class: CS 521 - Spring 1
Date: January 27, 2022
Prompt the user for a number. Calculate the cube of that number divided by
the number. Print the formula and result using the entered value, limited
to two decimal places.
# REFERENCE: https://pythonguides.com/python-print-2-decimal-places/
"""
user_num = float(input("Please enter a number: "))
format_val = "{:.2f}".format(user_num**3/user_num)
print (user_num, "**3/", user_num, " = ", format_val)
|
60f2a7146b46cc8275f1a5672199d0ec9cf994fd | Robinthatdoesnotsuck/Python-misc | /cola.py | 100 | 3.65625 | 4 | print("micola")
print("a iram le huele la cola")
for i in range(10):
print("contar " + str(i))
|
57796a4dcc6064f082813d53cdb19321ebddd62e | svicaria/svicaria.github.io | /Curso_basico_python/conversor_a_cop.py | 181 | 3.578125 | 4 | USD = input('¿Ingrese los USD que desea convertir? ')
USD = float(USD)
TRM = 3768
COP = USD*TRM
COP = round(COP, 1)
COP = str(COP)
print('Tendrías $ '+ COP + ' Pesos colombianos') |
423612f123db3b6593b131b5a8929bc4d38bd1ee | ykurylyak87/udemy | /methods/methodsdemo1_2.py | 354 | 4.03125 | 4 | def sum_nums(a, b):
"""
Get sum of two numbers
:param a:
:param b:
:return:
"""
return a + b
c = sum_nums(5, 5)
print(c)
def is_metro(city):
l = ['sfo', 'nyc', 'la']
if city in l:
return True
else:
return False
x = is_metro('sfo')
print(x)
y = is_metro(input("Input a city name: "))
print(y)
|
e16d3e6c8040204e8ca4e90f34379923d633d6cf | JhordanRojas/test | /perro/boleta restaurante.py | 1,521 | 3.984375 | 4 | #input
nombre_cliente=input("inserte el nombre del cliente:")
nombre_mesero=input("ingrese el nombre del mesero:")
cant_arroz_pato=int(input("ingrese la cantidad de arroz con pato:"))
precio_arroz=int(input("ingrese el precio unitario del arroz con pato:"))
cant_chica=int(input("ingres la cantidad de jarras de chicha:"))
precio_chicha=int(input("ingrese el precio unitario de la chicha"))
cant_gelatina=int(input("ingrese la cantidad de la gelatina:"))
precio_gelatina=int(input("ingrese el precio de la gelatina:"))
#processing
total_arroz=(cant_arroz_pato*precio_arroz)
total_chicha=(cant_chica*precio_chicha)
total_gelatina=(cant_gelatina*precio_gelatina)
consumo=(total_arroz+total_chicha+total_gelatina)
igv=(consumo*0.18)
total_pago=(consumo+igv)
#output
print("######################################")
print("# RESTAURANTE - PATO RICO CON LOCHE ")
print("######################################")
print("#Cliente:",nombre_cliente," Mesero:",nombre_mesero)
print("######################################")
print("#Producto cantidad P.U. total")
print("#Arroz con pato:" ,cant_arroz_pato,precio_arroz ,total_arroz)
print("#Jarra de chicha:",cant_chica ,precio_chicha ,total_chicha)
print("#Gelatina:" ,cant_gelatina ,precio_gelatina,total_gelatina)
print("######################################")
print("#Consumo :" ,consumo)
print("#IGV :" ,igv )
print("#Total a pagar :" ,total_pago)
print("######################################")
|
fd3760b1c30d5896f18f955ff10ee71a831aa25e | gschen/sctu-ds-2020 | /1906101063-何章逸/day0229/test06.py | 414 | 3.5 | 4 | #6. (使用def函数完成)编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n
def he(n):
sum=0
if n % 2==0:
for i in range(2,n+2,2):
k=1/i
sum+=k
return sum
else:
for i in range(1,n+1,2):
k=1/i
sum+=k
return sum
n=int(input())
print(he(n))
|
9ab57c5cc1b542d38737f5c3ca118f0383c80e27 | nvenegas-oliva/training | /hacker-rank/algorithms/grading_students.py | 611 | 3.5625 | 4 | import sys
def next_mult(num, mult):
num = num + 1
while num % mult != 0:
num = num + 1
return num
def solve(grades):
result = []
for g in grades:
if g >= 38 and next_mult(g, 5) - g < 3:
result.append(next_mult(g, 5))
else:
result.append(g)
return result
# return map(lambda x: 5*(1 + x//5) if (x > 37 and ((x%5) > 2)) else x, grades)
n = int(input().strip())
grades = []
grades_i = 0
for grades_i in range(n):
grades_t = int(input().strip())
grades.append(grades_t)
result = solve(grades)
print ("\n".join(map(str, result)))
|
1efb7cd8d66c9a4e3e8d4023c410cb395eacd57e | AGrigaluns/Algorithm-A1 | /exercise/ex1Operators.py | 398 | 4.28125 | 4 |
# Task
# The provided code stub reads two integers from STDIN, and
# . Add code to print three lines where:
# The first line contains the sum of the two numbers.
# The second line contains the difference of the two numbers (first - second).
# The third line contains the product of the two numbers.
a = int(input())
b = int(input())
print('{0} \n{1} \n{2}'.format((a + b), (a - b), (a * b)))
|
379529efd31b20db8b304795a440818faa800b79 | Charlzzz/mainhub | /Pystudy/lesson1step14.py | 425 | 3.75 | 4 | x = str(input())
if x == ("прямоугольник"):
a = int(input())
b = int(input())
s = (a * b)
print(s);
if x == ("круг"):
a = int(input())
pi = float(3.14)
s = float(pi * a ** 2)
print(s);
if x == ("треугольник"):
a = int(input())
b = int(input())
c = int(input())
p = (a + b + c) / 2 # 6
s = (p * (p - a) * (p - b) * (p - c)) ** 0.5
print(s);
|
c0f59471bed7cab235d17c27b0d27c0f78990d94 | fpgmaas/project-euler | /euler549.py | 2,668 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 21 11:17:36 2017
@author: florian
"""
import math
from sympy import sieve
from collections import Counter
def primefacs(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
def findlowest(x,n):
total = 0
i = 0
while(total<n):
i=i+x
j = i
while( j % x ==0):
total+=1
j = j/x
return(i)
total=0
N=100
primes = list(sieve.primerange(1, N+1))
for n in range(2,N+1):
if n in primes:
total += n
maximum = n
else:
factors = primefacs(n)
counter = Counter(factors)
maximum=0
for x in counter:
new = findlowest(x,counter.get(x))
if(new>maximum):
maximum=new
total+=maximum
#print('n: ' + str(n) + ', max: ' + str(maximum))
# simple brute force.
total=0
N = 10000
for n in range(2,N+1):
x = 2
found = False
while not found:
if math.factorial(x) % n ==0:
found =True
else:
x+=1
total+=x
print('n: ' + str(n) + ', x: ' + str(x))
#n: 2, x: 2
#n: 3, x: 3
#n: 4, x: 4
#n: 5, x: 5
#n: 6, x: 3
#n: 7, x: 7
#n: 8, x: 4
#n: 9, x: 6
#n: 10, x: 5
#n: 11, x: 11
#n: 12, x: 4
#n: 13, x: 13
#n: 14, x: 7
#n: 15, x: 5
#n: 16, x: 6
#n: 17, x: 17
#n: 18, x: 6
#n: 19, x: 19
#n: 20, x: 5
#n: 21, x: 7
#n: 22, x: 11
#n: 23, x: 23
#n: 24, x: 4
#n: 25, x: 10
#n: 26, x: 13
#n: 27, x: 9
#n: 28, x: 7
#n: 29, x: 29
#n: 30, x: 5
#n: 31, x: 31
#n: 32, x: 8
#n: 33, x: 11
#n: 34, x: 17
#n: 35, x: 7
#n: 36, x: 6
#n: 37, x: 37
#n: 38, x: 19
#n: 39, x: 13
#n: 40, x: 5
#n: 41, x: 41
#n: 42, x: 7
#n: 43, x: 43
#n: 44, x: 11
#n: 45, x: 6
#n: 46, x: 23
#n: 47, x: 47
#n: 48, x: 6
#n: 49, x: 14
#n: 50, x: 10
#n: 51, x: 17
#n: 52, x: 13
#n: 53, x: 53
#n: 54, x: 9
#n: 55, x: 11
#n: 56, x: 7
#n: 57, x: 19
#n: 58, x: 29
#n: 59, x: 59
#n: 60, x: 5
#n: 61, x: 61
#n: 62, x: 31
#n: 63, x: 7
#n: 64, x: 8
#n: 65, x: 13
#n: 66, x: 11
#n: 67, x: 67
#n: 68, x: 17
#n: 69, x: 23
#n: 70, x: 7
#n: 71, x: 71
#n: 72, x: 6
#n: 73, x: 73
#n: 74, x: 37
#n: 75, x: 10
#n: 76, x: 19
#n: 77, x: 11
#n: 78, x: 13
#n: 79, x: 79
#n: 80, x: 6
#n: 81, x: 9
#n: 82, x: 41
#n: 83, x: 83
#n: 84, x: 7
#n: 85, x: 17
#n: 86, x: 43
#n: 87, x: 29
#n: 88, x: 11
#n: 89, x: 89
#n: 90, x: 6
#n: 91, x: 13
#n: 92, x: 23
#n: 93, x: 31
#n: 94, x: 47
#n: 95, x: 19
#n: 96, x: 8
#n: 97, x: 97
#n: 98, x: 14
#n: 99, x: 11 |
82c6e2e4d2284eed5bf1625b40ab570dabfda5ba | broadlxx/171-172-271python- | /dayi/tutorial 10/Problem 5.py | 380 | 3.734375 | 4 | def getdetails():
if a=="quit":
print(items)
return None
else:
dictionary={}
dictionary['title']=input("What the title is:")
dictionary['cost']=input("What the title is:")
items.append(dictionary)
items=[]
while True:
a=input("answer")
if a=="quit":
getdetails()
break
else:
getdetails()
|
2e38845a8b0cf24d145ecc040faa521f1c9c6f42 | feecoding/Python | /Loops/Program 21.py | 102 | 3.609375 | 4 | ##created by feecoding
n=int(input("Type a number :"))
d=0
for i in range(1,n+1):
d=d+i
print(d)
|
e15ce01fd4d4eab58458e8c49c9c251dc5b62cb2 | rjmarshall17/trees | /leet_code_lowest_common_ancestor.py | 3,803 | 3.8125 | 4 | #!/usr/bin/env python3
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
ret = str(self.val)
ret += " left: %s" % ("None" if self.left is None else str(self.left.val))
ret += " right: %s" % ("None" if self.right is None else str(self.right.val))
return ret
"""
236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
From Wikipedia:
In graph theory and computer science, the lowest common ancestor (LCA) of two nodes v and w in
a tree or directed acyclic graph (DAG) T is the lowest (i.e. deepest) node that has both v and
w as descendants, where we define each node to be a descendant of itself (so if v has a direct
connection from w, w is the lowest common ancestor).
According to the definition of LCA on Wikipedia: ?The lowest common ancestor is defined between
two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow
a node to be a descendant of itself).?
Example 1:
3
/ \
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
3
/ \
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [1,2], p = 1, q = 2
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 105].
-10**9 <= Node.val <= 10**9
All Node.val are unique.
p != q
p and q will exist in the tree.
"""
def print_tree(tree):
if tree is None:
return
print("%s" % tree)
print_tree(tree.left)
print_tree(tree.right)
"""
A recursive solution for this challenge:
lowest_common_ancestor(root, p, q)
if p < root and q < root
lowest_common_ancestor(root.left, p, q)
if p > root and q > root
lowest_common_ancestor(root.right, p, q)
return root - At this point, this should be the lowest common ancestor
"""
def lowest_common_ancestor(root, p, q):
print("root=%s\n\tp=%s\n\tq=%s" % (root, p, q))
if root is None:
return None
if p.val < root.val and q.val < root.val:
return lowest_common_ancestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return lowest_common_ancestor(root.right, p, q)
else:
return root
bst1_tn0 = TreeNode(0)
bst1_tn1 = TreeNode(1)
bst1_tn2 = TreeNode(2)
bst1_tn3 = TreeNode(3)
bst1_tn4 = TreeNode(4)
bst1_tn5 = TreeNode(5)
bst1_tn6 = TreeNode(6)
bst1_tn7 = TreeNode(7)
bst1_tn8 = TreeNode(8)
bst1_tn9 = TreeNode(9)
bst1_tn6.left = bst1_tn2
bst1_tn6.right = bst1_tn8
bst1_tn2.left = bst1_tn0
bst1_tn2.right = bst1_tn4
bst1_tn8.left = bst1_tn7
bst1_tn8.right = bst1_tn9
bst1_tn4.left = bst1_tn3
bst1_tn4.right = bst1_tn5
bst2_tn1 = TreeNode(1)
bst2_tn2 = TreeNode(2)
bst2_tn2.left = bst2_tn1
if __name__ == '__main__':
print_tree(bst1_tn6)
print('='*80)
result = lowest_common_ancestor(bst1_tn6, bst1_tn2, bst1_tn4)
print("The result is: %s" % result)
print_tree(bst2_tn2)
print('='*80)
result = lowest_common_ancestor(bst2_tn2, bst2_tn2, bst2_tn1)
print("The result is: %s" % result)
|
31416de1fd472c7690369195693b3129c59451ae | XinyuYun/cs1026-labs | /lesson5/task2/task.py | 249 | 4.21875 | 4 | # Replace the placeholders and complete the Python program.
def factorial(n):
result = n
for Complete the for loop statement:
Compute a new result value
return result
print(factorial(5))
print(factorial(7))
print(factorial(9))
|
b7b974522f7cdc7cdd593538c082dd59f1ebd151 | adibsxion19/CS1114 | /HW/hw1_q2.py | 592 | 3.609375 | 4 | # Author: Aadiba Haque
# Assignment / Part: HW1 - Q2
# Date due: 2020-02-14
# I pledge that I have completed this assignment without
# collaborating with anyone else, in conformance with the
# NYU School of Engineering Policies and Procedures on
# Academic Misconduct.
current_pop = 330109174
year = int(input("How many years have passed? "))
birth = ((7*3600)*24)*365
death = ((13*3600)*24)*365
immigrants = ((35*3600)*24)*365
net_gain = birth - death + immigrants
new_pop = current_pop + (year * net_gain)
print("The estimated population for",str(year),"is:",new_pop) |
ce34c71895130071c839d22e7870142f86581f9b | amoor22/patterns | /Bday cake pattern.py | 444 | 3.78125 | 4 | num = int(input("How big do you want the cake? "))
num2 = 2
for x in range(num):
for y in range(2):
for i in range(num * 2 - 2):
print(' ', end='')
for a in range(num2):
print('*',end='')
if y == 0:
print()
num2 += 4
num -= 1
print()
# input: 4
# output:
# **
# **
# ******
# ******
# **********
# **********
# **************
# ************** |
d94e939cd9ba086bd9f6be15c9ede7b08b7a5435 | ddeepak2k14/python-practice | /com/deepak/python/practice/sipmlePython.py | 634 | 3.609375 | 4 | __author__ = 'deepak.k'
def triangle(base,height):
area=1.0/2*base*height
return area
print(triangle(3,4))
def hangeTocelcius(faren):
celcius=(5.0/9)*(faren-32)
return celcius
print(hangeTocelcius(30))
a=1
b=1
print(bool(a and b))
c="hello"=="hell"
print(c)
def greet(friend,money):
if friend and (money>20):
print("hi")
money=money-20
else:
print("not true")
return money
greet(True,20)
def areaOfTriangle(a,b,c):
import math
s=a+b+c/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
return area
print(areaOfTriangle(2,3,4))
import random
print(random.randrange(1,9))
|
d8c5443040e9816466f47dbbb267ca582b19e4b2 | cydu/datasci_course_materials | /assignment3/asymmetric_friendships.py | 1,044 | 3.75 | 4 | import MapReduce
import sys
"""
The relationship "friend" is often symmetric, meaning that if I am your friend, you are my friend. Implement a MapReduce algorithm to check whether this property holds. Generate a list of all non-symmetric friend relationships.
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
from sets import Set
def mapper(record):
person = record[0]
friend = record[1]
mr.emit_intermediate(person, (friend, 1))
mr.emit_intermediate(friend, (person, 0))
def reducer(key, list_of_values):
frieds_0 = [x for x, v in list_of_values if v == 0]
frieds_1 = [x for x, v in list_of_values if v == 1]
asym_friends = [x for x in frieds_1 if x not in frieds_0]
asym_friends += [x for x in frieds_0 if x not in frieds_1]
for person in Set(asym_friends):
mr.emit((key, person))
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
3d29e425361ab009504e60ab9858c856992a14f5 | KevinSarav/Python-Projects | /identityMatrix.py | 458 | 3.9375 | 4 | def generate_identity_matrix(n):
identityMatrix = []
for emptyLists in range(0, n):
identityMatrix.append([])
for column in range(0, n):
for row in range(0, n):
if column == row:
identityMatrix[column].append(1)
else:
identityMatrix[column].append(0)
return identityMatrix
n = 3
print(generate_identity_matrix(n))
n = 5
print(generate_identity_matrix(n)) |
8990c6297bbe769fb9bc33230bb57968a55e551b | SpookyJelly/Python_Practice | /leetcode/49_GroupAnagrams.py | 1,618 | 3.84375 | 4 | #49. Group Anagrams
"""
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
typically using all the original letters exactly once.
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lower-case English letters.
"""
# 개쩌는 아이디어 : 애너그램 관계인 문자열은, 정렬하면 같은 값이 된다.
class Solution:
def groupAnagrams(self, strs: list) -> list:
word_dic = {
}
# 딕셔너리 자료형의 장점을 십분 이용하자
for word in strs:
a = ''.join(sorted(word))
print(a)
# .get()에 그냥 sorted(word) 넣으니까 list는 unhashable하다고 나오는데, 애초에 hash 가 뭘까?
# 아무튼, sorted 하면 리스트가 나오는데, 그걸 join 메서드를 이용해서 다시 문자꼴로 묶어줬다.
# 그리고 항상 자주 쓰던 방식으로, 키 값 없이도 디폴트 값 만들어주는 사전을 이용했다.
word_dic[a] = word_dic.get(a,[]) + [word]
# 마지막으로 동일 범주로 묶인 value들을 일괄 반환하자
return word_dic.values()
a =Solution()
strs = ["eat","tea","tan","ate","nat","bat"]
print(a.groupAnagrams(strs))
"""
Success Details
Runtime: 92 ms, faster than 88.71% of Python3 online submissions for Group Anagrams.
Memory Usage: 17.4 MB, less than 71.87% of Python3 online submissions for Group Anagrams.
Next challenges:
""" |
1b26a57161ceabd5958bd08a1e936ce79876fd97 | akashvshroff/Puzzles_Challenges | /quick_sort.py | 902 | 4.21875 | 4 | def quick_sort(arr):
"""
A less memory efficient technique of comparison based sorting where a random
pivot is chosen and the rest of elements are partitioned into 2 groups that
are less than or equal to the pivot and greater than the pivot. At each
partition, the pivot is placed in its final position and this step is
recursively called for each partitioned portion.
"""
less, same, more = [], [], [] # 3 partition lists
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
for i in arr:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
same.append(i)
less = quick_sort(less)
more = quick_sort(more)
return less + same + more
nums = [23, 41, 32, 43, 1, 2, 34, 323, 4, 3, 5, 7, 86, 5, 4]
print(quick_sort(nums))
|
30415ea4c160a9fb1814380a6be11743c79b3842 | Sarahjdes/ninjeanne | /portal_validation/draft_validation.py | 2,467 | 3.515625 | 4 | print "CSV validation"
import csv # import csv module
# file1 ele | fName | lName
# file2 prof | fName | lName
# file3 prog | title | group
# file4 ele | group
## Unregristered students ##
f = open('1.csv')
csv_1 = csv.reader(f)
ele_1 = []
for row in csv_1:
ele_1.append(row[0])
f = open ('4.csv')
csv_4 = csv.reader(f)
ele_4 = []
for row in csv_4:
ele_4.append(row[0])
ele_1_set = set(ele_1)
ele_4_set = set(ele_4)
forgotten_ele = ele_4_set.difference(ele_1_set)
print 'unregistered students :'
print list(forgotten_ele)
## Unexisting groups ##
f = open('4.csv')
csv_4 = csv.reader(f)
group_4 = []
for row in csv_4:
group_4.append(row[1])
f = open ('3.csv')
csv_3 = csv.reader(f)
group_3 = []
for row in csv_3:
group_3.append(row[2])
group_4_set = set(group_4)
group_3_set = set(group_3)
forgotten_group = group_4_set.difference(group_3_set)
print 'unexisting groups :'
print list(forgotten_group)
## Unregistered teachers ##
f = open('3.csv')
csv_3 = csv.reader(f)
prof_3 = []
for row in csv_3:
prof_3.append(row[0])
f = open ('2.csv')
csv_2 = csv.reader(f)
prof_2 = []
for row in csv_2:
prof_2.append(row[0])
prof_3_set = set(prof_3)
prof_2_set = set(prof_2)
forgotten_prof = prof_3_set.difference(prof_2_set)
print 'unregistered teachers :'
print list(forgotten_prof)
## Teachers and students sharing same ID ##
sharing_ele_prof = []
for x in prof_2:
if (x in ele_1):
sharing_ele_prof.append(x)
print 'teachers and student share same id :'
print list(sharing_ele_prof)
f = open ('1.csv')
csv_1 = csv.reader(f)
sharing_ele = []
for row in csv_1:
if row[0] in sharing_ele_prof:
sharing_ele.append(row)
if sharing_ele != []:
print 'students with a student ID: '
print list(sharing_ele)
f = open ('2.csv')
csv_2 = csv.reader(f)
sharing_prof = []
for row in csv_2:
if row[0] in sharing_ele_prof:
sharing_prof.append(row)
if sharing_prof != []:
print 'teachers sharing a student ID: '
print list(sharing_prof)
## Duplicate students IDs ##
f = open ('1.csv')
csv_1 = csv.reader(f)
duplicate_ele = set([x for x in ele_1 if ele_1.count(x) > 1])
print 'duplicate students ID :'
print list(duplicate_ele)
## Duplicate teachers IDs ##
duplicate_prof = set([x for x in prof_2 if prof_2.count(x) > 1])
print 'duplicate teachers ID :'
print list(duplicate_prof)
|
7a9e78e6b93e0680774b4624d14bdd1a8ec0be7c | sungminoh/algorithms | /leetcode/solved/85_Maximal_Rectangle/solution.py | 3,108 | 3.671875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 sungminoh <smoh2044@gmail.com>
#
# Distributed under terms of the MIT license.
"""
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = [["0"]]
Output: 0
Example 3:
Input: matrix = [["1"]]
Output: 1
Constraints:
rows == matrix.length
cols == matrix[i].length
1 <= row, cols <= 200
matrix[i][j] is '0' or '1'.
"""
import sys
from typing import List
import pytest
class Solution:
def maximalRectangle(self, matrix):
"""08/14/2018 22:15"""
def largestRectangleArea(heights):
ret = 0
stack = []
heights.append(0)
for i, h in enumerate(heights):
while stack and heights[stack[-1]] >= h:
ph = heights[stack.pop()]
w = i - (stack[-1] if stack else -1) - 1
ret = max(ret, ph * w)
stack.append(i)
return ret
if not matrix:
return 0
h, w = len(matrix), len(matrix[0])
m = [[0]*w for _ in range(h)]
ret = 0
heights = [0] * w
for i in range(h):
for j in range(w):
heights[j] = (heights[j] + 1) if int(matrix[i][j]) == 1 else 0
ret = max(ret, largestRectangleArea(heights))
return ret
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0])
def find_max_area(nums):
nums += [0]
ret = 0
stack = []
for i, n in enumerate(nums):
while stack and nums[stack[-1]] >= n:
height = nums[stack.pop()]
j = -1 if not stack else stack[-1]
width = (i-1) - j
ret = max(ret, width*height)
stack.append(i)
return ret
ret = 0
row = [0]*n
for i in range(m):
for j in range(n):
if matrix[i][j] == '0':
row[j] = 0
else:
row[j] += 1
ret = max(ret, find_max_area(row))
return ret
@pytest.mark.parametrize('matrix, expected', [
([["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]], 6),
([["0"]], 0),
([["1"]], 1),
([["0","0","1"],["1","1","1"]], 3),
([["0","1","1","0","1"],
["1","1","0","1","0"],
["0","1","1","1","0"],
["1","1","1","1","0"],
["1","1","1","1","1"],
["0","0","0","0","0"]], 9),
])
def test(matrix, expected):
assert expected == Solution().maximalRectangle(matrix)
if __name__ == '__main__':
sys.exit(pytest.main(["-s", "-v"] + sys.argv))
|
765ae4f49073c45d0f14d4b271ca1371f7594e39 | fionaEyoung/Interdisciplinary-Research-Skills | /book/_build/jupyter_execute/4_simulation/simulation.py | 9,984 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Workshop 4: Modelling and Simulation
#
# ## Introduction
#
# A [scientific model ](https://www.britannica.com/science/scientific-modeling) is a mathematical or conceptual representation of a real-world process or phenomenon.
#
# In the previous workshop, we simulated the motion of an object moving under gravity using a simple quadratic equation. The equation was a model of the motion of the object, but in reality it's only a prediction of the object's movement.
#
# We can test the model by performing an experiment and comparing the result of the experiment against the prediction of the model. We can think of the model as a 'scientific hypothesis' which we confirm or refute based on the results of the experiment, a key component of the [scientific method](https://www.britannica.com/science/scientific-method).
#
# In reality we might find that the model is a reasonable appoximation to reality - but by making refinements to the model we can improve its predictive power.
#
# :::{admonition} Coming soon
# :class: hint
# Later you will work in small groups of students to perform a real experiment which tests a model of the motion of an object under gravity.
# :::
#
# In this workshop you will make predictions about populations of bacteria using simple quantitative models of population growth.
#
# :::{admonition} What you'll learn
# :class: hint
# 1. How to model a system using simple difference equations
# 1. How to load data and plot it
# 1. How to using model fitting to estimate the parameters of a model
# :::
#
# ## Exponential Growth
# Bacteria grown in the lab provide an example of **exponential growth**. In exponential growth, the growth rate of the population is in proportion to the size of the population. Bacteria reproduce by binary fission, and the time between divisions is about an hour.
#
# Suppose we place a 1000 bacteria in a flask with an unlimited supply of nutrients. After one hour, each bacterium will divide, yielding 2000 bacteria (an increase of 1000). After 2 hours, each of the 2000 bacteria will divide, producing 4000 (an increase of 2000 bacteria). After 3 hours, each of the 4000 bacteria will divide, producing 8000 (an increase of 4000 bacteria).
#
# The key concept of exponential growth is that the number of cells added in each generation is in direct proportion to the number cells.
#
# ## Modelling Exponential Growth
#
# Suppose a population of bacteria belonging to species X doubles in size every hour. Then we can model the population using the following equation:
#
# $$x_{i+1} = x_i + rx_i $$
#
# where $x_i$ is the population at hour $i$ and $r$ is the growth rate. For this scenario, where the population doubles with each step, we set $r=1$. The equation represents the fact that the population at hour $i+1$ is $r+1$ times the population at hour $i$.
#
# Suppose that the initial population is exactly $1000$ cells and we would like to simulate the population size over the course of 8 hours.
#
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
r_X = 1
n_hours = 8
initial_population = 1000
pop_X = np.zeros(n_hours + 1)
pop_X[0] = initial_population
for i in range(n_hours):
pop_X[i + 1] = pop_X[i] + pop_X[i] * r_X
print("Population of species X:", pop_X)
# :::{note}
# Python uses *exponential notation* to express decimal numbers e.g. $2048 = 2.048 \times 10^3$ is expressed as `2.048e+03`.
# :::
#
# Using `plt.plot` we can visualise the population curve over the 8 hours:
# In[2]:
plt.figure(figsize=(6,3))
plt.plot(pop_X)
plt.xlabel("time (hours)")
plt.ylabel("population")
plt.title("Species X")
# Now suppose we have another bacterial species Y with a slower growth rate $r = 0.1$.
#
# |Species|r|
# |---|---|
# |X|1.0|
# |Y|0.1|
#
# > Use the code above to simulate the growth of population Y.
#
# > Plot the predicted population of species Y on a separate figure.
# ## Experimental Data
#
# ### Eight hour experiment
#
# Now suppose that we perform a laboratory experiment in order to measure the growth in the two species of bacteria. The population of each was recorded every hour for 8 hours.
#
# :::{seealso}
# See [here](https://courses.lumenlearning.com/boundless-microbiology/chapter/counting-bacteria/) for how you might measure a bacterial population in practice.
# :::
#
# |Time (hours)|0|1|2|3|4|5|6|7|8|
# |---|---|---|---|---|---|---|---|---|---|
# |Species X population (thousands)|1.0|2.18|4.45|8.91|16.1|31.49|60.89|117.58|214.4|
# |Species Y population (thousands)|1.0|1.47|2.02|2.81|4.16|5.88|7.98|10.99|15.59|
#
# Let's plot this experimental data on the same graph as the model simulation.
# In[3]:
data_X = np.array([ 1. , 2.18, 4.45, 8.91, 16.1 , 31.49, 60.89, 117.58, 214.4 ]) * 1000
plt.figure(figsize=(6,3))
plt.plot(pop_X, label="model")
plt.plot(data_X, label="experiment")
plt.xlabel("time (hours)")
plt.ylabel("population")
plt.title("Species X")
plt.legend()
# Notice that the the experimental data is a good fit to the model prediction, so at this point we can be confident in our model, and our value of $r=1$.
#
# > On a new figure, plot the experimental data and model prediction for species Y.
#
# You should find that the model and experiment aren't such a good fit for species Y.
#
# > By changing the value of `r_Y` until the two graphs coincide, determine a good value of $r$ for species Y.
#
# ### 24 hour experiment
#
# The experimenter continues the experiment for a full 24 hours. The results of the experiment are in the files `data_exp_X.txt` and `data_exp_Y.txt`.
#
# <a href="../workshop_4/data_exp_X.txt" download>data_exp_X.txt</a>
# <a href="../workshop_4/data_exp_Y.txt" download>data_exp_Y.txt</a>
#
# We can use the `numpy` function `np.loadtxt` to load the data into a numpy array:
# In[4]:
data_X = np.loadtxt("data_exp_X.txt")
print(data_X)
# We'll change the value of `n_hours` to `24` and re-run the model.
# In[5]:
r_X = 1
n_hours = 24
initial_population = 1000
pop_X = np.zeros(n_hours + 1)
pop_X[0] = initial_population
for i in range(n_hours):
pop_X[i + 1] = pop_X[i] + pop_X[i] * r_X
plt.figure(figsize=(6,3))
plt.plot(pop_X, label="model")
plt.plot(data_X, label="experiment")
plt.xlabel("time (hours)")
plt.ylabel("population")
plt.title("Species X")
plt.legend()
# The model and experimental data are no longer a good fit at all. At this scale, it looks like the experimental data is zero for the entire 24 hours. However, to see what's going on let's plot the experimental data alone:
# In[6]:
plt.figure(figsize=(6,3))
plt.plot(data_X, color='#ff7f0e')
# Notice that while the population increases exponentially at first, eventually it stops increasing, likely due to exhausting resources such as nutrients or physical space. Our simple exponential model is insufficient to take this into account.
#
# Instead, we can consider a more sophisticated model, *logistic growth*.
#
# ## Logistic Growth
#
# The logistic equation describes the growth of a population where the growth rate is limited by resources.
#
# $$x_{i+1} = x_i + r(1-x_i/K)x_i$$
#
# the growth rate $r$ has been replaced by the term $r(1-x_i/K)$. For small populations (when $x_i$ is much less than $K$) the growth rate is close to $r$. As the population size approaches the value $K$, the growth rate reduces to zero.
#
# :::{note}
# $K$ is called the **carrying capacity**.
# :::
#
# > Simulate the growth of species X use the new equation. You will need to create a new variable `K_X` and change the line `pop_X[i + 1] = pop_X[i] + pop_X[i] * r_X`. Use the value `K_X = 1e6`.
# > Plot the experimental and model prediction on the same graph.
#
# You should find that the two curves fit well, showing that our new model predicts the population growth well.
#
# > Repeat the simulation for species Y (Don't forget to load the 24h experimental data for Y, from the text file provided above!). Determine values of $r$ and $K$ that best fit the experimental data. Hint: the value of $r$ affects the steepness of growth, while $K$ is related to the point of saturation.
# ## Exercise
#
# The following three text files contain the results of 3 bacterial population growth experiments. For each one, plot the data and by running a simulation for each, estimate the value of $r$ and $K$.
#
# <a href="../workshop_4/data_exp_A.txt" download>data_exp_A.txt</a>
# <a href="../workshop_4/data_exp_B.txt" download>data_exp_B.txt</a>
# <a href="../workshop_4/data_exp_C.txt" download>data_exp_C.txt</a>
#
# Which data file corresponds to which of the three species in the table below?
#
# |Species|r|
# |---|---|
# |1|0.4|
# |2|0.7|
# |3|0.9|
#
# :::{admonition} Challenge
# :class: hint
# See if you can use simple functions, loops and arrays to solve this exercise efficiently. If you find yourself repeating the same code over and over, could you use a loop? Try defining a function that takes values for $r$, $K$, $x_0$ (initial population) and `n_hours` as inputs and returns an array of population values.
#
# :::
# ## Epidemic Model (Optional)
#
# The spread of an infectious disease amongst a population can be modelled by the following pair of coupled equations:
#
# $$ S_{i+1} = S_i - bS_iI_i $$
# $$ I_{i+1} = I_i + bS_iI_i - aI_i $$
#
# where $S_i$ represents the number of susceptible (uninfected) people and $I_i$ represents the number of infected people.
#
# There are two parameters: the recovery rate parameter $a$ and the infection rate parameter $b$.
#
# Starting with parameter values $a = 0.1$ and $b = 0.00005$ and the initial populations $S_0 = 20000$ and $I_0 = 100$, model the infection for 100 days.
#
# What happens as you change the values of $a$ and $b$?
#
# :::{admonition} SIR model
# :class: seealso
# This model is called the SIR model which is commonly used to [model epidemics such as COVID](https://www.nature.com/articles/d41586-020-01003-6).
# :::
#
#
|
e55a31880ef831787b218d00dc8fa14d04adaecc | Okreicberga/programming | /labs/Topic09-errors/myFunctions.py | 1,507 | 4.375 | 4 | # Function Fibonacci that makes a numbers and returns a list containing a Fibonacci sequence of that many numbers.
# Author: Olga Kreicberga
import logging
#logging.basicConfig(level=logging.DEBUG)
def fibonacci (number):
if number < 0:
raise ValueError('number must be > 0')
if number == 0:
return []
a = 0
b = 1
fibonacciSequence = [0]
# we have one in the list already so number - 1 times
# this isnot the most efficient code
# could have used yield
# # this is funky code make a = b and b = a + b
a , b = b, a + b
logging.debug("%d: %s",number, fibonacciSequence)
return fibonacciSequence
if __name__ == '__main__' :
# test will go here
return7 = [0,1,1,2,3,4,5,8]
return11 = [0,1,1,2,3,5,8,13,21,34,55]
logging.debug("%s", fibonacci(7))
assert fibonacci(7) == return7, 'incorrect return value for 7'
assert fibonacci(11) == return11, 'incorrect return value for 11'
assert fibonacci(0) == [], 'incorrect return value for 0'
assert fibonacci(1) == return11, 'incorrect return value for 1'
try:
fibonacci(-1)
except ValueError:
# we want this exception to be thrown
# so this is an example where we want to do nothing
pass
else:
# if the exception was not thrown we should throw
# Assertion error
assert False, 'fibonacci missing ValueError'
# or
# raise AssertionError("fibonacci no valueError")
print("all good") |
eb8e63167b79515053341b36725226c037378c52 | CiraciNicolo/AdvancedPython | /labs/es5-1.py | 499 | 3.546875 | 4 | import unittest
import string
def anagram(s):
s = s.translate(None, string.punctuation).lower().replace(' ', '')
return s==s[::-1]
class FunctionsTests(unittest.TestCase):
def test_anagram(self):
self.assertEqual(False, anagram("Test"))
self.assertEqual(True, anagram("I topi non avevano nipoti."))
self.assertEqual(True, anagram("Do geese see God?"))
self.assertEqual(True, anagram("Rise to vote, sir."))
if __name__ =='__main__':
unittest.main()
|
9a267fc6c8be6b751d2334c2f8e8fa6113d5ad7a | patricktuite/Learn-Python-The-Hard-Way- | /ex3.py | 999 | 4.53125 | 5 | # displays text about counting the chickens
print "I will now count my chickens:"
# displays the result of 25 plus 30 divided by 6
print "Hens", float(25 + 30 / 6)
# displays the result of 100 minus the remainder of (25 times 3) divided by 4
print "Roosters", float(100.00 - float(25.00 * 3.00 % 4.00))
# displays text
print "Now I will count the eggs:"
# displays the result of an arithmetic operation
print float(3 + 3 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
# displays text
print "Is it true that 3 + 2 < 5 - 7?"
# displays a conditional result of an inequality in this case it is false
print 3 + 2 < 5 -7
# displays an expression and the result
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
# displays text
print "Oh, that's why it's False."
# displays text
print "How about some more."
# displays a question and the answer
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
print 7 / 4
print 7.0 / 4.0
print float(7.0 / 4.0) |
4f70b06a2ebf6b73d90adadad70892936a37476c | bittubaiju/ccna-devnet | /sorting_list.py | 557 | 3.921875 | 4 | x=[]
n = int(input('total num of elements: '))
for i in range(n):
x.append(int(input('enter the element: ')))
print('list is: ',x)
already_sorted = True
for i in range(n-1): #beacuse range starts from 0
for j in range(n-1-i): #so that j won't go upto last element as it is already sorted
if x[j]>x[j+1]:
x[j],x[j+1]=x[j+1],x[j] #swaping because it is possible in python without temp variable
already_sorted = False
if already_sorted: #in case the list is already sorted.
break
print('sorted list is ',x)
|
866d5d3e1bb5521fd39a515a6912736d5a7244ba | ericjsolis/danapeerlab | /scf/src/parameterchanger.py | 10,163 | 3.5 | 4 | #!/usr/bin/env python
import string
import re
import logging
from collections import namedtuple
"""Keys are function names which will be annonated. If you call
ParameterChangerManager.get_current_changer from any of these function you will
get a ParameterChanger that can change the parameters of the function in the
current script. Values are mappings between strings to parameter number in the function."""
PARAMETER_CHANGER_FUNCTIONS = {}
class ParameterChangerManager:
def __init__(self, script):
self.changers = []
self.script = script
self.changers_valid = False
self.script.text_inserted += self.on_script_text_inserted
self.script.range_deleted += self.on_script_range_deleted
self.is_valid = True
self.current_changer = -1
self.name_to_annonate = []
def _create_changer_from_pos(self, pos, function_name):
"""This function creates a new parameter changer assuming pos is an
offset to a function name in a script.
The function also adds the needed marks for the changer in the script.
"""
global PARAMETER_CHANGER_FUNCTIONS
name_to_param_mapping = PARAMETER_CHANGER_FUNCTIONS[function_name]
print function_name
print PARAMETER_CHANGER_FUNCTIONS[function_name]
regions = []
start_mark = None
script_str = self.script.get_code_as_str()
params_start = script_str.find('(', pos)
if params_start == -1:
raise Exception('Could not parse parameters')
brackets_count = 1
LOOKING_FOR_START = 0
LOOKING_FOR_END = 1
DONE = 2
state = LOOKING_FOR_START
in_string = None
params = []
for pos in xrange(params_start + 1, len(script_str)):
#logging.debug('current char: %s, current state:%d' % (script_str[pos], state))
# Create markers.
if state == LOOKING_FOR_START:
if script_str[pos] == ')':
start_mark = self.script.add_mark(pos, 'left')
state = LOOKING_FOR_END
elif not script_str[pos] in string.whitespace:
start_mark = self.script.add_mark(pos, 'left')
state = LOOKING_FOR_END
if state == LOOKING_FOR_END and not in_string and brackets_count == 1:
if script_str[pos] == ',' or script_str[pos] == ')':
end_mark = self.script.add_mark(pos, 'right')
regions.append(ParameterRegion(start_mark, end_mark))
#logging.debug('********* APPENDED REGION*********')
state = LOOKING_FOR_START
# Handle strings. we want to know if we are in a ' or in a " type
# of string.
in_escape = pos > 1 and script_str[pos-1] == '\\' and script_str[pos-2] != '\\'
if script_str[pos] == "'" or script_str[pos] == '"':
if not in_string:
in_string = script_str[pos]
#logging.debug('We are in a %s string' % in_string)
elif in_string == script_str[pos] and not in_escape:
in_string = None
#logging.debug('We are no longer in string')
# Update bracket count.
if not in_string:
if script_str[pos] == '(' or script_str[pos] == '[':
brackets_count += 1
if script_str[pos] == ')' or script_str[pos] == ']':
brackets_count -= 1
# Break when we get to the last bracket
if brackets_count == 0:
break
return ParameterChanger(regions, self.script, self, name_to_param_mapping)
def annonate_script(self):
"""Annonates the script with calls that set the current changed.
If changers are invalid, this also creates new changers.
Annonation means turning a function call func(1,2,3) to
set_current_changer(changer_index, func)(1,2,3)
changer_index is the index of the changer that sets the parameters of
the function func.
We only annonate functions which are in names_to_annonate.
"""
def re_visitor(match):
"""Called by the regex engine for each function found while annonating"""
function_call = match.group()[:-1]
if not self.is_valid:
# we need a new ParameterChanger for this function.
# First determine which function we found:
function_found = None
sorted_function_list = PARAMETER_CHANGER_FUNCTIONS.keys()
def sort_by_len(w1,w2):
return len(w2) - len(w1)
sorted_function_list.sort(cmp=sort_by_len) #longer names will appear first
for candidate in sorted_function_list:
if candidate+'(' in match.group():
function_found = candidate
break
if not function_found:
raise Exception('Unexpected error in function search')
new_changer = self._create_changer_from_pos(match.start(), function_found)
self.changers.append(new_changer)
# Note that if is_valid == True we assume no new functions were added
# So we use the old changers in their original order.
# We now save the function call code with annonation:
debug_func = 'services.set_current_changer'
annonated = '%s(%d,%s)(' % (
debug_func, self.function_counter, function_call)
self.function_counter += 1
return annonated
with self.script.lock:
script_str = self.script.get_code_as_str()
# This re captures all functions calls (I hope):
# [\w.]+\(
# To catch only function with the given names we need:
# [\w.]*(?:name1|name2|name3)\(
# TODO(daniv): ignore function calls inside strings
# TODO(daniv): def with the same name will create an error...
global PARAMETER_CHANGER_FUNCTIONS
#must sort by length so that we won't catch small function names inside longer ones:
function_list = PARAMETER_CHANGER_FUNCTIONS.keys()
expression = r'[\w.]*(?:%s)\(' % '|'.join(function_list)
self.function_counter = 0
if PARAMETER_CHANGER_FUNCTIONS:
res = re.sub(
expression,
re_visitor,
script_str)
else:
res = script_str
self.is_valid = True
return res
def invalidate(self):
with self.script.lock:
self.is_valid = False
for c in self.changers:
c.is_valid = False
self.script.clear_marks()
self.changers = []
def on_script_text_inserted(self, position, text, sender):
# we don't invalidate changes created by this class, because these
# changes are always parameter changes (so no new functions to annonate).
with self.script.lock:
if sender != self and self.is_valid:
self.invalidate()
def on_script_range_deleted(self, start, end, sender):
with self.script.lock:
if sender != self and self.is_valid:
self.invalidate()
def set_current_changer(self, changer_index, func_to_return):
"""Called by annonated functions in the script.
This method is called from the script (only) after it had been annonated
(see compiler.py). For each function whose name is in the annonated names
list, the annotator turns the call func(a,b,c) to
services.set_script_location(curset_location, func)(a,b,c)
"""
self.current_changer = changer_index
return func_to_return
def get_current_changer(self):
#TODO(daniv): check stack, only from script thread
return self.changers[self.current_changer]
ParameterRegion = namedtuple('ParameterRegion',
['begin_mark_name','end_mark_name'])
class ParameterChanger:
def __init__(self, regions, script, manager, mapping):
self.regions = regions
self.manager = manager
self.script = script
self.is_valid = True
self.mapping = mapping
self.namespace = ''
def get_parameters(self):
with self.script.lock:
if not self.is_valid:
raise Exception('regions are not valid')
return [
self.script.get_code_as_str(r.begin_mark_name, r.end_mark_name)
for r in self.regions]
def set_parameters(self, parameters):
#TODO(daniv): check that parameters are simple
with self.script.lock:
if not self.is_valid:
raise Exception('regions are not valid')
if len(parameters) != len(self.regions):
raise Exception('parameter length mismatch')
for i in xrange(len(parameters)):
r = self.regions[i]
self.script.delete_range(
r.begin_mark_name, r.end_mark_name, self.manager)
self.script.insert_text(
r.begin_mark_name, parameters[i], self.manager)
def set_namespace(self, namespace):
self.namespace = namespace
def set_parameter_by_name(self, name, val):
if self.namespace:
name = self.namespace + '.' + name
if not self.mapping or not name in self.mapping:
raise Exception('Could not set value for name %s. Current mapping is: %s ' % (name, self.mapping))
return self.set_parameter(self.mapping[name], val)
def set_parameter(self, index, val):
with self.script.lock:
if not self.is_valid:
raise Exception('regions are not valid')
if len(self.regions) <= index:
raise Exception('parameter index')
r = self.regions[index]
self.script.delete_range(
r.begin_mark_name, r.end_mark_name, self.manager)
self.script.insert_text(
r.begin_mark_name, val, self.manager)
#register changer decorators:
def register_changer(func):
global PARAMETER_CHANGER_FUNCTIONS
if func.func_name in PARAMETER_CHANGER_FUNCTIONS and PARAMETER_CHANGER_FUNCTIONS[func.func_name] != None:
raise Exception('Two functions with conflicting mappings were registered. Function name is %s' % func.func_name)
PARAMETER_CHANGER_FUNCTIONS[func.func_name] = None
return func
def register_changer_mapping(mapping):
def register_changer_mapping_decorator_with_args(func):
global PARAMETER_CHANGER_FUNCTIONS
if func.func_name in PARAMETER_CHANGER_FUNCTIONS and PARAMETER_CHANGER_FUNCTIONS[func.func_name] != mapping:
raise Exception('Two functions with conflicting mappings were registered. Function name is %s' % func.func_name)
PARAMETER_CHANGER_FUNCTIONS[func.func_name] = mapping
return func
return register_changer_mapping_decorator_with_args |
3cbc08ba78894ba53982e15ff56c1dead819f76e | melission/Timus.ru | /1100_memory_limit.py | 1,037 | 3.640625 | 4 | # https://acm.timus.ru/problem.aspx?space=1&num=1100
# ru: https://habr.com/ru/post/455722/
# eng: https://habr.com/ru/post/458518/
import sys
itemcount = int(input().strip())
toSortList = []
for i in range(itemcount):
str_lst = input().strip().split()
# print(len(str_lst))
str_lst[1] = int(str_lst[1])
# team = []
# for srt_num in str_lst:
# num = int(srt_num)
# team.append(num)
toSortList.append(str_lst)
# print(sys.getsizeof(toSortList))
# print(toSortList)
# print(type(toSortList[0][0]))
def bubble_sort(toSortList):
changed = True
r = range(len(toSortList) - 1)
while changed:
changed = False
for item in r:
if toSortList[item][1] < toSortList[item+1][1]:
toSortList[item], toSortList[item+1] = toSortList[item+1], toSortList[item]
changed = True
return toSortList
# print(bubble_sort(toSortList))
sortedList = bubble_sort(toSortList)
for item in sortedList:
print('{} {}'.format(item[0], item[1]))
|
f9933925e47f793321777a0109bf652b55f0bebb | stnorling/Rice-Programming | /iipp/Week 8/quiz_ex_list_func.py | 488 | 3.609375 | 4 | class Point2D:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def translate(self, deltax=0, deltay=0):
"""Translate the point in the x direction by deltas
and in the y direction by deltay."""
self.x += deltax
self.y += deltay
def __str__(self):
return "<" + str(self.x) + ", " + str(self.y) + ">"
point = Point2D(3, 6)
# when using the list() function, the argument must be an iterable
lst = list(point)
|
0ce0f9ba60d23daec2ebe98d7198dfa95b70bf58 | henrikemx/PycharmProjects | /exercicios-cursoemvideo-python3-mundo3/Aula16/exerc077a.py | 224 | 3.890625 | 4 | # Dica do desafio 25 da Aula 09 do Mundo 1
nome = ('Adalberto Silva')
print('Seu nome tem Silva ? Resp.: {}'.format('Silva' in nome))
print('-'*30)
print(f'Seu nome tem Silva ? Resp.: {"Silva" in nome}')
print('-'*30)
print(f'A ')
|
c7d223c13698117491a160c40d8c37f6b189df79 | Grande-zhu/CSCI1100 | /LEC/lec20/lec20_ex_start.py | 690 | 4 | 4 | '''
Template program for Lecture 20 exercises.
'''
def linear_search( x, L ):
pass # replace with your code
if __name__ == "__main__":
# Get the name of the file containing data
fname = input('Enter the name of the data file => ')
print(fname)
# Open and read the data values
in_file = open(fname,'r')
values = []
for line in in_file:
v = float(line)
values.append(v)
# Search for each value requested by the user until -1 is entered
x = 0
while x != -1:
x = float(input("Enter a value to search for ==> "))
print(x)
if x != -1:
loc = linear_search(x, values )
print(loc)
|
ff5cffd30b319c54ede5d80dd2a826fac02eae53 | bluehat7737/pythonTuts | /56_classMethods.py | 382 | 3.75 | 4 | class Emp:
no_of_leaves = 8
def __init__(self, name, lname):
self.name = name
self.lname = lname
@classmethod
def changeLeaves(cls, newLeaves):
cls.no_of_leaves = newLeaves
anshul = Emp("Anshul", "Choursiya")
print(anshul.no_of_leaves)
print(Emp.no_of_leaves)
anshul.changeLeaves(37)
print(anshul.no_of_leaves)
print(Emp.no_of_leaves)
|
40635d64b0648ebbb5954ab225083ce5cb8e8d85 | mateenjameel/Python-Course-Mathematics-Department | /Object Oriented Programming/class_9.py | 730 | 3.6875 | 4 | class Employee:
no_of_emps= 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last +'@1992.com'
Employee.no_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
emp1 = Employee("Ali", "Usman", 50000)
emp2 = Employee("Furqan", "Azhar", 20000)
Employee.set_raise_amt(1.05)
print(Employee.raise_amt)
print(emp1.raise_amt)
print(emp2.raise_amt)
|
648aa0559e756d9e75bc0cb4d7c37f5a8f47d8af | GiovanaPalhares/python-introduction | /MaiorPrimo.py | 383 | 3.53125 | 4 |
def primo(x):
num = 2
while x % num != 0 and num <= x / num:
num = num + 1
if x % num == 0:
return False
else:
return True
def maior_primo(x):
if primo(x):
return(x)
else:
while x > 2:
i = 1
if primo(x-i):
return (x-i)
i = i + 1
(maior_primo(20))
|
0d439847ff347aa32e5a4062dd9db1be2e0edf83 | karthi007/dev | /BST.py | 804 | 3.703125 | 4 |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
start = 0
end = len(nums)-1
return self.BST(start,end,nums)
def BST(self,start,end,nums):
if start>end:
return None
mid = (start+end)//2
root = TreeNode(nums[mid])
root.left=self.BST(start,mid-1,nums)
root.right=self.BST(mid+1,end,nums)
return root
def printing(self,root):
if root.left!=None:
self.printing(root.left)
print root.val
if root.right!=None:
self.printing(root.right)
nums = [1,2,3,4,5,6,7,8,9]
x = Solution()
a = x.sortedArrayToBST(nums)
x.printing(a)
|
1d5524a8559ec80286dbbbb87082300502fad988 | momentum-team-4/examples | /py--objects-basics/simple_examples.py | 405 | 3.765625 | 4 | from typing import Generator
def generatelines(fname: str) -> Generator:
"""
Safe iterator over the lines of a file.
"""
with open(fname) as genfile:
for line in genfile:
yield line.strip()
if __name__ == "__main__":
assert list(generatelines("students-names.txt")) == ['Clint', 'Taylor', 'Kyle', 'Will', 'Jacqueline', 'Harrison', 'Jameel']
print("success!") |
e1e797b0cc9828d3c238fa6ef01e23e1932a26c7 | Jdicks4137/function | /decisions.py | 1,516 | 4.34375 | 4 | # Josh Dickey 10/5/16
# this program generates a random math problem in either addition, subtraction, or multiplication
import random
def maximum_value():
"""this allows the user to insert the maximum value"""
maximum = float(input("what is the maximum value?"))
return maximum
def correct_answer(problem, x, y):
"""this is the correct answer to the problem which is calculated by the program"""
if problem == '-':
return x - y
elif problem == '*':
return x * y
else:
return x + y
def response():
"""this allows the program to receive a response from the user"""
respond = float(input("your answer"))
return respond
def operation():
"""this allows the user to select the type of problem they wish to solve"""
problem_type = input("please select the type of problem you want: addition, subtraction, or multiplication.")
return problem_type
def main():
"""this is the main function that runs the program"""
maximum = maximum_value()
problem = operation()
x = random.randint(0, maximum)
y = random.randint(0, maximum)
print("what is", x, problem, y)
user_answer = response()
if user_answer == correct_answer(problem, x, y):
print("You are correct! Thanks for playing.")
else:
print("You suck at math. Honestly how can you not solve", x, problem, y, "? The correct answer was",
correct_answer(problem, x, y), "You don't deserve to play this game again! Goodbye!")
main()
|
8570c178224165e87e9f676a6c026692b990e816 | sreyansb/Codeforces | /codeforces4Awatermelon.py | 147 | 3.5 | 4 | n=int(input())
flag=0
for i in range(2,n,2):
if (n-i)%2==0:
print("YES")
flag=1
break
if flag==0:
print("NO")
|
907aa828b7acd78e06697c519b1f8919f0f89613 | 1325052669/leetcode | /src/data_structure/search/traversal_with_state.py | 3,491 | 3.578125 | 4 | from collections import defaultdict
from typing import List
# https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/
class Solution1466:
def minReorder_bfs(self, n: int, connections: List[List[int]]) -> int:
road = defaultdict(set)
for src, dest in connections:
road[src].add((dest, 1)) # from 0 -> 1 is free, but it needs reverse raod 1 -> 0 and cost is 1
road[dest].add((src, 0))
total = 0
queue = [0]
seen = [0] * n
seen[0] = 1
while queue:
curr = queue.pop(0)
for neighbor, cost in road[curr]:
if seen[neighbor] == 1: continue
seen[neighbor] = 1
total += cost
queue.append(neighbor)
return total
def minReorder_dfs(self, n: int, connections: List[List[int]]) -> int:
road = defaultdict(set)
for src, dest in connections:
road[src].add((dest, 1)) # from 0 -> 1 is free, but it needs reverse raod 1 -> 0 and cost is 1
road[dest].add((src, 0))
total = 0
seen = [0] * n
seen[0] = 1
def dfs(city):
nonlocal total
seen[city] = 1
for neighbor, cost in road[city]:
if seen[neighbor] == 1: continue
total += cost
dfs(neighbor)
dfs(0)
return total
# https://leetcode.com/problems/sliding-puzzle/
class Solution773:
def slidingPuzzle(self, board: List[List[int]]) -> int:
moves = {0: (1, 3), 1: (0, 2, 4), 2: (1, 5), 3: (0, 4), 4: (1, 3, 5), 5: (2, 4)}
m, n = len(board), len(board[0])
state = "".join(str(board[i][j]) for i in range(m) for j in range(n))
start = state.index('0')
seen = set()
queue = [(start, state)]
steps = 0
while queue:
size = len(queue)
for _ in range(size):
curr, state = queue.pop(0)
if state == '123450': return steps
for nxt in moves[curr]:
tmp = list(state)
tmp[curr], tmp[nxt] = tmp[nxt], tmp[curr]
tmp = ''.join(tmp)
if tmp in seen: continue
seen.add(tmp)
queue.append((nxt, tmp))
steps += 1
return -1
# https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
class Solution1293:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
queue = [(0, 0, 0)]
seen = {(0, 0): 0}
steps = 0
while queue:
size = len(queue)
for _ in range(size):
x, y, obs = queue.pop(0)
if x == m - 1 and y == n - 1: return steps
for dx, dy in directions:
nx, ny = x + dx, y + dy
if nx < 0 or ny < 0 or nx >= m or ny >= n: continue
nobs = obs + (1 if grid[nx][ny] == 1 else 0)
if nobs > k: continue
if (nx, ny) in seen and seen[
nx, ny] <= nobs: continue # has pass the position with same or lower obstacles
seen[nx, ny] = nobs
queue.append((nx, ny, nobs))
steps += 1
return - 1 |
bec930c4510526ab6697e1e7ecc789cf25c0f02c | evertondutra/udemy | /Seçao04/exe03.py | 133 | 4.15625 | 4 | soma = 0
for c in range(3):
n = int(input(f'Digite o {c+1}º número: '))
soma += n
print(f'A soma dos números é {soma}.')
|
5bb1f54e7fb93d82dc8178f7515d93b99944db23 | YashAgarwalDev/Learn-Python | /if condition3.py | 118 | 3.84375 | 4 | a = 10
b = 20
c = 30
if a < b or a < c or a == 10:
print('a is either 10 or a is greather than b @nd c')
|
bde73b5aa05d62f5b530b7670aa1edac41ef4c72 | borislavstoychev/exam_preparation | /exams_advanced/Python Advanced Retake Exam - 16 Dec 2020/problem_1.py | 1,090 | 3.515625 | 4 | from collections import deque
def div_25(m_or_f):
new_m_f = deque()
while m_or_f:
num = m_or_f.pop()
if num % 25 ==0:
try:
m_or_f.pop()
except IndexError:
break
continue
new_m_f.append(num)
return new_m_f
def print_result(m_f):
if len(m_f) > 0:
return ", ".join(list(map(str, m_f)))
else:
return "none"
male = deque(int(num) for num in input().split() if int(num) > 0)
female = deque(int(num) for num in input().split() if int(num) > 0)
matches = 0
if [new for new in male if new % 25 == 0]:
male = div_25(male)
if [new for new in female if new % 25 == 0]:
female = div_25(female)
female = deque(reversed(female))
while male and female:
m = male.pop()
f = female.popleft()
if not m == f:
m -= 2
if not m <= 0:
male.append(m)
else:
matches += 1
male = list(reversed(male))
print(f"Matches: {matches}")
print(f"Males left: {print_result(male)}")
print(f"Females left: {print_result(female)}") |
9023a90e3a5707ea7630fa7fc47f503f02fd7384 | cukejianya/leetcode | /trees_and_graphs/matrix_01.py | 1,402 | 3.5 | 4 | class Solution:
def updateMatrix(self, matrix):
queue = []
self.row_len = len(matrix)
self.col_len = len(matrix[0])
for x in range(self.row_len):
for y in range(self.col_len):
if matrix[x][y] == 0:
queue.append((x, y))
else:
matrix[x][y] = 10001
visited = set(queue)
while(queue):
x, y = queue.pop(0)
if x > 0:
self.handle_cell(matrix, queue, visited, (x - 1, y),
matrix[x][y] + 1)
if y > 0:
self.handle_cell(matrix, queue, visited, (x, y - 1),
matrix[x][y] + 1)
if x < self.row_len - 1:
self.handle_cell(matrix, queue, visited, (x + 1, y),
matrix[x][y] + 1)
if y < self.col_len - 1:
self.handle_cell(matrix, queue, visited, (x, y + 1),
matrix[x][y] + 1)
return matrix
def handle_cell(self, matrix, queue, visited, cell, level):
x, y = cell
if cell not in visited:
visited.add(cell)
dist = matrix[x][y]
if dist > level:
queue.append((x, y))
visited.add((x, y))
matrix[x][y] = level |
812ca27ac312b7cd9422a0a82662580d24511b2b | mohammaddanish85/Python-Coding | /Range Data type.py | 512 | 4.375 | 4 | # Program for Range Data type.
# Range data type represents sequence of numbers. Numbers in range cannot be modified.
r= range(10) # Create range number
for i in r: print(i) # Print values from 0 to 9 (Total 10 numbers)
r= range(2, 22 , 2) # Here range is starting from 2 and limit is 22. There will be an increment of 2 (Look at Last number).
for i in r: print(i) # Print the values starting from 2 and upto 20. (Total 10 values) |
efc60f37c7e2f8c598e4e6c292166c1193bc2aeb | Masheenist/Python | /lesson_code/ex27_Memorizing_Logic/ex27.py | 1,978 | 4.59375 | 5 | # Memorizing Truth Tables
# ==============================
# Write out the Truth Terms:
# => and
# => or
# => not
# => != (not equal) Write this with an exclamation point followed my an equals sign.
# => == (equal)
# => >= (greater-than-equal)
# => <= (less-than-equal)
# => True
# => False
print("The 'NOT' operator:")
print("\tnot True => ", not True) # => False
print("\tnot False => ", not False) # => True
print("\nThe 'OR' operator:")
print("\tTrue or False => ", True or False) # => True
print("\tTrue or True => ", True or True) # => True
print("\tFalse or True => ", False or True) # => True
print("\tFalse or False => ", False or False) # => False
print("\nThe 'AND' operator:")
print("\tTrue and False => ", True and False) # => False
print("\tTrue and True => ", True and True) # => True
print("\tFalse and True => ", False and True) # => False
print("\tFalse and False => ", False and False) # => False
print("\nLet's combine 'NOT OR':")
print("\tnot(True or False) => ", not(True or False)) # => False
print("\tnot(True or True) => ", not (True or True)) # => False
print("\tnot(False or True) => ", not (False or True)) # => False
print("\tnot(False or False) => ", not(False or False)) # => True
print("\nLet's combine 'NOT AND':")
print("\tnot(True and False) => ", not(True and False)) # => True
print("\tnot(True and True) => ", not (True and True)) # => False
print("\tnot(False and True) => ", not (False and True)) # => True
print("\tnot(False and False) => ", not(False and False)) # => True
print("\nThe 'not equals' operator (!=):")
print("\t1 != 0 => ", 1 != 0) # => True
print("\t1 != 1 => ", 1 != 1) # => False
print("\t0 != 1 => ", 0 != 1) # => True
print("\t0 != 0 => ", 0 != 0) # => False
print("\nThe '==' (equals) operator:")
print("\t1 == 0 => ", 1 == 0) # => False
print("\t1 == 1 => ", 1 == 1) # => True
print("\t0 == 1 => ", 0 == 1) # => False
print("\t0 == 0 => ", 0 == 0) # => True |
08472f23c61998aef40d7d69289c7e2a11601c52 | PandaCoding2020/pythonProject | /Python_Basic/10 公共的方法/7 range()方法.py | 143 | 3.890625 | 4 | # 1-9
# for i in range(1,10,1):
# print(i)
# 1-10的奇数
# for i in range(1,10,2):
# print(i)
# 0-9
for i in range(10):
print(i)
|
39ee454befe98c4d0e9b4936c27a23430f280d33 | hcourt/practice | /fibo.py | 733 | 3.546875 | 4 | def nacci(a, b, n):
if n == 0: return []
c = a + b
return [c] + nacci(b, c, n - 1)
def fibonacci_sequence(seed1, seed2, n):
if n > 1:
return [seed1, seed2] + nacci(seed1, seed2, n - 2)
elif n == 1:
return [seed1]
else: return []
def fibonacci_number(seed1, seed2, n):
return fibonacci_sequence(seed1, seed2, n) [-1]
def fast_fibo(seed1, seed2, n):
def matpow(m, n):
if (n > 1):
m = matpow(m, n/2)
m = m * m
elif (n % 2 == 1):
m = m * [[1,1],[1,0]]
matrix = [[1, 0],[0, 1]]
matrix = matpow(matrix, n-1)
return matrix[0][0]
#print fibonacci_sequence(0, 1, 25)
print fibonacci_number(0, 1, 45)
print fast_fibo(0, 1, 45)
|
360b0832224f6f4be7a6fb797d9860ee17ae67fa | dbenny42/streaker | /streaker/task.py | 739 | 3.59375 | 4 | import datetime
class Task:
def __init__(self):
self.taskid = "" # string uniquely identifying
self.userid = "" # string uniquely identifying
self.description = ""
self.start = None # date when first completed
self.end = None # date when last completed
def get_streak(self):
"""
get_streak() computes the current length of the streak.
end_datetime - start_datetime, in days, roughly.
"""
if self.start == None or self.end == None:
return 0
return (self.end - self.start).days
def completed_today(self):
if self.end == None:
return False
return ((datetime.datetime.today() - self.end).days == 0)
|
dd3e80f399c54a0daaa082f4779bc790bbdbfb5f | bschatzj/Algorithms | /recipe_batches/recipe_batches.py | 787 | 4.03125 | 4 |
import math
def recipe_batches(recipe, ingredients):
batches={}
max_batches = 10000
for i in recipe:
try:
#floor devision!!!! WOW THIS TOOK ME WAY TOO LONG TO FIND!!!
batches[i] = ingredients[i] // recipe[i]
except:
max_batches = 0
for i in batches.values():
if i < max_batches:
max_batches = i
return max_batches
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }
ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients)) |
92b07c4090892bbbe601378cdcc4a0c8e6203afd | waynewu6250/LeetCode-Solutions | /257.binary-tree-paths.py | 786 | 3.6875 | 4 | #
# @lc app=leetcode id=257 lang=python3
#
# [257] Binary Tree Paths
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
answer = []
items = ""
def recur(items, root):
if not root:
return
if not root.left and not root.right:
answer.append(items + str(root.val))
recur(items + str(root.val) + "->", root.left)
recur(items + str(root.val) + "->", root.right)
recur(items, root)
return answer
# @lc code=end
|
688bd6b6b5b7a45de7213e056d7d06edea3ccf4c | Andoree/Python-Study | /20181112requests/task0.py | 658 | 3.578125 | 4 | import requests
# download file
# https://wikipedia.org/wiki/London
def download_file_by_url(url):
filename = url.split('/')[-1]
print(filename)
r = requests.get(url)
# r.text
f = open(filename, 'wb')
f.write(r.content)
# print(r.headers.get('content-type'))
# менеджер контекста. При выходе из него будет вызван деструктор дескриптора.
# f - дескриптор.
# with open('', 'wb') as f:
# f.write(r.content)
f.close()
download_file_by_url \
('http://www.bestprintingonline.com/help_resources/Image/Ducky_Head_Web_Low-Res.jpg')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.