blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
81f9ffb5e49a38b96fb96ba1229d9fb634e08f85 | ghimireu57/AssignmentCA2020 | /Task 2/Q.6.py | 365 | 4.25 | 4 | # 6 What is the output of the following code examples?
x=123
for i in x:
print(i)
#int obj is not iterable(error)
i = 0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print('error')
#output: 0,1,2
count = 0
while True:
print(count)
count += 1
if count >= 5:
Break
#output: 0,1,2,3,4 |
f8053aa22c586606ffe61d586a3c2b6f97e78ae7 | amakumi/Binus_TA_Session_Semester_1 | /CLASS - EXERCISE/CLASS.py | 1,008 | 4.15625 | 4 |
class Students: #naming convention, class title capitalised
def __init__(self): #call the constructor by def and initializing
self.name = name
self.gpa = gpa
self.gender = gender
self.age = age
def view(self): #creates the interface!
print("Name: ",self.name)
print("GPA: ",self.gpa)
print("Gender: ",self.gender)
print("Age: ",self.age)
x = Students("Budi",3,"male","17") #way number 1
y = Students("John",3.5,"male","16")
x.view()
y.view()
arr = [] #creates an array
x.append(Students("Budi",3, "male","17"))
x.append(Students("John",3.5, "male","16"))
x.append(Students("Gal", 4, "female", "16"))
for e in arr: #prints each data one-by-one
e.view()
#create using a dictionary
print("DICT:")
book = {}
book["Budi"] = ("Budi",3,"male","17")
book["John"] = ("John",3.5,"male","16")
book["Gal"] = ("Gal", 4, "female", "16")
for e in book: # in dictionaries, '.values' are needed
e.view()
|
3c94fb6849373d4fac490066611ee3402884bbf3 | jschnab/leetcode | /binary_trees/get_next.py | 1,853 | 4.25 | 4 | # given a binary search tree node, get the value of the next node
class TreeNode:
def __init__(self, val=None, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
# the function get_next() is better than this one
def get_next2(node):
if node.right:
node = node.right
while node.left:
node = node.left
return node
# this is covered by the next block
if node == node.parent.left:
return node.parent
# cleaner code if we store both node and parent
if node == node.parent.right:
while node.parent and node.parent.left != node:
node = node.parent
if node.parent and node == node.parent.left:
return node.parent
def get_next(node):
if node.right:
node = node.right
while node.left:
node = node.left
return node
parent = node.parent
while parent and parent.left != node:
node = parent
parent = parent.parent
return parent
def test():
one = TreeNode(1)
two = TreeNode(2)
three = TreeNode(3)
four = TreeNode(4)
five = TreeNode(5)
six = TreeNode(6)
seven = TreeNode(7)
one.parent = two
two.left = one
two.right = three
two.parent = four
three.parent = two
four.left = two
four.right = six
six.parent = four
six.left = five
six.right = seven
five.parent = six
seven.parent = six
assert get_next(one) == two
assert get_next(two) == three
assert get_next(three) == four
assert get_next(four) == five
assert get_next(five) == six
assert get_next(six) == seven
assert get_next(seven) is None
print("test successful")
def main():
test()
if __name__ == "__main__":
main()
|
d10371e25ced48fdb2661a47fd2519e8c642593e | thales-mro/python-cookbook | /1-data-structures/named_tuple.py | 337 | 3.859375 | 4 | from collections import namedtuple
def main():
Subscriber = namedtuple('Subscriber', ['addr', 'joined'])
sub = Subscriber('thales@itaporanga.com', '2012-10-19')
print(sub)
print(sub.addr, sub.joined)
# still works as a tuple
print(len(sub))
addr, joined = sub
print(addr, joined)
if __name__ == "__main__":
main() |
88049ac909b0adf193fafebf59db868bf8cd758b | jiroyamada/Essence-of-ML | /ch4/plot1.py | 162 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
x = np.array([0,1,2,3])
y = np.array([3,4,7,8])
plt.plot(x,y,color="r")
plt.show() |
a66f1c8e93f5b714cc0c8c700bcba541793aa283 | naveen519/data_science | /Algorithms/chatbot/Chatbot AP/save_and_restore.py | 2,808 | 3.734375 | 4 | # Saving the variables
'''
Lets see how to save the parameters into the disk and restore the saved parameters from the disk.
The savable/restorable paramters of the network are Variables (i.e. weights and biases)
'''
# Example 1 - Save variables
'''
We will start with saving and restoring two variables in TensorFlow.
We will create a graph with two variables. Let's create two variables a = [3 3] and b = [5 5 5]
'''
import tensorflow as tf
tf.reset_default_graph()
# create variables a and b
a = tf.get_variable("A", initializer=tf.constant(3, shape=[2]))
b = tf.get_variable("B", initializer=tf.constant(5, shape=[3]))
# initialize all of the variables
init_op = tf.global_variables_initializer()
# run the session
with tf.Session() as sess:
# initialize all of the variables in the session
sess.run(init_op)
# run the session to get the value of the variable
a_out, b_out = sess.run([a, b])
print('a = ', a_out)
print('b = ', b_out)
'''
In order to save the variables, we use the saver function using tf.train.Saver() in the graph.
This function will find all the variables in the graph.
We can see the list of all variables in _var_list.
Let's create a saver object and take a look at the _var_list in the object
'''
# create saver object
saver = tf.train.Saver()
for i, var in enumerate(saver._var_list):
print('Var {}: {}'.format(i, var))
'''
Now that the saver object is created in the graph, in the session, we can call
the saver.save() function to save the variables in the disk. We have to pass the
created session (sess) and the path to the file that we want to save the variables
'''
# run the session
with tf.Session() as sess:
# initialize all of the variables in the session
sess.run(init_op)
# save the variable in the disk
saved_path = saver.save(sess, './saved_variable')
print('model saved in {}'.format(saved_path))
'''If you check your working directory, you will notice that 3 new files have been created
with the name saved_variable in them.
.data: Contains variable values
.meta: Contains graph structure
.index: Identifies checkpoints'''
import os
for file in os.listdir('.'):
if 'saved_variable' in file:
print(file)
###############################################################################
# Restoring variables
'''
Now that all the things that you need is saved in the disk, you can load your
saved variables in the session using saver.restore()
'''
# run the session
with tf.Session() as sess:
# restore the saved vairable
saver.restore(sess, './saved_variable') # instead of initializing the variables in the session, we restore them from the disk
# print the loaded variable
a_out, b_out = sess.run([a, b])
print('a = ', a_out)
print('b = ', b_out)
|
9a0757bf14abd099b4f3ffb0d9072bdc52fd49a0 | nicollebanos/Programacion | /Clases2/clasesyobjetos/talleres/tarea1.py | 2,078 | 3.703125 | 4 |
class Perro ():
'''Es un mamífero domestico carnívoro de la familia de
los cánidos. Lo caracterizan varios atributos que los diferencian
entre ellos:
nombreEntrada: Hace referencia al nombre del perro
generoEntrada: Hace referencia a si es macho o hembra
habitadEntrada: Hace referencia si es de casa o de calle
razaEntrada: Hace referencia al la raza
El canino presenta las siguentes aciones:
*dormir(accion):
Describe cada cuanto duerme
*jugar(accion):
Describe su felicidad a la hora de jugar
*mostrarAtributos():
Muestra los atributos del canino
'''
def __init__(self,nombreEntrada,razaEntrada,habitatEntrada,generoEntrada):
print("Holis, soy una perro muy amoroso")
self.nombre = nombreEntrada
self.genero = generoEntrada
self.habitat = habitatEntrada
self.raza = razaEntrada
def dormir (self):
print(f'''Podria decir que me considero un {self.raza} muy dormilon.
Duermo toda la noche y hago siestas al medio día.
''')
def jugar (self):
print(f''' Ademas de eso, vivo en una/la {self.habitat} difrutando y
jugando al máximo día y noche hasta caer cansado,
se pasa un rato agradable.
''')
def mostrarAtributos (self):
print(f'''Holis mi nombre es {self.nombre} y soy {self.genero}.
Me encuentro viviendo en una/la {self.habitat} y soy de
raza {self.raza} lo que me hace atractivo
para las personas cuando me ven.
''')
perro1 = Perro('Pancho', 'Bugdog Inglés', 'casa', 'macho')
perro2 = Perro('Milu', 'Chihuahua', 'casa', 'hembra')
perro3 = Perro('Rocky', 'Golden retriever', 'calle', 'macho')
#----------------- Print ----------------------#
print('--------------- Perro 1 ---------------')
perro1.mostrarAtributos()
perro1.dormir()
perro1.jugar()
print('--------------- Perro 2 ---------------')
perro2.mostrarAtributos()
perro2.dormir()
perro2.jugar()
print('--------------- Perro 3 ---------------')
perro3.mostrarAtributos()
perro3.dormir()
perro3.jugar()
|
c11cc39028ca9cbd1a9e9fca15734fd18b61b9b4 | Diqosh/PP2 | /TSIS1/additionalTasksInformatics/DataType/105.py | 250 | 3.875 | 4 | class Toupper:
def __init__(self, a, b):
self.a = a
self.b = b
def print(self):
print("yes") if self.a == self.b else print("no")
if __name__ == '__main__':
myclass = Toupper(input(), input())
myclass.print() |
f8574f5cb208c77d0df5c3371459bb653b3b3006 | Hani1-2/All-codes | /Untitled Folder/stackwithlist.py | 937 | 3.984375 | 4 | class mystack:
def __init__(self):
self.elements = list()
def isEmpty(self):
return len(self.elements) == 0
def pop(self):
assert not self.isEmpty(),"Empty stack!"
x = self.elements.pop()
#self.top -= 1
return x
def push(self,value):
#self.top += 1
self.elements.append(value)
##class mystack:
## def __init__(self,size):
## self.top = None
## self.size = size
## self.elements = list()
##
## def isEmpty(self):
## return len(self.elements) == 0
##
## def pop(self):
## if not self.isEmpty():
## print("Empty stack! underflow")
## x = self.elements.pop()
## #self.top -= 1
## return x
##
## def push(self,value):
## if len(self.elements) == self.size:
## print("Full stack , overflow")
## #self.top += 1
## self.elements.append(value)
##
|
a37e361b4554039b4f39848ef2e8bf4c528a1512 | sgorbaty/lexisort | /lexisort.py | 1,182 | 3.640625 | 4 |
# O ( n*m (log n) )
# m is length of string element
def lexicographicsort(args):
listToSort, lexP = args
global lexParam, cache
cache = dict()
lexParam = buildMap(lexP)
return _mergesort(listToSort)
def _mergesort(listToSort):
aSize = len(listToSort)
if aSize == 1:
return listToSort
elif aSize > 1:
middle = aSize/2
aList = listToSort[:middle]
bList = listToSort[middle:]
return merge(_mergesort(aList), _mergesort(bList))
def merge(aList,bList):
tmp = list()
while aList and bList:
if (lexisort(aList[0],bList[0])):
tmp.append(aList.pop(0))
else:
tmp.append(bList.pop(0))
if aList:
tmp.extend(aList)
if bList:
tmp.extend(bList)
return tmp
def lexisort(a,b):
return getMap(a, lexParam) < getMap(b, lexParam)
def buildMap(lexParam):
return dict([(a,k) for a,k in zip(lexParam,range(len(lexParam)))] )
def getMap(s, lexParam):
if s in cache:
return cache[s]
else:
cache[s] = ''.join(str(lexParam[a]) for a in s)
return cache[s]
if __name__ == "__main__":
data = [ (["acb", "abc", "bca"], "abc"),
(["acb", "abc", "bca"], "cba"),
(["aaa", "aa", ""], "a") ];
for d in data:
print d, '=>', lexicographicsort(d)
|
e3115059a052e910490f1209ecb64cccd84ab94f | heykarnold2010/blackjack_demo | /main.py | 5,568 | 3.671875 | 4 | import random
from IPython.display import clear_output
class Deck():
def __init__(self):
self.deck = []
def make_deck(self):
ranks = (['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'])
for rank in range(len(ranks)):
temp = (ranks[rank])
self.deck.append(temp)
random.shuffle(self.deck)
return self.deck
class Blackjack(Deck):
def __init__(self, deck, play):
self.deck = deck
self.play = play
def theInstructions(self):
print('Welcome to Blackjack!')
print('-------♠ ♡ ♢ ♣-------')
print('Think you can beat a computer?')
print('How to play:')
print('1. Have a higher score than me to win.')
print('2. Going over a value of 21 is called a \'bust\', which results in an automatic loss.')
print('3. I have to draw a card if I have under 17 points.')
print('4. If we tie, it\'s called a \'push\'')
print('5. Type \'hit\' to draw a card or \'stay\' to end your turn.')
def startGame(self, players):
for player in players:
player.getCard(self.draw())
player.getCard(self.draw())
def draw(self):
card = self.deck[0]
del self.deck[0]
return card
def showHands(self, player, dealer):
pc = player.sumHands()
dc = dealer.sumHands()
print(f'Dealer\'s Hand\t Total: {dc}.')
print('[X]')
for card in range(1,len(dealer.hand)):
print(f'[{dealer.hand[card]}]')
print(f'Player\'s Hand\t Total: {pc}.')
for card in range(1,len(player.hand)):
print(f'[{player.hand[card]}]')
class Player():
def __init__(self, tag):
self.tag = tag
self.hand = []
self.is_bust = False
def getCard(self, card):
self.hand.append(card)
def sumHands(self):
total = 0
ace = False
for card in self.hand:
if type(card) == int:
total += card
elif card == 'J' or card == 'Q' or card == 'K':
total += 10
elif card == 'A':
ace = True
if (total + 11) > 21:
total += 1
else:
total += 11
if total > 21 and ace == True:
for card in self.hand:
if card[0] == 'A':
total -= 10
return total
# [total += card[0] if card[0] == int else total += 10 if card[0] != 'A' and == str else total += 1 if card[0] == 'A' and (total + 11) > 21 else total += 11 for card in self.hand]
def loseCondition(player, dealer):
if player.is_bust == True:
print('You busted!')
elif dealer.sumHands() <= 21 and dealer.sumHands() > player.sumHands():
print(f'Dealer Sum: {dealer.sumHands()}')
print(f'Player Sum: {player.sumHands()}')
print('You lost to the dealer!')
else:
return False
def winCondition(player, dealer):
if player.sumHands == 21:
print('You win!')
elif player.sumHands() <= 21 and player.sumHands() > dealer.sumHands():
print(f'Dealer Sum: {dealer.sumHands()}')
print(f'Player Sum: {player.sumHands()}')
print('You won!')
else:
return False
def dealerTurn(player, dealer, game):
clear_output()
game.showHands(player, dealer)
if player.is_bust == False:
while True:
if dealer.sumHands() < 17:
clear_output()
dealer.getCard(game.draw())
# if the dealer hits show the cards again
game.showHands(player, dealer)
else:
break
def playerTurn(player, dealer, game):
clear_output()
game.showHands(player, dealer)
while True:
if player.sumHands() == 21:
print('You got Blackjack!')
return False
user_input = input('Would you like to HIT or STAY?')
clear_output()
if user_input.lower() == 'stay':
return False
elif user_input.lower() == 'hit':
player.getCard(game.draw())
else:
print('Not a valid entry! Type HIT or STAY!')
game.showHands(player, dealer)
def playAgain(self):
user_input = input('Would you like to play again? YES or NO?')
if user_input.lower() == 'no':
print('Thanks for playing!')
return False
if user_input.lower() == 'yes':
startGame()
else:
print('Not a valid entry! Type YES or NO!')
if player.sumHands() > 21:
player.is_bust = True
##############################################
##############################################
##############################################
while True:
print('Are you ready to play Blackjack?')
user_input = input('Type p to play or q to quit')
if user_input.lower() == 'q' or user_input.lower() == 'quit':
break
else:
d = Deck()
d.make_deck()
game = Blackjack(d.deck, 'Blackjack')
dealer = Player("Dealer")
player = Player("Player")
players = [dealer, player]
flag = True
while flag:
clear_output()
game.startGame(players)
game.theInstructions()
game.showHands(player, dealer)
playerTurn(player, dealer, game)
dealerTurn(player, dealer, game)
loseCondition(player, dealer)
winCondition(player, dealer)
break
|
70083657af587a9bdba9984b3803391e0b485d58 | guomxin/cvnd-facial-keypoints | /models.py | 8,287 | 3.65625 | 4 | ## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
'''
def __init__(self):
super(Net, self).__init__()
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
# output size = (W-F)/S+1 = (224-5)/1+1=220, the output tensor for one image will be (32, 220, 220)
# after one pooling layer, this becomes (32, 110, 110)
self.conv1 = nn.Conv2d(1, 32, 5)
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
# maxpool layer
# pool with kernel_size=2, stride=2
self.pool = nn.MaxPool2d(2, 2)
# dropout with p=0.4
self.conv1_drop = nn.Dropout(p=0.1)
# second conv layer: 32 inputs, 64 outputs, 5x5 kernel
# output size = (W-F)/S +1 = (110-5)/1 +1 = 106
# the output tensor will have dimensions: (64, 106, 106)
# after another pool layer this becomes (64, 53, 53)
self.conv2 = nn.Conv2d(32, 64, 5)
# dropout with p=0.4
self.conv2_drop = nn.Dropout(p=0.2)
# (64, 58, 58) => 1000
self.fc1 = nn.Linear(64*53*53, 1000)
# dropout with p=0.4
self.fc1_drop = nn.Dropout(p=0.3)
# finally, create 136 output values, 2 for each of the 68 keypoint (x,y) pairs
self.fc2 = nn.Linear(1000, 136)
'''
'''
def __init__(self):
super(Net, self).__init__()
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# 1 input image channel (grayscale), 16 output channels/feature maps, 5x5 square convolution kernel
# output size = (W-F)/S+1 = (224-5)/1+1=220, the output tensor for one image will be (16, 220, 220)
# after one pooling layer, this becomes (16, 110, 110)
self.conv1 = nn.Conv2d(1, 16, 5)
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
# maxpool layer
# pool with kernel_size=2, stride=2
self.pool = nn.MaxPool2d(2, 2)
# dropout with p=0.4
self.conv1_drop = nn.Dropout(p=0.1)
# second conv layer: 16 inputs, 32 outputs, 5x5 kernel
# output size = (W-F)/S +1 = (110-5)/1 +1 = 106
# the output tensor will have dimensions: (32, 106, 106)
# after another pool layer this becomes (32, 53, 53)
self.conv2 = nn.Conv2d(16, 32, 5)
# dropout with p=0.4
self.conv2_drop = nn.Dropout(p=0.2)
# (32, 53, 53) => 1000
self.fc1 = nn.Linear(32*53*53, 1000)
# dropout with p=0.4
self.fc1_drop = nn.Dropout(p=0.3)
# finally, create 136 output values, 2 for each of the 68 keypoint (x,y) pairs
self.fc2 = nn.Linear(1000, 136)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
# two conv/relu + pool layers
x = self.pool(F.relu(self.conv1(x)))
x = self.conv1_drop(x)
x = self.pool(F.relu(self.conv2(x)))
x = self.conv2_drop(x)
# prep for linear layer
# this line of code is the equivalent of Flatten in Keras
x = x.view(x.size(0), -1)
# two linear layers with dropout in between
x = F.relu(self.fc1(x))
x = self.fc1_drop(x)
x = self.fc2(x)
# final output
return x
'''
def __init__(self):
super(Net, self).__init__()
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# 1 input image channel (grayscale), 32 output channels/feature maps, 4x4 square convolution kernel
# output size = (W-F)/S+1 = (224-4)/1+1=221, the output tensor for one image will be (32, 221, 221)
# after one pooling layer, this becomes (32, 110, 110)
self.conv1 = nn.Conv2d(1, 32, 4)
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
# maxpool layer
# pool with kernel_size=2, stride=2
self.pool = nn.MaxPool2d(2, 2)
# dropout with p=0.1
self.conv1_drop = nn.Dropout(p=0.1)
# second conv layer: 32 inputs, 64 outputs, 3x3 kernel
# output size = (W-F)/S +1 = (110-3)/1 +1 = 108
# the output tensor will have dimensions: (64, 108, 108)
# after another pool layer this becomes (64, 54, 54)
self.conv2 = nn.Conv2d(32, 64, 3)
# dropout with p=0.2
self.conv2_drop = nn.Dropout(p=0.2)
# third conv layer: 64 inputs, 128 outputs, 2x2 kernel
# output size = (W-F)/S +1 = (54-2)/1 +1 = 53
# the output tensor will have dimensions: (128, 53, 53)
# after another pool layer this becomes (128, 26, 26)
self.conv3 = nn.Conv2d(64, 128, 2)
# dropout with p=0.3
self.conv3_drop = nn.Dropout(p=0.3)
# fourth conv layer: 128 inputs, 256 outputs, 1x1 kernel
# output size = (W-F)/S +1 = (26-1)/1 +1 = 26
# the output tensor will have dimensions: (256, 26, 26)
# after another pool layer this becomes (256, 13, 13)
self.conv4 = nn.Conv2d(128, 256, 1)
# dropout with p=0.4
self.conv4_drop = nn.Dropout(p=0.4)
# (256, 13, 13) => 1000
self.fc1 = nn.Linear(256*13*13, 1000)
# dropout with p=0.5
self.fc1_drop = nn.Dropout(p=0.5)
# 1000 => 1000
self.fc2 = nn.Linear(1000, 1000)
# dropout with p=0.6
self.fc2_drop = nn.Dropout(p=0.6)
# finally, create 136 output values, 2 for each of the 68 keypoint (x,y) pairs
self.fc3 = nn.Linear(1000, 136)
def forward(self, x):
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
# four conv/relu + pool layers
x = self.pool(F.relu(self.conv1(x)))
x = self.conv1_drop(x)
x = self.pool(F.relu(self.conv2(x)))
x = self.conv2_drop(x)
x = self.pool(F.relu(self.conv3(x)))
x = self.conv3_drop(x)
x = self.pool(F.relu(self.conv4(x)))
x = self.conv4_drop(x)
# prep for linear layer
# this line of code is the equivalent of Flatten in Keras
x = x.view(x.size(0), -1)
# three linear layers with dropout in between
x = F.relu(self.fc1(x))
x = self.fc1_drop(x)
x = F.relu(self.fc2(x))
x = self.fc2_drop(x)
x = self.fc3(x)
# final output
return x
|
203eb0a1f804345019a1292ba49b7cff8e2660c7 | EatTheGiant/PSA | /cvic 2.py | 3,270 | 3.953125 | 4 | #! /usr/bin/env python
APP_VERSION = "1.0"
class Movie:
def __init__(self, paTitle, paYear, paGenre, paEarnings, paRating, paDuration):
self.aTitle = paTitle
self.aYear = paYear
self.aGenre = paGenre
self.aEarnings = paEarnings
self.aRating = paRating
self.aDuration = paDuration
def toString(self):
return "{:20} {} {:10} ${:4} {:3}% {3}m".format(self.aTitle,
self.aYear,
self.aGenre,
self.aEarnings,
self.aRating,
self.aDuration)
class MovieLibrary():
def __init__(self):
self.aMovies = list()
def addMovie(self, paMovie):
self.aMovies.append()
def removeMovie(self, paMovieIndex):
self.aMovies.pop(paMovieIndex)
def showLibrary(self, paPrintIndex):
if paPrintIndex:
indexString = " ID "
else:
indexString = " "
print("{} {:20} {} {:10} {:5} {:4} {4}".format( indexString,
"Title",
"Year"
"Genre",
"Earn",
"RAT",
"Time"))
index = 0
for movie in self.aMovies:
if paPrintIndex:
indexString = "{:3} ".format(index)
else:
indexString = ""
print(indexString + movie.toString())
index += 1
def menu(paMovieLibrary):
while True:
print("Welcome to Movie Library v{}".format(APP_VERSION))
print(" Add Movie (1)")
print(" Remove Movie (2)")
print(" Show Library Content (3)")
print(" End the Program (q)")
opt = input("Select one option from the menu: ")
if(opt == "1"):
addMovie(paMovieLibrary)
print("Movie added")
elif(opt == "2"):
removeMovie(paMovieLibrary)
print("Movie removed")
elif(opt == "3"):
paMovieLibrary.printLibrary(False)
elif(opt == "q"):
print("Bye Bye")
exit(0)
else:
print("Incorrect option")
def addMovie(paMovieLibrary):
title = input("Enter movie title: ")
year = input("Enter year: ")
genre = input("Enter genre: ")
earn = input("Enter earnings in $M: ")
rating = input("Enter rating in %: ")
duration = input("Enter duration in minutes")
movie = Movie(title, year, genre, earn, rating, duration)
paMovieLibrary.addMovie(movie)
def removeMovie(paMovieLibrary):
paMovieLibrary.printLibrary(True)
index = input("Enter movie index for removal: ")
paMovieLibrary.removeMovie(int(index))
if __name__ == "__main__":
library = MovieLibrary
menu(library) |
f6402fa4f65ce8159945eaaca505e8d024e2185b | ohadlights/tensorflow-without-a-phd | /tensorflow-rl-hanabi/entities/color.py | 356 | 3.671875 | 4 | class Color:
def __init__(self, color_id: int, name: str):
self.color_id = color_id
self.name = name
def __str__(self):
return self.name
def __eq__(self, other):
return self.color_id == other.color_id
def __hash__(self):
return hash(repr(self))
BLUE = Color(0, 'Blue')
GREEN = Color(1, 'Green')
|
d2e33377beb764670f14c3ab7b83c69a11adf690 | Th3Lourde/l33tcode | /problemSets/top75/191.py | 249 | 3.515625 | 4 | class Solution:
def hammingWeight(self, n):
ones = 0
while n:
if n % 2 == 1:
ones += 1
n = n // 10
return ones
print(Solution().hammingWeight(11111111111111111111111111111101))
|
4d39a7e890f466f1ab18ba8fa0f57d6adb14ac98 | Parva1610/Multi-Programs | /Cryptography Codes/OTP.py | 795 | 3.703125 | 4 | import random
charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
def encrypt(plaintext):
otp = "".join(random.sample(charset, len(charset)))
result = ""
for c in plaintext.upper():
if c not in otp:
continue
else:
result += otp[charset.find(c)]
return otp, result
def decrypt(otp, secret):
result = ""
for c in secret.upper():
if c not in otp:
continue
else:
result += charset[otp.find(c)]
return result
Msg = input("Enter Your Message: ")
encrypted = encrypt(Msg)
decrypted = decrypt(encrypted[0], encrypted[1])
print("\nCharset: " + charset)
print("OTP: \t" + encrypted[0])
print("Encrypted Msg: " + encrypted[1])
print("Decrypted Msg: " + decrypted)
|
c437a32b84a7263617641e00f443692385c08115 | Gab-Aguilar/PRELIMINARIES | /ASSIGNMENT/R2.39/agr2.39try.py | 4,256 | 4.15625 | 4 | from abc import ABC, abstractmethod # need these definitions
class Polygon(ABC):
def __init__(self, lengths_of_sides):
self.number_of_sides = len(lengths_of_sides)
self.lengths_of_sides = [0] * self.number_of_sides
self.assign_values_to_sides(lengths_of_sides)
def print_num_sides(self):
"""a quick, informational print statement"""
print('There are ' + str(self.number_of_sides) + 'sides.')
def assign_values_to_sides(self, lengths_of_sides):
index = 0
while index < len(lengths_of_sides):
self.lengths_of_sides[index] = lengths_of_sides[index]
index += 1
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Triangle(Polygon):
def __init__(self, lengths_of_sides):
super().__init__(lengths_of_sides)
assert 3, self.number_of_sides
def area(self):
"""return the area of the triangle using the semi-perimeter method"""
a, b, c = self.lengths_of_sides
# calculate the semi-perimeter
s = (a + b + c) / 2
return (s * (s - a) * (s - b) * (s - c)) ** 0.5
def perimeter(self):
"""Return the perimeter of the polygon."""
# calculate the perimeter
s = (self.lengths_of_sides[0] + self.lengths_of_sides[1] + self.lengths_of_sides[2])
return s
class IsoscelesTriangle(Triangle):
def __init__(self, side, base): # [side, base]
super().__init__([side, side, base])
class EquilateralTriangle(Triangle):
def __init__(self, side): # side
super().__init__([side, side, side])
class Pentagon(Polygon):
def __init__(self, lengths_of_sides):
super().__init__(lengths_of_sides)
assert 5, self.number_of_sides
def area(self):
x, y = self.lengths_of_sides[0], self.lengths_of_sides[1]
return x * y
def perimeter(self):
"""Return the perimeter of the polygon."""
# calculate the perimeter
x, y = self.lengths_of_sides
return (x + y) * 2
class Hexagon(Polygon):
def __init__(self, lengths_of_sides):
super().__init__(lengths_of_sides)
assert 6, self.number_of_sides
def area(self):
x, y = self.lengths_of_sides[0], self.lengths_of_sides[1]
return x * y
def perimeter(self):
"""Return the perimeter of the polygon."""
# calculate the perimeter
x, y = self.lengths_of_sides
return (x + y) * 2
class Octagon(Polygon):
def __init__(self, lengths_of_sides):
super().__init__(lengths_of_sides)
assert 8, self.number_of_sides
def area(self):
x, y = self.lengths_of_sides[0], self.lengths_of_sides[1]
return x * y
def perimeter(self):
"""Return the perimeter of the polygon."""
# calculate the perimeter
x, y = self.lengths_of_sides
return (x + y) * 2
class Quadrilateral(Polygon):
def __init__(self, lengths_of_sides): # [side1, side2]
super().__init__([lengths_of_sides[0], lengths_of_sides[1], lengths_of_sides[0], lengths_of_sides[1]])
assert 4, self.number_of_sides
def area(self):
x, y = self.lengths_of_sides[0], self.lengths_of_sides[1]
return x * y
def perimeter(self):
"""Return the perimeter of the polygon."""
# calculate the perimeter
x, y = self.lengths_of_sides
return (x + y) * 2
class Rectangle(Quadrilateral):
def __init__(self, lengths_of_sides): # [side1, side2]
super().__init__(lengths_of_sides)
def area(self):
x, y = self.lengths_of_sides[0], self.lengths_of_sides[1]
return x * y
def perimeter(self):
"""Return the perimeter of the polygon."""
# calculate the perimeter
x, y = self.lengths_of_sides
return (x + y) * 2
class Square(Rectangle):
def __init__(self, side):
super().__init__([side, side])
def area(self):
x = self.lengths_of_sides[0]
return x * x
def perimeter(self):
"""Return the perimeter of the polygon."""
# calculate the perimeter
x = self.lengths_of_sides[0]
return x * 4
|
c5ab1d20bf5c74d60dcc044b91eff1b8422f96d6 | Xievv/Portfolio | /schoolWork/DatabaseManagement/informationGenerator/employee/employee_generator.py | 13,455 | 3.5 | 4 | #!/usr/bin/env python
# Script by Shawn Giroux
# Date: February 13 2016
#
# This Python script generates fake information for an Oracle Database.
# The output will be a .sql file.
import os # For finding out directory
import time # Finds our time elapsed
import random # Used to generates phone numbers and select names from array
import re # Used to pull names from raw data
# These lists will store information for randomize employees
firstNames = []
lastNames = []
streetNames = []
# departments = ['MARKETING', 'HUMAN RESOURCE', 'FINANCE', 'PRODUCTION', 'DEVELOPMENT', 'INFORMATION TECHNOLOGY']
marketSal = [3500, 3917, 4333, 4833]
hrSal = [4361, 4830, 5000, 4583]
financeSal = [5416, 5666, 5833, 4917]
develSal = [6166, 5833, 6500, 6667]
itSal = [4833, 5166, 4091, 5416]
EMPcount = 0
EADcount = 0
JOBcount = 0
EMRcount = 0
# This class fills out firstNames and lastNames list from text files
class FillList:
# Generate a list of first names
def genFirstNames():
male_text = open("dist.male.first.txt", 'r')
raw_text = male_text.readlines()
for x in range(0,len(raw_text)):
name = re.findall(r'[A-Z]\w+',raw_text[x])
firstNames.append(name)
male_text.close()
female_text = open("dist.female.first.txt", 'r')
raw_text = female_text.readlines()
for x in range(0,len(raw_text)):
name = re.findall(r'[A-Z]\w+',raw_text[x])
firstNames.append(name)
female_text.close()
return
# Generate a list of last names
def genLastNames():
last_text = open("dist.all.last.txt", 'r')
raw_text = last_text.readlines()
for x in range(0,len(raw_text)):
name = re.findall(r'[A-Z]\w+',raw_text[x])
lastNames.append(name)
last_text.close()
return
# Generate street names
def genStreetNames():
street_text = open("streets.txt", 'r')
raw_text = street_text.readlines()
for x in raw_text:
streetNames.append(x)
street_text.close()
return
# This class generates random personal information for employees
class InfoGen:
# Generates a random phone number with a 603 area code
def phone():
a = random.randint(1,9)
b = random.randint(0,9)
c = random.randint(0,9)
d = random.randint(0,9)
e = random.randint(0,9)
f = random.randint(0,9)
g = random.randint(0,9)
rPhone = ("(603){0}{1}{2}-{3}{4}{5}{6}".format(a,b,c,d,e,f,g))
return rPhone
# Pulls a random name from firstNames list
def firstName(nameList):
randomFirstName = random.randint(0,len(nameList) - 1) # Generates random integer to select a random first name
rFirstName = nameList[randomFirstName][0] # Selects random name. [0] is because there is a nested list
return rFirstName
# Pulls a random name from lastNames list
def lastName(nameList):
randomLastName = random.randint(0,len(nameList) - 1) # Generates a random integer to select a random last name
rLastName = nameList[randomLastName][0] # Selects random name. [0] is because there is a nested list
return rLastName
# Generate a street and street number (not anywhere close to accurate)
def street():
streetNum = random.randint(100,999)
streetName = random.choice(streetNames)
return str(streetNum) + " " + streetName
# Generates cities for customers using NH statistics from 2010
# of the top 10 cities.
# https://en.wikipedia.org/wiki/List_of_cities_and_towns_in_New_Hampshire
def city():
a = random.randint(1,100)
if (a > 0 and a <= 25):
return "MANCHESTER"
elif (a > 25 and a <= 45):
return "NASHUA"
elif (a > 45 and a <= 55):
return "CONCORD"
elif (a > 55 and a <= 63):
return "DERRY"
elif (a > 63 and a <= 70):
return "DOVER"
elif (a > 70 and a <= 77):
return "ROCHESTER"
elif (a > 77 and a <= 84):
return "SALEM"
elif (a > 84 and a <= 90):
return "MERRIMACK"
elif (a > 90 and a <= 95):
return "HUDSON"
elif (a > 95 and a <= 100):
return "LONDONDERRY"
else:
return "Not Option"
# Grabs the appropriate zipcode per city
def zipcode(city):
manchZip = ["03101","03102","03103","03104","03105","03107","03108","03109","03111"]
nashZip = ["03060","03061","03062","03063","03064"]
conZip = ["03301", "03302", "03303", "03305"]
derryZip = ["03038"]
doverZip = ["03820", "03821", "03822"]
rochZip = ["03839", "03866", "03867", "03868"]
salemZip = ["03089"]
merZip = ["03054"]
hudZip = ["03051"]
londonZip = ["03053"]
if (city == "MANCHESTER"):
return random.choice(manchZip)
elif (city == "NASHUA"):
return random.choice(nashZip)
elif (city == "CONCORD"):
return random.choice(conZip)
elif (city == "DERRY"):
return random.choice(derryZip)
elif (city == "DOVER"):
return random.choice(doverZip)
elif (city == "ROCHESTER"):
return random.choice(rochZip)
elif (city == "SALEM"):
return random.choice(salemZip)
elif (city == "MERRIMACK"):
return random.choice(merZip)
elif (city == "HUDSON"):
return random.choice(hudZip)
elif (city == "LONDONDERRY"):
return random.choice(londonZip)
else:
return "Not Option"
def keygen(label):
# Key counts for generation
global EMPcount
global EADcount
global JOBcount
global EMRcount
key = ""
if label == "EMR":
EMRcount += 1
key = label + str(EMRcount).zfill(5)
elif label == "EMP":
EMPcount += 1
key = label + str(EMPcount).zfill(5)
elif label == "EAD":
EADcount += 1
key = label + str(EADcount).zfill(5)
elif label == "JOB":
JOBcount += 1
key = label + str(JOBcount).zfill(5)
return key
# This class will generate salary information depending on the department our employee works in
class JobGen:
def marketing():
randomSal = random.randint(0,3)
salary = marketSal[randomSal]
return salary
def hr():
randomSal = random.randint(0,3)
salary = hrSal[randomSal]
return salary
def development():
randomSal = random.randint(0,3)
salary = develSal[randomSal]
return salary
def finance():
randomSal = random.randint(0,3)
salary = financeSal[randomSal]
return salary
def infotech():
randomSal = random.randint(0,3)
salary = marketSal[randomSal]
return salary
# This class will handle writing employee data into a text document
class Script:
# Creates marketing employees. Note that the random integer determines the amount of employees in the department
def marketEmp():
employee = open("load_data/employee_info.sql", 'w')
address = open("load_data/address_info.sql", 'w')
job = open("load_data/job_info.sql", 'w')
# Set back to a range of 0,23
for x in range(0,25):
empKey = InfoGen.keygen('EMP')
city = InfoGen.city()
lastname = InfoGen.lastName(lastNames)
employee.write("INSERT INTO employee_data (EMPLOYEE_ID, FIRST_NAME, LAST_NAME) VALUES('{0}', '{1}', '{2}');\n".format(empKey, InfoGen.firstName(firstNames), lastname))
address.write ("INSERT INTO employee_address_data (ADDRESS_ID, EMPLOYEE_ID, STREET, CITY, STATE, COUNTRY, ZIPCODE, PHONE_NUMBER) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');\n"
"".format(InfoGen.keygen('EAD'), empKey, InfoGen.street(), city, "NEW HAMPSHIRE", "UNITED STATES", InfoGen.zipcode(city), InfoGen.phone()))
job.write("INSERT INTO employee_job_data (JOB_ID, EMPLOYEE_ID, DEPARTMENT, SALARY) VALUES ('{0}', '{1}', '{2}', '{3}');\n".format(InfoGen.keygen('JOB'), empKey, "MARKETING", JobGen.marketing()))
employee.close()
address.close()
job.close()
return
# Creates HR employees. Note that the random integer determines the amount of employees in the department
def hrEmp():
employee = open("load_data/employee_info.sql", 'a+')
address = open("load_data/address_info.sql", 'a+')
job = open("load_data/job_info.sql", 'a+')
for x in range(0,8):
empKey = InfoGen.keygen('EMP')
city = InfoGen.city()
lastname = InfoGen.lastName(lastNames)
employee.write("INSERT INTO employee_data (EMPLOYEE_ID, FIRST_NAME, LAST_NAME) VALUES('{0}', '{1}', '{2}');\n".format(empKey, InfoGen.firstName(firstNames), lastname))
address.write ("INSERT INTO employee_address_data (ADDRESS_ID, EMPLOYEE_ID, STREET, CITY, STATE, COUNTRY, ZIPCODE, PHONE_NUMBER) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');\n"
"".format(InfoGen.keygen('EAD'), empKey, InfoGen.street(), city, "NEW HAMPSHIRE", "UNITED STATES", InfoGen.zipcode(city), InfoGen.phone()))
job.write("INSERT INTO employee_job_data (JOB_ID, EMPLOYEE_ID, DEPARTMENT, SALARY) VALUES ('{0}', '{1}', '{2}', '{3}');\n".format(InfoGen.keygen('JOB'), empKey, "HUMAN RESOURCE", JobGen.hr()))
employee.close()
address.close()
job.close()
return
# Creates finance employees. Note that the random integer determines the amount of employees in the department
def financeEmp():
employee = open("load_data/employee_info.sql", 'a+')
address = open("load_data/address_info.sql", 'a+')
job = open("load_data/job_info.sql", 'a+')
for x in range(0,7):
empKey = InfoGen.keygen('EMP')
city = InfoGen.city()
lastname = InfoGen.lastName(lastNames)
employee.write("INSERT INTO employee_data (EMPLOYEE_ID, FIRST_NAME, LAST_NAME) VALUES('{0}', '{1}', '{2}');\n".format(empKey, InfoGen.firstName(firstNames), lastname))
address.write ("INSERT INTO employee_address_data (ADDRESS_ID, EMPLOYEE_ID, STREET, CITY, STATE, COUNTRY, ZIPCODE, PHONE_NUMBER) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');\n"
"".format(InfoGen.keygen('EAD'), empKey, InfoGen.street(), city, "NEW HAMPSHIRE", "UNITED STATES", InfoGen.zipcode(city), InfoGen.phone()))
job.write("INSERT INTO employee_job_data (JOB_ID, EMPLOYEE_ID, DEPARTMENT, SALARY) VALUES ('{0}', '{1}', '{2}', '{3}');\n".format(InfoGen.keygen('JOB'), empKey, "FINANCE", JobGen.finance()))
employee.close()
address.close()
job.close()
return
# Creates development employees. Note that the random integer determines the amount of employees in the department
def develEmp():
employee = open("load_data/employee_info.sql", 'a+')
address = open("load_data/address_info.sql", 'a+')
job = open("load_data/job_info.sql", 'a+')
for x in range(0,31):
empKey = InfoGen.keygen('EMP')
city = InfoGen.city()
lastname = InfoGen.lastName(lastNames)
employee.write("INSERT INTO employee_data (EMPLOYEE_ID, FIRST_NAME, LAST_NAME) VALUES('{0}', '{1}', '{2}');\n".format(empKey, InfoGen.firstName(firstNames), lastname))
address.write ("INSERT INTO employee_address_data (ADDRESS_ID, EMPLOYEE_ID, STREET, CITY, STATE, COUNTRY, ZIPCODE, PHONE_NUMBER) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');\n"
"".format(InfoGen.keygen('EAD'), empKey, InfoGen.street(), city, "NEW HAMPSHIRE", "UNITED STATES", InfoGen.zipcode(city), InfoGen.phone()))
job.write("INSERT INTO employee_job_data (JOB_ID, EMPLOYEE_ID, DEPARTMENT, SALARY) VALUES ('{0}', '{1}', '{2}', '{3}');\n".format(InfoGen.keygen('JOB'), empKey, "DEVELOPMENT", JobGen.development()))
employee.close()
address.close()
job.close()
return
# Creates IT employees. Note that the random integer determines the amount of employees in the department
def itEmp():
employee = open("load_data/employee_info.sql", 'a+')
address = open("load_data/address_info.sql", 'a+')
job = open("load_data/job_info.sql", 'a+')
for x in range(0,4):
empKey = InfoGen.keygen('EMP')
city = InfoGen.city()
lastname = InfoGen.lastName(lastNames)
employee.write("INSERT INTO employee_data (EMPLOYEE_ID, FIRST_NAME, LAST_NAME) VALUES('{0}', '{1}', '{2}');\n".format(empKey, InfoGen.firstName(firstNames), lastname))
address.write ("INSERT INTO employee_address_data (ADDRESS_ID, EMPLOYEE_ID, STREET, CITY, STATE, COUNTRY, ZIPCODE, PHONE_NUMBER) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');\n"
"".format(InfoGen.keygen('EAD'), empKey, InfoGen.street(), city, "NEW HAMPSHIRE", "UNITED STATES", InfoGen.zipcode(city), InfoGen.phone()))
job.write("INSERT INTO employee_job_data (JOB_ID, EMPLOYEE_ID, DEPARTMENT, SALARY) VALUES ('{0}', '{1}', '{2}', '{3}');\n".format(InfoGen.keygen('JOB'), empKey, "INFORMATION TECHNOLOGY", JobGen.infotech()))
employee.close()
address.close()
job.close()
return
# Creates production employees. Note that the random integer determines the amount of employees in the department
startTime = time.time() # Gets current time to compare with the end time
# Fill out name lists
FillList.genFirstNames()
FillList.genLastNames()
FillList.genStreetNames()
# Run our employee generation scripts
Script.marketEmp()
Script.hrEmp()
Script.financeEmp()
Script.develEmp()
Script.itEmp()
elapsedTime = (time.time() - startTime) # Tells us the elapsed time
currentDir = os.getcwd() # Current directory to let user know where their file is
print("\nProcess Complete! Elapsed time: {0} seconds".format(str(int(elapsedTime)))) |
d3822b886c58571088a545c57b0fce52a24c2e05 | sonji16/pythonPractice | /one_bite_prime_number.py | 5,923 | 3.546875 | 4 | # 55 튜플 = 값 변경 불가
# clovers_1 = (1, 2, 3)
# clovers_2 = [1, 2, 3]
# clovers_2[2] = 4
# print (clovers_2[2])
# 56 패킹, 언패킹
# clovers = 1, 2, 3
# print(clovers)
# r, g, b = 240, 248, 255
# print(r, g, b)
# 57 패킹, 언패킹 예제(사탕 바꾸기)
# dodo = '박하맛'
# alice = '딸기맛'
# dodo, alice = alice, dodo
# print('도도새:', dodo,'앨리스:', alice)
# 58 Dictionary 기본구조
# # 파이썬 = 비단뱀
# my_dict1 = {}
# print(my_dict1)
# my_dict2 = {'이름': '앨리스', '나이': 10, '시력': [1,0, 1.2]}
# print(my_dict2)
# 59 딕셔너리 값 바꾸기
# dic = {}
# dic[0] = 1
# dic[1] = 2
# print(dic)
# dic[0] = 3
# print(dic)
# 61 딕셔너리 값 print 하기(.get)
# jiwoo = {'age': 17, 'job': 'student','number': 10119}
# print(jiwoo['number'])
# print(jiwoo['age'])
# print(jiwoo.get('job'))
# 62 딕셔너리 키, 값 제거
# jiwoo = {'age': 17, 'job': 'student', 'number': 10119}
# del jiwoo['age']
# print(jiwoo)
# 63 딕셔너리 예제(라면 주문)
# order = {'spade1': 'bibim_ramen', 'dia2': 'spicy_ramen'}
# print(order)
# order['clover3'] = 'curry_ramen'
# print(order)
# order['dia2'] = '짜장라면'
# print(order)
# del order['spade1']
# print(order)
# 64 함수 종류
# 내장함수 built in function
# 모듈의 함수
# 사용자 정의 함수
# 65 함수의 기본 구조
# def 함수이름(인수):
# 실행할 명령
#return 반환값
# def my_func():
# print('토끼야 안녕')
# def add(num1, num2):
# return num1 + num2
# print(add(2,3))
# def add_mul(num1, num2):
# return num1 + num2, num1*num2
# print(add_mul(5,6))
# 66 함수 이용해서 반복 피하기
# def judge_cards(name):
# print(name, '1 유죄!')
# print(name, '2 유죄!')
# print(name, '3 유죄!')
# judge_cards('하트')
# judge_cards('클로버')
# judge_cards('스페이드')
# 67 모듈
# 모듈: 다른 사람들이 만들어놓은 것들
# import 모듈이름.함수이름
# 68 모듈- 랜덤하게 뽑기(random. choice/sample/randint)
# import random
# animals = [1, 2, 3, 4, 5, 6, 7]
# print(random.choice(animals)) # 랜덤 한개 뽑기
# print(random.sample(animals, 2)) # 랜덤 중복없이 두개 뽑기
# print(random.randint(5, 10)) # 5~10정수 중 하나를 랜덤 뽑기
# 69 랜덤으로 뽑기 예제(죄인뽑기)
# import random
# cards = ['하트', '클로버', '스페이드']
# chosen_card = random.choice(cards)
# print(chosen_card, '유죄!')
# 70 모듈을 사용하는 이유
# 이미 만들어진 것을 이용하여 간결하고 쉽게 만들기 위해서
# 71~ 연습문제
# print(3 + 1 - 2)
# print(3 - 1 + 2)
# print(3/1 - 2)
# 4
# 1
# 2
# 24
# adcdef
# 1
# 73 연습문제(3)
# nums = [1, 2, 3]
# print(nums)
# []
# fruits = ['자몽', '멜론', '레몬']
# print(fruits)
# del fruits[0]
# print(fruits)
# 74 연습문제(2)
# nums = [1, 3]
# nums[1] = 2
# nums.append(3)
# nums.append(4)
# print(nums)
# 3
# 3
# 1, 2, 3,
# 3, 4, 5
# 75 횟수로 반복하기 연습문제(1)
# fruits = ['멜론', '거봉', '레몬']
# print(fruits)
# fruits.sort()
# print(fruits)
# for num in [3, 1, 2]:
# print(num)
# for num in range(2):
# print(num)
# clovers = ['클로버1', '클로버2', '클로버3']
# for clover in clovers:
# print(clover)
# clovers = ['클로버1', '클로버2', '클로버3']
# for idx in range(3):
# print(clovers[idx]
# for i in range(1,4):
# print('*'*i)
# stars = [2, 1, 3]
# for num in stars:
# print('*'*num)
# total = total + num
# total = 0
# card_nums = [1, 3, 6, 7]
# for num in card_nums:
# total = total + num
# print(total / len(card_nums))
# switch = 'on'
# if switch == 'on':
# print('조명이 켜졌어요.')
# else:
# print('조명이 꺼졌어요.')
# input_number = -9
# if input_number >= 0:
# absolute_value = input_number
# else:
# absolute_value = -(input_number)
# print(absolute_value)
# 총 주문금액은 18500원입니다.
# odd_nums = []
# for num in range(10):
# if num % 2 != 0:
# odd_nums.append(num)
# print(odd_nums)
# 윤년 계산하기
# year = 2016
# if year % 400 == 0:
# print(year, '년은 윤년입니다.')
# elif year % 4 == 0 and year % 100 != 0:
# print(year, '년은 윤년입니다.')
# else:
# print(year, '년은 윤년이 아닙니다.')
# 1~5까지 총합 구하기
# count = 1
# while count < 4:
# count = count + 1
# print(count)
# total = 0
# count = 1
# while count <= 5:
# total = total + count
# count = count + 1
# print('총합은', total)
# my_list = [1, 2, 3, 4, 5]
# print(sum(my_list))
#3부터 1까지 거꾸로 세기
# count = 3
# while count >= 1:
# print(count)
# count = count - 1
# num = 1
# while True:
# print(num)
# num = num + 1
# if num > 3:
# break
# price = 0
# while price != -1:
# price = int(input('가격을 입력하세요 (종료:-1):'))
# if price> 10000:
# print('너무 비싸요')
# elif price > 5000:
# print('괜찮은 가격이네요.')
# elif price > 0:
# print('정말 싸요.')
# 소수 판정하기
while True:
number = int(input('2 이상의 정수를 입력하세요(종료: -1):'))
if number == -1:
break
count = 2
is_prime = True
while count < number:
if number % count == 0:
is_prime = False
break
count = count + 1
if number >= 2:
if is_prime:
print(number, '은(는) 소수입니다.')
else:
print(number, '은(는) 소수가 아닙니다.')
else:
'2 이상의 정수를 입력하세요.'
|
2f02d243dba8f3e1ae3527b19e6e60d89d9833c8 | another-computer/hanabi-py | /Hanabi/Card.py | 1,781 | 3.71875 | 4 | # The deck is a randomized list of cards
# 5 colors
# 1 five, 2 fours/threes/twos, 3 ones per color
# Total 50 cards
# Hands are lists of 5 cards each
# Discard pile is a list of all cards that have been removed from a hand through discard
# Cards have color, number, and clue status for both
colors = {'Unknown': '[7;37;48m', 'Red': '[7;31;48m', 'Blue': '[7;34;48m',
'Green': '[7;32;48m', 'Yellow': '[7;33;48m', 'White': '[7;30;48m',
'Rainbow': '[0;35;48m'}
numbers = ['1', '2', '3', '4', '5']
class Card(object):
def __init__(self, color, number):
self.color = color
self.number = number
self.color_clue = False
self.number_clue = False
def __str__(self):
color_display = 'Unknown'
number_display = '?'
if self.color_clue is True:
color_display = self.color
if self.number_clue is True:
number_display = self.number
return '\x1b{}{}\x1b[0m'.format(colors[color_display], number_display)
def __repr__(self):
color_display = 'Unknown'
number_display = '?'
if self.color_clue is True:
color_display = self.color
if self.number_clue is True:
number_display = self.number
return '\x1b{}{}\x1b[0m'.format(colors[color_display], number_display)
def clue_check(self, clue):
if clue == self.color:
self.color_clue = True
if clue == self.number:
self.number_clue = True
if __name__ == '__main__':
test = Card('Blue', '5')
print(test)
print('')
test.clue_check('Blue')
print(test)
print('')
test.clue_check('5')
print(test)
|
c90231464e7ca095b795cc804ea919e16ae8865b | al00014/covid19-sir | /covsirphy/analysis/predicter.py | 5,553 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from datetime import datetime, timedelta
import pandas as pd
from covsirphy.analysis.simulation import simulation
from covsirphy.util.plotting import line_plot
class Predicter(object):
"""
Predict the future using models.
"""
def __init__(self, name, total_population,
start_time, tau, initials, date_format="%d%b%Y"):
"""
@name <str>: place name
@total_population <int>: total population
@start_time <datatime>: the start time
@tau <int>: tau value (time step)
@initials <list/tupple/np.array[float]>:
initial values of the first model
@date_format <str>: date format to display in figures
"""
self.name = name
self.total_population = total_population
self.start_time = start_time.replace(
hour=0, minute=0, second=0, microsecond=0)
self.tau = tau
self.date_format = date_format
# Un-fixed
self.last_time = start_time
self.axvlines = list()
self.initials = initials
self.df = pd.DataFrame()
self.title_list = list()
self.reverse_f = lambda x: x
self.model_names = list()
def add(self, model, end_day_n=None, count_from_last=False, vline=True,
**param_dict):
"""
@model <ModelBase>: the epidemic model
@end_day_n <int/None>:
day number of the end date (0, 1, 2,...), or None (now)
- if @count_from_last <bool> is True,
start point will be the last date registered to Predicter
@vline <bool>: if True, vertical line will be shown at the end date
@**param_dict <dict>: keyword arguments of the model
"""
# Validate day number, and calculate step number
vline_yesterday = False
if end_day_n == 0:
end_day_n = 1
vline_yesterday = True
if end_day_n is None:
end_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
else:
if count_from_last:
end_time = self.last_time + timedelta(days=end_day_n)
else:
end_time = self.start_time + timedelta(days=end_day_n)
if end_time <= self.last_time:
raise Exception(
f"Model on {end_time.strftime(self.date_format)} has been registered!")
step_n = int(
(end_time - self.last_time).total_seconds() / 60 / self.tau) + 1
self.last_time = end_time.replace(
hour=0, minute=0, second=0, microsecond=0)
# Perform simulation
new_df = simulation(model, self.initials, step_n=step_n, **param_dict)
new_df["t"] = new_df["t"] + len(self.df)
self.df = pd.concat([self.df, new_df.iloc[1:, :]], axis=0).fillna(0)
self.initials = new_df.set_index("t").iloc[-1, :]
# For title
self.model_names.append(model.NAME)
if vline:
vline_date = end_time.replace(
hour=0, minute=0, second=0, microsecond=0)
if vline_yesterday:
vline_date -= timedelta(days=1)
self.axvlines.append(vline_date)
r0 = model(**param_dict).calc_r0()
if len(self.axvlines) == 1:
self.title_list.append(
f"{model.NAME}(R0={r0}, -{vline_date.strftime(self.date_format)})")
else:
if model.NAME == self.model_names[-2]:
self.title_list.append(
f"({r0}, -{vline_date.strftime(self.date_format)})")
else:
self.title_list.append(
f"{model.NAME}({r0}, -{end_time.strftime(self.date_format)})")
# Update reverse function (X, Y,.. to Susceptible, Infected,...)
self.reverse_f = model.calc_variables_reverse
return self
def restore_df(self, min_infected=1):
"""
Return the dimentional simulated data.
@min_infected <int>: if Infected < min_infected, the records will not be used
@return <pd.DataFrame>
"""
df = self.df.copy()
df["Time"] = self.start_time + \
df["t"].apply(lambda x: timedelta(minutes=x * self.tau))
df = df.drop("t", axis=1).set_index("Time") * self.total_population
df = df.astype(np.int64)
upper_cols = [n.upper() for n in df.columns]
df.columns = upper_cols
df = self.reverse_f(df, self.total_population).drop(upper_cols, axis=1)
df = df.loc[df["Infected"] >= min_infected, :]
return df
def restore_graph(self, drop_cols=None, min_infected=1, **kwargs):
"""
Show the dimentional simulate data as a figure.
@drop_cols <list[str]>: the columns not to be shown
@min_infected <int>: if Infected < min_infected, the records will not be used
@kwargs: keyword arguments of line_plot() function
"""
df = self.restore_df(min_infected=min_infected)
if drop_cols is not None:
df = df.drop(drop_cols, axis=1)
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
axvlines = [
today, *self.axvlines] if len(self.axvlines) == 1 else self.axvlines[:]
line_plot(
df,
title=f"{self.name}: {', '.join(self.title_list)}",
v=axvlines[:-1],
h=self.total_population,
**kwargs
)
|
c01c7cbc495513921a21f6df9c674a298e9f0f82 | arossbrian/my_short_scripts | /flip.py | 224 | 3.53125 | 4 | from random import randint
heads = 0
tails = 0
for trial in range(0, 1000):
while randint(0,1) == 0:
tails = tails + 1
heads = heads + 1
print("heads/ tails", heads/tails)
print(heads)
print(tails)
|
1d93915e737224b111597ada58ece5ba299d0c52 | liuyang1/test | /codeforces/problemset/653/653B.py | 777 | 3.796875 | 4 | #! /usr/bin/env python3
def applyRule(rule, s):
a, b = rule[0], rule[1]
if a == s[0]:
return b + s[1:]
return None
def applyRules(rules, ss):
ret = [applyRule(r, s) for r in rules for s in ss]
return [i for i in ret if i is not None]
def search(rules, m):
"""
search from 'a', extend it one step with all rules,
until to specific length
"""
ret = ['a']
for i in range(m - 1):
ret = applyRules(rules, ret)
return len(ret)
def main():
line = [int(i) for i in input().split()]
m, n = line[0], line[1]
rules = []
for i in range(n):
line = input().split()
line.reverse()
rules.append(line)
l = search(rules, m)
print(l)
if __name__ == "__main__":
main()
|
62c9e35cc9d3bb0d2c7e1045f3b114d1001a1817 | heymrtoufiq/uri-online-judge | /problemas/1100/1144.py | 157 | 3.640625 | 4 | for i in range(1, int(input()) + 1):
quadrado = i ** 2
cubo = i ** 3
print(f'{i} {quadrado} {cubo}')
print(f'{i} {quadrado + 1} {cubo + 1}')
|
d3ac2a490896b844e9f4f5e2e14ff5ad70c0ac28 | HenriqueLBorges/WI-FI-Fingerprints-with-Machine-Learning | /Raspberry Pi/compassTest.py | 594 | 3.75 | 4 | import json
with open('config.json') as json_data_file:
data = json.load(json_data_file)
#Gets compass bearing
def getCompassBearing():
destination = raw_input('destination = ')
return destination
#Returns the offset in between two cardinal points
def getDifference (cardinal1, cardinal2):
difference = raw_input('difference = ')
return int(difference)
#Receives an angle and returns the cardinal point
def compassBearing(angle):
for key, value in data['compass_rose'].iteritems():
if angle >= value['min'] and angle <= value['max']:
return key |
d22921da777f3609dbd6a49a43f32063f9d34deb | cuitianfeng/Python | /python3基础/3.Python修炼第三层/day3_预习/函数的返回值和调用_预习.py | 1,176 | 4.25 | 4 |
#函数的返回值和函数调用的三种形式
# def func():
# print('from func')
# # return 0
#
# res=func()
# print(res)
'''
大前提:return的返回值没有类型限制
1.没有return: 返回None 等同于return None
2.return 一个值:返回该值
3.return val1,val2,val3: 返回:(val1,val2,val3)
返回值
什么时候该有?
调用函数,经过一系列的操作,最后要拿到一个明确的结果,则必须要有返回值
通常有参函数需要有返回值,输入参数,经过计算,得到一个最终的结果
什么时候不需要有?
调用函数,仅仅只是执行一系列的操作,最后不需要得到什么结果,则无需有返回值
通常无参函数不需要有返回值
'''
# def my_max(x,y):
# if x > y:
# return x
# else:
# return y
#
# my_max(1,2) #语句形式
#
# res=my_max(1,2)*10 #表达式形式
#
# # res1=my_max(1,2)
# # res2=my_max(res1,3)
#
# res2=my_max(my_max(1,2),3) #函数调用可以当做另外一个函数的参数
# print(res2)
|
e10b1374cfd759ee56e4b6ad5641d592a4876bdb | kituu02/lab3 | /py/4.c.py | 110 | 3.953125 | 4 | a = input()
b = input()
print("string is present in it") if b in a else print("string is not present in it") |
4906c10b1fbefd139e8dd046b68d4d91916dd8cf | hungry-me/General-programming | /DS/src/Strings/Spacing/PutSpaces.py | 570 | 4.125 | 4 | #You are given an array of characters which is basically a sentence. However there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after following amendments:
#(i) Put a single space between these words.
#(ii) Convert the uppercase letters to lowercase
def putSpaces():
s=input("Enter a string:");
res=s[0].lower();
for i in range(1,len(s)):
if(s[i].isupper()):
res+=" "+s[i].lower();
else:
res+=s[i];
print(res);
putSpaces(); |
c2b5bf503885f798ecf934fc26de47cce7397de8 | rizkysaputra4/coding-test | /nawadata/Untitled-1.py | 501 | 3.671875 | 4 | def Factor(inputList):
print("Input: ", inputList)
n = 0
result = []
loop = True
t = bool
while (loop == True):
n += 1
for i in range(2, n-1):
mod = n % i
if ((mod == 0)):
t = False
if t :
result.append(n)
print('loop')
if (len(result) == inputList):
loop = False
print("Output: ", result, end='\n\n')
Factor(125) |
28e816f83da2323d4b1742f0cb616335c33c71f0 | hissue/Python | /Python_sw_academy/python_beginner/python_02/ex_47.py | 487 | 3.984375 | 4 | '''
반지름 정보를 갖고, 원의 면적을 계산하는 메서드를 갖는 Circle 클래스를 정의하고,
생성한 객체의 원의 면적을 출력하는 프로그램을 작성하십시오.
출력
원의 면적: 12.56
'''
class Circle:
def __init__(self,value):
self.values=value
self.ca=0
def mun_cal(self):
self.ca=pow(self.values,2)*3.14
return self.ca
result=Circle(2)
print('원의 면적: {:0.2f}'.format(result.mun_cal()))
|
68fc576bfc52bda308a3418e4647a500c0d02cb2 | krohak/Project_Euler | /LeetCode/Hard/First Missing Positive/sol-improve.py | 910 | 3.59375 | 4 | def firstMissingPositive(nums):
size = len(nums)
i = 0
nums.append(-1)
while (i<size):
# if num at correct index, negative or greater then size of array
if nums[i] == i or nums[i] < 0 or nums[i] > size:
i+=1
else:
if nums[nums[i]] == nums[i]: # nums[nums[3]] == nums[5] ?
nums[i] = -1 # mark
else:
tmp = nums[nums[i]] # nums[5] is x
nums[nums[i]] = nums[i] # nums[5] = nums[3]
nums[i] = tmp # nums[3] = x
i = 1
while (i<=size):
if nums[i] != i:
return i
i+=1
return i
def main():
arr = [39,8,43,12,38,11,-9,12,34,20,44,32,10,22,38,9,45,26,-4,2,1,3,3,20,38,17,20,25,41,35,37,18,37,34,24,29,39,9,36,28,23,18,-2,28,34,30]
missing = firstMissingPositive(arr)
print(missing)
if __name__ == "__main__":
main() |
5d88511fde2e0be0d08b7220a1884c8a575d6122 | Dean-Coakley/ProgrammingTraining | /Kattis/40_Easiest_Python/Easiest.py | 215 | 3.625 | 4 | N = 1
while N != 0:
N = int(input())
sum1 = 0
for a in range(1, N):
sum1 += int(a)
print(sum1)
if sum1 > 10 and len(str(sum1)) == len(str(N)):
print(sum1)
N = input()
|
3eb63126dc6614155c1377b457ae4fdc6debb33a | justien/lpthw | /ex31_MakeDec.py | 1,550 | 3.578125 | 4 | # -*- coding: utf8 -*-
# Exercise 32: Making Decisions
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
print "========================================================================"
print "Exercise 32: Making Decisions"
print
print
print """
You enter a dark room with two doors.
Do you go through door #1 or door #2?
"""
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cake. what do you do?"
print "1. Take the cake."
print "2. Surprise the bear."
bear = raw_input("> ")
if bear == "1":
print "the bear is very focussed on eating cake, so eats you too."
elif bear == "2":
print "bear does not enjoy the surprise, and pushes you to the floor."
else:
print "Yes. %s is a better thing. Bear exits the scenario." % bear
elif door == "2":
print "You stare into the endless abyss."
print "1. Blueberries from the forest."
print "2. Clothespins made of wasps."
print "3. Gunfire's song is your song now."
insanity = raw_input("> ")
if insanity == "1" or insanity == "2":
print "Your body survives with a mind half in the past, half in the sun."
else:
print "The insanity becomes part of your hands and eyes,\na new fifth limb of perception."
else:
print "You stumble around. There is a knife, which you take on your journey into the dustlands."
print
print
print "=======================================================================" |
ad5462f9874146f0b2fd48968baed6e9ea5e3fa7 | geniousisme/CodingInterview | /leetCode/Python/344-reverseString.py | 468 | 3.671875 | 4 | class Solution1(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
res = []
for i in xrange(len(s) - 1, -1, -1):
res.append(s[i])
return "".join(res)
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
if __name__ == "__main__":
s = Solution()
print s.reverseString("Hello")
|
2bc1d78e21bb52996e7f098601705accb9a9570d | salesvictor/DesignPatterns | /state.py | 1,258 | 3.75 | 4 | from abc import ABC, abstractmethod
class StateMachine:
def __init__(self):
self._state = S1()
def set_state(self, state):
self._state = state
def action(self):
self._state.action(self)
class S1:
class __Singleton:
def action(self, machine):
print('Doing action with state S1')
machine.set_state(S2())
instance = None
def __init__(self):
if not S1.instance:
S1.instance = S1.__Singleton()
def __getattr__(self, name):
return getattr(S1.instance, name)
class S2:
class __Singleton:
def action(self, machine):
print('Doing action with state S2')
machine.set_state(S3())
instance = None
def __init__(self):
if not S2.instance:
S2.instance = S2.__Singleton()
def __getattr__(self, name):
return getattr(S2.instance, name)
class S3:
class __Singleton:
def action(self, machine):
print('Doing action with state S3')
machine.set_state(S1())
instance = None
def __init__(self):
if not S3.instance:
S3.instance = S3.__Singleton()
def __getattr__(self, name):
return getattr(S3.instance, name)
def main():
machine = StateMachine()
for i in range(10):
machine.action()
if __name__ == "__main__":
main()
|
f52874f5628a2672c0585e30d3944fbb09490599 | pscx142857/python | /作业/Python基础第五天/第三题.py | 321 | 3.828125 | 4 | #3.封装函数,实现返回三个数的最小值
def min_3(a,b,c):
"""
返回三个数的最小值
:param a: 第一个数字
:param b: 第二个数字
:param c: 第三个数字
:return: 返回三个中最小的数字
"""
ls = [a,b,c]
mi = min(ls)
return mi
print(min_3(101,2,99)) |
099c36205dad8e4baa6aaceb9c41a2004e74b2e1 | NakonechnyiMykhail/py1902 | /start/10-11/logic.py | 1,316 | 4.3125 | 4 | # логические операции
print('and:')
print(False and False)
print(False and True)
print(True and False)
print(True and True)
print()
print('or:')
print(False or False)
print(False or True)
print(True or False)
print(True or True)
print()
print('not:')
print(not False)
print(not True)
print()
# логические выражения
a = True
b = False
c = True
f = a and not b or c or (a and (b or c))
print(f)
# #####################################
a = 3
b = a
a = a - 1
print(a, b)
print(a < b) # меньше
print(b > 3) # больше
print(a <= 2) # меньше или равно
print(b >= 7) # больше или равно
print(a < 3 < b) # двойное сравнение
print(a == b) # равенство
print(a != b) # неравенство
print(a is b) # идентичность объектов в памяти
print(a is not b) # a и b – разные объекты (хотя значения их могуть быть равны)
string = "some string"
second_string = string
third_string = input('Введите строку: ')
print(string is second_string)
print(string is third_string)
# x = int(input('Enter the card: ')) #37000
# r = int(x / 1000)
# (r >= 37 and r <= 42) or (r >= 5500 and r < 6000)
print() |
25ffe5d8c831203a268dbf106b5ee7b096c273df | Geneveroth/Coding_Dojo_Assignments | /Assignments/Python_Stack/Python/OOP/Bank_Account.py | 1,195 | 3.953125 | 4 | import math
class BankAccount:
def __init__(self, name, int_rate, balance=0):
self.name=name
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance+=amount
return self
def withdraw(self, amount):
if self.balance<=0:
print("Insufficient funds: Charging $5 fee.")
self.balance-5
else:
self.balance-=amount
return self
def display_account_info(self):
print((self.name),"has a balance of ", round(self.balance*self.int_rate,2))
return self
def yield_interest(self):
if self.balance>0:
self.int_rate=1+(self.int_rate/100)
print(f"Interest Accrued: ",round(((self.balance*self.int_rate)-self.balance),2))
else:
print("Balance too low to accrue interest.")
return self
account_1 = BankAccount("Sam", .1, 100)
account_2 = BankAccount("Bob", .2, 200)
account_1.deposit(50).deposit(50).deposit(50).withdraw(100).yield_interest().display_account_info()
account_2.deposit(100).deposit(50).withdraw(150).withdraw(400).yield_interest().display_account_info()
|
617b83d89bcef190f63099ea56c615aec54b9edd | plsmaop/leetcode | /python/easy/007.py | 287 | 3.5 | 4 | class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
ans = 0
if x < 0:
ans = int('-' + str(x)[1::][::-1])
else: ans = int(str(x)[::-1])
return ans if -(1<<31) < ans < (1<<31) - 1 else 0
|
d8900354994b8fb64bc73b692811d1619592d1f5 | hshrimp/letecode_for_me | /letecode/121-240/193-216/204.py | 615 | 3.75 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: wushaohong
@time: 2020/7/16 下午4:30
"""
"""204. 计数质数
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。"""
class Solution:
def countPrimes(self, n: int) -> int:
val = [1] * n
val[0] = val[1] = 0
for i in range(1, int(n ** 0.5) + 1):
if val[i]:
val[i * i::i] = [0] * len(val[i * i::i])
return sum(val)
if __name__ == '__main__':
sol = Solution()
print(sol.countPrimes(5))
|
8210b019628d8a1a3e24ac0140ac30fa0f5d908a | KrishnaPramodParupudi/Face_Recognition | /match.py | 914 | 3.78125 | 4 | ''' Finding whether people in two images are the same '''
# import necessary stuff
import face_recognition
# load images first one is used to train and second one to verify the person
image1 = face_recognition.load_image_file('Gal1.jpg')
image2 = face_recognition.load_image_file('Gal2.jpg')
# face_encodings gives a list of encodings of all faces in an image and here, since we have only one face, we took only the zeroth index
original_image_encoded = face_recognition.face_encodings(image1)[0]
current_image_encoded = face_recognition.face_encodings(image2)[0]
# Comparision of face in current image with a list of encoded images
result = face_recognition.compare_faces(
[original_image_encoded], current_image_encoded)
# compare_faces gives a list of boolean values, if there is match, it's true else false
if(result[0]==True):
print("There is a match")
else:
print("There is no match")
|
1fb2029cff8cd48713dd51380f0e8d841f612c8d | ICT710-TAIST/Project-Cloud | /reviser.py | 1,992 | 4.03125 | 4 | # Check if the values of the message are in a possible range
def in_range(val, min, max):
if min <= val <= max:
return True
else :
return False
# Check if the values can parse to integer
def is_integer(val):
try:
num = int(val)
except ValueError:
return False
return True
# Check messag of plausibility
def check_msg(X):
for msg in X:
if is_integer(msg):
pass
else:
# Instead of print log the the message
print("Message contains not parse able values!")
return False
if in_range(int(X[0]), -360, 360):
pass
else:
# Instead of print log the the message
print("Message contains not parse able values!")
return False
if in_range(int(X[1]), -360, 360):
pass
else:
# Instead of print log the the message
print("Message contains not parse able values!")
return False
if in_range(int(X[2]), -360, 360):
pass
else:
# Instead of print log the the message
print("Message contains not parse able values!")
return False
if in_range(int(X[3]), -100, 100):
pass
else:
# Instead of print log the the message
print("Message contains not parse able values!")
return False
if in_range(int(X[4]), -100, 100):
pass
else:
# Instead of print log the the message
print("Message contains not parse able values!")
return False
if in_range(int(X[5]), -100, 100):
pass
else:
# Instead of print log the the message
print("Message contains not parse able values!")
return False
if in_range(int(X[6]), 0, 1):
pass
else:
# Instead of print log the the message
print("Message contains not parse able values!")
return False
return True |
fca1aa40bf1b5c924c83c9d8fedc43d1462470c5 | gdparra/lpthw | /ex38.py | 552 | 3.765625 | 4 | ten_things="Apples Oranges Crows Telephone Lights Sugar"
print "Wait there are not 10 things in the list. Lets fix that"
stuff=ten_things.split(' ')
more_stuff=["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]
while len(stuff)!=10:
next_one=more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "There are %d items now" %len(stuff)
print "There we go: ", stuff
print "Lets do things with stuff"
print stuff[1]
print stuff[-1]
print stuff.pop()
print join(stuff)
print ' '.join(stuff)
print '#'.join(stuff[3:5])
|
f6d668b922b4d60dac9fc8df5ce945281cfda699 | kumarhegde76/Scripting-Language | /SL Lab/SL_Lab_Test1/lettersaround.py | 413 | 3.84375 | 4 | def LettersAround(s):
flag=True
equal=0
plus=0
for i in range(0,len(s)):
if(s[i] == '='):
equal+=1
continue
elif(s[i] == '+'):
plus+=1
continue
elif(s[i].isalpha()):
if(s[i-1] == '+' and s[i+1] == '+'):
continue
else:
flag==False
break
if(flag == True and equal>0 and plus > 0):
print("Accepted")
else:
print("Rejected")
LettersAround(str(input("Enter A String :"))) |
4b822f110750157b455e8dacfb8e82089cc2a1fe | TahsinTariq/Python | /Projects/Class_Work/Intro_to_AI/Adversareal Search/MinMax_DLS.py | 1,527 | 3.53125 | 4 | def MinMax_DLS(node, depth, Is_Max):
if depth == 0:
return EvalFunction[node]
if node in TerminalValue.keys():
return TerminalValue[node]
if Is_Max:
value = -float('inf')
for child in OwO[node]:
print(child)
value = max(value, MinMax_DLS(child, depth-1, 0))
return value
else:
value = float('inf')
for child in OwO[node]:
print(child)
value = min(value, MinMax_DLS(child, depth-1, 1))
return value
if __name__ == '__main__':
OwO = {}
MinOrMax = {}
TerminalValue = {}
EvalFunction = {}
# File contains Initial node.
# If a node takes the max value, it is assigned 1; if min, 0. If it is a terminal node, it's assigned -1
# Then it contains the child nodes number following child node names
# Terminal nodes have 0 child nodes and one value
# The last value for non terminal nodes are the Evaluation function estimates
with open('wiki_minmax_example_DLS', "r") as f:
for line in f:
arr = line.split()
if int(arr[1]) >= 0:
OwO[arr[0]] = [i for i in arr[3:-1]]
EvalFunction[arr[0]] = int(arr[-1])
else:
TerminalValue[arr[0]] = int(arr[3])
# print(OwO)
# print(TerminalValue)
# print(EvalFunction)
print("Searched Through: ")
# c = MinMax_DLS('a', float('inf'), 1)
c = MinMax_DLS('a', 3, 1)
print("\n"+ "Max Utility: " + str(c)) |
ecea150d164a9a629c349b67a4757560724e6d9a | jakubfolta/AddDigits | /AddingNumbers.py | 331 | 3.71875 | 4 | def adding(numbers):
return sum(int(dig) for dig in str(numbers))
print(adding(11234))
def add(numbers):
total = 0
for dig in str(numbers):
total += int(dig)
return total
print(add(12765))
def add(numbers):
total = []
for dig in str(numbers):
total.append(int(dig))
return sum(total)
print(add(32456))
|
02dc0aa7da6e5c89ecc1d8cdabab39f577226d97 | nishanthgampa/PythonPractice | /Unsorted/whileloop.py | 201 | 3.9375 | 4 | while True:
print("Who are you?")
name = input()
if (name != "Nishanth"):
continue
print("What is the Password?")
password = input()
if password == 'Harshini':
break
print('Access Granted') |
f7045baabd744f4326fa34b3c9e453fcbb970f47 | bssrdf/pyleet | /R/ReplaceElementsinanArray.py | 1,741 | 4.03125 | 4 | '''
-Medium-
*Hash Table*
You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0] exists in nums.
operations[i][1] does not exist in nums.
Return the array obtained after applying all the operations.
Example 1:
Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]
Output: [3,2,7,1]
Explanation: We perform the following operations on nums:
- Replace the number 1 with 3. nums becomes [3,2,4,6].
- Replace the number 4 with 7. nums becomes [3,2,7,6].
- Replace the number 6 with 1. nums becomes [3,2,7,1].
We return the final array [3,2,7,1].
Example 2:
Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]]
Output: [2,1]
Explanation: We perform the following operations to nums:
- Replace the number 1 with 3. nums becomes [3,2].
- Replace the number 2 with 1. nums becomes [3,1].
- Replace the number 3 with 2. nums becomes [2,1].
We return the array [2,1].
Constraints:
n == nums.length
m == operations.length
1 <= n, m <= 105
All the values of nums are distinct.
operations[i].length == 2
1 <= nums[i], operations[i][0], operations[i][1] <= 106
operations[i][0] will exist in nums when applying the ith operation.
operations[i][1] will not exist in nums when applying the ith operation.
'''
from typing import List
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
pos = {v:i for i,v in enumerate(nums)}
for a,b in operations:
i = pos[a]
nums[i] = b
pos[b] = i
return nums
|
13df24a077117b855725ee76245db55ee8d30c92 | andrest50/CS362-HW3 | /andres_tobon_hw3.py | 1,086 | 4.3125 | 4 | """
This is an updated version of the file from homework 1, except
there is now some error handling.
To run the script, use the following command:
python3 andres_tobon_hw3.py
"""
def main():
valid = False
""" Continuously receive input until valid input or force quit """
while(valid == False):
yearString = input("Input a year: ")
""" Try converting input into int and catch exceptions below """
try:
year = int(yearString)
if(year < 1):
raise ValueError
valid = True
except ValueError:
print("Invalid year. Input a positive integer number.")
""" Calculate if the year is a leap year and print result """
if(year % 4 == 0):
if(year % 100 == 0):
if(year % 400 == 0):
print("{} is a leap year.".format(year))
else:
print("{} is not a leap year.".format(year))
else:
print("{} is a leap year.".format(year))
else:
print("{} is not a leap year.".format(year))
main() |
5c6e9e5b58366990eabfb05b869bfc1593d83aed | Mbiederman/qbb2017-answers | /day2-afternoon/00-iteration.py | 344 | 4.09375 | 4 | #!/usr/bin/env python
import sys
f = open( sys.argv[1] )
#the most basic way
#while True:
#the_line = f.readline().rstrip("\r\n")
#if not the_line:
#break
#print the_line
#my_iter = iter( f )
#while True:
#the_line = my_iter.next()
#print the_line
for line in f:
print line
|
86d911e3459cede99bda30b21b5f812ec5042e9a | btonasse/RandomSampler | /random_sampler/logger/__init__.py | 2,012 | 3.5 | 4 | import logging
import types
level_map = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}
def add_separator(self: logging.Logger, level: str, message: str = '') -> None:
'''
Create a log record with a given string without the default formatting.
Useful for creating separator lines in the log
'''
for handler in self.handlers:
handler.setFormatter(self.naked_formatter)
self.log(level_map[level], message)
for handler in self.handlers:
handler.setFormatter(self.formatter)
def logger_setup(name: str, file: str) -> logging.Logger:
'''
Encapsulate logger set-up and add a method called 'sep', which logs a naked string instead of the default format.
'''
# Create logger
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# Formatters
formatter = logging.Formatter("%(asctime)s:%(name)s:%(levelname)s: %(message)s")
naked_formatter = logging.Formatter("%(message)s")
# Handlers
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.WARNING)
logger.addHandler(console_handler)
file_handler = logging.FileHandler(filename=file, mode='w', encoding='utf-8')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
# Extend functionality with extra formatter
logger.handlers = [console_handler, file_handler]
logger.formatter = formatter
logger.naked_formatter = naked_formatter
logger.sep = types.MethodType(add_separator, logger)
return logger
if __name__ == '__main__':
logger = logger_setup('Sampler', 'test.log')
logger.debug('Debugging...')
logger.info('Infoing...')
logger.sep(logging.WARNING, '*'*10)
logger.warning('Warning...')
logger.error('Ooopsie..')
logger.critical('Ooopsie even more..')
|
94701e9e3588c587cdda3cd69c2285dfa368d6a7 | juanfepi27/DatosYAlgoritmos1 | /ordenamiento_202110146010_202110129010_202110015010/11 ordListas.py | 2,719 | 4.03125 | 4 | """
11. (10) se tiene una lista A con 100 elementos A[ a1……a100 ]
B de 60 elementos B[ b1……b60 ]
Se desean resolver las siguientes tareas
a.) Ordenar cada lista aplicando el método Quicksort
b.) Crear una lista C que sea la unión de la lista A y B
c.) Ordenar la lista C y visualizarla
"""
from random import randrange
A=[]
for i in range(100):
num=randrange(-100,100)
A.append(num)
B=[]
for i in range(60):
num=randrange(-100,100)
B.append(num)
print("\npreviamente A estaba así:\n"+str(A))
print("\npreviamente B estaba así:\n"+str(B))
def particion(arr, inicio, fin):
#se toma cualquier numero como el pivote
indice_pivote = randrange(inicio, fin + 1)
pivote = arr[indice_pivote]
#se crea una variable para tener control de los menores que el pivote
ultimo_menor = inicio - 1
for actual in range(inicio, fin+1):
# se organizan los datos respecto al pivote
if actual == indice_pivote:
#se ignora el pivote
continue
if arr[actual] < pivote:
#en caso de encontrar uno menor se aumenta la variable de control
#y se ubica al dato actual en el valor de la variable
#y el que estaba en la variable se va a la actual
ultimo_menor += 1
if(ultimo_menor==indice_pivote) :
arr[actual], arr[ultimo_menor] = arr[ultimo_menor], arr[actual]
indice_pivote=actual
else:
arr[actual], arr[ultimo_menor] = arr[ultimo_menor], arr[actual]
#al finalizar se ubica el pivote en el siguiente justo del último menor
arr[ultimo_menor + 1], arr[indice_pivote] = arr[indice_pivote], arr[ultimo_menor + 1]
return ultimo_menor + 1
def quickSort(arr, inicio, fin):
#siempre que el indice de inicio sea menor (no igual)
# podrá hacer el ordenamiento
if(inicio < fin):
#se hace la particion/ordenamiento del arreglo en mitades
#y se asigna el indice del pivote
indice_pivote = particion(arr, inicio, fin)
#se realiza el proceso anterior para
# los datos mayores y menores del pivote
quickSort(arr, inicio, indice_pivote - 1)
quickSort(arr, indice_pivote + 1, fin)
quickSort(A,0,len(A)-1)
quickSort(B,0,len(B)-1)
print("\na)")
print("\nLuego del quicksort A esta así:\n"+str(A))
print("\nLuego del quicksort B esta así:\n"+str(B))
print("\nb) se crea lista c")
C=A+B
quickSort(C,0,len(C)-1)
print("\nc)")
print("\nLuego del quicksort C esta así:\n"+str(C)) |
72074eefc15e0ae68c82ff467350589c5a070ae5 | ocornel/Andela | /fizz_buzz.py | 472 | 4.09375 | 4 | def fizz_buzz(number):
if number % (3 * 5) == 0: #Numbers devisible by x and y are divisible by xy
return 'FizzBuzz'
elif number % 3 == 0:
return 'Fizz'
elif number % 5 == 0:
return 'Buzz'
else:
return number
def range_fizz_buzz(limit):
#accepts an ending number then does fizzbuzz on all the numbers giving output
number = 0
while number <= limit:
print (number ," : ", fizz_buzz(number))
number += 1
|
2e9edffab36e3a907ab516f39292092dc082a982 | CodecoolKRK20173/erp-mvc-project-predator | /model/common.py | 1,082 | 3.984375 | 4 | """ Common functions for models
implement commonly used functions here
"""
import random
def generate_random(table):
"""
Generates random and unique string. Used for id/key generation:
- at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letter
- it must be unique in the table (first value in every row is the id)
Args:
table (list): Data table to work on. First columns containing the keys.
Returns:
string: Random and unique string
"""
generated = ''
# your code
return generated
def get_table_from_file(file_name):
"""
Reads csv file and returns it as a list of lists.
Lines are rows columns are separated by ";"
Args:
file_name (str): name of file to read
Returns:
list: List of lists read from a file.
"""
with open(file_name, "r") as file:
lines = file.readlines()
table = [element.replace("\n", "").split(";") for element in lines]
return table
def get_input(title):
inp = input(title)
return inp
|
2d30297726d3ecfc58a8b71b3590f63c673f2701 | samridhrakesh/test | /inheritance.py | 553 | 4.1875 | 4 | class Fish:
def __init__(self, first_name, last_name="Fish", skeleton="bone", eyelids=False):
self.first_name = first_name
self.last_name = last_name
self.skeleton = skeleton
self.eyelids = eyelids
def Swim(self):
print("Fish is swiming")
def swim_back(self):
print("fish swim back")
'''Creating a child class:'''
class Trout(Fish):
pass
terry = Trout("sam")
print(terry.first_name + "" + terry.last_name)
print(terry.skeleton)
print(terry.eyelids)
terry.Swim()
terry.swim_back()
|
671d69e80ae454b80db2c2a0bf9624196a59efbd | cankutergen/Other | /LowestCommonAncestorBT.py | 1,072 | 3.703125 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
p_path = self.pathToNode(root, p, [])
q_path = self.pathToNode(root, q, [])
if len(p_path) <= len(q_path):
longer = q_path
shorter = p_path
else:
longer = p_path
shorter = q_path
matching = [x for x in longer if x in shorter]
return matching[-1]
def pathToNode(self, node, x, path):
if node is None:
return []
if node.val == x.val:
path.append(x)
return path
left = self.pathToNode(node.left, x, path + [node])
right = self.pathToNode(node.right, x, path + [node])
if left: return left
if right: return right
|
618347e5e223b33c081dd5554cbbf7421eee8ded | miango1904/bucles_python | /ejercicios_profundizacion.py | 14,242 | 3.84375 | 4 | #!/usr/bin/env python
'''
Bucles [Python]
Ejercicios de profundización
---------------------------
Autor: Inove Coding School
Version: 1.1
Descripcion:
Programa creado para que practiquen los conocimietos
adquiridos durante la semana
'''
__author__ = "Inove Coding School"
__email__ = "alumnos@inove.com.ar"
__version__ = "1.1"
# Variable global utilizada para el ejercicio de nota
notas = [70, 82, -1, 65, 55, 67, 87, 92, -1]
# Variable global utilizada para el ejercicio de temperaturas
temp_dataloger = [12.8, 18.6, 14.5, 20.8, 12.1, 21.2, 13.5, 18.6,
14.7, 19.6, 11.2, 18.4]
def ej1():
print('Comenzamos a ponernos serios!')
'''
Realice un programa que pida por consola dos números que representen
el principio y fin de una secuencia numérica.
Realizar un bucle "for" que recorra esa secuencia armada con "range"
y cuente cuantos números ingresados hay, y la sumatoria de todos los números
Tener en cuenta que "range" no incluye el número de "fin" en su secuencia,
sino que va hasta el anterior
'''
# inicio = ....
# fin = ....
# cantidad_numeros ....
# sumatoria ....
# bucle.....
# Al terminar el bucle calcular el promedio como:
# promedio = sumatoria / cantidad_numeros
# Imprimir resultado en pantalla
inicio = int(input('Ingrese el primer número de la secuencia\n'))
fin = int(input('ingrese numero mayor o igual al anterior\n'))
lista_1 = list(range(inicio,fin))
list(range(len(lista_1)))
cantidad = list(range(len(lista_1)))
tot_elem = 0
for n in lista_1:
tot_elem += 1
print ('numeros ingresados :', tot_elem)
for numbers in range(inicio, fin):
lista1 = [ [inicio, fin] ]
cantidad = list(range(len(lista_1)))
total = len(cantidad)
nume=0
for i in lista1:
for m in i:
nume += m
print('suma de numeros :',nume)
promedio = nume/tot_elem
print('el promedio es :',promedio)
def ej2():
print("Mi Calculadora (^_^)")
'''
Realice una calculadora:
Dentro de un bucle se debe ingresar por línea de comando dos números
Luego se ingresará como tercera entrada al programa el símbolo de la operación
que se desea ejecutar:
- Suma (+)
- Resta (-)
- Multiplicación (*)
- División (/)
- Exponente/Potencia (**)
Se debe efectuar el cálculo correcto según la operación ingresada por consola
Imprimir en pantalla la operación realizada y el resultado
El programa se debe repetir dentro del bucle hasta que como operador
se ingrese la palabra "FIN", en ese momento debe terminar el programa
Se debe debe imprimir un cartel de error si el operador ingresado no es
'''
s = int(input('ingrese primer valor\n'))
e = int(input('ingrese segundo valor\n'))
print('ingrese el numero equivalente al simbolo de operacion deseada')
Suma = (s + e)
Resta = (s - e)
Multiplicación = (s * e)
División = (s/e)
Potencia = (s**e)
while True:
op = input('1-suma\n 2-Resta\n 3-multiplicar\n 4-dividir\n 5-potencia\n FIN\n')
if op == '1':
print(Suma)
break
elif op == '2':
print(Resta)
break
elif op == '3':
print(Multiplicación)
break
elif op == '4':
print(División)
break
elif op== 'FIN':
break
else:
print('numero erroneo')
def ej3():
print("Mi organizador académico (#_#)")
'''
Tome el ejercicio de "calificaciones":
<condicionales_python / ejercicios_practica / ej3>,
copielo a este ejercicio y modifíquelo para cumplir
el siguiente requerimiento
Las notas del estudinte se encuentran almacenadas en una
lista llamada "notas" que ya hemos definido al comienzo del archivo
Debe caluclar el promedio de todas las notas y luego transformar
la califiación en una letra según la escala establecida en el ejercicio
"calificaciones" <condicionales_python / ejercicios_practica / ej3>
A medida que recorre las notas, no debe considerar como válidas aquellas
que son negativas, en ese caso el alumno estuvo ausente
Debe contar la cantidad de notas válidas y la cantidad de ausentes
'''
# Si el puntaje es mayor igual a 90 --> imprimir A
# Si el puntaje es mayor igual a 80 --> imprimir B
# Si el puntaje es mayor igual a 70 --> imprimir C
# Si el puntaje es mayor igual a 60 --> imprimir D
# Si el puntaje es manor a 60 --> imprimir F
# Para calcular el promedio primero debe obtener la suma
# de todas las notas, que irá almacenando en esta variable
sumatoria = 0 # Ya le hemos inicializado en 0
cantidad_notas = 0 # Aquí debe contar cuantas notas válidas encontró
cantidad_ausentes = 0 # Aquí debe contar cuantos ausentes hubo
x = (len(notas))
for numero in notas:
if numero > 0:
sumatoria = sumatoria + numero
elif numero < 0:
cantidad_ausentes= cantidad_ausentes + numero
print('los dias no asisitidos fueron :',cantidad_ausentes)
cantidad_notas= x + cantidad_ausentes
promedio= sumatoria/cantidad_notas
if promedio >= 90:
print ('a'.upper())
elif promedio>=80:
print('b'.upper())
elif promedio>=70:
print('la calificacion es c'.upper())
elif promedio <=60:
print('f'.upper())
# Realice aquí el bucle para recorrer todas las notas
# y cacular la sumatoria
# Terminado el bucle calcule el promedio como
# promedio = sumatoria / cantidad_notas
# Utilice la nota promedio calculada y transformela
# a calificación con letras, imprima en pantalla el resultado
# Imprima en pantalla al cantidad de ausentes
def ej4():
print("Mi primer pasito en data analytics")
'''
Tome el ejercicio:
<condicionales_python / ejercicios_profundizacion /ej5>,
copielo a este ejercicio y modifíquelo para cumplir el
siguiente requerimiento
En este ejercicio se lo provee de una lista de temperatuas,
esa lista de temperatuas corresponde a los valores de temperaturas
tomados durante una temperorada del año en Buenos Aires.
Ustede deberá analizar dicha lista para deducir
en que temporada del año se realizó el muestreo de temperatura.
La variable con la lista de temperaturas se llama "temp_dataloger"
definida al comienzo del archivo
Debe recorrer la lista "temp_dataloger" y obtener los siguientes
resultados
1 - Obtener la máxima temperatura
2 - Obtener la mínima temperatura
3 - Obtener el promedio de las temperatuas
Los resultados se deberán almacenar en las siguientes variables
que ya hemos preparado para usted.
NOTA: No se debe ordenar la lista de temperaturas, se debe obtener
el máximo y el mínimo utilizando los mismos métodos vistos
durante la clase (ejemplos_clase)
'''
temperatura_max = None # Aquí debe ir almacenando la temp máxima
temperatura_min = None # Aquí debe ir almacenando la temp mínima
temperatura_sumatoria = 0 # Aquí debe ir almacenando la suma de todas las temp
temperatura_promedio = 0 # Al finalizar el loop deberá aquí alamcenar el promedio
temperatura_len = (len(temp_dataloger)) # Aquí debe almacenar cuantas temperatuas hay en la lista
# Colocar el bucle aqui......
for num in temp_dataloger:
if (temperatura_max is None or num > temperatura_max):
temperatura_max = num
elif (temperatura_min is None or num < temperatura_min):
temperatura_min = num
for numero in temp_dataloger:
if numero > 0:
temperatura_sumatoria = temperatura_sumatoria + numero
temperatura_promedio = temperatura_sumatoria/temperatura_len
for numero in temp_dataloger:
if numero > 8 < 14:
print('La epoca del año es \n invierno')
elif numero > 11 < 20:
print('La epoca del año es \n otoño')
elif numero > 10 < 24:
print('La epoca del año es \n primavera')
elif numero > 19 < 28:
print('la epoca del año es \n verano')
# Al finalizar el bucle compare si el valor que usted calculó para
# temperatura_max y temperatura_min coincide con el que podría calcular
# usando la función "max" y la función "min" de python
# función "max" --> https://www.w3schools.com/python/ref_func_max.asp
# función "min" --> https://www.w3schools.com/python/ref_func_min.asp
# Al finalizar el bucle debe calcular el promedio como:
# temperatura_promedio = temperatura_sumatoria / cantidad_temperatuas
# Corroboren los resultados de temperatura_sumatoria
# usando la función "sum"
# función "sum" --> https://www.w3schools.com/python/ref_func_sum.asp
'''
Una vez que tengamos nuestros valores correctamente calculados debemos
determinar en que epoca del año nos encontramos en Buenos Aires utilizando
la estadística de años anteriores. Basados en el siguiente link realizamos
las siguientes aproximaciones:
verano --> min = 19, max = 28
otoño --> min = 11, max = 20
invierno --> min = 8, max = 14
primavera --> min = 10, max = 24
Referencia:
https://es.weatherspark.com/y/28981/Clima-promedio-en-Buenos-Aires-Argentina-durante-todo-el-a%C3%B1o
'''
# En base a los rangos de temperatura de cada estación,
# ¿En qué época del año nos encontramos?
# Imprima el resultado en pantalla
# Debe utilizar temperatura_max y temperatura_min para definirlo
def ej5():
print("Ahora sí! buena suerte :)")
'''
Tome el ejercicio:
<condicionales_python / ejercicios_profundizacion / ej4>,
copielo a este ejercicio y modifíquelo para cumplir
el siguiente requerimiento
Realize un programa que corra indefinidamente en un bucle, al comienzo de la
iteración del bucle el programa consultará al usuario con el siguiente menú:
1 - Obtener la palabra más grande por orden alfabético (usando el operador ">")
2 - Obtener la palabra más grande por cantidad de letras (longitud de la palabra)
3 - Salir del programa
En caso de presionar "3" el programa debe terminar e informar por
pantalla de que ha acabado,
en caso contrario si se presionar "1" o "2" debe continuar con la siguiente tarea
NOTA: Si se ingresa otro valor que no sea 1, 2 o 3 se debe enviar
un mensaje de error y volver a comenzar el bucle
(vea en el apunte "Bucles - Sentencias" para encontrar
la sentencia que lo ayude a cumplir esa tarea)
Si el bucle continua (se presionó "1" o "2") se debe ingresar a otro bucle
en donde en cada iteración se pedirá una palabra. La cantidad de iteración
(cantidad de palabras a solicitar) lo dejamos a gusto del alumno, intente que esa
condición esté dada por una variable (ej: palabras_deseadas = 4)
Cada palabra ingresada se debe ir almacenando en una lista de palabras, dicha
lista la debe inicializar vacia y agregar cada nuevo valor con el método "append".
Luego de tener las palabras deseadas almacenadas en una lista de palabras
se debe proceder a realizar las siguientes tareas:
Si se ingresa "1" por consola se debe obtener la palabra
más grande por orden alfabético
Luego de terminar de recorrer toda la lista (utilizar un bucle "for")
se debe imprimir en pantalla cual era la palabra
más grande alfabeticamente.
Recuerde que debe inicializar primero su variable
donde irá almacenando la palabra que cumpla dicha condición.
¿Con qué valor debería ser inicializada dicha variable?
Si se ingresa "2" por consola se debe obtener la palabra
con mayor cantidad de letras
Luego de terminar de recorrer toda la lista (utilizar un bucle "for")
se debe imprimir en pantalla cual era la palabra con
mayor cantidad de letras.
Recuerde que debe inicializar primero su variable
donde irá almacenando la palabra que cumpla dicha condición.
¿Con qué valor debería ser inicializada dicha variable?
NOTA: No se debe ordenar la lista de palabras, se debe obtener
el máximo utilizando el mismos métodos vistos durante la clase
(ejemplos_clase), tal como el ejercicio anterior. Ordenar una
lista representa un problema mucho más complejo que solo
buscar el máximo.
NOTA: Es recomendable que se organice con lápiz y papel para
hacer un bosquejo del sistema ya que deberá utilizar 3 bucles en total,
1 - El bucle principal que hace que el programa corra hasta ingresar un "3"
2 - Un bucle interno que corre hasta socilitar todas las palabras deseadas
que se deben ir guardando en una lista
3- Otro bucle interno que corre luego de que termine el bucle "2" que
recorre la lista de palabras y busca la mayor según el motivo ingresado ("1" o "2")
'''
pa_1 = (input('Ingrese primer palabra:\n'))
pa_2 = (input('Ingrese segunda palara:\n'))
pa_3 = (input('Ingrese tercer palabra:\n'))
lista = [pa_1,pa_2,pa_3]
alf = sorted(lista)
long = sorted(lista,key=len, reverse=True)
if __name__ == '__main__':
print("Ejercicios de práctica")
#ej1()
#ej2()
#ej3()
#ej4()
#ej5()
|
320a20094d8085f682590c72584bc750afa12039 | zjz2018/pyproject | /basic-kw/zjz_04_list.py | 3,386 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 专门用于存储 一串 信息
# 列表用 [] 定义,数据 之间使用 , 分隔
# 列表的 索引 从 0 开始
# 列表 通常存储相同类型的数据
# 通过 迭代遍历,在循环体内部,针对列表中的每一项元素,执行相同的操作
# ------------------基本使用-------------------
name_list = ["zhangsan", "lisi", "wangwu"]
# 1. 取值和取索引
# list index out of range - 列表索引超出范围
print(name_list[2])
# 知道数据的内容,想确定数据在列表中的位置
# 使用index方法需要注意,如果传递的数据不在列表中,程序会报错!
print(name_list.index("wangwu"))
# 2. 修改
name_list[1] = "李四"
# list assignment index out of range
# 列表指定的索引超出范围,程序会报错!
# name_list[3] = "王小二"
# 3. 增加
# append 方法可以向列表的末尾追加数据
name_list.append("王小二")
# insert 方法可以在列表的指定索引位置插入数据
name_list.insert(1, "小美眉")
# extend 方法可以把其他列表中的完整内容,追加到当前列表的末尾
temp_list = ["孙悟空", "猪二哥", "沙师弟"]
name_list.extend(temp_list)
# 4. 删除
# remove 方法可以从列表中删除指定的数据
name_list.remove("wangwu")
# pop 方法默认可以把列表中最后一个元素删除
name_list.pop()
# pop 方法可以指定要删除元素的索引
name_list.pop(3)
# clear 方法可以清空列表
name_list.clear()
print(name_list)
# ----------------删除-----------------------
name_list = ["张三", "李四", "王五"]
# (知道)使用 del 关键字(delete)删除列表元素
# 提示:在日常开发中,要从列表删除数据,建议使用列表提供的方法
del name_list[1]
# del 关键字本质上是用来将一个变量从内存中删除的
name = "小明"
del name
# 注意:如果使用 del 关键字将变量从内存中删除
# 后续的代码就不能再使用这个变量了
print(name)
print(name_list)
# ----------------长度-----------------------
name_list = ["张三", "李四", "王五", "王小二", "张三"]
# len(length 长度) 函数可以统计列表中元素的总数
list_len = len(name_list)
print("列表中包含 %d 个元素" % list_len)
# count 方法可以统计列表中某一个数据出现的次数
count = name_list.count("张三")
print("张三出现了 %d 次" % count)
# 从列表中删除第一次出现的数据,如果数据不存在,程序会报错
name_list.remove("张三")
print(name_list)
# ---------------排序------------------------
name_list = ["zhangsan", "lisi", "wangwu", "wangxiaoer"]
num_list = [6, 8, 4, 1, 10]
# 升序
# name_list.sort()
# num_list.sort()
# 降序
# name_list.sort(reverse=True)
# num_list.sort(reverse=True)
# 逆序(反转)
name_list.reverse()
num_list.reverse()
print(name_list)
print(num_list)
# ----------------遍历-----------------------
name_list = ["张三", "李四", "王五", "王小二"]
# 使用迭代遍历列表
"""
顺序的从列表中依次获取数据,每一次循环过程中,数据都会保存在
my_name 这个变量中,在循环体内部可以访问到当前这一次获取到的数据
for my_name in 列表变量:
print("我的名字叫 %s" % my_name)
"""
for my_name in name_list:
print("我的名字叫 %s" % my_name)
|
9ff663ef879c820d6bcae96adf3cc19cdb689d34 | krzysztof-kozak/practicePythonClass | /main.py | 2,112 | 3.71875 | 4 | from math import ceil
from copy import copy
class Person:
def __init__(self, name, age):
print("Pozdrowienia od konstruktora!")
self.name = name
self.age = age
self.semester = 7
self.address = None
def set_address(self, address: object):
self.address = address
@property
def hello(self):
print("Hello!")
def greet_user(self, user):
print(f'Hello {user}')
def intruduce_self(self):
print(f'Hello, my name is {self.name} and I am {self.age} years old')
def grow_older(self, number_of_years=1):
self.age += number_of_years
def get_age_in_months(self):
return self.age * 12
def get_study_year_info(self):
return ceil(self.semester / 2)
class Address:
def __init__(self, street_name, street_number, city, postal_code):
self.street_name = street_name
self.street_number = street_number
self.city = city
self.postal_code = postal_code
def get_full_address(self):
return (self.street_name, self.street_number, self.city, self.postal_code)
# Można, ale nie trzeba, nazywać swoje argumenty
# Dzięki nazywaniu argumentów można np. zmieniać ich kolejność (pog!)
some_house = Address(
street_name='Roscoe', street_number=5, city='New York', postal_code=555)
dude = Person("Alfred", 79)
dude.intruduce_self()
dude.grow_older()
dude.intruduce_self()
my_age_in_months = dude.get_age_in_months()
my_study_year = dude.get_study_year_info()
print(my_age_in_months)
print(my_study_year)
dude.hello
another_dude = copy(dude)
another_dude.grow_older(50)
dude.intruduce_self()
# Można też stowrzyć odpowiednią właściwość obiektu pt. address oraz napisać metodę, która będzie wyznaczać ten adres, co w sumie teraz zrobię, a linijki poniżej zakomentuje.
# dude.address = some_house
# another_dude.address = some_house
print(dude.address) # Homeless LOL!
dude_with_address = Person("Richard", 19)
dude_with_address.set_address(some_house)
print(dude_with_address.address.get_full_address()) # Not homeless!
|
13fbc3ed5e4168fbb59ee015c3b7e6c2fb2455e1 | banjin/everyday | /questions/fab.py | 2,770 | 3.6875 | 4 | #!/usr/bin/env python
# coding:utf-8
"""斐波那契数列
"""
def fabltion(n):
if n < 2:
return 1
return fabltion(n-2) + fabltion(n-1)
def fabltion2(n):
a, b = 0, 1
while n:
yield b
a, b = b, a + b
n -= 1
def fabltion3(n):
"""斐波契纳数列1,2,3,5,8,13,21............根据这样的规律
编程求出400万以内最大的斐波契纳数,并求出它是第几个斐波契纳数。
n = fabltion3(4000000)
for i in n:
print(i)
"""
a, b = 0, 1
count = 0
while b < n:
yield b
a, b = b, a + b
count += 1
print(count, b)
def add_dict(dict1, dict2):
"""
实现两个字典的相加,不同的key对应的值保留,相同的key对应的值相加后保留,如果是字符串就拼接
intput:
dicta = {"a":1,”b”:2,”c”:3,”d”:4,”f”:”hello” }
dictb = {“b”:3,”d”:5,”e”:7,”m”:9,”k”:”world”}
output:
dictc = {“a”:1,”b”:5,”c”:3,”d”:9,”e”:7,”m”:9,”f”:”hello”,”k”:”world”}
"""
result = {}
key1 = set(dict1.keys())
key2 = set(dict2.keys())
in_dict1 = list(key1 - key2)
in_dict2 = list(key2 - key1)
all_in = key1 & key2
for i in in_dict1:
result.update({i: dict1[i]})
for f in in_dict2:
result.update({f: dict2[f]})
for a in all_in:
t1 = dict1.get(a)
t2 = dict2.get(a)
if (isinstance(t1, int) and isinstance(t2, int)) or (isinstance(t1, str) and isinstance(t2, str)):
result.update({a: t1+t2})
elif isinstance(t1, int) and isinstance(t2, str):
result.update({a: str(t1)+t2})
elif isinstance(t1, str) and isinstance(t2, int):
result.update({a: str(t2)+t1})
else:
pass
return result
def taozi():
"""
海滩上有一堆桃子,五只猴子来分,第一只猴子把这堆桃子平均分成五份,
多了一个,这只猴子把多的一个扔到了海里,拿走了一份,
第二只猴子把剩下的把四堆桃子合在一起,
又平均分成五份,又多了一个,
它同样把多的一个扔到了海里,
拿走了一份,第三只,第四只,第五只都是这样做的,
问海滩上原来最少有多少桃子
"""
i = 0
j = 1
x = 0
while (i < 5):
x = 4 * j
for i in range(0, 5):
if(x % 4 != 0):
break
else:
i += 1
x = (x/4) * 5 + 1
j += 1
print(x)
def romanToInt(s):
d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
if __name__ == "__main__":
taozi()
|
07de19fbd68ce2aeba25f41985c08c8bf9df6134 | sosoivy/PythonChallenge | /pythonchallenge 15.py | 294 | 3.515625 | 4 | # -*- coding:utf-8 -*-
import datetime
# 闰年
years = [y for y in range(1006, 1997) if str(y)[-1] == '6' and y % 4 == 0]
# date和weekday对应
year_c = []
for y in years:
d = datetime.date(y, 1, 27)
if d.weekday() == 1:
year_c.append(y)
# second youngest
print year_c[-2] |
6ca00500ac6342c00c9c9f09c5f0b3279432a5dc | sishirsubedi/common_problems | /12_DyanmicProg_IV_LongestCommonSubstring.py | 1,686 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 03 14:50:29 2016
@author: ibm-lenovo
"""
def maxCommonSubstring(str1,str2):
len1 = len(str1)
len2 = len(str2)
common =[]
K = [[0 for x in range(len2+1)] for x in range(len1+1)]
for i in range(len1+1):# 0 to n
for j in range(len2+1): # 0 to n
if i==0 or j==0:
K[i][j] = 0
elif str1[i-1]==str2[j-1]:
K[i][j] = K[i-1][j-1] + 1
if str2[j-1] not in common:
common.append(str2[j-1]) # this to show which are common ones
else:
K[i][j] = max(K[i-1][j],K[i][j-1])
return common#K
def maxCommonSubstring2(word,pattern):
len1 = len(word)
len2 = len(pattern)
mat = [[0 for x in range(len1 + 1)] for y in range(len2 + 1)]
for p in range(1,len2 + 1):
for w in range(1,len1+1):
if word[w-1]==pattern[p-1]:
mat[p][w] = mat[p-1][w-1] + 1
else:
mat[p][w] = max(mat[p-1][w] ,mat[p][w-1])
return mat
# Driver program to test above functions
string1 = ['a','b','c','d','e','f']
string2 =['a','c','b','c','f']
#price= [2,5,7,8,9] # cost of each length rod
#length = [1,2,3,4,5]
#print(string1, string2, "Common max sequence is " + str(maxCommonSubstring(string1,string2) ))
print str(maxCommonSubstring(string1,string2))
pattern = ['b','c','d']
word =['a','b','c','d','e']
mat = maxCommonSubstring(word,pattern)
for i in mat:
print i
X = "zxabcdezy"
y = "yzabcdezx"
mat = maxCommonSubstring2(X, y)
for i in mat:
print i |
f4fc1f9733ae09be4e27a718a19f9707a17c67cf | Mikaelia/hashmap_vending-machine | /interface.py | 2,731 | 3.734375 | 4 | #!/usr/bin/env python3
"""
Interactive console
"""
import sys
import cmd
import shlex
from vending_machine import VendingHash
class VendingCommand(cmd.Cmd):
"""
A console allowing users to interact with vending machine
"""
prompt = ("*Beep* ")
def do_quit(self, args):
"""
Quit command to exit the program
"""
return True
def do_EOF(self, args):
"""
Exit progam upon EOF signal
"""
return True
def do_buy(self, args):
"""
"Purchase" an item to remove it from machine
"""
try:
args = shlex.split(args)
snackotron.buy(args[0].title())
except:
print("** Please choose an item **")
def do_restock(self, args):
"""
Reset machine to default item counts
"""
snackotron.restock()
def do_money(self, args):
"""
Return the amount of money the machine has collected since last restock
"""
snackotron.value()
def do_add(self, args):
"""
Adds/updates an item in the machine
"""
item_dict = {
'count': 1,
'price': 0
}
try:
args = shlex.split(args)
item = args[0].title()
snackotron.add(item, item_dict)
except:
print("** Please provide item name **")
def do_check(self, args):
"""
Returns information about a specific item
"""
try:
args = shlex.split(args)
item = args[0].title()
if not snackotron.find(item):
print("There are no {}s".format(item))
except:
print("** Please provide item name **")
def do_price(self, args):
"""
Updates price of an item
"""
item_dict = {
'count': 0,
'price': 0
}
try:
args = shlex.split(args)
item = args[0].title()
if len(args) > 1:
item_dict.update({'price': int(args[1])})
snackotron.add(item, item_dict)
except:
print("** please provide item name and associated data **")
def do_schema(self, args):
"""
Prints vending machine hashmap schema
"""
snackotron.schema()
def do_inventory(self, args):
"""
Prints all vending machine items and descriptions
"""
snackotron.tell()
if __name__ == '__main__':
"""
Entry point for command loop.
"""
# Creates size of hash table
snackotron = VendingHash(5)
VendingCommand().cmdloop() |
d20d5154b22450148d92a8cdf7a4000fb516fc8a | dindaya28/School-Work | /Python/CLASS/test.py | 3,382 | 3.578125 | 4 | # Lists
listOfKeywords = []
pacificScore = []
mountainScore = []
centralScore = []
easternScore = []
# Function for calculating happiness score within each tweet
def happinessCalculator():
wordValue = 0
for el in range(5, len(line)): # Need to make this a function to repeat within the other timezones
if el in listOfKeywords:
wordValue = wordValue + int(listOfKeywords[listOfKeywords.index(el)][1])
#print(el) # REMOVE AFTER TESTING
#else: DON'T NEED THIS SHIT
#pass
return wordValue
def clean():
for el in range(int(line[5]), len(line)):
line[el] = line[el].strip(".,/*@#!$%^&()_-:;\n")
return line
try:
# Prompt user for file input
keywords = open(input("Enter the file name containing keywords: "), "r")
line = keywords.readline()
while line != "":
line = line.strip("\n")
line = line.split(",")
listOfKeywords.append(line)
line = keywords.readline()
keywords.close()
#print(listOfKeywords)
except IOError:
print("Error: file not found.")
try:
# prompt user for tweets file
tweets = open(input("Enter the file name containing tweets: "), "r")
tweetLine = tweets.readline()
while tweetLine != "":
print(tweetLine)
tweetLine = tweetLine.lower()
tweetLine = tweetLine.replace(",","").strip("[").lower().split()
tweetLine[1] = tweetLine[1].rstrip("]")
latitude = float(tweetLine[0])
longitude = float(tweetLine[1])
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0
if 24.660845 <= latitude <= 49.189787:
if -87.518395 <= longitude <= -67.444574:
#clean()
easternTweets = easternTweets + 1
happinessCalculator()
easternScore.append(happinessCalculator())
elif -101.998892 <= longitude < -87.518395:
#clean()
centralTweets = centralTweets + 1
happinessCalculator()
centralScore.append(happinessCalculator())
elif -115.236428 <= longitude < -101.998892:
#clean()
mountainTweets = mountainTweets + 1
happinessCalculator()
mountainScore.append(happinessCalculator())
elif -125.242264 <= longitude < -115.236428:
#clean()
pacificTweets = pacificTweets + 1
happinessCalculator()
pacificScore.append(happinessCalculator())
else:
line = tweets.readline()
tweets.close()
except IOError:
print("Error: file not found.")
pacificScore = sum(pacificScore)/pacificTweets
mountainScore = sum(mountainScore)/mountainTweets
centralScore = sum(centralScore)/centralTweets
easternScore = sum(easternScore)/easternTweets
print("The happiness score for the Pacific timezone is ", pacificScore, ", from", pacificTweets, "number of tweets!")
print("The happiness score for the Mountain timezone is ", mountainScore, ", from", mountainTweets, "number of tweets!")
print("The happiness score for the Central timezone is ", centralScore, ", from", centralTweets, "number of tweets!")
print("The happiness score for the Eastern timezone is ", easternScore, ", from", easternTweets, "number of tweets!")
|
e83ce1a4ec7e447c5eb2eb6941493837f3ffa8aa | Saalim95/Data-Structure | /Tree Comparison.py | 988 | 3.96875 | 4 | class Node:
def __init__(self, val):
self.right = None
self.left = None
self.data = val
def __str__(self):
return str(self.data)
def add(root, x):
if root==None:
root = Node(x)
return root
if x>root.data:
if root.right==None:
root.right = Node(x)
else:
root.right = add(root.right, x)
else: #for x<root.data
if root.left == None:
root.left = Node(x)
else:
root.left = add(root.left, x)
return root
def compare(a, b):
#if both are None
if a==b==None:
return True
#if both are not-empty
if a is not None and b is not None:
return compare(a.right, b.right) and compare(a.left, b.left)
#one is empty and one is not
else:
return False
t1 = Node(3)
add(t1, 7)
add(t1, 0)
t2 = Node(6)
add(t2, 10)
add(t2,1)
print(compare(t1, t2))
|
c95bf7dd5175de5793f6a22e04edbfd1bfca2299 | bourneagain/pythonBytes | /addSubMulDiv.py | 625 | 3.921875 | 4 | def add(a,b):
return a+b
def mult(a,b):
if a==0 or b==0:
return 0
count=1;
result=0;
while count<=abs(b):
print count
result+=a
count+=1
if(b<0):
return neg(result)
else:
return result
def subt(a,b):
return a+neg(b)
def divide(a,b):
if b==0:
raise Exception("divide by zero")
#a/b=x
#a=bx
c=abs(b)
result=0
while(c<=abs(a)):
result+=1
c+=abs(b)
if ( a>0 and b>0 ) or ( a<0 and b<0 ):
return result
else:
return neg(result)
def neg(n):
neg=0
if n>0:
flag=-1
else:
flag=1
result=0
while(n!=0):
result+=flag
n+=flag
return result
print divide(19,2)
#print subt(-2,-3) |
f274dfa6ae29a15699bef58b6adc3e0765a388b2 | Gackle/leetcode_practice | /53.py | 889 | 3.640625 | 4 | # coding: utf-8
""" 53. 最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
"""
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
import sys
if nums == []:
return None
i = 0
max_count = -sys.maxsize - 1
current = 0
while i < len(nums):
current = max(current + nums[i], nums[i])
max_count = max(max_count, current)
i += 1
return max_count
if __name__ == '__main__':
s = Solution()
# nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
nums = [1, 2]
print(s.maxSubArray(nums))
|
f9e4a1941cd9ad3e7d224be041ed22b847962fdc | Amit-CBS/Machine-Learning-with-Python | /Day6/age_calc_from_dob_gui.py | 3,023 | 3.671875 | 4 | # age_calc_from_dob_gui.py
# Testing Tkinter features with Python
# calculating age from DOB
from tkinter import *
from tkinter import messagebox as msg
from datetime import datetime, date
class GetAge:
# Constructor
def __init__(self, root1):
self.f = Frame(root1, height=350, width=500)
self.f.pack() # Place the frame on root1 window
# Creating label and Entry widgets
self.message_label = Label(self.f,text='Enter your DOB (dd/mm/yyyy) :',font=('Arial', 14))
self.output_label = Label(self.f,text='', font=('Arial', 14))
self.age = Entry(self.f, font=('Arial', 14), width=12)
self.age.bind('<Return>', self.calc_age) # Hit Enter key to call 'calculate' func
# Creating button widgets
self.calc_button = Button(self.f,text='Get Age', font=('Arial', 14), bg='Orange', fg='Black', command=self.calc_age)
self.reset_button = Button(self.f,text='Clear', font=('Arial', 14), bg='Brown', fg='Black', command=self.reset)
self.exit_button = Button(self.f,text='Exit', font=('Arial', 14), bg='Yellow', fg='Black', command=root1.destroy)
# Placing the widgets using grid manager
self.message_label.grid(row=0, column=0)
self.age.grid(row=0, column=1)
self.calc_button.grid(row=2, column=1)
self.reset_button.grid(row=2, column=2)
self.exit_button.grid(row=2, column=3)
self.output_label.grid(row=1, column=0, columnspan=3)
# Focus the cursor on age field
self.age.focus()
def calc_age(self):
try:
# Age calculation based on DOB input
temp_dt = self.age.get()
lst = temp_dt.split('/')
print(lst)
yr = int(lst[2])
mm = int(lst[1])
dy = int(lst[0])
print(yr,mm, dy)
birth_dt = date(yr,mm,dy)
days_in_year = 365.2425
age = int((date.today() - birth_dt).days / days_in_year)
print('Age :', age, ' years')
self.output_label.configure(text = 'Age : ' + str(age) + ' years')
except (ValueError, IndexError) as e:
self.output_label.configure(text='Please enter a valid Date Of Birth.' + str(e))
msg.showerror('Enter a valid Date of Birth', 'Date of Birth must be valid')
self.reset()
self.age.focus()
def reset(self):
self.age.delete(0,END) # clears the entry box
self.output_label.configure(text = '') # Erase the contents of the label text
self.age.focus() # Focus the cursor on age field
#----------------------------------------
root1 = Tk()
root1.title('Age Calculation from Date Of Birth')
root1.geometry('600x400')
temp_conv = GetAge(root1)
# mainloop
root1.mainloop() |
3b504da6cc8f61ac4265f6dbb6825d1db4ef964e | bbj3/cracking-the-coding-interview | /3 - Stacks/1_ArrayStack.py | 2,257 | 3.625 | 4 | # 3.1
class ThreeStacks:
def __init__(self, cap):
self.capacity = cap
self.lst = [None] * 3 * cap
self.size = [0,0,0]
def push(self, data, stackNum):
if stackNum < 3 and stackNum >= 0:
if self.isFull(stackNum):
print("Full - please pop")
return False
self.size[stackNum] = self.size[stackNum]+1
topindex = self.indexOfTop(stackNum)
self.lst[topindex] = data
return True
def pop(self, stackNum):
if stackNum < 3 and stackNum >= 0:
if self.isEmpty(stackNum):
print("Empty")
return False
topindex = self.indexOfTop(stackNum)
temp = self.lst[topindex]
self.lst[topindex] = None
self.size[stackNum] = self.size[stackNum]-1
return temp
def size(self, stackNum):
return self.top[stackNum]
def isFull(self, stackNum):
if self.size[stackNum] >= self.capacity:
return True
def isEmpty(self, stackNum):
if self.size[stackNum] <= 0 :
return True
def indexOfTop(self, stackNum):
offset = stackNum*self.capacity
index = self.size[stackNum]+offset
return index
import unittest
class TestStringMethods(unittest.TestCase):
def test_array_stack(self):
my3 = ThreeStacks(3)
self.assertEqual(my3.push(-100,0), True)
self.assertEqual(my3.push(-110,0), True)
self.assertEqual(my3.push(-10,0), True)
self.assertEqual(my3.push(-20,0), False)
self.assertEqual(my3.pop(0), -10)
self.assertEqual(my3.pop(0), -110)
self.assertEqual(my3.pop(0), -100)
self.assertEqual(my3.pop(0), False)
self.assertEqual(my3.push(-200,1), True)
self.assertEqual(my3.push(-210,1), True)
self.assertEqual(my3.pop(1), -210)
self.assertEqual(my3.pop(1), -200)
self.assertEqual(my3.push(-300,2), True)
self.assertEqual(my3.push(-310,2), True)
self.assertEqual(my3.pop(2), -310)
self.assertEqual(my3.push(-210,1), True)
self.assertEqual(my3.pop(2), -300)
if __name__ == '__main__':
unittest.main()
|
40488a28faa75e34725410d03ccb6ef93e700cd8 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4007/codes/1590_842.py | 240 | 3.5 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
n = input()
soma = sum(int(i) for i in str(n))
print(soma) |
d40d68dbeee03f6d633d8986c4e25b57eefa3946 | coledixon/Tech_Academy_coding_drills_2015 | /Python_drills/training_drill/% inserts.py | 302 | 3.515625 | 4 | my_name = "Cole"
my_age = "27"
my_height = 5
my_height2 = 10
my_weight = 145
my_eye = "hazel"
print("My name is %s." % my_name )
print("I am %s years old." % my_age)
print("I am %sft %sins tall." %(my_height, my_height2))
print("I weigh approx. %slbs." % my_weight)
print("My eyes are %s." % my_eye)
|
ccdf4c7262c5968154d0736510da2bf1205c4a48 | MahmudHossain/Solved-Problems-C-Java-Python- | /Hackerrank_Python/diamond.py | 130 | 3.65625 | 4 | n=int(input())
for i in range(n-1):
print((n-i)*' '+(2*i+1)*'*')
for i in range(n-1,-1,-1):
print((n-i)*' '+(2*i+1)*'*')
|
282f8b4152e5cf57e33509640d8079ca085ade15 | wclau/ENGG4030 | /hw34/mf_corrected.py | 2,434 | 3.84375 | 4 | #!/usr/bin/python
#
# Created by Albert Au Yeung (2010)
# http://www.quuxlabs.com/blog/2010/09/matrix-factorization-a-simple-tutorial-and-implementation-in-python
# An implementation of matrix factorization
#
from __future__ import print_function
try:
import numpy
numpy.random.seed(1)
except:
print("This implementation requires the numpy module.")
exit(0)
###############################################################################
"""
@INPUT:
R : a matrix to be factorized, dimension N x M
P : an initial matrix of dimension N x K
Q : an initial matrix of dimension M x K
K : the number of latent features
steps : the maximum number of steps to perform the optimisation
alpha : the learning rate
beta : the regularization parameter
@OUTPUT:
the final matrices P and Q
"""
def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02):
Q = Q.T
for step in range(steps):
newP, newQ = numpy.zeros(P.shape), numpy.zeros(Q.shape)
for i in range(len(R)):
for j in range(len(R[i])):
if R[i][j] > 0:
eij = R[i][j] - numpy.dot(P[i,:],Q[:,j])
for k in range(K):
newP[i][k] = P[i][k] + alpha * (2 * eij * Q[k][j] - beta * P[i][k])
newQ[k][j] = Q[k][j] + alpha * (2 * eij * P[i][k] - beta * Q[k][j])
P, Q = newP, newQ
eR = numpy.dot(P,Q)
e = 0
for i in range(len(R)):
for j in range(len(R[i])):
if R[i][j] > 0:
e = e + pow(R[i][j] - numpy.dot(P[i,:],Q[:,j]), 2)
for k in range(K):
e = e + (beta/2) * ( pow(P[i][k],2) + pow(Q[k][j],2) )
if e < 0.001:
break
return P, Q.T
###############################################################################
if __name__ == "__main__":
R = [
[1, 1, 6, 4, 4, 0],
[0, 3, 0, 4, 5, 4],
[6, 0, 0, 2, 4, 4],
[2, 1, 4, 5, 0, 5],
[4, 4, 2, 0, 3, 1]
]
TEST_R, TEST_C = 1, 2
R = numpy.asarray(R)
N = R.shape[0]
M = R.shape[1]
K = 2
P = numpy.random.rand(N,K)
Q = numpy.random.rand(M,K)
nP, nQ = matrix_factorization(R, P, Q, K)
print("P:")
print(nP)
print("Q:")
print(nQ)
print("Prediction:", numpy.dot(nP[TEST_R, :], nQ.T[:, TEST_C]))
|
8ced80c2fcc35bb0416be0ecfa15099a0f8747f8 | eencdl/leetcode | /python/binaryTreeZigZagLevelOrderTraversal.py | 2,208 | 4.03125 | 4 | __author__ = 'don'
"""
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
confused what "{1,#,2,3}"
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[][]}
def zigzagLevelOrder(self, root):
# using the array smartly as a queue and stack
# when insert at front, pop from back
# when append at back, pop from the front
# append back (left, then right), when pop at front
# insert front (right, then left), when pop at back
# in both cases: you want to the queue = [left right left right left right]
# so that if you want the reverse just pop from back, or pop from front to get normal order
def bfs(root):
if root is None:
return []
r, cnt, level, q, res = False, 0, 1, [root], []
while len(q) > 0:
if r:
node = q.pop()
if node.right:
cnt += 1
q.insert(0, node.right)
if node.left:
cnt += 1
q.insert(0,node.left)
else:
node = q.pop(0)
if node.left:
cnt += 1
q.append(node.left)
if node.right:
cnt += 1
q.append(node.right)
level -= 1
res.append(node.val)
if level == 0:
level, cnt = cnt, 0
r = ~r
tres.append(res[:])
res = []
tres =[]
bfs(root)
return tres
|
c756ca96d4adf2bcc117cfa834b1e2f08a00f7e0 | gayatri-p/python-stuff | /challenge/problems/infinite_array.py | 704 | 3.953125 | 4 | '''
You are given an array A of size N.
You have also defined an array B as the concatenation of
array A for infinite number of times.
Eg:
A = [1, 3, 5]
B = [1, 3, 5, 1, 3, 5, 3, 5, ...]
given range x to y in B, print sum of that range in B
L = initial value of ranges
R = final value of ranges
'''
def solve (a, r, l):
sums = []
n = len(a)
for x, y in zip(l, r):
s = 0
f = y-x+1
i = (x-1)%n
while f > 0:
s += a[i]
i += 1
f -= 1
if i == n:
i = 0
sums.append(s)
return sums
A = [4, 1, 5]
L = [1, 3, 9, 2]
R = [4, 7, 10, 10]
out_ = solve(A, R, L)
print(out_) |
a93d891f0d3264bdc6cd183af22058c1ccf110ab | vivek1395/python-code | /fibonacci.py | 413 | 4.09375 | 4 | #write a program to print fibonacci series.
n=10
def fibonacci():
a=0
b=1
global n
while (n>0):
sum=a+b
yield a,b,a+b
a=b
b=sum
n=n+1
f=fibonacci()
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
|
4e233fcda368ed34c74a6503700d31085c720278 | Psingh12354/GeeksPy | /CumulativeSum.py | 238 | 3.53125 | 4 | list1 = [10, 20, 30, 40, 50]
list2 = []
count=0
for i in range(len(list1)):
if i==0:
count=list1[i]
list2.append(count)
if i>0:
count+=list1[i]
list2.append(count)
print(list2)
|
a120eda00f26fa85edb534fccfd59ed32930d663 | BriBean/Variables | /variables_primary.py | 3,565 | 4.46875 | 4 | # author: <Brianna Blue>
# date: <7/2/21>
#
# description: <variables>
# --------------- Section 1 --------------- #
# 1.1 | Variable Creation | Strings
#
# Relevant Documentation
# - https://www.w3schools.com/python/python_variables.asp
# - https://www.w3schools.com/python/python_variables_names.asp
#
# Variables
# 1) Create a variable that holds your name.
# 2) Create a variable that holds your birthday.
# 3) Create a variable that holds the name of an animal you like.
# Print
# 4) Print each variable, describing it when you print it.
# Example Code
example_name = 'elia'
print('EXAMPLE: my name is' , example_name)
# WRITE CODE BELOW
first_name = 'Brianna'
b = 'October 26th'
a = 'cats'
print()
print('my name is', first_name)
print('my birthday is', b)
print('one of my favorite animals are', a)
# 1.2 | Variable Creation | Integers / Floats
#
# Relevant Documentation
# - https://www.w3schools.com/python/python_variables.asp
# - https://www.w3schools.com/python/python_variables_names.asp
#
# All variables created in this section should hold either an integer or float.
#
# Variables
# 1) Create a variable that holds your favorite number.
# 2) Create a variable that holds the day of the month of your birthday.
# 3) Create a variable that holds a negative number.
# 4) Create a variable that holds a floating (decimal) point number.
#
# Print
# 5) Print each variable, describing the value you print.
# WRITE CODE BELOW
print()
x = 111
y = 26
z = 5.8
print('my favorite number is', x)
print('the day of my birthday is', y)
print(z)
# 1.3 | Overwriting Variables
#
# Relevant Documentation
# - https://www.w3schools.com/python/python_variables.asp
# - https://www.w3schools.com/python/python_variables_names.asp
#
# Variables
# 1) Overwrite the variable holding your name, and save a different name to it.
# 2) Overwrite the variable holding birthday with the day you think would be best to have a birthday on.
# 3) Overwrite the variable holding your favorite number and set it to a number you think is unlucky.
#
# Print
# 4) Print the variables you've overwritten, describing the values you print.
#
# Example Code
example_name = 'lucia'
print('EXAMPLE: my new name is', example_name)
# WRITE CODE BELOW
print()
first_name = 'Mya'
b = 1
u = 23
print('my new name is', first_name)
print(b)
print(u)
# 1.4 | Operations
#
# Relevant Documentation
# - https://www.w3schools.com/python/python_variables.asp
# - https://www.w3schools.com/python/python_variables_names.asp
#
# Variables
# 1) Create a variable that is the sum of two numbers.
# 2) Create a variable that is the product of three numbers.
# 3) Create a variable by dividing the previously created sum, with the previously created product.
#
# 4) Create a variable that is the concatenation of your name and an animal you like (use the variables!)
# 5) Create a variable that is an acronym (like 'lol') multiplied by your birth day.
#
# 6) Create a variable that is difference of itself minus the number you think is unlucky.
# 7) Overwrite the lucky variable with the itself squared.
#
# Print
# 7) Print all the new variables you've created along with what the represent
#
# Example Code
example_sum = 11 + 21
print('EXAMPLE: the sum of 11 and 21 is', example_sum)
# WRITE CODE BELOW
print()
first_sum = 29 + 20
first_product = 8 * 5 * 3
x = 'Brianna' + 'cat'
y = 'lmao' * 26
z = z - 23
c = 26 ** 2
print(' the sum of 29 and 20 is', first_sum)
print('the product of 8, 5 and 3 is', first_product)
print(x)
print(y)
print(z)
print(c) |
95e324940b556ba041a7cb66318d7fdb7f5e7bd3 | alrod2005/HackerRankChallenges | /triplets.py | 758 | 3.5625 | 4 | #!/bin/python3
import os
import sys
def solve_a(a0, a1, a2, b0, b1, b2):
alice_score = 0
bob_score = 0
if a0 > b0:
alice_score += 1
elif a0 < b0:
bob_score += 1
if a1 > b1:
alice_score += 1
elif a1 < b1:
bob_score += 1
if a2 > b2:
alice_score += 1
elif a2 < b2:
bob_score += 1
return (alice_score, bob_score)
def solve_b(a0, a1, a2, b0, b1, b2):
a_triplet =[a0, a1, a2]
b_triplet = [b0, b1, b2]
alice_points = 0
bob_points = 0
for a_val, b_val in zip(a_triplet, b_triplet):
if a_val < b_val:
bob_points += 1
elif a_val > b_val:
alice_points += 1
print(alice_points, bob_points)
|
c058414b5483ff4d62777f01574f2909a695e5d2 | capncrockett/Udemy_PY_MC | /7_DictAndSet_Remaster/dict_intro.py | 1,332 | 3.8125 | 4 | vehicles = {'dream': 'Honda 250T',
# 'roadster': 'BMW R1100',
'er5': 'Kawasaki ER5',
'can-am': 'Bombardier Can-Am 250',
'virago': 'Yamaha XV250',
'tenere': 'Yamaha XT650',
'jimny': 'Suzuki Jimny 1.5',
'fiesta': 'Ford Fiesta Ghia 1.4',
'roadster': 'Triumph Street Triple',
# "starfighter": "Lockheed F-104",
# "learjet": "Bombardier Learjet 75",
# "toy": "Glider",
# "virago": "Yamaha XV535"
}
vehicles["starfighter"] = "Lockheed F-104"
vehicles["learjet"] = "Bombardier Learjet 75"
vehicles["toy"] = "Glider"
# Upgrade the Virago
vehicles["virago"] = 'Yamaha XV535'
del vehicles["starfighter"]
# This doesn't exists so cause an error
# del vehicles["f1"]
# Better way to check if a key exists.
result = vehicles.pop("f1", f"f1?! {None} You wish! Sell the LearJet and you might afford a racing car")
print(result)
# plane = vehicles.pop("learjet")
# print(plane)
bike = vehicles.pop("tenere", "not present")
print(bike)
print()
# Not an efficient way to work with Dicts
# for key in vehicles:
# print(key, vehicles[key], sep=", ")
# .items() is the better way.
for key, value in vehicles.items():
print(key, value, sep=", ")
|
53cf9831c943f0fd8dfcaffb84452b3217b63699 | yalothman97/Python | /loops_task.py | 568 | 3.921875 | 4 | print("\nCASHIER HELPER 9000 🧾")
print("The Coded Electronics Store")
items=[]
while True:
name=input('\nInsert product name (enter "done" when finished): ')
if name=='done':
break
price=float(input("Insert price: "))
quantity=int(input("Insert quantity: "))
items.append({'name':name,'price':price,'quantity':quantity})
print('-'*14+'\n RECEIPT\n'+'-'*14)
total_price=0
for item in items:
total_price+=item['price']*item['quantity']
print('%d %s %.3fKD'%(item['quantity'],item['name'],item['price']))
print('-'*14)
print('TOTAL: %.3fKD'%(total_price)) |
c17d2dee7f5cffed2c23ef9428f841a3bc4e8357 | ashi-06-jul/Chatbot | /db.py | 1,291 | 3.796875 | 4 |
import sqlite3
class DB:
def __init__(self, dbname="details.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
def setup(self):
stmt = "CREATE TABLE IF NOT EXISTS INFO(city text, locality text, pincode integer, req text, standard text, board text, medium text, subjects text, contact integer, email text, confirm text)"
self.conn.execute(stmt)
self.conn.commit()
def add_item(self, City, Locality,Pincode, Req, Standard, Board, Medium, Subjects, Contact, Email, Confirm):
stmt = "INSERT INTO INFO (city, locality, pincode, req, standard, board, medium, subjects, contact, email, confirm) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
args = (City, Locality, Pincode, Req, Standard, Board, Medium,
Subjects, Contact, Email, Confirm)
self.conn.execute(stmt, args)
self.conn.commit()
def delete_item(self, item_text):
stmt = "DELETE FROM items WHERE description = (?)"
args = (item_text, )
self.conn.execute(stmt, args)
self.conn.commit()
def get_items(self):
stmt = "SELECT City, Locality, Pincode, Req, Standard, Board, Medium, Subjects, Contact, Email, Confirm FROM INFO"
return [x for x in self.conn.execute(stmt)]
|
aa4a1b238a58b29dda036325d6a23111fea8b9da | wenxinjie/leetcode | /tree/python/leetcode106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py | 1,112 | 4.09375 | 4 | # Given inorder and postorder traversal of a tree, construct the binary tree.
# Note:
# You may assume that duplicates do not exist in the tree.
# For example, given
# inorder = [9,3,15,20,7]
# postorder = [9,15,7,20,3]
# Return the following binary tree:
# 3
# / \
# 9 20
# / \
# 15 7
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not inorder or not postorder or len(inorder) == 0 or len(postorder) == 0:
return None
else:
index = inorder.index(postorder[-1])
root = TreeNode(inorder[index])
root.left = self.buildTree(inorder[:index], postorder[:index])
root.right = self.buildTree(inorder[index+1:], postorder[index:-1])
return root
# Time:O(n)
# Space: O(n)
# Difficulty: medium
|
57b0a8be724704ddbab70111d432bcfa44144833 | ronvoluted/kaggle-nba | /src/data/getAbsolute.py | 744 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import logging
import pandas as pd
import joblib
def abs(df, name):
"""Convert the dataframe value to absolute:
***WARNING*** This module converts all negative values to positive values in dataframe.
Parameters
----------
df : dataframe
Features of dataset
name: string
The name of the dataset, and it will be used as the filename of data dump
Returns
-------
df : dataframe
Converted dataframe with all values in absolute
"""
logger = logging.getLogger(__name__)
logger.info('turning dataframe '+name+ ' to be absolute value')
df = df.abs()
joblib.dump(df, "../data/processed/abs_"+name)
return df
|
a98142829352c73d3c980e314a39d415b92531ac | Hellofafar/Leetcode | /Easy/475.py | 2,294 | 3.90625 | 4 | # ------------------------------
# 475. Heaters
#
# Description:
# Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
# Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
# So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.
# Note:
# Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
# Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
# As long as a house is in the heaters' warm radius range, it can be warmed.
# All the heaters follow your radius standard and the warm radius will the same.
#
# Example 1:
# Input: [1,2,3],[2]
# Output: 1
# Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
#
# Example 2:
# Input: [1,2,3,4],[1,4]
# Output: 1
# Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
#
# Version: 1.0
# 07/08/18 by Jianfa
# ------------------------------
import bisect
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
minDists = []
heaters.sort()
for h in houses:
pos = bisect.bisect(heaters, h)
if pos == 0:
minDists.append(heaters[pos] - h)
elif pos == len(heaters):
minDists.append(h - heaters[pos-1])
else:
minDists.append(min(h - heaters[pos-1], heaters[pos] - h))
print(minDists)
return max(minDists)
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Basic idea is to find the minimum distance for every house, then get the maximum distance among those minimum distances.
# Heaters should be sorted so that locate the position of house among heaters. |
903dd0e2f64716914fc1eaa860859fe2bd54a790 | yehnan/project_euler_python | /p031.py | 1,152 | 3.546875 | 4 |
# Problem 31: Coin sums
# https://projecteuler.net/problem=31
# dynamic programming
def coin_sum(total, coins):
ways = [1] + ([0] * total)
for coin in coins:
for i in range(coin, total+1):
ways[i] += ways[i - coin]
return ways[total]
# recursion
def coin_sum_r(total, coins):
if len(coins) == 1:
return 1
elif total < coins[-1]:
return coin_sum_r(total, coins[:-1])
else:
return coin_sum_r(total-coins[-1], coins) + coin_sum_r(total, coins[:-1])
#
coins_england = (1, 2, 5, 10, 20, 50, 100, 200)
#
def test():
coins_testa = (1, 5, 10, 25)
coins_testb = (1, 5, 10, 25, 50, 100)
if (coin_sum(100, coins_testa) == 242 and
coin_sum(100000, coins_testb) == 13398445413854501 and
coin_sum(200, coins_england) == coin_sum_r(200, coins_england)):
return 'Pass'
else:
return 'Fail'
def main():
return coin_sum(200, coins_england)
if __name__ == '__main__':
import sys
if len(sys.argv) >= 2 and sys.argv[1] == 'test':
print(test())
else:
print(main())
|
32e9bbc093b5a2dbca7f850df2559f03dc022d6a | mkai5/McGalaxy | /constellation.py | 1,362 | 3.53125 | 4 | import star
class Constellation:
constellations = ["Big_Dipper","Aquila"]
def __init__(self, stars):
self.stars = stars
self.size = len(stars)
def get_centroid(self):
x=0
y=0
for i in self.stars:
x = x + i.coordinates[0]
y = y + i.coordinates[1]
size=len(self.stars)
x = x / size
y = y / size
return (x,y)
def list_names(self):
names = []
for i in self.stars:
names.append(i.name)
return names
def constellation_lookup(s,star_data):
if (s=="Big_Dipper"):
con_data= star_data.loc[(star_data["Proper name"] == "Alioth")
| (star_data["Proper name"] == "Dubhe")
| (star_data["Proper name"] == "Merak")
| (star_data["Proper name"] == "Alkaid")
| (star_data["Proper name"] == "Phad")
| (star_data["Proper name"] == "Megrez")
| (star_data["Proper name"] == "Mizar")]
elif (s=="Aquila"):
con_data= star_data.loc[(star_data["Proper name"] == "Altair")
| (star_data["Proper name"] == "Alshain")
| (star_data["Proper name"] == "Tarazed")]
else:
raise ValueError("Constellation not included in lookup function")
return con_data
|
1864ad17fe89a83edf4237f51e81a8e44c23688e | sergio-lira/data_structures_algorithms | /project_3/submission/problem_1.py | 1,801 | 4.4375 | 4 | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if not is_valid_input(number):
return None
return sqrt_recursive_sol(number/2, number)
def is_valid_input(number):
if number == None:
return False
if isinstance(number, int) or isinstance(number, float):
if number >= 0:
return True
return False
def calculate_new_guess(guess, number):
return guess - ( (guess*guess - number) / (2 * guess))
def is_acceptable(guess, number, error=0.01):
return abs(number - guess*guess) <= error
def sqrt_recursive_sol(guess, number, error=0.01):
#Use Newton's method of computing square root
# https://en.wikipedia.org/wiki/Newton%27s_method#Square_root_of_a_number
# https://m.tau.ac.il/~tsirel/dump/Static/knowino.org/wiki/Newton's_method.html
#print("guess: {} number= {}".format(guess, number))
if is_acceptable(guess, number):
return guess//1
else:
return sqrt_recursive_sol(calculate_new_guess(guess,number),number)
print("<< Basic Test Cases >> ")
print("Square root of 9: "+ "Pass" if (3 == sqrt(9)) else "Fail")
print("Square root of 0: "+ "Pass" if (3 == sqrt(9)) else "Fail")
print("Square root of 4: "+ "Pass" if (3 == sqrt(9)) else "Fail")
print("Square root of 1: "+ "Pass" if (3 == sqrt(9)) else "Fail")
print("Square root of 5: "+ "Pass" if (3 == sqrt(9)) else "Fail")
print("\n<< Additional Test Cases >> ")
print("Square root of -1: "+ "Pass" if (None == sqrt(-1)) else "Fail")
print("Square root of 99999: "+ "Pass" if (316 == sqrt(99999)) else "Fail")
print("Square root of None: "+ "Pass" if (None == sqrt(None)) else "Fail")
|
b9963d31b685095c633d3e7be218b2fc70898e69 | candyer/leetcode | /May LeetCoding Challenge/29_canFinish.py | 1,975 | 4.03125 | 4 | # https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/538/week-5-may-29th-may-31st/3344/
# Course Schedule
# There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
# Some courses may have prerequisites, for example to take course 0 you have to first take course 1,
# which is expressed as a pair: [0,1]
# Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
# Example 1:
# Input: numCourses = 2, prerequisites = [[1,0]]
# Output: true
# Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0.
# So it is possible.
# Example 2:
# Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
# Output: false
# Explanation: There are a total of 2 courses to take.
# To take course 1 you should have finished course 0, and to take course 0 you should
# also have finished course 1. So it is impossible.
# Constraints:
# The input prerequisites is a graph represented by a list of edges, not adjacency matrices.
# Read more about how a graph is represented.
# You may assume that there are no duplicate edges in the input prerequisites.
# 1 <= numCourses <= 10^5
from typing import List
from collections import defaultdict
def canFinish(numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = defaultdict(set)
neighbors = defaultdict(set)
for course, pre in prerequisites:
graph[course].add(pre)
neighbors[pre].add(course)
nodes_without_cycle = 0
stack = [course for course in range(numCourses) if course not in graph]
while stack:
node = stack.pop()
nodes_without_cycle += 1
for n in neighbors[node]:
graph[n].remove(node)
if not graph[n]:
stack.append(n)
return nodes_without_cycle == numCourses
assert(canFinish(2, [[1,0]]) == True)
assert(canFinish(2, [[1,0],[0,1]]) == False)
assert(canFinish(8, [[1,5],[1,6], [5,4], [6,3],[2,7],[3,1]]) == False)
|
57ea61813e2d3a4070ed6e0d3dbb5d46f0b14f30 | nunberty/au-fall-2014 | /python/hw3/4.py | 2,599 | 3.6875 | 4 | #!/usr/bin/env python3
"Alina Kramar"
import math
class Vector3(object):
dim = 3
def __init__(self, vector):
self.value = [0] * Vector3.dim
for i in range(Vector3.dim):
self.value[i] = vector[i]
class Matrix(object):
dim = 3
def __init__(self, matrix=None):
if not matrix:
self.value = [[0] * Matrix.dim for _ in range(Matrix.dim)]
else:
self.value = matrix
def __add__(self, rhs):
ret = Matrix()
for i in range(Matrix.dim):
for j in range(Matrix.dim):
ret.value[i][j] = self.value[i][j] + rhs.value[i][j]
return ret
def __mul__(self, rhs):
if isinstance(rhs, Matrix):
ret = Matrix()
for i in range(Matrix.dim):
for j in range(Matrix.dim):
for k in range(Matrix.dim):
ret.value[i][j] += self.value[i][k] * rhs.value[k][j]
return ret
elif isinstance(rhs, Vector3):
result = [0]*Matrix.dim
for i in range(Matrix.dim):
for j in range(Matrix.dim):
result[i] += self.value[i][j]*rhs.value[j]
return Vector3(result)
else:
ret = Matrix()
for i in range(Matrix.dim):
for j in range(Matrix.dim):
ret.value[i][j] = self.value[i][j] * rhs;
return ret
def __invert__(self):
ret = Matrix()
m, n = ret.value, self.value
m[0][0] = n[1][1] * n[2][2] - n[2][1] * n[1][2]
m[0][1] = n[2][1] * n[0][2] - n[0][1] * n[2][2]
m[0][2] = n[0][1] * n[1][2] - n[1][1] * n[0][2]
m[1][0] = n[2][0] * n[1][2] - n[1][0] * n[2][2]
m[1][1] = n[0][0] * n[2][2] - n[2][0] * n[0][2]
m[1][2] = n[1][0] * n[0][2] - n[0][0] * n[1][2]
m[2][0] = n[1][0] * n[2][1] - n[2][0] * n[1][1]
m[2][1] = n[2][0] * n[0][1] - n[0][0] * n[2][1]
m[2][2] = n[1][0] * n[0][1] - n[0][0] * n[1][1]
return ret * (1 / self.det())
def det(self):
m = self.value
return ( m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
- m[0][1] * (m[1][0] * m[2][2] - m[2][0] * m[1][2])
+ m[0][2] * (m[1][0] * m[2][1] - m[2][0] * m[1][1]))
class RotationMatrix(Matrix):
def __init__(self, angle):
matrix = [[math.cos(angle), -math.sin(angle), 0],
[math.sin(angle), math.cos(angle), 0],
[ 0, 0, 1]]
super().__init__(matrix)
|
2696ced25664aa0f87ccc89520f60c5101efbbc1 | yKuzmenko740/Geek_Brains_tutorial | /Fifth_lesson/chain_map.py | 979 | 3.875 | 4 | from collections import ChainMap
# цепочка из словарей, позволяет организовать роботу с несколькими словарями
d_1 = {'a': 2, "b": 4, 'c': 6}
d_2 = {'a': 10, "b": 7, 'd': 40}
d_map = ChainMap(d_1, d_2)
print(d_map)
d_2['a'] = 100 # ссылочная структура данных
print(d_map)
print(d_map['a'])
print(d_map['d'])
print("*" * 100)
# Methods
x = d_map.new_child({"a": 12, "b": 32, 'd': 333}) # ADD NEW DICT AT THE BEGINNING OF THE COLLECTION
print(x)
# getting dictionaries in the collection
print(x.maps[0])
print(x.maps[-1])
# getting dicts before method new_child()
print(x.parents)
print("*" * 100)
y = d_map.new_child()
print(y)
print(y['a'])
y["a"] = 1 # если нет ключа "а" в первом словаре,то оно добавляется
print(y)
print(list(y)) # ключи по алфавитному порядку
print(list(y.values())) # значение
|
8a578a0f5214a04a01c7992aff167c47d75aa85b | arayariquelmes/curso_python_abierto | /41_ejercicio_28.py | 382 | 3.9375 | 4 | #Realiza una función llamada area_circulo(radio)
#que devuelva el área de un círculo a
#partir de un radio. Calcula el área de un
#círculo de 5 de radio.
#El área de un círculo se obtiene al elevar
#el radio a dos y multiplicando el resultado
#por el número pi
from math import pi
def area_circulo(radio):
return pi*radio**2
area = area_circulo(5)
print(round(area,2)) |
97dd00850f95fa542e58cbfa8ba4337e73d14b88 | paulobazooka/intro-python-ifsp | /2018-05-14/jogo-simples.py | 738 | 3.75 | 4 | # Jogo Desenvolvimento na Classe
# Paulo Sérgio do Nascimento 160013-3
from random import randint
# Classe personagem
class Personagem:
pontos = 0
def __init__(self, patas, idade):
self.idade = idade
self.patas = patas
def getIdade(self):
return self.idade
def addPonto(self):
self.pontos = self.pontos + 1
def getPontos(self):
return self.pontos
# Programa Principal
bruxa = Personagem(3,45)
monstro = Personagem(4,33)
i = 0
while(i < 1000):
# Random
numBruxa = randint(0,9)
numMonstro = randint(0,9)
# Comparação
if(numBruxa > numMonstro):
bruxa.addPonto()
else:
if(numBruxa < numMonstro):
monstro.addPonto()
i = i + 1
print("Pontos da Bruxa:",bruxa.getPontos())
print("Pontos do Monstro:",monstro.getPontos()) |
98bd014f0d842ff265ba64ddea97f39b65713217 | artcheng/eular | /palindrome.py | 294 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def palindrome(num):
return str(num) == str(num)[::-1]
i=999
while i>900:
j=999
while j>=i:
x=i*j
if palindrome(x):
print x
j=j-1
i=i-1 |
26f9bd1d93ac1d74ff6943961a1592fa45b9f60b | ZackPashkin/3d-game-with-neural-network | /player.py | 1,314 | 3.609375 | 4 | from settings import *
import pygame as pg
import math
class Player:
def __init__(self):
self.x, self.y = PLAYER_POSITION
self.angle = PLAYER_ANGLE
@property
def position(self):
return (self.x, self.y)
def movement(self):
"""
Player control here
K_UP --> up arrow,
K_DOWN --> down arrow,
K_RIGHT --> right arrow,
K_LEFT --> left arrow
"""
sin_a = math.sin(self.angle)
cos_a = math.cos(self.angle)
keys = pg.key.get_pressed()
if keys[pg.K_UP]:
self.x += PLAYER_SPEED * cos_a
self.y += PLAYER_SPEED * sin_a
print("UP")
if keys[pg.K_DOWN]:
self.x += -PLAYER_SPEED * cos_a
self.y += -PLAYER_SPEED * sin_a
print("DOWN")
if keys[pg.K_LEFT]:
self.x += PLAYER_SPEED * sin_a
self.y += -PLAYER_SPEED * cos_a
print("LEFT")
if keys[pg.K_RIGHT]:
self.x += -PLAYER_SPEED * sin_a
self.y += PLAYER_SPEED * cos_a
print("RIGHT")
# to turn
if keys[pg.K_a]:
self.angle -= 0.03
if keys[pg.K_d]:
self.angle += 0.03
|
7ddd256f5b13343c21c058d9a99f57320b4599e7 | 0x0400/LeetCode | /p169.py | 679 | 3.65625 | 4 | # https://leetcode.com/problems/majority-element/
from collections import Counter
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cnt = Counter(nums)
return cnt.most_common(1)[0][0]
def majorityElementV2(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums)>>1]
def majorityElementV3(self, nums: List[int]) -> int:
major, cnt = nums[0], 0
for num in nums:
if cnt == 0:
major, cnt = num, 1
continue
if num == major:
cnt += 1
else:
cnt -= 1
return major
|
20777c27393a0b1099dc887546cd35fdb57ebdf8 | meankiat95/TeamDF | /historyscrap/ExtractBrowserHistory.py | 5,181 | 4.03125 | 4 | import csv
import os
import sqlite3
import sys
def get_username():
"""
Get username of the computers
"""
drives = input("Please input the drive (e.g. C): ")
username = input("Please enter user profile name (case-sensitive & space sensitive): ")
name = drives +":\\" +"Users"+ "\\"+ username
while not os.path.exists(name):
print("Invalid user name found.")
drives = input("Please input the drive (e.g. C): ")
username = input("Please enter user profile name (case-sensitive & space sensitive): ")
name = drives + ":\\" + "Users" + "\\" + username
return name
def get_database_paths():
"""
Get paths to the database of browsers and store them in a dictionary.
It returns a dictionary: its key is the name of browser in str and its value is the path to database in str.
Only for chrome and firefox
"""
browser_path_dict = dict()
User_path = get_username()
abs_chrome_path = os.path.join(User_path, 'AppData', 'Local', 'Google', 'Chrome', 'User Data', 'Default', 'History')
abs_firefox_path = os.path.join(User_path, 'AppData', 'Roaming', 'Mozilla', 'Firefox', 'Profiles')
# it creates string paths to broswer databases
if os.path.exists(abs_chrome_path):
browser_path_dict['chrome'] = abs_chrome_path
if os.path.exists(abs_firefox_path):
firefox_dir_list = os.listdir(abs_firefox_path)
for f in firefox_dir_list:
if f.find('.default') > 0:
abs_firefox_path = os.path.join(abs_firefox_path, f, 'places.sqlite')
if os.path.exists(abs_firefox_path):
browser_path_dict['firefox'] = abs_firefox_path
return browser_path_dict
def get_browserhistory() :
"""Get the user's browsers history by using sqlite3 module to connect to the dabases.
It returns a dictionary: its key is a name of browser in str and its value is a list of
tuples, each tuple contains four elements, including url, title, and visited_time.
Example
-------
"""
# browserhistory is a dictionary that stores the query results based on the name of browsers.
browserhistory = {}
# call get_database_paths() to get database paths.
paths2databases = get_database_paths()
for browser, path in paths2databases.items():
try:
conn = sqlite3.connect(path)
cursor = conn.cursor()
_SQL = ''
# SQL command for browsers' database table
if browser == 'chrome':
_SQL = """SELECT url, title, datetime((last_visit_time/1000000)-11644473600, 'unixepoch', 'localtime')
AS last_visit_time FROM urls ORDER BY last_visit_time DESC"""
elif browser == 'firefox':
_SQL = """SELECT url, title, datetime((visit_date/1000000), 'unixepoch', 'localtime') AS visit_date
FROM moz_places INNER JOIN moz_historyvisits on moz_historyvisits.place_id = moz_places.id ORDER BY visit_date DESC"""
else:
pass
# query_result will store the result of query
query_result = []
try:
cursor.execute(_SQL)
query_result = cursor.fetchall()
print("This may take awhile. Please wait.")
except sqlite3.OperationalError:
print('* Notification * ')
print('Please Completely Close ' + browser.upper() + ' Window')
except Exception as err:
print(err)
# close cursor and connector
cursor.close()
conn.close()
# put the query result based on the name of browsers.
browserhistory[browser] = query_result
except sqlite3.OperationalError:
print('* ' + browser.upper() + ' Database Permission Denied.')
return browserhistory
def write_browserhistory_csv():
"""It writes csv files that contain the browser history in
the current working directory. It will writes into one common csv files called "general_history.csv ."""
browserhistory = get_browserhistory()
if os.path.exists('general_history.csv'):
os.remove('general_history.csv')
for browser, history in browserhistory.items():
if os.path.exists('general_history.csv'):
with open('general'+'_history.csv', mode ='a', encoding='utf-8',newline='') as csvfile:
csv_writer = csv.writer(csvfile, delimiter=',',
quoting=csv.QUOTE_ALL)
for data in history:
csv_writer.writerow(data)
else:
with open('general' + '_history.csv', mode='w', encoding='utf-8', newline='') as csvfile:
csv_writer = csv.writer(csvfile, delimiter=',',
quoting=csv.QUOTE_ALL)
csv_writer.writerow(['URL','Title','DateTime'])
for data in history:
csv_writer.writerow(data)
|
9c454266e5c3eeb134149cd1247a3b7a0bfcaaa0 | vrtineu/learning-python | /funcoes/ex102.py | 699 | 4.28125 | 4 | # Crie um programa que tenha uma funçao fatorial() que receba dois parametros: o primeiro que indique o numero a calcular e o outro chamado show, que sera um valor logico(opcional) indicando se sera mostrado ou nao na tela o processo de calculo do fatorial.
def fatorial(n, show=False):
"""
-> Calcula o fatorial de um numero.
:param n: Numero a ser calculado.
:param show: (Opcional), Mostra ou não a conta.
:return: O valor do fatorial de um numero.
"""
f = 1
while n >= 1:
if show == True:
print(f'{n}', end='')
print(' x ' if n > 1 else ' = ', end='')
f *= n
n -= 1
return f
print(fatorial(5, show=True))
|
29303abbd54b03233ab8a8a9b46812a29f1059a5 | BabyPringles/10ISTB-work | /Area of the circle.py | 404 | 4.25 | 4 | """
Program to combine the area of a circle.
"""
# import libraries
import math
# define functions
def areaofcircle(r):
area = math.pi * r * r
print("Returning area to main program.")
return(area)
# main program
radius = float(input("What is the radius of the circle in cm?"))
print("Radius is ", radius, " cm")
print("Area is equal to " , areaofcircle(radius), "cm2")
|
2b1459a924238853e7792785b5b58c6f15ec28a1 | mauricioZelaya/QETraining_BDT_python | /WilmaPaca/Practice1/Applying_operators.py | 1,791 | 4.34375 | 4 | # Defining the triangule type
import math
def isosceles(a,b,c):
if a != 0 and b != 0 and c != 0:
if a == b:
text = print("a: %d = b: %d and c: %d is not equal" %(a,b,c))
elif a == c:
text = print("a: %d = c: %d and b: %d is not equal" % (a, c, b))
elif b == c:
text = print("b: %d = c: %d and a: %d is not equal" % (b, c, a))
elif a == b:
text = print("a: %d = b: %d and c: %d is not equal" %(a,b,c))
else:
text = ''
else:
text = ''
return text
def perimeter_triangle(a,b,c):
return (a + b + c) / 2
def area_triangle(a,b,c):
s = perimeter_triangle(a,b,c)
area_t = math.sqrt(s*(s-a)*(s-b)*(s-c))
return area_t
def triangule_type(a,b,c):
if a < b and b < c:
print("if %d < %d < %d then is : " %(a,b,c),"Righ triangle")
elif a == b and b == c and c == a:
print("if %d = %d = %d then is : " % (a, b, c), "Equilateral triangle")
elif isosceles(a,b,c) != '':
print_t=isosceles(a,b,c)
print(print_t,"Triangle isosceles")
else:
print("Undefined triangle")
print("If you want to know the permiter -> option: 1\n If you want to know the area -> option: 2 \n Exit -> option: 0 ")
option = int(input("option -> "))
if option is 1:
print("Perimeter : %d " % (perimeter_triangle(a,b,c)))
elif option is 2:
print("Area : %d " %(area_triangle(a,b,c)))
else:
print("Thanks a lot, :) ")
print("----------- Determining the triangule and perimeter or area ----------")
side_one = int(input("Enter the first side: "))
side_two = int(input("Enter the second side: "))
side_three = int(input("Enter the third side: "))
triangule_type(side_one,side_two,side_three)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.