blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bae66fd1190c013b7091d34e74ab5f271bb1c2df | caseyprogramming/Intro-to-Python-Programming | /GuessingGameAI.py | 1,107 | 3.828125 | 4 | #Python 2.7
import random
gameActive = True
#this can be used to make sure the player isnt cheating
userNumber = input("Please give me a number to guess: ")
userInput = input("What is the maximum range, 1 to ___? ")
computerGuess = random.randint(1,userInput)
ceiling = 100
floor = 0
print "Is your number " + str(computerGuess)
while gameActive:
comparison = raw_input("Tell me too high with >, too low with <, or y if I got it! \n")
if(comparison == ">"):
ceiling = computerGuess
computerGuess = (ceiling + floor)/2
#computerGuess = (computerGuess-floor)/2
#computerGuess = computerGuess + floor
print(computerGuess)
continue
elif (comparison == "<"):
floor=computerGuess
computerGuess = ((ceiling+floor)/2)
#computerGuess = computerGuess+floor
print(computerGuess)
continue
elif (comparison == "y"):
print("Thank You for playing!")
gameActive = False
else:
print("Please enter an accepted input!!!")
continue
|
410ef287fbcdab73b4f3e3d1567bcbd76ee998aa | nascarsayan/lintcode | /677.py | 1,112 | 3.640625 | 4 | from collections import deque
class Solution:
"""
@param grid: a 2d boolean array
@param k: an integer
@return: the number of Islands
"""
def numsofIsland(self, grid, k):
# Write your code here
try:
nr, nc = len(grid), len(grid[0])
except IndexError:
return 0
isls = 0
visited = [[False] * nc for _ in range(nr)]
for ir in range(nr):
for ic in range(nc):
if grid[ir][ic] == 0 or visited[ir][ic]:
continue
que, sz = deque([(ir, ic)]), 0
visited[ir][ic] = True
while (que):
jr, jc = que.popleft()
sz += 1
for dr, dc in [(0, -1), (-1, 0), (0, 1), (1, 0)]:
kr, kc = jr + dr, jc + dc
if not (0 <= kr < nr and
0 <= kc < nc) or visited[kr][kc] or grid[kr][kc] == 0:
continue
que.append((kr, kc))
visited[kr][kc] = True
if sz >= k:
isls += 1
return isls
print(Solution().numsofIsland(
[[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]], 2))
|
769e589afad3c538ae643ae24981eec3a8a1dca6 | eoriont/machine-learning | /src/graphs/graph.py | 1,841 | 3.5625 | 4 | from node import Node
class Graph:
def __init__(self, edges, vertices=None):
self.nodes = [Node(i, value=v) for i, v in enumerate(vertices)]
for x, y in edges:
self.nodes[x].set_neighbor(self.nodes[y])
def depth_first_search(self, starting_index):
return self.nodes[starting_index].depth_first_search([])
def breadth_first_search(self, starting_index):
queue, result = [self.nodes[starting_index]], []
while len(queue) > 0:
next_val = queue.pop()
queue[:0] = [
node for node in next_val.neighbors if node not in queue+result]
result.append(next_val)
return [node.index for node in result]
def calc_distance(self, p1, p2):
gens, current_gen = 0, [p1]
while p2 not in current_gen:
current_gen = list(
{node.index for i in current_gen for node in self.nodes[i].neighbors})
gens += 1
return gens
def calc_shortest_path(self, p1, p2):
layers = [[self.nodes[p1]]]
self.nodes[p1].set_parent(None)
current_layer = 0
while p2 not in [x.index for l in layers for x in l]:
new_layer = []
for node in layers[current_layer]:
for neighbor in node.neighbors:
if neighbor.index not in [x.index for l in layers for x in l]:
neighbor.set_parent(node)
new_layer.append(neighbor)
layers.append(new_layer)
current_layer += 1
return self.get_path_recursive(self.nodes[p2])
def get_path_recursive(self, node, path=None):
path = [] if path is None else path
return self.get_path_recursive(node.parent, [node.index]+path) if node.parent is not None else [node.index]+path
|
8cb29059defb808bd0b053a807991665e39a2574 | tsabz/python_practice | /functions.py | 277 | 3.859375 | 4 | # to write a function start with def
def say_hi(name):
print("hello " + name)
# print("Top")
say_hi("tonia")
# print("Bottom")
# list = [5, 2, 3, 1, 4]
def order_list(arr):
arr.sort()
arr.append(2)
# arr.count(2)
print(arr)
order_list([5, 2, 3, 1, 4]) |
75b6c90c7727681316416185103a75a1c5f32247 | xiaochuanjiejie/python_exercise | /Exercise/15-18/exercise_13.10.py | 950 | 3.609375 | 4 | #-*- coding: utf-8 -*-
class PerlArray(object):
def __init__(self,li=[]):
self.li = li
def empty(self):
if len(self.li) == 0:
return 1
else:
return 0
def shift(self):
if self.empty():
print '空数组'
else:
print 'remove [',self.li[0],']'
self.li.remove(self.li[0])
def unshift(self,value):
print '在首位插入新值',value
self.li.insert(0,value)
def push(self,value):
print '在队尾插入新值',value
self.li.append(value)
def pop(self):
if self.empty():
print '空数组'
else:
print 'remove: [',self.li.pop(),']'
def listall(self):
print self.li
if __name__ == '__main__':
p = PerlArray([1,2,3,'q'])
p.shift()
p.listall()
p.unshift(111)
p.listall()
p.push('qq')
p.listall()
p.pop()
p.listall() |
c0bbb9e98cebedae5041fdc2a2f5081456031571 | thiagocharao/tw-galaxy-convert | /resources.py | 904 | 3.875 | 4 | from exception import UnknownResource
class Resource(object):
"""Represents a resource
Attributes:
credits_per_unit (float): Amount of credits per galaxy unit
"""
credits_per_unit = 0
def __init__(self, credits_per_unit=0):
self.credits_per_unit = credits_per_unit
@staticmethod
def factory(type):
"""Factory method to create a given type of Resource
Args:
type (str): Resource type name.
Returns:
An instance of a Resource Type.
Raises:
UnknownResource if no type found.
"""
if type == "Silver":
return Silver()
if type == "Gold":
return Gold()
if type == "Iron":
return Iron()
raise UnknownResource(type)
class Silver(Resource):
pass
class Gold(Resource):
pass
class Iron(Resource):
pass
|
8a6752a6dd39b1e61af963340af98cb35ff8f293 | z1223343/Leetcode-Exercise | /134_109_ConvertSortedListtoBinarySearchTree.py | 2,595 | 3.5 | 4 | """
1. Recursion
2. Recursion + Conversion toArray
3. Inorder Simulation (有点骚)
time space
1. O(NlogN) O(logN)
2. O(N) O(N)
3. O(N) O(logN)
"""
# solution 1:
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
if not head:
return None
mid = self.findMiddle(head)
node = TreeNode(mid.val)
if head == mid:
return node
node.left = self.sortedListToBST(head)
node.right = self.sortedListToBST(mid.next)
return node
def findMiddle(self, head):
prePtr = None
slowPtr = head
fastPtr = head
while fastPtr.next.next is not None:
prevPtr = slowPtr
slowPtr = slowPtr.next
fastPtr = fastPtr.next.next
if prePtr:
prePtr.next = None
return slowPtr
# solution 2:
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def mapListToValues(head):
vals = []
while head:
vals.append(head.val)
head = head.next
return vals
def convertListtoBST(left, right):
if left > right:
return None
mid = left + (right - left) // 2
node = TreeNode(values[mid])
node.left = convertListtoBST(left, mid - 1)
node.right = convertListtoBST(mid + 1, right)
return node
values = mapListToValues(head)
root = convertListtoBST(0, len(values) - 1)
return root
# solution 3:
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
size = self.findSize(head)
def convert(l, r):
nonlocal head
if l > r:
return None
mid = (l + r) // 2
left = convert(1, mid - 1)
node = TreeNode(head.val)
node.left = left
head = head.next
node.right = convert(mid + 1, r)
return node
return convert(0, size - 1)
def findSize(self, head):
ptr = head
c = 0
while ptr:
ptr = ptr.next
c += 1
return c
"""
==用于判断数值是否相等,因此对于六大基本数据类型而言,相同的值即可判定相等。而对于其他类的实例化对象而言,
存储和比较的可以认为是内存地址或者id,因此此时即使拥有相同属性也会因为id不同而被判定为不相等。
is,这是用于直接比较二者的地址是否相同
""" |
920174306a7f30463c9c4d73906f62773361aaad | JonesQuito/estudos_de_python | /cursos/EXERCICIOS_PYTHON_EXCRIPT/exercicios/TiposDeDados.py | 803 | 4.28125 | 4 | num_int = 5
num_dec = 10.5
val_str = "um texto qualquer"
"""
print(type(num_int))
print(type(num_dec))
print(type(val_str))
"""
print("\n")
print("O valor de 'num_int' é:",num_int) #Concatenamos um texto com outro valor qualquer usando uma vírgula para separá-los
print("O valor de 'num_int' é: %i" %num_int) # Usando os marcadores de porcetagem para concatenar str com outros tipos de dados
print("O valor de 'num_int' é: " + str(num_int)) # converte um valor inteiro em str e concatena com o texto anterior
print("\n")
print("Concatenando decimal: ", num_dec)
print("Concatenando decimal: %.2f" %num_dec)
print("Concatenando decimal: " + str(num_dec))
print("\n")
print("Concatenando Strings:", val_str)
print("Concatenando Strings: %s" %val_str)
print("Concatenando Strings: " + str(val_str))
|
ee909e994807a6d44501cee466150de50af4dc23 | matheusmcz/Pythonaqui | /Mundo2/ex043.py | 441 | 3.84375 | 4 | from math import pow
nome = str(input('Insira seu nome: ')).strip().lower()
altura = float(input('Altura: '))
peso = float(input('Peso:'))
imc = peso / pow(altura, 2)
print('Paciente: {}'.format(nome.title()))
if imc <= 18.5:
print('Abaixo do Peso.')
elif 18.5 < imc <= 25:
print('Peso Ideal.')
elif 25 < imc <= 30:
print('Sobrepeso.')
elif 30 < imc <= 40:
print('Obesidade.')
elif imc > 40:
print('Obesidade Mórbida.')
|
32c2d3bc8f5282f81777e94aa1af4d18a2298f81 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4322/codes/1602_1014.py | 85 | 3.5 | 4 | TotalDeVendas = float(input("valor da venda?"))
print(round(TotalDeVendas * 0.3, 2))
|
8f752a1d9fdde3085794d9524dde9b695716c403 | kaydee0502/Data-Structure-and-Algorithms-using-Python | /DSA/Queue/queue_ll.py | 1,561 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 21:07:12 2020
@author: KayDee
"""
class Node():
def __init__(self,data):
self.data = data
self.next = None
class Queue():
def __init__(self,size):
self.first = None
self.last = None
self.size = size
self.length = -1
def enqueue(self,val):
addnode = Node(val)
if self.last == None:
self.first = addnode
self.last = addnode
self.length += 1
return
if self.length == self.size:
print("Queue is full")
return
self.last.next = addnode
self.last = addnode
self.length += 1
def dequeue(self):
if self.first == None:
print("Queue is empty")
return
if self.first.next == None:
a = self.first.data
self.first = None
self.length -= 1
return a
active = self.first.data
self.first = self.first.next
self.length -= 1
return active
def peek(self):
return self.last.data
def printQ(self):
temp = self.first
while temp:
print(temp.data,"-> ",end="")
temp = temp.next
Q = Queue(5)
'''Q.enqueue(3)
Q.enqueue(4)
Q.enqueue(5)
Q.enqueue(6)
Q.enqueue(89)
Q.dequeue()
Q.dequeue()
Q.enqueue(85)
Q.dequeue()
Q.printQ() ''' |
b97351b554c1e98334a7c9ca229e43292c66dcaf | vinoroy/homeBakedPi | /app/dateTimeConversion.py | 2,495 | 4.0625 | 4 | #!/usr/bin/env python
"""
@author: Vincent Roy [*]
This module contains functions to convert a datetime object into a
datenumber and back to a datetime object. The datenumber system is based on the Excel
datenumber system which sets datenumber 0 equivalent to 1900\01\00
"""
from __future__ import division
from datetime import datetime
from datetime import timedelta
def conDateTimeToNum(dateToBeConv):
"""
Converts date object into a datenumber of the Excel datenumber system (1900/01/00)
Args :
- dateToBeConv : (datetime) date to be converted
Returns :
- dateNum : (float)
"""
dateOrigin = datetime(1899, 12, 31)
delta = dateToBeConv - dateOrigin
dateNum = float(delta.days) + (float(delta.seconds) / 86400)
return dateNum
def conNumToDateTime(dateNum):
"""
Converts a date number back to a date object
Args :
- dateNum : (float) date number to be converted to a date object
Return :
- dateObj : (datetime) date time object of the date number
"""
dateOrigin = datetime(1899, 12, 31)
delta = timedelta(days=dateNum)
dateObj = dateOrigin + delta
return dateObj
def conNumToNumDateGregorian(dateNum):
"""
Converts a date number of the excel datenumber system (1900-01-01) to the Gregorian date (0000-01-01)
Args :
- dateNum : (float) date number to be converted to Gregorian date number
Return :
- dateNum : (float) date number to be converted to Gregorian date number
"""
# add the number of days since the birth of christ 0000 01 01
dateNum = dateNum +693594
return dateNum
def conDateNumToDateStr(dateNum):
"""
Converts a date number to a date in string format
Args :
- dateNum (float) date number to be converted to a string representation of the date
Return :
- (string) string representation of the date
"""
return conNumToDateTime(dateNum).strftime("%Y-%m-%d %H:%M:%S")
def nowInHours():
"""
Helper function to get the current time in decimal hours
"""
curDateTime = datetime.now()
curHr = curDateTime.hour
curMin = curDateTime.minute
curSec = curDateTime.second
curTimeDecimalHours = curHr + curMin/60 + curSec/3600
return curTimeDecimalHours
if __name__ == "__main__":
print 'Decimal hrs : ' + str(nowInHours())
print 'Decimal days : ' + str(conDateTimeToNum(datetime.now()))
|
53f709efcc1fc23132797108ebf58f05edd9437a | k200x/algo_practice | /medium/first_duplicate_value.py | 283 | 3.90625 | 4 | def firstDuplicateValue(array):
queue_list = list()
for i in array:
if i in queue_list:
return i
else:
queue_list.append(i)
return -1
if __name__ == '__main__':
arr = [2, 1, 5, 2, 3, 3, 4]
print(firstDuplicateValue(arr))
|
d44791828bc2896fb05779c120ab5441b79af228 | leleluv1122/Python | /py1/0603/0604-1.py | 254 | 3.90625 | 4 | # 처음 - 끝 효과적이지못함
def linearSearch(lst, key):
for i in range(len(lst)):
if key == lst[i]:
return i
return -1
lst = [1,4,4,2,5,-3,6,2]
i = linearSearch(lst, 4)
print(i)
j = linearSearch(lst, -4)
print(j) |
fbd8021cb0e543c3310cbca60af12fe3850412ce | coolcrazycool/python_developer | /main.py | 2,732 | 3.5625 | 4 | from array import array
class Arr:
def __init__(self, element_type, *elements):
self.el_type = element_type
self.data = array(element_type, elements)
def __getitem__(self, item):
if isinstance(item, slice):
return self.data[item]
else:
return self.data[item]
def __delitem__(self, key):
del self.data[key]
def __setitem__(self, key, value):
for i in range(len(self.data)):
if self.data[i] == key:
self.data[i] = value
def __len__(self):
return len(self.data)
def __contains__(self, item):
for i in range(len(self.data)):
if self.data[i] == item:
return True
return False
def __iter__(self):
return Iterator(self.data)
def __reversed__(self):
return Iterator(self.data, -1)
def index(self, item):
for i in range(len(self.data)):
if self.data[i] == item:
return i
return -1
def count(self, item):
counter = 0
for i in range(len(self.data)):
if self.data[i] == item:
counter += 1
return counter
def insert(self, position, item):
sec_array = [_ for _ in self.data[position::]]
second_part = Arr(self.rtype, *sec_array)
fir_array = [_ for _ in self.data[:position:]]
first_part = Arr(self.rtype, *fir_array)
new_array = Arr(self.rtype, *first_part, *item, *second_part)
self.data = new_array
@property
def rtype(self):
return self.el_type
def append(self, item):
new_array = Arr(self.rtype, *self.data, item)
self.data = new_array
def extend(self, item):
new_array = Arr(self.rtype, *self.data, *item)
self.data = new_array
def clear(self):
for i in range(len(self.data) - 1, -1, -1):
del self.data[i]
def pop(self, item):
last = self.data[item]
del self.data[item]
return last
def remove(self, item):
del self.data[item]
def isEmpty(self):
return self.data == []
class Iterator:
def __iter__(self):
return self
def __init__(self, collection, cursor=1):
self.collection = collection
self.cursor = cursor
if cursor == 1:
self._cursor = -1
self.step = 1
if cursor == -1:
self._cursor = len(self.collection)
self.step = -1
def __next__(self):
self._cursor += self.step
if self._cursor < 0 or self._cursor >= len(self.collection):
raise StopIteration()
return self.collection[self._cursor]
|
5e978694991902734968a0c73d665f90fbcbf760 | ismailsinansahin/PythonAssignments | /Assignment_04/Question_12.py | 547 | 4.21875 | 4 | package = input("What is your package: A, B, or C --> ")
hours = int(input("How many hours did you use internet this month: "))
if package == 'A' or package == 'a':
if hours > 10:
charge = 9.95 + (2 * (hours-10))
else:
charge = 9.95
elif package == 'B' or package == 'b':
if hours > 20:
charge = 13.95 + (1 * (hours - 20))
else:
charge = 13.95
elif package == 'C' or package == 'c':
charge = 19.95
else:
print("Invalid input")
print(f"Your charge for Package {package} is : $", charge) |
d021495427f2fc2f5b4436a20bc58d8225058274 | Karl8/PythonCNN | /codes/network.py | 2,111 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
class Network(object):
def __init__(self):
self.info = []
self.layer_list = []
self.params = []
self.num_layers = 0
def add(self, layer):
self.layer_list.append(layer)
self.num_layers += 1
self.info.append(layer.info)
def forward(self, input):
output = input
for i in range(self.num_layers):
output = self.layer_list[i].forward(output)
return output
def backward(self, grad_output):
grad_input = grad_output
for i in range(self.num_layers - 1, -1, -1):
grad_input = self.layer_list[i].backward(grad_input)
def update(self, config):
for i in range(self.num_layers):
if self.layer_list[i].trainable:
self.layer_list[i].update(config)
def show(self):
img = self.layer_list[1].digit_data
n, c, h, w = img.shape
img = img[0:4,:,:,:].reshape([-1, h, w])
vis_square(img)
plt.savefig('../result/digit.png')
#vis_square(self.layer_list[0].output_data.reshape)
def vis_square(data):
"""Take an array of shape (n, height, width) or (n, height, width, 3)
and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)"""
# normalize data for display
data = (data - data.min()) / (data.max() - data.min())
# force the number of filters to be square
n = int(np.ceil(np.sqrt(data.shape[0])))
padding = (((0, n ** 2 - data.shape[0]),
(0, 1), (0, 1)) # add some space between filters
+ ((0, 0),) * (data.ndim - 3)) # don't pad the last dimension (if there is one)
data = np.pad(data, padding, mode='constant', constant_values=1) # pad with ones (white)
# tile the filters into an image
data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
plt.imshow(data); plt.axis('off')
|
be051315c65036c7ecbbbf3749f2176d4be9e365 | jxie0755/Learning_Python | /LeetCode/LC520_detect_capital.py | 1,690 | 4.125 | 4 | # LC520 Detect Capital
# Easy
# Given a word, you need to judge whether the usage of capitals in it is right or not.
# We define the usage of capitals in a word to be right when one of the following cases holds:
# All letters in this word are capitals, like "USA".
# All letters in this word are not capitals, like "leetcode".
# Only the first letter in this word is capital if it has more than one letter, like "Google".
# Otherwise, we define that this word doesn't use capitals in a right way.
#
# Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
# """
# :type word: str
# :rtype: bool
# """
class Solution:
def detectCapitalUse(self, word):
# check condition
if all(i.isupper() for i in word) or all(i.islower() for i in word):
return True
elif word[0].isupper() and word[1:].islower():
return True
else:
return False
def detectCapitalUse(self, word):
# compare method
return word == word.upper() or word == word.lower() or word == word.title()
def detectCapitalUse(self, word):
# compare method, two conditions
return word[1:] == word[1:].lower() or word == word.upper()
if __name__ == "__main__":
assert Solution().detectCapitalUse("USA") == True, "all up"
assert Solution().detectCapitalUse("FlaG") == False, "up in elsewhere"
assert Solution().detectCapitalUse("Flag") == True, "Title like"
assert Solution().detectCapitalUse("flag") == True, "all low"
assert Solution().detectCapitalUse("a") == True, "one low"
assert Solution().detectCapitalUse("A") == True, "one up"
print("All passed")
|
f64782317bf7504fdb0b437fcb2703a77bf8dfec | dmbee/seglearn | /examples/plot_nn_training_curves.py | 3,031 | 3.625 | 4 | """
=======================================
Plotting Neural Network Training Curves
=======================================
This is a basic example using a convolutional recurrent neural network to learn segments directly from time series data
"""
# Author: David Burns
# License: BSD
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.python.keras.layers import Dense, LSTM, Conv1D
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.wrappers.scikit_learn import KerasClassifier
from pandas import DataFrame
from sklearn.model_selection import train_test_split
from seglearn.datasets import load_watch
from seglearn.pipe import Pype
from seglearn.transform import Segment
##############################################
# Simple NN Model
##############################################
def crnn_model(width=100, n_vars=6, n_classes=7, conv_kernel_size=5,
conv_filters=3, lstm_units=3):
input_shape = (width, n_vars)
model = Sequential()
model.add(Conv1D(filters=conv_filters, kernel_size=conv_kernel_size,
padding='valid', activation='relu', input_shape=input_shape))
model.add(LSTM(units=lstm_units, dropout=0.1, recurrent_dropout=0.1))
model.add(Dense(n_classes, activation="softmax"))
model.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy'])
return model
##############################################
# Setup
##############################################
# load the data
data = load_watch()
X = data['X']
y = data['y']
# split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# create a segment learning pipeline
pipe = Pype([('seg', Segment(width=100, step=100, order='C')),
('crnn', KerasClassifier(build_fn=crnn_model, epochs=4, batch_size=256,
verbose=0, validation_split=0.2))])
##############################################
# Accessing training history
##############################################
# this is a bit of a hack, because history object is returned by the
# keras wrapper when fit is called
# this approach won't work with a more complex estimator pipeline, in which case
# a callable class with the desired properties should be made passed to build_fn
pipe.fit(X_train, y_train)
history = pipe.history.history
print(DataFrame(history))
# depends on version
if 'accuracy' in history:
ac_train = history['accuracy']
ac_val = history['val_accuracy']
elif 'acc' in history:
ac_train = history['acc']
ac_val = history['val_acc']
else:
raise ValueError("History object doesn't contain accuracy record")
epoch = np.arange(len(ac_train)) + 1
##############################################
# Training Curves
##############################################
plt.plot(epoch, ac_train, 'o', label="train")
plt.plot(epoch, ac_val, '+', label="validation")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
|
59b0c7f955c1396bd9c842f07e71eabd5f51d398 | SaveliiLapin/learning_projects | /4_xor.py | 251 | 3.90625 | 4 | def xor(xx, yy):
if xx:
if yy:
return 0
else:
return 1
else:
if yy:
return 1
else:
return 0
x = int(input())
y = int(input())
print(xor(x, y))
|
c00bb8733591a6e8f0167ddf82553367d2cf6820 | tnakaicode/jburkardt-python | /geometry/line_imp2exp.py | 2,346 | 3.65625 | 4 | #! /usr/bin/env python
#
def line_imp2exp ( a, b, c ):
#*****************************************************************************80
#
## LINE_IMP2EXP converts an implicit line to explicit form in 2D.
#
# Discussion:
#
# The implicit form of line in 2D is:
#
# A * X + B * Y + C = 0
#
# The explicit form of a line in 2D is:
#
# ( P1, P2 ).
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 21 July 2018
#
# Author:
#
# John Burkardt
#
# Reference:
#
# Adrian Bowyer and John Woodwark,
# A Programmer's Geometry,
# Butterworths, 1983.
#
# Parameters:
#
# Input, real A, B, C, the implicit line parameters.
#
# Output, real P1(2), P2(2), two points on the line.
#
import numpy as np
from sys import exit
normsq = a * a + b * b
if ( normsq == 0.0 ):
print ( '' )
print ( 'LINE_IMP2EXP - Fatal error!' )
print ( ' A * A + B * B = 0.' )
exit ( 'LINE_IMP2EXP - Fatal error!' )
p1 = np.zeros ( 2 )
p2 = np.zeros ( 2 )
p1[0] = - a * c / normsq
p1[1] = - b * c / normsq
if ( abs ( b ) < abs ( a ) ):
p2[0] = - ( a - b / a ) * c / normsq
p2[1] = - ( b + 1.0 ) * c / normsq
else:
p2[0] = - ( a + 1.0 ) * c / normsq
p2[1] = - ( b - a / b ) * c / normsq
return p1, p2
def line_imp2exp_test ( ):
#*****************************************************************************80
#
## LINE_IMP2EXP_TEST tests LINE_IMP2EXP.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 21 July 2018
#
# Author:
#
# John Burkardt
#
from line_exp2imp import line_exp2imp
from r8vec_print import r8vec_print
print ( '' )
print ( 'LINE_IMP2EXP_TEST' )
print ( ' LINE_IMP2EXP converts implicit to explicit lines.' )
a = 1.0
b = 2.0
c = 3.0
print ( '' )
print ( ' Implicit line A, B, C = %f %f %f' % ( a, b, c ) )
p1, p2 = line_imp2exp ( a, b, c )
r8vec_print ( 2, p1, ' The point P1:' )
r8vec_print ( 2, p2, ' The point P2:' )
a, b, c = line_exp2imp ( p1, p2 )
print ( ' Recovered A, B, C = %f %f %f' % ( a, b, c ) )
#
# Terminate.
#
print ( '' )
print ( 'LINE_IMP2EXP_TEST:' )
print ( ' Normal end of execution.' )
return
if ( __name__ == '__main__' ):
from timestamp import timestamp
timestamp ( )
line_imp2exp_test ( )
timestamp ( )
|
c7e67402418367eace4403cefd8f5f1cae2e510a | ishantk/GW2020P1 | /Session20F.py | 973 | 3.78125 | 4 | import os
print(os.name)
print(os.uname())
print(os.getlogin())
print(os.getppid()) # Process Id in which this program is getting executed
print("Current Working Directory:", os.getcwd())
path_to_directory = "/Users/ishantkumar/Downloads"
path_to_file = "/Users/ishantkumar/Downloads/key.json"
print("Downloads Directory Exists?", os.path.isdir(path_to_directory))
print("key.json File Exists?", os.path.isfile(path_to_file))
files = os.walk(path_to_directory)
all_files = list(files)
for file in all_files:
print(file)
# explore -> mkdir (make a directory) and rmdir (remove directory) | PS: use rmdir very carefully
# Assignment: Using os.walk, walk in some directory and pull below information
# show Documents and count of documents (.pdf, .doc, .docx, .txt)
# show images and count of images (.jpg, .png, .jpeg)
# show audio/video and count of audio/video (.mp3, .mp4 etc..) |
0be041124b4aea04e7e97676c91cc627a8863ea2 | Abhi2285/icdstest | /carprking.py | 203 | 3.6875 | 4 | #print("My First Python code")
#5Earningfortheday=0
Earningfortheday = input("Enter the earning: ")
print(Earningfortheday)
if int(Earningfortheday) > 500:
print("profitable")
else:
print("Loss") |
5d03047ccf7aef5a6c335d51bc82a5ffe96005d4 | uabinf/nlp-group-project-fall-2020-disneyqanda | /disneyqanda/local_dependencies/quest_processing/focus.py | 1,279 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# Function to get head words, to find the focus of the question being asked
# import spaCy for dependency parsing
import en_core_web_sm
nlp = en_core_web_sm.load()
def q_head_words(q):
# Use en_core_web_sm for dependency parsing
doc = nlp(q)
words = [(x.text, x.pos_, x.head.text, x.dep_) for x in doc]
print("Dependency parsing:___________________________\n", words,"\n")
# Get the root word
root_word = [x[0] for x in words if x[3] == "ROOT"]
print("Root word:", root_word,"\n")
# Get words dependent on the root word
dep_on_root = [x[0] for x in words if x[2] == root_word[0]]
print("Words dependent on root:", dep_on_root,"\n")
# Get nouns dependent on the root word
nouns = [x[0] for x in words if x[1] == "NOUN" and x[0] in dep_on_root]
print("Nouns dependent on root:", nouns,"\n")
# Get adjectives describing it or nouns making it compound
add_words = [x[0] for x in words if x[2] in nouns and x[3] in ["compound","ADJ"]]
print("Words related to those nouns:", add_words, "\n")
head_words = add_words + nouns
if not head_words:
head_words = root_word
print("Head words found:\n", head_words, "\n")
return head_words
|
5bfd8f9c029b70a035f67d119b8ff0492c27e089 | radiosd/csvDataBase | /rgrCsvData/csvDataBase.py | 9,526 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Access to csv database
CsvItem A line in the file held as a dict with the heading
used as the keys
CsvDataBase A list of CsvItems read from a csv file
All items that are not under a heading are grouped
together into a list using the last heading name.
rgr01jul17
"""
from __future__ import print_function
import logging
logger = logging.getLogger(__name__)
from collections import OrderedDict
import re
class CsvItem(OrderedDict):
def __init__(self, keys):
"""Initiate a blank ordered dict with the last item as a list
keys : list of strings that are the keys"""
_entry = [(k, '') for k in keys]
self.length = len(keys)
super(CsvItem, self).__init__(_entry)
self[keys[-1]] = []
def read(self, values):
"""Read values into the keys in the order given. Any missing at the end
are left blank and any excess are mereged into the last list item
values : list, any excess white space will be stripped off"""
logger.debug(values)
values = [x for x in values if len(x)>0]
keys = list(self.keys())
end = keys.pop(-1)
n = len(keys)
(fixed, variable) = values[:n], values[n:]
for key, value in zip(keys, fixed):
self[key] = value
self[end] = []
for v in variable:
self[end].append(v)
return self
def isList(self, key):
"""indicate if the key is the last one, which is always a list"""
logger.debug('key position '+str(self.keys().index(key)))
return self.keys().index(key)-self.length==-1
def valueStrf(self, key, width='0'):
"""return the value for the key in the given field width"""
# longer values are truncated to fit
# default 0 gives the minimum required width keyStrf
value = self[key] # exact key name needed
w = len(value) if width=='0' else int(width)
if w<6:
# after inserting padding there is nothing left - so KISS
value = value[:w]
elif w<len(value):
padding = ' .'+w%3*'.'+' '
# this goes wrong if w<6 because w3=0
w3 = (w - len(padding))/3
logger.debug('splitting: '+value+' at '+str(w3))
value = value[:2*w3]+padding+value[-w3:]
logger.debug('format using: '+'{:'+str(w)+'}')
return ('{:'+str(w)+'}').format(value)
def write(self): # no tests set
"""output in the key_order given by the csv database"""
output = []
for key in self.iterkeys():
_item = self[key]
if isinstance(_item, list):
[output.append(x) for x in _item]
else:
output.append(_item)
return output
def output(self, *args): # no tests set
if len(args) == 0:
args = self.keys()
max_key = max(len(a) for a in args)
key_format = '{{:{:n}s}}'.format(max_key + 1)
ans = []
for key in args:
ans.append((key_format+' {:s}').format(key+':', str(self[key])))
return '\n'.join(ans)
def pick(self, *fields):
"""return a list of just the values of fields given in *fields"""
# exact field names are expected
# have to expand the list field if needed
return [' '.join(self[x]) if self.isList(x) else self[x]
for x in fields if x in self.keys()]
def extract(self, *fields):
"""return a dict of the fields given in *fields"""
return {f:self[f] for f in fields}
from os import path
import csv, shutil
from rgrLib.fileUtils import changeExt
class CsvDataBase(list):
def __init__(self, f_name, itemClass=CsvItem):
self.field_names = None
self.itemClass = itemClass
## self.indexed = None # the field used to build the index
self.index = None
self.time_stamp = None # fields used to control backup
# what if filename doesn't exist?
self.filename = changeExt(f_name, 'csv')
self.load()
def __repr__(self):
"""DB can be v big, so simplified repr"""
return '<class CsvDataBase>'
def load(self):
self._load(self.filename)
def getFileTimeStamp(self):
"""return the current time stamp of the DB cvs file"""
return path.getmtime(self.filename)
def _load(self, f_name):
"""general load to allow other files to be used"""
logger.debug('loading: \t'+f_name)
with open(f_name, 'r') as fin:
self.time_stamp = path.getmtime(f_name)
reader = csv.reader(fin)
self.field_names = [x for x in reader.next() if len(x)>0]
for each in reader:
_item = self.itemClass(self.field_names)
self.append(_item.read(each))
logger.info('loaded '+str(len(self))+' records')
def _save(self, f_name, order_by=None):
if f_name==self.filename: # make a back backup
_new_time_stamp = path.getmtime(f_name)
# use a zero value to over-ride this
if self.time_stamp!=0 and _new_time_stamp>self.time_stamp:
logger.warning('csv file has changed since it was opened')
return
_back_up = changeExt(f_name, 'bak', True)
shutil.copy(f_name, _back_up)
logger.info('created back-up: '+_back_up)
if order_by is not None:
if self.field_names.count(order_by)>0:
self.sort(key = lambda x: x[order_by])
else:
self.sort(key=order_by)
try:
with open(f_name, 'wb') as fout:
writer = csv.writer(fout)
writer.writerow(self.field_names)
for each in self:
writer.writerow(each.write())
logger.info('saved '+str(len(self))+' records')
except IOError:
logger.info('IOError opening '+f_name+' permssion denied')
# re-stamp the in-memory data
self.time_stamp = self.getFileTimeStamp()
def save(self, order_by=None):
"""save in the order given, default is by the first field"""
self._save(self.filename, order_by)
def findKey(self, key, ignore_case=True, first=True):
"""given a text fragment, return an exact field name"""
r = re.compile(key, re.IGNORECASE if ignore_case else 0)
ans = filter(r.match, self.field_names)
if len(ans)>0 and first:
return ans[0]
elif len(ans)>0:
return ans
raise KeyError(key +' not in ' + str(self.itemClass))
def makeIndex(self, key, *fields):
"""save in index all items by key given holding just those fields"""
self.index = {x[key]:x.extract(*fields) for x in self}
def isIndexed(self):
"""return whether database has an index"""
return self.index is not None
def search(self, key, info, ignore_case=True):
"""regex search the DB for any reference to info in key provided"""
# keys can be abbreviated, uses a regex search for info
# returns a list, empty if no match
if len(self)==0:
return
_key = self.findKey(key, first=False)
if _key is None:
logger.warning('key: '+key+' not found')
return []
key = _key[0]
r = re.compile(info, re.IGNORECASE if ignore_case else 0)
# all items are the same so use [0] for test
if self[0].isList(key):
# search each item if the field is a list
return [x for x in self if filter(r.search, x[key])]
else:
return [x for x in self if r.search(x[key])]
def _show(self, index, formatted=False, *args):
if formatted:
fields = [[a, '0'] if len(a.split(':'))==1 else a.split(':')
for a in args]
ans = []
logger.debug('formatter: '+str(fields))
for f in fields:
key = self.findKey(f[0])
ans.append(self[index].valueStrf(key, f[1]))
print(' '.join(ans))
else:
print(self[index].output(*args))
def show(self, start, stop=None, *args):
"""print a list using the range and fileds given in the args"""
if len(args)==0:
args = self.field_names
# extra False for when args=[]
formatted = max([x.count(':')>0 for x in args], False)
if stop is None:
self._show(start, formatted, *args)
else:
for i in range(start, stop):
self._show(i, formatted, *args)
def test(f_name):
logger.info('\tre-testing using' + f_name)
return CsvDataBase(f_name)
if __name__=='__main__':
from sys import stdout
from time import strftime
#logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG)
logging.basicConfig(stream=stdout)
logger.level = logging.INFO
logger.info('\tstarting: '+path.basename(__file__)+'\t==='
+ strftime('%a-%d %H:%M') + ' ===')
cc = test('../test/CategoriesDB')
|
631e6d481c8e42781a98831736bc8ab72c2f0dfe | BaeNayeong/Algorithms | /Dynamic Programming/4_bottom_up_fibonacci.py | 147 | 3.65625 | 4 | d = [0]*100
def fibonacci(n):
d[1]=1
d[2]=1
for i in range(3, n+1):
d[i]=d[i-1]+d[i-2]
return d[n]
print(fibonacci(6)) |
d02ebbec43c4c23b6968c9348c931dd5c027cb3f | darya-ver/PhotomosaicCreater | /getSquare.py | 1,323 | 3.609375 | 4 | ####################
# getSquare.py
####################
from PIL import Image
import math
#
# converts the image into a square
#
# returns: [array of pixels of square image, size of new image]
#
# im: image that is being converted into sqaure
#
def squareImage(im):
# load the pixel data from im.
pixels = im.getdata()
# get the width and height of the current image
width, height = im.size
# will be set to the shortest dimension later on
newSize = 0
# create a list to hold the new image pixel data.
new_pixels = []
# if image is horizontal
if(width > height):
newSize = height
dif = (width - height) // 2
row = 0
while (row * width) < len(pixels):
rowIndex = row * width
for col in range(height):
i = row * width + dif + col
new_pixels.append(pixels[i])
row += 1
# if image is vertical
else:
newSize = width
dif = (height - width)//2
# moves past the first dif rows
i = width * dif
# copies over the next width rows
widthSqaured = width * width
for j in range(widthSqaured):
new_pixels.append(pixels[i])
i += 1
return [new_pixels, newSize]
|
2fb81e0776b2020a75ff280878c4c18238e8dadd | loftusa/playing-with-git | /james-powell-talk.py | 1,080 | 4.28125 | 4 | # dec.py
"""
0. run python file in console, open as environment
1. use dis to get information about method
2. look at byte code for method
3. look at default arguments for method
4. look at name of method
"""
# %%
# foo is a decorator which will add ', heckin.' to the sentence created by bar.
# bar is a method that will return "Hi, my name is x".
def foo(func):
def f(*args, **kwargs):
return func(*args, **kwargs) + ", heckin."
return f
@foo
def bar(x):
return "Hi, my name is {}".format(x)
@foo
def biff(x):
return str(x)
def print_goals():
print("""
0. run python file in console, open as environment
1. use dis to get information about method. This will tell you the exact stuff that the method is doing.
2. look at byte code for method
3. look at default arguments for method
4. look at name of method
""")
#%%
def testing_out_syntax(num1: int, num2: int, st: str) -> str:
return str('num1 + num2 = {} '.format(num1 + num2) + ', and the string is {}'.format(st))
print(testing_out_syntax(1, 2, 5)) |
05ad2579b6438516fbcee55ed6795943edd6c03f | syurskyi/Python_Topics | /070_oop/008_metaprogramming/_exercises/templates/abc_Abstract Base Classes/a_003_abc_subclass.py | 1,198 | 3.6875 | 4 | # # abc_subclass.py
#
# # Implementation Through Subclassing
# # Subclassing directly from the base avoids the need to register the class explicitly.
#
# ______ a..
# ____ a_001_abc_base ______ P..
#
#
# c_ SubclassImplementation P..
#
# ___ load input
# r_ i__.r..
#
# ___ save output data
# r_ o___.w.. d..
#
#
# __ ______ __ _____
# print('Subclass:', iss.. S..
# P...
# print('Instance:', isi...(S...
# P...
#
#
# # $ python3 abc_subclass.py
# #
# # Subclass: True
# # Instance: True
#
#
# # In this case, normal Python class management features are used to recognize SubclassImplementation as implementing
# # the abstract PluginBase.
#
# python 2
# # import abc
# # from abc_base import PluginBase
# #
# #
# # class SubclassImplementation(PluginBase):
# #
# # def load(self, input):
# # return input.read()
# #
# # def save(self, output, data):
# # return output.write(data)
# #
# #
# # if __name__ == '__main__':
# # print 'Subclass:', issubclass(SubclassImplementation, PluginBase)
# # print 'Instance:', isinstance(SubclassImplementation(), PluginBase)
|
302c3449f89640aabbf2c07263847106d3eeba51 | satyampandeygit/ds-algo-solutions | /Algorithms/Implementation/Almost Sorted/solution.py | 1,034 | 3.984375 | 4 | # input array size
input()
# input array elements
array = [int(x) for x in input().split(" ")]
# store the sorted array
sorted_array = sorted(array)
# If the array is already sorted, output yes on the first line
if array == sorted_array:
print("yes")
# If you can sort this array using one single operation out of the two permitted operations
# then output yes on the first line and then do as given in the instructions
else:
wrong = []
for i, (a, b) in enumerate(zip(array, sorted_array)):
if a != b:
wrong.append(i)
if len(wrong) > 2:
break
if len(wrong) == 2:
print("yes")
print("swap", wrong[0]+1, wrong[1]+1)
else:
index = sorted_array.index(array[wrong[0]])+1
if sorted_array[wrong[0]:index] == list(reversed(array[wrong[0]:index])):
print("yes")
print("reverse", wrong[0]+1, index)
# If you cannot sort the array either way print no on the first line
else:
print("no") |
04451784bb25fd576ac64f18b42a2d8d8939109c | Rishab9991/EE5609 | /Assignments/Assignment3/Assignment3.1/Assignment3.1.py | 1,286 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 16:08:45 2020
@author: Rishab
"""
'''import matplotlib.pyplot as plt'''
import math as m
''' Different inputs are used in .tex and .py files'''
a = [0,3]
b = [0,0]
c = [3,-0.5]
d = [3,5]
def distancebetn(P,Q):
return float(m.sqrt((Q[0]-P[0])**2 + (Q[1]-P[1])**2))
d1 = round(distancebetn(a,b),2)
d2 = round(distancebetn(b,c),2)
d3 = round(distancebetn(c,d),2)
d4 = round(distancebetn(d,a),2)
'''Since AB and CD are the smallest and largest sides in the quadrilateral. If that condition holds true then the problem can be solved'''
if(d1<d2 and d2<d4 and d4<d3):
print("AB and CD are the smallest and largest sides in the quadrilateral. Hence the problem can be solved.")
else:
print("The problem cannot be solved.")
'''
plt.plot(a[0],a[1],'o')
plt.text(0,3,'A')
plt.plot(b[0],b[1],'o')
plt.text(0,0,'B')
plt.plot(c[0],c[1],'o')
plt.text(3,-0.5,'C')
plt.plot(d[0],d[1],'o')
plt.text(3,5,'D')
x=[0,0,3,3]
y=[3,0,-0.5,5]
plt.plot(x,y,'ro')
def connect(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'k-')
connect(x,y,0,1)
connect(x,y,1,2)
connect(x,y,2,3)
connect(x,y,3,0)
plt.axis('equal')
plt.show()
'''
|
5404109d7442cddea0aa44b7ba148bb394868e04 | computerscienceioe/Lesson-14 | /Challenge 5.py | 1,993 | 3.609375 | 4 | students = ["John Smith","Jane Doe", "Mary Murphy", "Michael Lawlor", "Conor Whelan", "Kate Walsh", "Shane Duffy"]
ages = [16, 17, 18, 17, 18, 15, 19]
marks = [90, 88, 50, 60, 100, 75, 95]
zipped_lists = zip(students, marks)
sorted_pairs = sorted(zipped_lists)
tuples = zip(*sorted_pairs)
sorted_students, sorted_marks = [ list(tuple) for tuple in tuples]
# Part 2
import matplotlib.pyplot as plt
zipped_lists = zip(marks, students)
sorted_pairs = sorted(zipped_lists)
tuples = zip(*sorted_pairs)
sorted_marks, sorted_students = [ list(tuple) for tuple in tuples]
plt.bar(sorted_students, sorted_marks)
plt.savefig("1MarksAscending.png")
plt.show()
# Part 3
zipped_lists = zip(marks, students)
sorted_pairs = sorted(zipped_lists, reverse = True)
tuples = zip(*sorted_pairs)
sorted_marks, sorted_students = [ list(tuple) for tuple in tuples]
plt.bar(sorted_students, sorted_marks)
plt.savefig("2MarksDescending.png")
plt.show()
# Part 4
zipped_lists = zip(students, ages)
sorted_pairs = sorted(zipped_lists)
tuples = zip(*sorted_pairs)
sorted_students, sorted_ages = [ list(tuple) for tuple in tuples]
plt.plot(sorted_students, sorted_ages)
plt.savefig("3StudentsAlphabetical.png")
plt.show()
# Part 5
zipped_lists = zip(students, ages)
sorted_pairs = sorted(zipped_lists, reverse = True)
tuples = zip(*sorted_pairs)
sorted_students, sorted_ages = [ list(tuple) for tuple in tuples]
plt.plot(sorted_students, sorted_ages)
plt.savefig("4StudentsReverseAlphabetical.png")
plt.show()
# Part 6
zipped_lists = zip(ages, students)
sorted_pairs = sorted(zipped_lists)
tuples = zip(*sorted_pairs)
sorted_ages, sorted_students = [ list(tuple) for tuple in tuples]
plt.plot(sorted_students, sorted_ages)
plt.savefig("5AgesAscending.png")
plt.show()
# Part 7
zipped_lists = zip(ages, students)
sorted_pairs = sorted(zipped_lists, reverse = True)
tuples = zip(*sorted_pairs)
sorted_ages, sorted_students = [ list(tuple) for tuple in tuples]
plt.plot(sorted_students, sorted_ages)
plt.savefig("6AgesDescending.png")
plt.show()
|
030d4a2026e4d89e5828aaf228d534314f513854 | daniel-reich/ubiquitous-fiesta | /LgXMXThsKcYtdYHrb_11.py | 115 | 3.5 | 4 |
def split_and_delimit(txt, num, delimiter):
return delimiter.join(txt[a:a+num] for a in range(0,len(txt),num))
|
0d9cde392f0a05f5fb33236a03795565289975de | Ponkiruthika112/Guvi | /prime20.py | 691 | 3.625 | 4 | stack=[]
st=[]
list=[]
new_list=[]
new_list2=[]
list3=[]
for x in range(1,100):
c=0
for y in range(2,x):
if x%y==0:
c=1
if (c==0) and (x!=1) and (x!=2):
stack.append(x)
for x in stack:
sum=0
while x>0:
temp=x%10
sum=sum+temp
x=x/10
st.append(sum)
for x in st:
d=0
for y in range(2,x):
if x%y==0:
d=1
if (d==0) and (x!=2):
list.append(x)
for i in list:
if i not in new_list:
new_list.append(i)
else:
new_list2.append(i)
for i in new_list2:
if i not in list3:
list3.append(i)
print "It is the all prime number which is the sum of digit of the prime numbers below 100"
print (new_list)
print "Repeated prime numbers:"
print(list3)
|
3128b0b7d3f17c3f2a270f7916b784840eb9b587 | mxtdsg/interview | /longestCommonPrefix.py | 361 | 3.515625 | 4 | ####
#
# find the longest common prefix of a list of strs
#
# leetcode 14.
#
####
def longestCommonPrefix(strs):
if len(strs) == 0: return ""
minlength = min([len(st) for st in strs])
re = ""
for i in range(minlength):
for st in strs:
if st[i] != strs[0][i]:
return re
re += strs[0][i]
return re |
90d386972d19b62895d32ec74559d7385eb4cf54 | balloonio/algorithms | /lintcode/advanced_algorithm/4_sweep_line_binary_search/391_number_of_airplanes_in_the_sky.py | 833 | 3.6875 | 4 | """
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param airplanes: An interval array
@return: Count of airplanes are in the sky.
"""
def countOfAirplanes(self, airplanes):
# write your code here
if not airplanes:
return 0
events = [] # (timestamp, True for taking off/ False for landing)
for interval in airplanes:
take_off = (interval.start, True)
land = (interval.end, False)
events += [take_off, land]
events.sort()
result = 0
in_air = 0
for (time, take_off) in events:
in_air += 1 if take_off else -1
result = max(result, in_air)
return result
|
6c77382fb52578d6465e88289d67209650cd690b | mauung-sudo/python-exercises | /e6.py | 268 | 3.84375 | 4 | def computepay(hours,rate):
if hours > 40:
bonus_hr = hours - 40.0
bonus = bonus_hr * rate * 0.5
xp = hours * rate + bonus
else :
xp = hours * rate
print("Pay : " , xp)
computepay(float(input ("Enter Hours: ")), float(input ("Enter Rate: ")))
|
7ac0ace8b17c80af072aa80be36b1831684c91da | 1505069266/python- | /面向对象/静态方法.py | 1,015 | 4.125 | 4 | class Student:
name = ''
age = 0
# 一个班级里所有学生的总数
sum1 = 0
# 实例方法
def __init__(self, name, age):
# 构造函数 实例化的时候会运行这里的代码
self.name = name
self.age = age
self.__class__.sum1 += 1
print("当前班级人数:" + str(self.__class__.sum1))
# print('我是:' + name)
# print("我是:" + self.name)
# 行为与特征
def myNameAge(self):
print(self.name)
print(self.age)
@classmethod # 类方法 下面方法的参数为cls
def plus_sum(cls):
cls.sum1 += 1
print(cls.sum1)
@staticmethod # 静态方法
def add(x, y):
# print(self.sum1) # 报错
print('这是静态方法!')
# 模板
student1 = Student('zhuxiaole', 23)
Student.plus_sum()
Student.add(1, 2)
print(student1.__dict__) # 保存着student1中的所有变量
print(Student.__dict__) # 保存着Student中的所有变量和方法
|
3a0eaa713296fd01d25964d192dd6ce1756ac503 | thePortus/dhelp | /dhelp/text/_bases.py | 5,966 | 3.734375 | 4 | #!/usr/bin/python
import re
from collections import UserString
class BaseText(UserString):
"""Performs text manipulation and natural language processing.
Base class for all Text objects. Can be used on its own to perform a number
of operations, although it is best used with on of its language-specific
children.
Args:
text (:obj:`str`) Text to be stored for processing/nlp
options (:obj:`dict`, optional) Options settings found at respective keywords
Example:
>>> from dhelp import BaseText
>>> text = BaseText('Lorem ipsum dolor sit amet...')
>>> print(text)
'Lorem ipsum dolor sit amet...'
""" # noqa
options = {
'encoding': 'utf-8',
'language': 'english'
}
def __init__(self, text, *args, **kwargs):
super().__init__(str)
# update .options if options keyword arg passed
if 'options' in kwargs:
if type(kwargs['options']) == dict:
self.options.update(kwargs['options'])
self.data = text
def __enter__(self):
pass
def __exit__(self, ctx_type, ctx_value, ctx_traceback):
pass
def stringify(self):
"""Returns the text of this object as a pure string type.
Can be useful when you need the text back in a string object format
for comparison with regular strings.
Returns:
:obj:`str` String form of the text
Example:
>>> text = BaseText('Lorem ipsum dolor sit amet...')
>>> stringified_text = text.stringify()
>>> print(type(stringified_text))
<class 'str'>
"""
return str(self.data)
def rm_lines(self):
"""Removes endlines.
Gives a new version of the text with all endlines removed. Removes
any dashed line endings and rejoins split words.
Returns:
:obj:`self.__class__` New version of text, with endlines removed
Example:
>>> text = BaseText('Lorem\\nipsum do-\\nlor sit amet....\\n')
>>> modified_text = text.rm_lines()
>>> print(modified_text)
'Lorem ipsum dolor sit amet...'
"""
rexr = re.compile(r'\n+')
# substituting single endlines for matching endline blocks
clean_text = rexr.sub(' ', self.data)
return self.__class__(
clean_text
.replace('-\n ', '').replace('- \n', '').replace('-\n', '')
.replace(' - ', '').replace('- ', '').replace(' -', '')
.replace('\n', ' '),
self.options
)
def rm_nonchars(self):
"""Removes non-language characters.
Gives a new version of the text with only latin characters remaining,
or Greek characters for Greek, texts, and so on. Defaults to assuming
Latin based.
Returns:
:obj:`self.__class__` Returns new version of text, with non-letters removed
Example:
>>> text = BaseText('1αLorem ipsum 2βdolor sit 3γamet...')
>>> modified_text = text.rm_nonchars()
>>> print(modified_text)
'Lorem ipsum dolor sit amet...'
""" # noqa
if self.options['language'] == 'greek':
valid_chars_pattern = '([ʹ-Ϋά-ϡἀ-ᾯᾰ-῾ ])'
else:
valid_chars_pattern = '([A-Za-z ])'
return self.__class__(
"".join(re.findall(valid_chars_pattern, self.data)),
self.options
)
def rm_edits(self):
"""Removes text inside editor's marks.
Gives a new version with any text between editorial marks such as
brackets or parentheses removed.
Returns:
:obj:`self.__class__` Returns new version of text, with editoria removed
Example:
>>> text = BaseText('Lore[m i]psum {dolo}r sit a(met)...')
>>> modified_text = text.rm_edits()
>>> print(modified_text)
'Lor psum r sit a...'
""" # noqa
return self.__class__(
re.sub("\〚(.*?)\〛", "", re.sub("\{(.*?)\}", "", re.sub(
"\((.*?)\)", "", re.sub("\<(.*?)\>", "", re.sub(
"\[(.*?)\]", "", self.data))))),
self.options
)
def rm_spaces(self):
"""Removes extra whitespace.
Gives a new version of the text with extra whitespace collapsed.
Returns:
:obj:`self.__class__` Returns new version of text, with extra spaced collapsed
Example:
>>> text = BaseText('Lorem ipsum dolor sit amet...')
>>> modified_text = text.rm_spaces()
>>> print(modified_text)
'Lorem ipsum dolor sit amet...'
""" # noqa
# regex compiler for all whitespace blocks
rexr = re.compile(r'\s+')
# substituting single spaces for matching whitespace blocks
clean_text = rexr.sub(' ', self.data)
return self.__class__(
clean_text.strip(),
self.options
)
def re_search(self, pattern):
"""Search text for matching pattern.
Receives search pattern and returns True/False if it matches. Pattern
can be a simple string match (e.g. .re_search('does this match?')), or
a full Regular Expression.
Args:
pattern (:obj:`str`) String with the desired Regular Expression to search
Returns:
:obj:`bool` True if matching, False if not
Example:
>>> text = BaseText('Lorem ipsum dolor sit amet...')
>>> print(text.re_search('Lorem ipsum'))
True
>>> print(text.re_search('Arma virumque cano'))
False
""" # noqa
# Converting pattern to regex
pattern = re.compile(pattern)
if pattern.search(self.data):
return True
else:
return False
|
2f214aae5e30e4e01471a8a0f8cd0af1c401f0da | Aparecida-Silva/ProjetoAnimal | /Animal.py | 462 | 3.546875 | 4 | class Animal():
def __init__(self, nome, numMembros, habitat):
self.nome = nome
self.numMembros = numMembros
self.habitat = habitat
def mover(self):
print(self.nome + " movendo de forma genérica")
def comer(self):
print(self.nome + "comendo de forma genérica")
def __str__(self):
return "Nome: " + self.nome + ", numMembros: " + str(self.numMembros) + ", Habitat: " + self.habitat
|
68dff3090cd12f29fdb060bda651e8d355311e71 | 0xjojo/Exercise-Chapter-Eight-8.4 | /Exercise-Chapter-Eight-8.4.py | 407 | 3.6875 | 4 | #file_name = input ("Enter file:\n")
#file_hand = open(file_name , 'r')
file_hand = open( 'romeo.txt', 'r')
count = 0
words = []
smart_words = []
for line in file_hand :
words = line.split()
x = len(words)
while count < x :
if words[count] in smart_words :
count = count + 1
continue
smart_words.append(words[count])
count = count + 1
smart_words.sort()
print (smart_words)
|
9a637f31bbc919382f667c673390454e2d5abdef | colbydarrah/cis_202_book_examples | /CH7_list_if-clause_select_specific_pieces_of_loop.py | 1,164 | 4.25 | 4 | # Colby Darrah
# 3/23/2021
# IF CLAUSES pg 398
# Use "if-clause" to select only certain elements whne processing a list.
# this code only selects integers from the list taht are less than 10
def main():
#========================= NUMBERS ============================================
####### EXAMPLE ##############################
list1 = [1, 12, 2, 20, 3, 15, 4]
list2 = []
for n in list1:
# the "IF" statement appears inside for-loop causing
# code to only append elements that are <10 to list2.
if n < 10:
list2.append(n)
######## EXAMPLE USING COMPREHENSION #########
list1 = [1, 12, 2, 20, 3, 15, 4]
list2 = [item for item in list1 if item < 10]
# ===================== STRING =================================================
######## EXAMPLE #############################
# if clause selects only names that are less than 6 characters long
last_names = ['jackson', 'smith', 'hildebrandt', 'jones']
short_names = [name for name in last_names if len(name) < 6]
print(short_names)
# Call the main function
if __name__ == '__main__':
main() |
db57f7378de6635b01ac57b040796a254a94f5a6 | dcl67/DataStructures | /Assignment1/main.py | 346 | 4.25 | 4 | from palindrome import isPalindrome
def main():
print("Welcome to Palindrome Checker!\nEnter a word. The program will tell you if it is a palindrome.\nTo quit enter a blank line.")
string = input("Enter word to check: ")
while string != "":
isPalindrome(string)
string = input("Enter word to check: ")
if __name__ == "__main__":
main()
|
fc19f2c514d6d8f0ae83238f52b196108b4190a4 | dlomelin/Algorithms | /algorithms/test/test_Sort.py | 1,089 | 3.71875 | 4 | import unittest
import algorithms.Sort as Sort
class TestSort(unittest.TestCase):
def setUp(self):
self.unsortedList = [5, 2, 4, 7, 1, 3, 2, 6]
self.pythonSorted = sorted(self.unsortedList)
def test_merge_sort(self):
# Function sorts list in place
Sort.merge_sort(self.unsortedList)
self.assertEqual(self.unsortedList, self.pythonSorted)
def test_heap_sort(self):
# Function returns a sorted list
self.assertEqual(Sort.heap_sort(self.unsortedList), self.pythonSorted)
def test_insertion_sort(self):
# Function sorts list in place
Sort.insertion_sort(self.unsortedList)
self.assertEqual(self.unsortedList, self.pythonSorted)
def test_selection_sort(self):
# Function sorts list in place
Sort.selection_sort(self.unsortedList)
self.assertEqual(self.unsortedList, self.pythonSorted)
def test_bubble_sort(self):
# Function sorts list in place
Sort.bubble_sort(self.unsortedList)
self.assertEqual(self.unsortedList, self.pythonSorted)
|
eff9c4bb282b42acbf0d28e05ed41f81daea25a3 | caseymm/python_class_materials | /assorted/num_count.py | 781 | 4.03125 | 4 | array = [0, 3, 2, 5, 6, 3, 4, 1, 0, 4]
def find_duplicates(array):
#Create an empty dicitonary to store i as key and count as value
num_dict = {}
for i in array:
#counts number of times item appears in array
num_count = array.count(i)
#outputs results to dictionary
num_dict.setdefault(i, num_count)
print num_dict
#creates list to store repeated numbers in
repeats = []
for item in num_dict:
#if the value associated w/the item is 2 or more, the number was repeated at
#least once in the original array, no append that number to the repeats list
if num_dict[item] >= 2:
repeats.append(item)
print repeats
find_duplicates(array)
|
9a94f60360f9dc8c1979e5817f572334b19e9861 | sandrejev/bioopt | /model.py | 45,748 | 3.625 | 4 | #!/usr/bin/env python
import re
import thread
import itertools
import warnings
import math
def _is_number(s):
if s in ['0', '1', '2', '1000']:
return True
try:
float(s)
return True
except ValueError:
return False
def _starts_with_number(s):
return s[0] in ['-', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
class Bounds(object):
"""
:class:`Bounds` holds description of reactions constraints
:param lb: Minimal amount of of flux that can go through a reaction (Lower bound). Negative numbers denote reverse direction.
:param ub: Maximal amount of of flux that can go through a reaction (Upper bound). Negative numbers denote reverse direction.
:return: :class:`Bounds`
"""
def __init__(self, lb=float("-inf"), ub=float("inf")):
self.__assert_valid(lb, ub)
self.__lb = lb
self.__ub = ub
def copy(self):
"""
Create a deep copy of current object
:rtype: :class:`Bounds`
"""
return Bounds(self.__lb, self.__ub)
@property
def lb_is_finite(self):
"""
Returns inf False if lower bound is -infinity or +infinity
"""
return self.__lb != self.inf() and self.__lb != -self.inf()
@property
def lb(self):
"""
Minimal amount of of flux that can go through a reaction (Lower bound). Negative numbers denote reverse direction.
"""
return self.__lb
@lb.setter
def lb(self, lb):
self.__assert_valid(lb, self.ub)
self.__lb = float(lb)
@property
def ub_is_finite(self):
"""
Returns inf False if upper bound is -infinity or +infinity
"""
return self.__ub != self.inf() and self.__ub != -self.inf()
@property
def ub(self):
"""
Maximal amount of of flux that can go through a reaction (Upper bound). Negative numbers denote reverse direction.
"""
return self.__ub
@ub.setter
def ub(self, value):
self.__assert_valid(self.lb, value)
self.__ub = float(value)
@property
def direction(self):
"""
Suggested reaction direction. If lower bound is negative the reaction is suggested to be reversible. Otherwise
irreversibility is implied. This is only a suggestion to :class:`Reaction` class and this suggestion can be
broken by enabling reaction reversibility through :attr:`Reaction.direction`
:rtype: :class:`Direction`
"""
return Direction.forward() if self.lb >= 0 else Direction.reversible()
@staticmethod
def inf():
"""
Returns infinity
:return: :class:`float`
"""
return float("Inf")
def __assert_valid(self, lb, ub):
if not isinstance(ub, (int, float)):
raise TypeError("Upper bound is not a number: {0}".format(type(ub)))
if not isinstance(lb, (int, float)):
raise TypeError("Lower bound is not a number: {0}".format(type(lb)))
if lb > ub:
raise ValueError("Lower bound is greater than upper bound ({0} > {1})".format(lb, ub))
def __eq__(self, other):
return type(self) == type(other) and \
self.lb == other.lb and \
self.ub == other.ub
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return "[{0}, {1}]".format(self.lb, self.ub)
class Metabolite(object):
"""
:class:`Metabolite` holds information about metabolite. Currently only supported information is metabolite name
and whether metabolite satisfies boundary condition (imported/exported)
:param name: Metabolite name. Metabolite name should be a non-empty string.
:param boundary: Boundary condition (imported/exported - True; otherwise - false)
:return: :class:`Metabolite`
"""
def __init__(self, name, boundary=False):
self.__assert_name(name)
self.__assert_boundary(boundary)
self.__name = name
self.__boundary = boundary
self.__order_boundary = 0
def copy(self):
"""
Create a deep copy of current object
:rtype: :class:`Metabolite`
"""
m = Metabolite(self.__name, self.__boundary)
m.order_boundary = self.__order_boundary
return m
@property
def name(self):
"""
Metabolite name. Metabolite name should be a non-empty string.
"""
return self.__name
@name.setter
def name(self, name):
self.__assert_name(name)
self.__name = name
@property
def boundary(self):
"""
Boundary condition (imported/exported - True; otherwise - false)
"""
return self.__boundary
@boundary.setter
def boundary(self, boundary):
self.__assert_boundary(boundary)
self.__boundary = boundary
@property
def order_boundary(self):
"""
Priority of displaying this metabolite. Metabolites with higher priority (lower numbers) are displayed earlier
in "-External Metabolites" section
"""
return self.__order_boundary
@order_boundary.setter
def order_boundary(self, order_boundary):
if not _is_number(order_boundary):
raise TypeError("Display priority should be a number: {0}".format(type(order_boundary)))
self.__order_boundary = order_boundary
def __eq__(self, other):
return type(self) == type(other) and \
self.name == other.name and \
self.boundary == other.boundary
def __ne__(self, other):
return not self.__eq__(other)
def __assert_name(self, name):
if not isinstance(name, str):
raise TypeError("Metabolite name is not a string: {0}".format(type(name)))
if not len(name):
raise ValueError("Metabolite name is empty string")
if name == "":
warnings.warn("Metabolite '{0}' contains spaces".format(name), UserWarning)
# TODO: Do we need this?
if _starts_with_number(name) and _is_number(name):
warnings.warn("Metabolite name is a number: '{0}'".format(name), UserWarning)
def __assert_boundary(self, boundary):
if not isinstance(boundary, bool):
raise TypeError("Metabolite boundary condition is not a boolean: {0}".format(type(boundary)))
def __rmul__(self, other):
if isinstance(other, (float, int)):
return ReactionMember(metabolite=self, coefficient=other)
raise TypeError("Can only multiply by numeric coefficient")
def __repr__(self):
b = "*" if self.boundary else ""
return "{0}{1}".format(self.name, b)
class ReactionMember(object):
"""
:class:`Bounds` is a wrapper for :class:`Metabolite` object when used in reaction reactants or products. It
contains reference to the metabolite itself and to it's coefficient in the reaction.
:param metabolite: Reference to :class:`Metabolite` object
:param coefficient: Multiplier associated with metabolite
:return: :class:`ReactionMember`
"""
def __init__(self, metabolite, coefficient=1):
self.__assert_metabolite(metabolite)
self.__assert_coefficient(coefficient)
self.__metabolite = metabolite
self.__coefficient = float(coefficient)
def copy(self):
"""
Create a deep copy of current object
:rtype: :class:`ReactionMember`
"""
rm = ReactionMember(self.__metabolite.copy(), self.__coefficient)
return rm
@property
def metabolite(self):
"""
Reference to metabolite
:rtype: :class:`Metabolite`
"""
return self.__metabolite
@metabolite.setter
def metabolite(self, metabolite):
self.__assert_metabolite(metabolite)
self.__metabolite = metabolite
@property
def coefficient(self):
"""
Multiplier associated with metabolite
"""
return self.__coefficient
@coefficient.setter
def coefficient(self, coefficient):
self.__assert_coefficient(coefficient)
self.__coefficient = float(coefficient)
def __add__(self, other):
if isinstance(other, ReactionMember):
return ReactionMemberList([self, other])
elif isinstance(other, ReactionMemberList):
rml = ReactionMemberList(other)
rml.insert(0, self)
return rml
else:
raise TypeError("Can only join ReactionMember objects")
def __repr__(self):
return "{0:.5g} {1}".format(self.coefficient, self.metabolite)
def __eq__(self, other):
return type(self) == type(other) and \
self.metabolite == other.metabolite and \
self.coefficient == other.coefficient
def __ne__(self, other):
return not self.__eq__(other)
def __assert_metabolite(self, metabolite):
if not isinstance(metabolite, Metabolite):
raise TypeError("Reaction member is not of type <Metabolite>: {0}".format(type(metabolite)))
def __assert_coefficient(self, coefficient):
if not isinstance(coefficient, (int, float)):
raise TypeError("Reaction member coefficient is not a number: {0}".format(type(coefficient)))
class Direction(object):
"""
Describe reaction directionality. Don't use this class directly! Use factory constructors
:meth:`Direction.forward` and :meth:`Direction.reversible`
:param type: f - Irreversible (**f** orward); r - Reversible (**r** eversible)
:return: :class:`Direction`
"""
__lockObj = thread.allocate_lock()
__forward = None
__reversible = None
def __init__(self, type):
if not type in ["f", "r"]:
raise ValueError("Invalid reaction direction type. Allowed values are: {0}".format(', '.join(type)))
self.__type = type
def copy(self):
"""
Create a deep copy of current object
:rtype: :class:`Direction`
"""
return Direction(self.__type)
@staticmethod
def forward():
"""
Returns irreversible directionality descriptor singleton of type :class:`Direction`
:return: :class:`Direction`
"""
Direction.__lockObj.acquire()
try:
if Direction.__forward is None:
Direction.__forward = Direction("f")
finally:
Direction.__lockObj.release()
return Direction.__forward
@staticmethod
def reversible():
"""
Returns reversible directionality descriptor singleton of type :class:`Direction`
:return: :class:`Direction`
"""
Direction.__lockObj.acquire()
try:
if Direction.__reversible is None:
Direction.__reversible = Direction("r")
finally:
Direction.__lockObj.release()
return Direction.__reversible
def __eq__(self, other):
return type(self) == type(other) and self.__type == other.__type
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
if self.__type == "f":
return "->"
if self.__type == "r":
return "<->"
class ReactionMemberList(list):
"""
:class:`ReactionMemberList` is a list of :class:`ReactionMember` instances. :class:`ReactionMemberList` inherits
from :class:`list` all the usual functions to manage a list
"""
def copy(self):
"""
Create a deep copy of current object
:rtype: :class:`ReactionMemberList`
"""
rml = ReactionMemberList()
rml.extend(rm.copy() for rm in self)
return rml
def find_member(self, name):
"""
Find metabolite by name in the list
:rtype: :class:`ReactionMember`
"""
for mb in self:
if mb.metabolite.name == name:
return mb
return None
def __radd__(self, other):
if isinstance(other, ReactionMember):
rml = ReactionMemberList()
rml.append(other)
rml.extend(self)
return rml
return super(ReactionMemberList, self).__radd__(other)
def __add__(self, other):
if isinstance(other, ReactionMember):
rml = ReactionMemberList()
rml.extend(self)
rml.append(other)
return rml
return super(ReactionMemberList, self).__add__(other)
def __iadd__(self, other):
if isinstance(other, ReactionMember):
self.append(other)
return self
elif isinstance(other, ReactionMemberList):
self.extend(other)
return self
return super(ReactionMemberList, self).__iadd__(other)
def __repr__(self):
return " + ".join(m.__repr__() for m in self)
class Reaction(object):
"""
:class:`Reaction` class holds information about reaction including reaction name, members, directionality and constraints
:param name: Reaction name. Reaction name should be non-empty string
:param reactants: Reaction left-hand-side. Object of class :class:`ReactionMemberList`.
:param products: Reaction right-hand-side. Object of class :class:`ReactionMemberList`.
:param direction: Reaction direction. Object of class :class:`Direction`.
:param bounds: Reaction constraints. Object of class :class:`Bounds`.
:rtype: :class:`Reaction`
"""
def __init__(self, name, reactants=ReactionMemberList(), products=ReactionMemberList(), direction=None, bounds=None):
if bounds is None and direction is None:
direction = Direction.reversible()
if direction is None and bounds is not None:
direction = bounds.direction
if bounds is None and direction is not None:
bounds = Bounds(-float('inf'), float('inf')) if direction == Direction.reversible() else Bounds(0, float('inf'))
self.__assert_name(name)
self.__assert_members(reactants)
self.__assert_members(products)
self.__assert_direction(direction)
self.__assert_bounds(bounds)
self.__name = name
self.__direction = direction
self.__bounds = bounds
if isinstance(reactants, ReactionMember):
self.__reactants = ReactionMemberList([reactants])
else:
self.__reactants = reactants
if isinstance(products, ReactionMember):
self.__products = ReactionMemberList([products])
else:
self.__products = products
def copy(self):
"""
Create a deep copy of current object
:rtype: :class:`Reaction`
"""
reactants = self.__reactants.copy()
products = self.__products.copy()
bounds = self.__bounds.copy()
r = Reaction(self.name, reactants, products, direction=self.__direction.copy(), bounds=bounds)
return r
@property
def name(self):
"""
Reaction name
"""
return self.__name
@name.setter
def name(self, name):
self.__assert_name(name)
self.__name = name
@property
def reactants(self):
"""
Reactants
:rtype: :class:`ReactionMemberList`
"""
return self.__reactants
@reactants.setter
def reactants(self, reactants):
self.__assert_members(reactants)
if isinstance(reactants, ReactionMember):
self.__reactants = ReactionMemberList([reactants])
else:
self.__reactants = reactants
@property
def products(self):
"""
Products
:rtype: :class:`ReactionMemberList`
"""
return self.__products
@products.setter
def products(self, products):
self.__assert_members(products)
if isinstance(products, ReactionMember):
self.__products = ReactionMemberList([products])
else:
self.__products = products
@property
def direction(self):
"""
Reaction direction
:rtype: :class:`Direction`
"""
return self.__direction
@direction.setter
def direction(self, direction):
self.__assert_direction(direction)
self.__direction = direction
@property
def bounds(self):
"""
Reaction constraints
:rtype: :class:`Bounds`
"""
return self.__bounds
@bounds.setter
def bounds(self, bounds):
self.__assert_bounds(bounds)
self.__bounds = bounds
def bounds_reset(self):
"""
Reset bounds to predefined default. For reversible reaction defaults bounds are **[-inf, +inf]**. For forward
reactions it is **[0, +inf]**
"""
if self.direction == Direction.forward():
self.bounds = Bounds(0, Bounds.inf())
else:
self.bounds = Bounds(-Bounds.inf(), Bounds.inf())
def find_effective_bounds(self):
"""
Find effective bounds. For example if reaction is described as irreversible but constraints are [-10, 10] the
effective bounds would be [0, 10]
:rtype: :class:`Bounds`
"""
lb = 0 if self.__direction == Direction.forward() and self.__bounds.lb < 0 else self.__bounds.lb
ub = self.__bounds.ub
return Bounds(lb, ub)
def reverse(self):
"""
Reverse reactions. This functions change reactants and products places and inverses constraints so that reaction
would go other way
"""
if self.direction != Direction.reversible():
raise RuntimeError("Reaction direction is not reversible. Only reversible reactions can be reversed")
if self.bounds.lb > 0 and self.bounds.ub > 0:
raise RuntimeError("Reaction effective direction is strictly forward and cannot be reversed")
tmp = self.__products
self.__products = self.__reactants
self.__reactants = tmp
self.__bounds = Bounds(-self.bounds.ub, -self.bounds.lb)
def __assert_name(self, name):
if not isinstance(name, str):
raise TypeError("Reaction name is not a string: {0}".format(type(name)))
if not len(name):
raise ValueError("Reaction name is empty string")
if name == "":
warnings.warn("Reaction '{0}' contains spaces".format(name), UserWarning)
# TODO: Do we need this?
if _starts_with_number(name) and _is_number(name):
warnings.warn("Reaction name is a number: '{0}'".format(name), UserWarning)
def __assert_members(self, reactants):
if not isinstance(reactants, (ReactionMemberList, ReactionMember)):
raise TypeError("Reaction reactants is not of type ReactionMemberList or ReactionMember: {0}".format(type(reactants)))
def __assert_direction(self, direction):
if not isinstance(direction, Direction):
raise TypeError("Reaction direction is not of type ReactionDirection: {0}".format(type(direction)))
def __assert_bounds(self, bounds):
if not isinstance(bounds, Bounds):
raise TypeError("Reaction bounds is not of type bounds: {0}".format(type(bounds)))
def __repr__(self):
return "{name}{bnds}: {lhs} {dir} {rhs}".format(name=self.name, lhs=self.reactants, dir=self.direction, rhs=self.products, bnds=self.bounds)
def __eq__(self, other):
return type(self) == type(other) and \
self.name == other.name and \
self.reactants == other.reactants and \
self.products == other.products and \
self.bounds == other.bounds and \
self.direction == other.direction
def __ne__(self, other):
return not self.__eq__(other)
class Operation(object):
"""
Object describing operation type. **Don't use this class directly! Instead use factory constructors:**
* :meth:`Operation.addition`
* :meth:`Operation.subtraction`
* :meth:`Operation.multiplication`
* :meth:`Operation.division`
* :meth:`Operation.negation` (Unary operation)
:param operation: String describing the operation (binary operations: ``+-/*``, unary operations: ``-``)
:param is_unary: Describes what type of operation is created. Unary operations support only one argument, while binary support two.
:return: :class:`Operation`
"""
__lockObj = thread.allocate_lock()
__addition = []
__subtraction = []
__negation = []
__multiplication = []
__division = []
__unary_priority = ["-"]
__binary_priority = ["*", "/", "+", "-"]
def __init__(self, operation, is_unary):
if not isinstance(is_unary, bool):
raise TypeError("Parameter is_unary is not of type bool: {0}".format(type(is_unary)))
if not is_unary and operation not in Operation.__binary_priority:
raise ValueError("Invalid binary operation: {0}".format(operation))
if is_unary and operation not in Operation.__unary_priority:
raise ValueError("Invalid unary operation: {0}".format(operation))
self.__is_unary = is_unary
self.__operation = operation
if is_unary:
priority = Operation.__unary_priority.index(operation)
else:
priority = len(Operation.__unary_priority)
priority += Operation.__binary_priority.index(operation)
self.__priority = priority
@staticmethod
def __create_singleton(type, operation, instance):
Operation.__lockObj.acquire()
try:
if not instance:
instance.append(Operation(operation, type))
finally:
Operation.__lockObj.release()
return instance[0]
@property
def is_unary(self):
"""
Is operation unary. True - unary; otherwise False
:return: :class:`bool`
"""
return self.__is_unary
@property
def symbol(self):
"""
Short description of operation
* + Addition
* - Subtraction
* / Division
* * Multiplication
* - Negation
:rtype: :class:`Operation`
"""
return self.__operation
@property
def priority(self):
"""
Operation priority. Operations with higher priority (lower numbers) are executed before lower priority operations
:rtype: :class:`Operation`
"""
return self.__priority
@staticmethod
def addition():
"""
Returns addition operation singleton
:rtype: :class:`Operation`
"""
return Operation.__create_singleton(False, "+", Operation.__addition)
@staticmethod
def subtraction():
"""
Returns subtraction operation singleton
:rtype: :class:`Operation`
"""
return Operation.__create_singleton(False, "-", Operation.__subtraction)
@staticmethod
def multiplication():
"""
Returns multiplication operation singleton
:rtype: :class:`Operation`
"""
return Operation.__create_singleton(False, "*", Operation.__multiplication)
@staticmethod
def division():
"""
Returns division operation singleton
:rtype: :class:`Operation`
"""
return Operation.__create_singleton(False, "/", Operation.__division)
@staticmethod
def negation():
"""
Returns negation operation (unary) singleton
:rtype: :class:`Operation`
"""
return Operation.__create_singleton(True, "-", Operation.__negation)
def __repr__(self):
return self.symbol
class MathExpression(object):
def __init__(self, operation, operands):
"""
Class describing mathematical expression
:param operation: Reference to :class:`Operation`
:param operands: A list of operands (two for binary, one for unary). An operand can be a constant (number) or
another :class:`MathExpression`
:return: :class:`MathExpression`
"""
self.__assert_valid(operation, operands)
self.__operands = operands
self.__operation = operation
@property
def operation(self):
"""
Reference to :class:`Operation`
:rtype: :class:`Operation`
"""
return self.__operation
@operation.setter
def operation(self, operation):
self.__assert_valid(operation, self.operands)
self.__operation = operation
@property
def operands(self):
"""
A list of operands (two for binary, one for unary). An operand can be a constant (number) or
another :class:`MathExpression`
:rtype: list of :class:`Operation`
"""
return self.__operands
@operands.setter
def operands(self, operands):
self.__assert_valid(self.operation, operands)
self.__operands = operands
def __eq__(self, other):
return type(self) == type(other) and \
self.operands == other.operands and \
self.operation == other.operation
def __ne__(self, other):
return not self.__eq__(other)
def find_variables(self, remove_duplicates=True):
vars = []
for o in self.operands:
if isinstance(o, type(self)):
vars.extend(o.find_variables(False))
elif not o is None:
vars.append(o)
if remove_duplicates:
seen = set()
return [x for x in vars if x not in seen and not seen.add(x)]
return vars
@staticmethod
def format_var(var):
var = "({0})".format(var) if isinstance(var, MathExpression) else var
var = var.name if isinstance(var, (Reaction, Metabolite)) else var
return var
def __indent(self, text, indent=" "):
return "\n".join([indent + l for l in text.split("\n")])
def __repr__(self, tree=False):
if not tree:
return " {0} ".format(self.operation).join(str(self.format_var(o)) for o in self.operands)
else:
operands = []
for o in self.operands:
operands.append(o.__repr__(tree=True) if isinstance(o, MathExpression) else "{0}({1})".format(type(o).__name__, self.format_var(o)))
return "{0}(\n{1}\n)".format(
type(self).__name__,
self.__indent("\n{0}\n".format(self.operation).join(operands))
)
def __assert_valid(self, operation, operands):
if not isinstance(operation, (Operation, type(None))):
raise TypeError("Operation is not an instance of class <Operation>: {0}".format(type(operation)))
if not isinstance(operands, list):
raise TypeError("Operands are not a list: {0}".format(type(operands)))
# TODO: test these exceptions
if operation is None:
if len(operands) != 1:
raise ValueError("Math expression not representing any operation (<None>) have number of operands different from one")
else:
if operation.is_unary and len(operands) != 1:
raise ValueError("Unary operation have number of operands different from one")
elif not operation.is_unary and len(operands) < 2:
raise ValueError("Binary operation have less than 2 operands")
class Model(object):
"""
BioOpt model is a main class in package. It contains list of reactions in the model and other additional information.
"""
def __init__(self):
self.__reactions = list()
self.__objective = None
self.__design_objective = None
@property
def reactions(self):
"""
List of reactions in the model
:rtype: list of :class:`Reaction`
"""
return self.__reactions
@reactions.setter
def reactions(self, reactions):
# TODO: assert
self.__reactions = reactions
@property
def objective(self):
"""
Optimization target (i.e. Biomass)
:rtype: class:`MathExpression`
"""
return self.__objective
@objective.setter
def objective(self, objective):
self.__assert_objective(objective)
self.__objective = objective
@staticmethod
def __extract_expression(expression):
r = next(r for r in expression.operands if isinstance(r, Reaction))
c = next(r for r in expression.operands if isinstance(r, (int, float)))
return r, c
@staticmethod
def __extract_objective_dict(objective):
coefficients = {}
if objective.operation == Operation.addition():
for exp in objective.operands:
r, c = Model.__extract_expression(exp)
coefficients[r.name] = c
elif objective.operation == Operation.multiplication():
r, c = Model.__extract_expression(objective)
coefficients[r.name] = c
return coefficients
@property
def objective_dict(self):
return Model.__extract_objective_dict(self.objective)
@property
def design_objective_dict(self):
return Model.__extract_objective_dict(self.objective)
def get_objective_coefficient(self, reaction):
# TODO: Implement generic operation handling
self.objective
model.objective.operands[2]
pass
@property
def design_objective(self):
"""
Design optimization target (i.e. Ethanol)
:rtype: list of :class:`MathExpression`
"""
return self.__design_objective
@design_objective.setter
def design_objective(self, design_objective):
self.__assert_objective(design_objective)
self.__design_objective = design_objective
def find_reaction(self, names=None, regex=False):
"""
Searches model for reactions with specified names (patterns). If multiple reactions are found this function
returns only the first one.
:param names: name or list of names of reactions
:param regex: If True names argument is assumed to be a regular expression
:rtype: :class:`Reaction`
"""
r = self.find_reactions(names, regex=regex)
if len(r) > 1:
warnings.warn("Found {0} reactions corresponding to name '{1}'. Returning first!".format(len(r), names), RuntimeWarning)
return r[0] if len(r) else None
def find_reactions(self, names=None, regex=False):
"""
Searches model for reactions with specified names (patterns). This function is capable of returning multiple
reactions.
:param names: name or list of names of reactions
:param regex: If True names argument is assumed to be a regular expression
:rtype: list of :class:`Reaction`
"""
if not self.reactions:
return []
import collections
if names is None:
return [r for r in self.reactions]
elif isinstance(names, str):
if regex:
names = re.compile(names)
return [r for r in self.reactions if names.search(r.name)]
else:
for r in self.reactions:
if r.name == names:
return [r]
return []
elif isinstance(names, collections.Iterable):
names = set(names)
if regex:
names = [re.compile(n) for n in names]
return [r for r in self.reactions if any(n.search(r.name) for n in names)]
else:
return [r for r in self.reactions if r.name in names]
else:
raise TypeError("Names argument should be iterable, string or <None>")
def unify_metabolite_references(self):
metabolites = dict((m.name, m) for m in self.find_metabolites())
for reaction in self.reactions:
for member in reaction.reactants:
member.metabolite = metabolites[member.metabolite.name]
for member in reaction.products:
member.metabolite = metabolites[member.metabolite.name]
def __unify_objective_references(self, expression, reactions):
if isinstance(expression, MathExpression):
for i, o in enumerate(expression.operands):
if isinstance(o, MathExpression):
self.__unify_objective_references(o, reactions)
elif isinstance(o, Reaction):
if o.name in reactions:
expression.operands[i] = reactions[o.name]
def unify_reaction_references(self):
# TODO: What if more than one reaction with same name (Use first)
reactions = dict((r.name, r) for r in self.reactions)
self.__unify_objective_references(self.objective, reactions)
self.__unify_objective_references(self.design_objective, reactions)
def unify_references(self):
"""
Find metabolite with identical names which are stored as different instances and unify instances.
"""
self.unify_metabolite_references()
self.unify_reaction_references()
def __fix_math_reactions(self, expression, reactions):
if isinstance(expression, MathExpression):
for i, o in enumerate(expression.operands):
if isinstance(o, MathExpression):
self.__fix_math_reactions(o, reactions)
elif isinstance(o, Reaction):
expression.operands[i] = reactions[o.name]
def find_metabolite(self, names=None, regex=False):
"""
Searches model for metabolites with specified names (patterns). If multiple metabolites are found this function
returns only the first one.
:param names: name or list of names of metabolites
:param regex: If True names argument is assumed to be a regular expression
:rtype: :class:`Metabolite`
"""
m = self.find_metabolites(names, regex=regex)
if len(m) > 1:
warnings.warn("Found {0} metabolites corresponding to name '{1}'. Returning first!".format(len(m), names), RuntimeWarning)
return m[0] if len(m) else None
# TODO: Test with multiple instances of the same metabolite (result should contain two instances)
# TODO: Test with no reaction section. Metabolite present in ext. metabolites should be accessible
def find_metabolites(self, names=None, regex=False):
"""
Searches model for metabolites with specified names (patterns). This function is capable of returning multiple
metabolites.
:param names: name or list of names of metabolites
:param regex: If True names argument is assumed to be a regular expression
:rtype: list of :class:`Metabolite`
"""
metabolites_set = set()
metabolites = []
for r in self.reactions:
for rm in r.reactants:
if rm.metabolite.name == "atp_c":
pass
metabolites_set.add(rm.metabolite)
for rm in r.products:
if rm.metabolite.name == "atp_c":
pass
metabolites_set.add(rm.metabolite)
#if rm.metabolite not in metabolites_set:
#metabolites.append(rm.metabolite)
metabolites = list(metabolites_set)
import collections
if names is None:
return metabolites
elif isinstance(names, str):
if regex:
names = re.compile(names)
return [m for m in metabolites if names.search(m.name)]
else:
for m in metabolites:
if m.name == names:
return [m]
return []
elif isinstance(names, collections.Iterable):
names = set(names)
if regex:
names = [re.compile(n) for n in names]
return [m for m in metabolites if any(n.search(m.name) for n in names)]
else:
return [m for m in metabolites if m.name in names]
else:
raise TypeError("Names argument should be iterable, string or <None>")
def find_boundary_metabolites(self):
"""
Searches for imported/exported metabolites
:rtype: list of :class:`Metabolite`
"""
return [m for m in self.find_metabolites() if m.boundary]
def find_boundary_reactions(self):
"""
Searches for reactions exporting or importing metabolites
:rtype: list of :class:`Reaction`
"""
return [r for r in self.reactions if any(m.metabolite.boundary for m in r.reactants) or any(m.metabolite.boundary for m in r.products)]
def get_max_bound(self):
mb = 0
for r in self.reactions:
lb = math.fabs(r.bounds.lb)
if lb > mb:
mb = lb
ub = math.fabs(r.bounds.ub)
if ub > mb:
mb = ub
return mb
@staticmethod
def commune(models, model_prefix="ML{0:04d}_", env_prefix="ENV_", block=[]):
"""
Merge two or more models into community model. Community model allows organisms represented by models to share
metabolites. Briefly, the algorithm first appends reaction and metabolite names in original models with ML****_
prefix. Then for every metabolite exported in original models boundary condition is set to :class:`False` and new
export reaction is created. This export reactions allows metabolites to travel from joined models into shared
environment and back. This setup allows organisms to exchange metabolites through common environment.
Originally this merging framework was described in `"OptCom: A Multi-Level Optimization Framework for the Metabolic Modeling and Analysis of Microbial Communities" <http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1002363>`_
by Ali R. Zomorrodi and Costas D. Maranas.
:param models: List of :class:`Model` to join
:param model_prefix: Model prefix, Model prefix is added to all reaction names to avoid name collision in joined model.
:param env_prefix: Prefix of metabolites in shared environment.
:param block: List of names (in original models) of metabolites which should be not allowed to be exchanged between
organisms. An obvious example of such metabolite is biomass.
:rtype: :class:`Model`
"""
block = [block] if not isinstance(block, list) else block
block = [re.compile(b) for b in block]
boundary_metabolites = {}
fwd = Direction.forward()
model = Model()
for i, mod in enumerate(models):
env_reactions = []
for m in mod.find_boundary_metabolites():
m_in = Metabolite(model_prefix.format(i) + m.name)
m_out = Metabolite(env_prefix + m.name)
boundary_metabolites[m_out.name] = m_out
r_out = Reaction(model_prefix.format(i) + 'OUT_' + m.name, ReactionMemberList([ReactionMember(m_in, 1)]),
ReactionMemberList([ReactionMember(m_out, 1)]), Direction.forward(), Bounds(0, Bounds.inf()))
r_in = Reaction(model_prefix.format(i) + 'IN_' + m.name, ReactionMemberList([ReactionMember(m_out, 1)]),
ReactionMemberList([ReactionMember(m_in, 1)]), Direction.forward(), Bounds(0, Bounds.inf()))
env_reactions.extend([r_out, r_in])
reactions = []
metabolites = set()
for r in mod.reactions:
r = r.copy()
r.name = model_prefix.format(i) + r.name
for m in r.reactants:
metabolites.add(m.metabolite)
for m in r.products:
metabolites.add(m.metabolite)
reactions.append(r)
for m in metabolites:
m.name = model_prefix.format(i) + m.name
m.boundary = False
for r in reactions:
if not any(b.search(r.name) for b in block):
model.reactions.append(r)
for r in env_reactions:
if not any(b.search(r.name) for b in block):
model.reactions.append(r)
model.unify_references()
for m_name, m_out in boundary_metabolites.items():
m_ext = Metabolite("{0}xtX".format(m_name), True)
r_out = Reaction(m_out.name+"xtO", ReactionMemberList([ReactionMember(m_out)]), ReactionMemberList([ReactionMember(m_ext)]), fwd)
r_in = Reaction(m_out.name+"xtI", ReactionMemberList([ReactionMember(m_ext)]), ReactionMemberList([ReactionMember(m_out)]), fwd)
if not any(b.search(r_out.name) for b in block):
model.reactions.append(r_out)
if not any(b.search(r_in.name) for b in block):
model.reactions.append(r_in)
return model
def __assert_objective(self, objective):
if not (objective is None or isinstance(objective, MathExpression)):
raise TypeError("Objective is not None or <MathExpression>: {0}".format(type(objective)))
def save(self, path=None, inf=1000):
"""
Save model on disc in bioopt format
:param path: The name or full pathname of the file where the BioOpt model is to be written.
:param inf: Number which would be used for constraints with infinite bounds
"""
ret = "-REACTIONS\n"
for r in self.reactions:
reactants = " + ".join("{0}{1}".format("" if abs(m.coefficient) == 1 else "{0:.5g} ".format(m.coefficient), m.metabolite.name) for m in r.reactants)
products = " + ".join("{0}{1}".format("" if abs(m.coefficient) == 1 else "{0:.5g} ".format(m.coefficient), m.metabolite.name) for m in r.products)
dir = "->" if r.direction == Direction.forward() else "<->"
ret += "{name}\t:\t{lhs} {dir} {rhs}".format(name=r.name, lhs=reactants, dir=dir, rhs=products) + "\n"
ret += "\n"
ret += "-CONSTRAINTS\n"
for r in self.reactions:
lb = -inf if r.bounds.lb == -Bounds.inf() else r.bounds.lb
ub = inf if r.bounds.ub == Bounds.inf() else r.bounds.ub
if not (r.bounds.direction == Direction.forward() and r.bounds == Bounds(0)) and \
not (r.bounds.direction == Direction.reversible() and r.bounds == Bounds()):
ret += "{0}\t[{1:.5g}, {2:.5g}]".format(r.name, lb, ub) + "\n"
ret += "\n"
ret += "-EXTERNAL METABOLITES\n"
b_metabolites = self.find_boundary_metabolites()
b_metabolites = sorted(b_metabolites, key=lambda x: x.order_boundary)
for m in b_metabolites:
ret += m.name + "\n"
ret += "\n"
if self.objective:
ret += "-OBJECTIVE\n"
ret += " ".join(str(MathExpression.format_var(o)) for o in self.objective.operands)
ret += "\n\n"
if self.design_objective:
ret += "-DESIGN OBJECTIVE\n"
ret += " ".join(str(MathExpression.format_var(o)) for o in self.design_objective.operands)
ret += "\n\n"
if path:
f = open(path, 'w')
f.write(ret)
return f.close()
else:
return ret
def __repr__(self):
ret = "-REACTIONS\n{0}\n\n".format("\n".join(r.__repr__() for r in self.reactions))
ret += "-CONSTRAINTS\n{0}\n\n".format("\n".join("{0}\t{1}".format(r.name, r.bounds) for r in self.reactions))
ret += "-EXTERNAL METABOLITES\n{0}\n\n".format("\n".join(m.__repr__() for m in self.find_boundary_metabolites()))
ret += "-OBJECTIVE\n{0}\n\n".format(self.objective)
ret += "-DESIGN OBJECTIVE\n{0}\n\n".format(self.design_objective)
return ret
def __eq__(self, other):
return type(self) == type(other) and \
self.reactions == other.reactions and \
self.objective == other.objective and \
self.design_objective == other.design_objective
def __ne__(self, other):
return not self.__eq__(other) |
e2b1714e3281dca2021ece4056c88777966f817e | udwivedi394/misc | /redundantBraces.py | 574 | 4.15625 | 4 | #https://www.interviewbit.com/problems/redundant-braces/
#Return 1 if redundant Braces are present
def redundantBraces(A):
stack = []
for i in A:
if i == ')':
valid = False
while stack[-1] != '(':
if stack.pop() in ('+','*','-','/'):
valid = True
if valid==False:
return 1
stack.pop()
elif i in ('(','+','*','-','/'):
stack.append(i)
return 0
A = "((a + b))"
print redundantBraces(A)
A = "(a + (a + b))"
print redundantBraces(A)
|
e28a8b4dc17de6c52e3a268cb1b99fe8d10696d9 | skimaiyo16/andela-bc-5 | /data_stuctures.py | 881 | 3.921875 | 4 | # phone book example
# use a list
class PhoneBookList(object):
def __init__(self):
self.book = []
def add_contact(self, username, phone_number):
record = [username, phone_number]
self.book.append(record)
def search(self, username):
''' returns a `dict` wih a phone number and
the number of loop count eg
{'count:20}
'''
count = 0
for u,p in self.book:
count += 1
if u == username:
result = {'count': count,'phone_number': p}
return result
result = {'count': count,'phone_number': None}
return result
class PhoneBookDict(object):
def __init__(self):
self.book = {}
def add_contact(self, username, phone_number):
self.book[username] = phone_number
def search(self, username):
result = {
'count': 1,
'phone_number': self.book.get(username,None)
}
return result
|
44ab6bef6931cd9225b02bb385f59760bda9fd89 | dwibagus154/TUBES-TPB-ITB | /cari_pemain.py | 427 | 3.734375 | 4 | import csv
def CariPemain():
user = input('Masukkan username:')
userfile = csv.reader(open('user.csv'))
found = False
for row in userfile:
if user == row[3]:
found = True
print("Nama Pemain: ", row[0])
print("Tinggi Pemain: ", row[2])
print("Tanggal Lahir Pemain: ", row[1])
if found == False:
print("Pemain tidak ditemukan")
CariPemain()
|
337f8bc0691e6fd6944dcfe9066419330e2f0c4a | Andrewlearning/Leetcoding | /leetcode/Stack/581. 最短的无序连续子串(stack).py | 1,395 | 4.0625 | 4 | """
给你一个应当是从小到大排列的数组(允许元素相等),但里面有一部分连续的子串是混乱的
让你求,
"""
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
stack = []
left = len(nums)
right = 0
for i in range(len(nums)):
while len(stack) > 0 and nums[stack[-1]] > nums[i]:
left = min(left, stack.pop())
stack.append(i)
stack = []
for i in range(len(nums) - 1, -1, -1):
while len(stack) > 0 and nums[stack[-1]] < nums[i]:
right = max(right, stack.pop())
stack.append(i)
if right - left > 0: return right - left + 1
return 0
"""
https://www.youtube.com/watch?v=ExaJeXua-h0
有两种做法
1.排序法,我们先做一个原数组的deepcopy,然后把它给sort,然后用两个指针
分别从两个数组的头尾向中间扫,找到两个第一个出现非递增的元素,right-left+1
时间复杂度高一点
2.stack
1.从头到尾时,我们把满足递增的index加进stack,当遇到非递增的,就pop出来
然后left一直取min index
2.从尾巴到头,我们把满足递减(反过来了)的index加进stack,遇到非递减的,就pop出来
然后right一直取max index
3. right- left + 1
""" |
2b5e877f6edb6686bd3d496efc8014ac60e47bd7 | JoseBorras/Tarea1Modelacion | /ejemplo4-3-Malalasekera.py | 5,002 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Example 4.3 from Malalasekera Book
----------------------------------
In the final worked example of this chapter we discuss the cooling of a
circular fin by means of convective heat transfer along its length. Convection
gives rise to a temperature-dependent heat loss or sink term in the governing
equation. Shown in Figure 4.9 is a cylindrical fin with uniform crosssectional
area A. The base is at a temperature of 100°C (T_A) and the end is
insulated. The fin is exposed to an ambient temperature of 20°C. Onedimensional
heat transfer in this situation is governed by
$
\dfrac{d}{dx} \left( k A \dfrac{d T}{dx} \right) - hP(T - T∞) = 0
$
where h is the convective heat transfer coefficient, P the perimeter, k the
thermal conductivity of the material and $T_\infty$ the ambient temperature.
Calculate the temperature distribution along the fin and compare the results
with the analytical solution given by
$\frac{T - T∞}{T_A - T∞} = \frac{\cosh[n(L-x)]}{\cosh(nL)}$
where $n^2 = hP/(kA)$, $L$ is the length of the fin and $x$ the distance along the
fin. Data: $L = 1$ m, $hP/(kA) = 25/m^2$ (note that $kA$ is constant).
The governing equation in the example contains a sink term, −hP(T − T∞),
the convective heat loss, which is a function of the local temperature T.
___________________________________________________________
|<-------------- 1.0 m ------------->|
A
|
|
|------------------------------------|
|------------------------------------| Flujo igual a zero
| Temp. Ambiente (T∞)
| |
|
T_A = 100 \frac{\partial T}{\partial dx} = q = 0
___________________________________________________________
Figure 4.9
When $kA$ = constant, the governing equation can be written as
$
\dfrac{d}{dx} \left( \dfrac{d T}{dx} \right) - n^2(T - T∞) = 0
$
"""
import FiniteVolumeMethod as fvm
import numpy as np
import matplotlib.pyplot as plt
#Definición de la solución que representa la solución analítica que se muestra en Malalasekera
def analyticSol(x):
return (TA - Tambiente) * np.cosh(n * (longitud - x)) / np.cosh(n * longitud) + Tambiente
#------------------Se establecen los parámetros que definen el problema ---------------------
longitud = 1.0 # metros
Tambiente = 20 # °C
TA = 100 # °C
n2 = 25 # /m^2
n=5
fluxB = 0 # Flujo igual a cero
N = 11 # Número de nodos
#---------------------------------------------------------------------------------------------
# Creamos la malla y obtenemos datos importantes
#
malla = fvm.Mesh(nodes = N, length = longitud)
nx = malla.nodes() # Número de nodos
nvx = malla.volumes() # Número de volúmenes
delta = malla.delta() # Tamaño de los volúmenes
#
# Imprimimos los datos del problema (nicely)
#
fvm.printData(Longitud = longitud,
Temperatura_A = TA,
Flujo_B = fluxB,
n2 = n2,
Nodos = nx,
Volúmenes = nvx,
Delta = delta)
#
# Creamos los coeficientes de FVM
#
df1 = fvm.Diffusion1D(nvx, Gamma = 1, dx = delta)
df1.alloc(nvx) # Se aloja memoria para los coeficientes
df1.calcCoef() # Se calculan los coeficientes
df1.setSu(n2 * Tambiente) # Se agrega la fuente uniforme
df1.setSp(-n2)
#print(df1.aP(),df1.aW(), df1.aE(), df1.Su(), sep = '\n')
#
# Se construye el arreglo donde se guardará la solución
#
T = np.zeros(nvx) # El arreglo contiene ceros
T[0] = TA # Condición de frontera izquierda
df1.bcDirichlet('LEFT_WALL', T[0]) # Se actualizan los coeficientes
df1.bcNeumman('RIGHT_WALL', fluxB) # de acuerdo a las cond. de frontera
#
# Se construye el sistema lineal de ecuaciones a partir de los coef. de FVM
#
Su = df1.Su() # Vector del lado derecho
A = fvm.Matrix(malla.volumes()) # Matriz del sistema
A.build(df1) # Construcción de la matriz en la memoria
#
# Se resuelve el sistema usando un algoritmo del módulo linalg
#
T[1:-1] = np.linalg.solve(A.mat(),Su[1:-1])
T[-1] = T[-2] # Condición de frontera tipo Neumman
#
# Se construye un vector de coordenadas del dominio
#
x = malla.createMesh()
#
# Calculamos la solución exacta y el error
#
Ta = analyticSol(x)
error = fvm.calcError(T, Ta)
datos = {'x(m)': x,
'T(x)': T,
'Analytic': Ta,
'Error': error}
fvm.printFrame(datos)
print('||Error|| = ', np.linalg.norm(error))
print('.'+ '-'*70 + '.')
#
# Calculamos la solución exacta en una malla más fina para graficar
#
x1 = np.linspace(0,longitud,100)
n = np.sqrt(n2)
Ta = analyticSol(x1)
#
# Se grafica la solución
#
plt.plot(x1,Ta, '-', label = 'Sol. analítica')
plt.plot(x,T,'o', label = 'Sol. FVM')
plt.title('Solución de $\partial^2 T/\partial x^2 - hP(T-T_\infty) = 0$ con FVM')
plt.ylim(10,110)
plt.xlabel('$x$ [m]')
plt.ylabel('Temperatura [$^o$C]')
plt.grid()
plt.legend()
plt.savefig('example03.pdf')
plt.show()
|
a6a8fe06f493e2c73f067d0c39c5d24c493fa1cd | peltierchip/the_python_workbook_exercises | /chapter_1/exercise_2.py | 98 | 3.765625 | 4 | #enter username
name=input("Enter your name\n")
#print greeting to user
print("Hello %s!" %name)
|
318f8f830dc562f1d1497d6d6eeb57420fe66da5 | Hironobu-Kawaguchi/atcoder | /atcoder/abc067_a.py | 183 | 3.59375 | 4 | # https://atcoder.jp/contests/abc067/tasks/abc067_a
A, B = map(int, input().split())
if A % 3 and B % 3 and (A + B) % 3:
print("Impossible")
else:
print("Possible")
|
37bad9107dfc386f518b5f849f1e98c7ae69be2b | deepakdeedar/python_projects | /reduce.py | 448 | 3.828125 | 4 | from functools import reduce
my_list = [1, 2, 3]
your_list = [10, 20, 30]
their_list = [5, 25, 125]
def multiply_by2(item):
return item*2
def only_odd(item):
return item % 2 != 0
def accumulator(acc, item):
print(acc, item)
return acc + item
print(list(map(multiply_by2, my_list)))
print(list(filter(only_odd, my_list)))
print(list(zip(my_list, your_list, their_list)))
print(reduce(accumulator, my_list, 0))
print(my_list)
|
577ea0241ef48d173c69f38d4eeb3b4185b7bf90 | Jeson-fly/tools | /data_structure/double_link_list.py | 3,317 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/5/13 13:13
@Author : lining
@email:lining01@tuyooganme.com
@desc: 双端链表
"""
class ListNode(object):
def __init__(self, data=None):
self.pre_node = None
self.next_node = None
self.date = data
def clean_pointer(self):
"""清空指针,避免不必要的连接错误"""
self.pre_node = None
self.next_node = None
def destory(self):
"""节点销毁"""
self.clean_pointer()
self.date = None
class DoubleLinkList(object):
def __init__(self):
"""初始化"""
self._head_node = ListNode()
self._tail_node = ListNode()
self._head_node.next_node = self._tail_node
self._tail_node.pre_node = self._head_node
self.size = 0
def _insert_data(self, node: ListNode, pre_node: ListNode, next_node: ListNode):
"""插入节点"""
node.clean_pointer()
pre_node.next_node = node
node.pre_node = pre_node
next_node.pre_node = node
node.next_node = next_node
self.size += 1
def _remove_data(self, node: ListNode):
"""删除数据"""
if node is self._head_node or node is self._tail_node:
return
if node.pre_node is not self._head_node:
node.pre_node.next_node = node.next_node
if node.next_node is not self._tail_node:
node.next_node.pre_node = node.pre_node
node.clean_pointer()
self.size -= 1
return node
def push_front(self, node):
"""队首添加数据,时间复杂度O(1)"""
assert isinstance(node, ListNode)
self._insert_data(node, self._head_node, self._head_node.next_node)
def push_back(self, node):
"""队尾添加元素,时间复杂度O(1)"""
assert isinstance(node, ListNode)
self._insert_data(node, self._tail_node, self._tail_node.pre_node)
def pop_front(self):
"""弹出队首元素,时间复杂度O(1)"""
return self._remove_data(self._head_node.next_node)
def remove_node(self, node):
"""移除指定节点"""
assert isinstance(node, ListNode)
self._remove_data(node)
def pop_back(self):
"""弹出队尾元素"""
return self._remove_data(self._tail_node.pre_node)
def get_head(self):
"""获取队首元素"""
if self._head_node.next_node is self._tail_node:
return None
return self._head_node.next_node
def get_back(self):
"""获取队尾元素"""
if self._tail_node.pre_node is self._head_node:
return None
return self._tail_node.pre_node
def get_size(self):
"""获取链表长度"""
return self.size
def clear_node(self):
"""清除链表节点"""
next_node = self._head_node.next_node
while next_node:
tmp_node = next_node.next_node
next_node.destory()
next_node = tmp_node
self._head_node.next_node = self._tail_node
self._tail_node.pre_node = self._head_node
self.size = 0
def destory(self):
"""链表的销毁"""
self.clear_node()
self._head_node and self._head_node.destory()
self._tail_node and self._tail_node.destory()
|
a372e99100bec16f1ce6ecab0c73ccacf8d8d830 | RicardoStephen/algorithms | /test/test_heapq.py | 2,773 | 3.53125 | 4 | import unittest
import math
from algorithms.graphs import Heapq
class TestHeapq(unittest.TestCase):
"""
Note, the heappush tests are only smoke tests.
"""
def setUp(self):
self.heaps = {'empty': []}
states = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
for idx, state in enumerate(states):
self.heaps['int_' + state] = list(reversed(range(idx + 1)))
self.heaps['str_' + state] = list(reversed('bcdefgh'[:idx+1]))
self.small_int, self.large_int = -1, 7
self.small_str, self.large_str = 'a', 'i'
for heap in self.heaps.values():
Heapq.heapify(heap)
self.check_heaporder(heap)
def check_heaporder(self, arr):
for idx in range(len(arr) - 1, 0, -1):
pidx = (idx - 1) // 2
self.assertLessEqual(arr[pidx], arr[idx])
def test_heapify(self):
pass
def test_heappush_small(self):
for state, heap in self.heaps.items():
with self.subTest(heap = heap):
# Push 1 layer of small elements.
elem = self.small_int if state[:3] == 'int' else self.small_str
height = math.ceil(math.log(len(heap) + 1, 2))
missing_leaves = (2**height - 1) - len(heap)
next_layer = 2**height
for _ in range(missing_leaves + next_layer):
Heapq.heappush(heap, elem)
self.check_heaporder(heap)
def test_heappush_large(self):
for state, heap in self.heaps.items():
with self.subTest(heap = heap):
# Push 1 layer of large elements.
elem = self.large_int if state[:3] == 'int' else self.large_str
height = math.ceil(math.log(len(heap) + 1, 2))
missing_leaves = (2**height - 1) - len(heap)
next_layer = 2**height
for _ in range(missing_leaves + next_layer):
Heapq.heappush(heap, elem)
self.check_heaporder(heap)
def test_heappop(self):
for heap in self.heaps.values():
with self.subTest(heap = heap):
for _ in range(len(heap)):
val = heap[0]
self.assertEqual(Heapq.heappop(heap), val)
self.check_heaporder(heap)
def test_heappop_invalid(self):
for heap in self.heaps.values():
with self.subTest(heap = heap):
for _ in range(len(heap)):
val = heap[0]
self.assertEqual(Heapq.heappop(heap), val)
self.check_heaporder(heap)
with self.assertRaises(IndexError):
val = Heapq.heappop(heap)
|
67854c3ac91cf58a13601f30e600afae7db2d0ea | UnderLurker/insect | /PythonApplication1/day03_numpy.py | 6,401 | 4.1875 | 4 | import numpy as np
"""
安装了anaconda,在pycharm 中import numpy 不成功的。
1、cmd中 输入python-------import numpy
2、如果成功,设置pycharm的setting
其他方法安装:cmd------输入:pip install numpy
"""
# 一、创建数组
# 1、array函数,可以传入列表、元组。
arr1 = np.array([1, 2, 3])
# print(arr1)
# arr2 = np.array([[1, 2, 3],
# [2, 3, 1]
# ])
# print(arr2)
# 二、数组的属性
# shape、ndim、dtype、size、itemsize
# 使用方法:数组名.属性名
# print(arr2.shape) # 返回数组的形状,行、列。元组的形式
# print(arr2.ndim)
# print(arr2.dtype) # 数组中元素的类型
# print(arr2.size) # 数据中 所有元素
# print(arr2.itemsize) # --->8 每个元素的字节数。 1个字节=X位 64位的float/8位=
# 重点:一维数组 没有行列的概念。只有一个元素的元组(元素1,)
# print("arr1.shape:-----{}".format(arr1.shape)) # -->(3,) (1,3)X
# 创建数组2 ----特殊函数
# start stop step(默认1)
arr3 = np.arange(1, 11, 3) # 从1到10 前闭后开[a, b)
# print(arr3)
# 全0 2行3列
arr4 = np.zeros(shape=(2, 3), dtype=int)
# print(arr4)
# np.eye 对角数组(矩阵), 1单位数组(矩阵)。
arr5 = np.eye(3)
# print(arr5)
# 对角矩阵
arr6 = np.diag([1, 2, 3])
# print(arr6)
arr7 =np.logspace(0, 2, num=3) # base 10 # [0, 1, 2]
# print(arr7)
# 随机数 种子 seed 可复现性
np.random.seed(0)
arr8 = np.random.random((2, 3)) # 传入的shape
# print(arr8)
# 四、数据访问: 下标法、切片法 (前闭后开)
# arr2 = np.array([[1, 2, 3],
# [2, 3, 1],
# [3, 2, 1],
# [4, 5, 6]
# ])
# print(arr2[0, 1])
# print(arr2[0, 0:2])
# 取出所有行第一列
# print(arr2[0:5, 0])
# bool_index = arr2[0:5, 0]%2== 0
# print(bool_index)
#
# bool_index1 = np.array([1, 0, 2], dtype=bool)
# print(bool_index1)
# bool 索引的长度 必须和行、列的长度相等
# print(arr2[:, bool_index1]) # bool 索引
# 五、数组的变形
# 1、一维数组到二维数组、二维数组到1维,二维到二维
arr2 = np.array([[1, 2, 3],
[2, 3, 1],
[3, 2, 1],
[4, 5, 6]
])
# 1、直接使用shape属性
# arr2.shape = (12,) # 行优先访问
# print(arr2)
# 2、reshapes函数. 不就地修改.建议大家用reshape
arr9 = arr2.reshape(12,)
# print(arr9)
# print(arr2)
# -1占位符号,元素个数/2
# 变形必须保证 总size一致
# arr10 = np.arange(1, 9).reshape(2, -1)
# print(arr10)
# flatten 函数,如果修改一维数组 不会改变原始的高维数组。
# ravel 函数 如果修改一维数组 会改变原始的高维数组。
arr11 = np.random.random((2,3))
# print(arr11)
# arr12 = arr11.flatten()
arr12 = arr11.ravel() # 展平为1维数组
# print(arr12)
arr12[0] = 100
# print('*'*60)
# print(arr11)
# print(arr12)
# 六、矩阵的创建
mat1 = np.mat(arr2)
# print(mat1)
# print(type(mat1))
# print(type(arr2))
mat2 = np.mat('1 2 3; 2 3 1')
# print(mat2)
# print(mat2.T)
# print(type(mat2.A))
mat3 = np.mat([[1, 1, 1],
[2, 2, 2]])
# print(mat3)
# 矩阵的运算:加法、减法。 操作的矩阵shape是一致的
# print(mat2 + mat3)
# # print(mat2.shape)
# print('-'*60)
# print(np.multiply(mat2, mat3))
# print(mat2*mat3) 需要遵守数学里的矩阵乘法的规则
# 数组和矩阵是可以相互转换的。
# mat.A----> 对应的数组
# np.mat(数组) -----对应的矩阵
# 七、数组的运算:算术运算(+、-、*、**)、逻辑运算和比较运算
arr13 = np.array([[1, 2],
[3, 4],
[5, 6]])
arr14 = np.array([[1, 2],
[2, 4]])
# 算术运算(+、-、*、**, /) 要求:操作的数组 shape必须一致
# print(arr13 * arr14)
# 数组的关系 运算 就是。数组中对应位置元素的运算
# print(arr13 == arr14)
# print(np.all(arr13 == arr14)) # and 是否所有元素都XX
# print(np.any(arr13 == arr14)) # or 是否存在元素XX
# print(np.all(arr13>3))
# arr13是一个2行3列的。3只是一个值
# 数组的广播机制
# 一维数组 充当 列的位置
arr15 = np.array([2, 3, 3])
# print(arr15.shape)
# print(arr15.ndim)
# 八、数组的读写:。二进制文件
# 单个数组的读写 save、load
# 保存数组时,默认后缀为npy
np.save("数组arr15", arr15)
# 读npy文件中,必须加后缀
new_arr = np.load("数组arr15.npy")
# print(new_arr)
# 多个数组的读写
# 后缀为npz,保存时 默认为字典的形式,key为arr_X[0,1,------]
np.savez("多个数组", arr14=arr14, arr15=arr15)
new_arrs = np.load("多个数组.npz")
# print(new_arrs)
# for i in new_arrs:
# print(i)
# print(new_arrs[i])
# 默认保存的是浮点数
np.savetxt("数组.txt", arr14, fmt="%d")
# 九、数组的统计分析
# sort函数,就地修改
arr16 = np.array([1, 2, 3, 6, 5, 4])
# print(arr16)
# arr16.sort()
# print(arr16)
# 排序默认是递增的,默认是axis=1
arr17 = arr16.reshape(3, 2)
# print(arr17)
# print('*'*60)
# arr17.sort(axis=1)
# print(arr17)
# 返回的排序元素的下标值
sort_index = arr16.argsort() # 0 1 2 5 4 3
# print(arr16[sort_index[:4]])
# unique 对数组进行去重,并排序
arr18 = np.array([4,1,2,3,1,2,2,1,1,1,1,1])
# print(np.unique(arr18))
arr16 = np.array([1, 2, 3, 6, 5, 4])
# print(np.max(arr16))
# print(np.sum(arr16))
arr17 = arr16.reshape(3, 2)
# print(arr17)
# print(np.max(arr17, axis=1))
# print(np.sum(arr16))
# print(np.cumsum(arr16))
# (1)员工的平均薪资为多少?
# (2)公司任职最久的员工是谁?
# (3)员工的平均工作年限是多少?
# (4)员工总体流失率是多少?
# (5)员工整体满意程度如何?
data_info = np.load("lol_data.npz")
data = data_info["data"]
cloumns = data_info["cloumns"]
# print(cloumns)
# ['工号' '姓名' '部门' '岗位' '薪资' '工龄' '满意度' '状态']
print(data.shape)
salary = data[:, 4].astype(int)
print("员工的平均薪资为{0}".format(np.mean(salary)))
years = data[:,5].astype(int)
print("员工的平均年限为{0}".format(np.mean(years)))
max_year = np.min(years) # ----- 10
bool_index = years == max_year # 谁的工作年限为10
print(bool_index)
print("工作最短的是:", data[bool_index, 1][0])
|
099a75fb765ccb5b8178baf4de97d5213eb9ba6f | lianlian-YE/Mypycharm | /Python_file/python_westos_teacher_doc/day09/11_私有属性和变量.py | 1,092 | 3.8125 | 4 | #!/usr/bin/env python
# coding:utf-8
""""
Name: 11_私有属性和变量.py
Date: 2018/05/19
Connect: xc_guofan@163.com
Author: lvah
Desc:
"""
# 子类也不能直接使用父类的私有属性和私有方法;
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
# 以双下划线开头的属性名或者方法名, 外部是不可以访问的;
self.__score = score
def set_score(self, value):
if 0<=value<=150:
self.__score = value
def __get_level(self):
if 90<self.__score<=100:
return "%s,%s,A" %(self.name,self.age)
elif 80<self.__score<=90:
return "%s,%s,B" %(self.name,self.age)
else:
return "%s,%s,C" %(self.name,self.age)
class MathStudent(Student):
def get_score(self):
print(self.__score)
s1 = Student("westos", 18, 100)
print(s1.name)
s2 = MathStudent("helo",10,90)
# print(s2.__score)
# s1.__get_level()
# print(s1.__score)
# s1.name = "fentiao"
# print(s1.name)
# s1.score = 150
# print(s1.score) |
7ae875dedd85b4a3ca039d319c659b02bcf7648a | epheat/ieeextreme_10 | /problems/painters_dilemma/painter.py | 2,503 | 3.609375 | 4 | def main():
tests = int(input())
for i in range(tests):
brush1 = 0
brush2 = 0
changes = 0;
numc = int(input())
clrs = input()
clrs = clrs.split(" ")
for k in range(numc):
clrs[k] = int(clrs[k])
#print(clrs)
for j in range(numc):
searchList = clrs[j:]
#print(searchList)
if((searchList[0] == brush1) or (searchList[0] == brush2)):
#if (searchList[0] == brush1):
#print("brush1 already prepped.")
#if (searchList[0] == brush2):
#print("brush2 already prepped.")
continue
ind1 = -1
ind2 = -1
p1canchange = False
p2canchange = False
try:
ind1 = searchList.index(brush1)
except ValueError:
p1canchange = True
#print(str(brush1) + " not found later in list.")
try:
ind2 = searchList.index(brush2)
except ValueError:
p2canchange = True
#print(str(brush2) + " not found later in list.")
if (p1canchange == False and p2canchange == False):
#get the smaller of the 2 indices
if(ind1 > ind2):
p1canchange = True
else:
p2canchange = True
if (p1canchange):
brush1 = searchList[0]
changes += 1
continue
#print("brush1 changed to " + str(brush1) + ", changes: " + str(changes))
if (p2canchange):
brush2 = searchList[0]
changes += 1
#print("brush2 changed to " + str(brush2) + ", changes: " + str(changes))
print(changes)
main()
|
c02230439b102cc186dfe29c0e2e672f6382e492 | xiaoyaoshuai/- | /作业/7.11/erase_zero.py | 226 | 3.625 | 4 | a = int(input("苹果(元):"))
b = float(input("香蕉(元):"))
c = int(input("火腿(元):"))
d = float(input("可乐(元):"))
money = a+b+c+d
print ('总计(元)')
print (money)
print ("实际金额")
print(str(int(money)))
|
96d6d4e94404ee9a6b60edcaabbdcadae33438a6 | RevansChen/online-judge | /Codefights/arcade/intro/level-6/25.Array-Replace/Python/solution1.py | 158 | 3.65625 | 4 | # Python3
def arrayReplace(inputArray, elemToReplace, substitutionElem):
return [ (substitutionElem if e == elemToReplace else e) for e in inputArray ]
|
c04d46e418d294fb9b7fa4b8ff688ff76e976716 | OmarMontero/150-challenges-for-python | /twenty-two.py | 208 | 4.09375 | 4 | name = input("Write your name in lower case, please: ")
surname = input("Write your surname in lower case, please: ")
name = name.title()
surname = surname.title()
whole = name + " " + surname
print(whole) |
cb7cf447a2081958d3ac7e012485e254bc9a17b1 | amitdh123/codeabbey-solutions | /sumloop.py | 196 | 3.75 | 4 | def sumloop(items, numberlist ):
sum = 0;
for i in range(0,items):
sum = sum + numberlist[i]
return sum
length = 5
numberlist = [1,5,0,4,3,]
result = sumloop(length,numberlist)
print(result) |
b0bbba917c888e069d23921f6681662ad02172ef | Ajay-2007/Python-Codes | /hackerearth/Data Structures/Arrays/1-D/Monk_And_Welcom_Problem.py | 915 | 3.703125 | 4 | """Monk and Welcome Problem
Args: arrays(int)
Returns: array(int)
Algorithm:
arr_c[i] = arr_a[i] + arr_b[i]
Problem Link: https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/monk-and-welcome-problem/
"""
class Monk_And_Welcom:
def __init__(self, size_n, arr_a, arr_b):
self.size_n = size_n
self.arr_a = arr_a
self.arr_b = arr_b
self.arr_c = []
def monk_and_welcom(self):
for i in range(self.size_n):
self.arr_c.append(self.arr_a[i] + self.arr_b[i])
return self.arr_c
def main():
size_n = int(input())
arr_a = list(map(int, input().split()))
arr_b = list(map(int, input().split()))
m = Monk_And_Welcom(size_n, arr_a, arr_b)
c_arr = m.monk_and_welcom()
for i in range(size_n):
print(c_arr[i], end=' ')
if __name__ == "__main__":
main()
|
96b6264ac02434da30ca4320f3590d6a78865dd9 | ShreyashSoni/linear_regression | /regression-demo.py | 2,542 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 22 20:47:34 2017
@author: Shreyash Soni
"""
from numpy import *
def compute_error_for_line_given_points(b, m, points):
#initialize at zero
totalError = 0
#for every point
for i in range(0, len(points)):
#get the x-values
x = points[i, 0]
#get the y-values
y = points[i, 1]
#get the difference, square it, add it to the total
totalError += (y-(m * x + b)) ** 2
#get the average
return totalError / float(len(points))
def step_gradient(b_current, m_current, points, learningRate):
#starting points for our gradient
b_gradient = 0
m_gradient = 0
N = float(len(points))
for i in range(0, len(points)):
x = points[i, 0]
y = points[i, 1]
#direction with respect to the b and m
#computing partial derivatives of the error function
b_gradient += -(2/N) * (y - ((m_current * x) + b_current))
m_gradient += -(2/N) * x * (y - ((m_current * x) + b_current))
#update our b and m values using the partial derivatives
new_b = b_current - (learningRate * b_gradient)
new_m = m_current - (learningRate * m_gradient)
return [new_b, new_m]
def gradient_descent_runner(points, starting_b, starting_m, learning_rate, num_iterations):
#initial b and m
b = starting_b
m = starting_m
#gradient descent
for i in range(num_iterations):
#update b and m with the more accurate b and m by performing this
#gradient step
b, m = step_gradient(b, m, array(points), learning_rate)
if i % 100 == 0:
print('After {} iterations, b={:0.9f}, m={:0.9f}, error={:.9f}'.format(i, b, m, compute_error_for_line_given_points(b, m, points)))
return [b, m]
def run():
#step-1 collect the data
points = genfromtxt('data.csv', delimiter = ',')
#step-2 define the hyperparameters
learning_rate = 0.0001
initial_b = 0
initial_m = 0
num_iterations = 1000
#step-3 train the model
print('starting gradient descent at b={:0.9f}, m={:0.9f}, error={:0.9f}'.format(initial_b, initial_m, compute_error_for_line_given_points(initial_b, initial_m, points)))
print('Running...')
[b, m] = gradient_descent_runner(points, initial_b, initial_m, learning_rate, num_iterations)
print('After {} iterations, b={:0.9f}, m={:0.9f}, error={:0.9f}'.format(num_iterations, b, m, compute_error_for_line_given_points(b, m, points)))
if __name__ == '__main__':
run() |
7ddcf156628e85b6a5d55b31b76aa194e79203c6 | stubbi/nqs | /nqs/operator.py | 1,776 | 3.5 | 4 | from ._C_nqs.operator import *
import numpy as _np
def Ising(hilbert, h, J=1.0):
"""
Constructs a new ``Ising`` given a hilbert space, a transverse field,
and (if specified) a coupling constant.
Args:
hilbert: Hilbert space the operator acts on.
h: The strength of the transverse field.
J: The strength of the coupling. Default is 1.0.
Examples:
Constructs an ``Ising`` operator for a 1D system.
```python
>>> import nqs
>>> g = nqs.graph.Hypercube(length=20, n_dim=1, pbc=True)
>>> hi = nqs.hilbert.Spin(s=0.5, graph=g)
>>> op = nqs.operator.Ising(h=1.321, hilbert=hi, J=0.5)
>>> print(op.hilbert.size)
20
"""
sigma_x = _np.array([[0, 1], [1, 0]])
sz_sz = _np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
return GraphOperator(hilbert, siteops=[-h * sigma_x], bondops=[J * sz_sz])
def Heisenberg(hilbert):
"""
Constructs a new ``Heisenberg`` given a hilbert space.
Args:
hilbert: Hilbert space the operator acts on.
Examples:
Constructs a ``Heisenberg`` operator for a 1D system.
```python
>>> import nqs
>>> g = nqs.graph.Hypercube(length=20, n_dim=1, pbc=True)
>>> hi = nqs.hilbert.Spin(s=0.5, total_sz=0, graph=g)
>>> op = nqs.operator.Heisenberg(hilbert=hi)
>>> print(op.hilbert.size)
20
"""
sz_sz = _np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
exchange = _np.array([[0, 0, 0, 0], [0, 0, 2, 0], [0, 2, 0, 0], [0, 0, 0, 0]])
if hilbert.graph.is_bipartite:
heis_term = sz_sz - exchange
else:
heis_term = sz_sz + exchange
return GraphOperator(hilbert, bondops=[heis_term])
|
f14c2fc7a425e87e6050b802fe20e5f36ca6a60f | JohnsonClayton/DeepLearning-DNSoverHTTPS | /utils/data_preprocessing.py | 2,187 | 3.90625 | 4 | def get_data(path, layer=0, nans=False):
""" get_data function
Description: This function will take the given path and user-defined layer from the dataset, import the datafiles, and then return the combined pandas DataFrame
Arguments:
path => string, path to the directory containing the l1-doh.csv, l1-nonhod.csv, etc files.
layer => int, the level of layer desired. This will change the dataset that is imported. Values can be 1 or 2. Default is 0.
nans => boolean, Whether the user wants NaNs in the data or wants them removed. This function will automatically remove all rows with Nan values.
Returns:
df => pandas.DataFrame, contains complete data
Raises:
AttributeError for incorrect layer number
Any additional read errors are raised to the user
"""
import pandas as pd
if layer not in [1,2]:
raise AttributeError('Must provide valid layer for dataset: layer equals 1 or 2')
else:
# Select the files that the user has chosen
filenames = []
if layer == 1:
filenames.append('l1-doh.csv')
filenames.append('l1-nondoh.csv')
else:
filenames.append('l2-benign.csv')
filenames.append('l2-malicious.csv')
# Read the files into dataframes
df0 = pd.read_csv(path + '/' + filenames[0])
df1 = pd.read_csv(path + '/' + filenames[1])
df = pd.concat([df0, df1])
# Remove any rows with Nan values
if not nans:
df.dropna(axis='index', inplace=True)
return df
def balance_data(df, label_column):
labels = df[label_column].unique()
sample_length_list = []
for i in range(len(labels)):
samples = df.loc[ df[label_column] == labels[i] ]
sample_length_list.append( len(samples) )
#print('Number of {} samples: {}'.format(labels[i], len( samples )))
random_state = 0
smallest_count = min(sample_length_list)
dfs = []
for i in range(len(labels)):
dfs.append( df.loc[ df[label_column] == labels[i] ].sample(smallest_count) )
return pd.concat(dfs)
|
5fe155a646573315ba63f4579407656a7f0af6bb | navneetpurohitt/LibraryManagementSystem | /check.py | 2,206 | 4.1875 | 4 | ## import pickle
# Let we create a class
class Car:
def __init__(self, name, model, color):
self.name = name
self.model = model
self.color = color
def display(self):
print(self.name, "\t", self.model, "\t", self.color)
def dump():
with open("car.pkl", "wb") as f:
l = []
n = int(input("How many record to be entered"))
for i in range(n):
name = input("Name:")
model = input("Model:")
color = input("Color:")
c = Car(name, model, color)
l.append(c)
pickle.dump(l, f)
print("Record updated successfully")
def load():
with open("car.pkl", 'rb') as f:
while (1):
try:
obj = pickle.load(f)
for i in obj:
i.display()
except EOFError:
print("Data read is completed")
break
def remove():
obj = None
with open("car.pkl", "rb") as f:
h = input("Enter the name of the Car you want to remove: ")
while (1):
try:
obj = pickle.load(f)
for i in obj:
print(i.name)
if i.name == h:
obj.remove(i)
except EOFError:
print("Data read is removed")
break
with open("car.pkl", "wb") as f:
pickle.dump(obj, f)
def modify():
obj = None
with open("car.pkl", "rb") as f:
h = input("Enter the name of the Car you want to modify: ")
while (1):
try:
obj = pickle.load(f)
for i in obj:
if i.name == h:
i.model = input("Enter the model to change")
except EOFError:
print("Data read is modified")
break
with open("car.pkl", "wb") as f:
pickle.dump(obj, f)
ch = 9
while (ch != 0):
print("\n1:Enter record\n2:View record\n3:Remove\n4:Modify\n0:Exit")
ch = int(input())
if ch == 1:
dump()
elif ch == 2:
load()
elif ch == 3:
remove()
elif ch == 4:
modify()
|
e9ed1f96ff9806251fbe107b11b887c98825a5c4 | adamltyson/imlib | /imlib/array/size.py | 759 | 4.15625 | 4 | import numpy as np
def pad_with_number_1d(array, final_length, pad_number=0):
"""
For a given array, pad with a value (symmetrically on either side) so that
the returned array is of a given length.
:param np.array array: Input array.
:param int final_length: How long should the final array be.
:param (float, int) pad_number: What value to pad with. Default: 0.
:return: New array of length: final_length
"""
length = len(array)
pad_length = int((final_length - length) / 2)
pad = pad_number * np.ones((pad_length, 1))
new_array = np.append(pad, array)
new_array = np.append(new_array, pad)
if len(new_array) < final_length:
new_array = np.append(new_array, pad_number)
return new_array
|
00357bbb66656ce9c0e36e8c1dcd090ed77ed3fc | Harshhg/Apache_Spark | /py code/Spark RDD/RDD_word_count.py | 1,433 | 3.8125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import findspark
findspark.init('/home/ec2-user/spark')
# In[2]:
import pyspark
from pyspark import SparkContext
# In[3]:
sc = SparkContext()
# In[33]:
# Creating a RDD
data = ["Hello world how are you? are you ok? thanks world"]
rdd = sc.parallelize(data)
# In[34]:
# Now splitting the file using flatMap() function so that we get each word as seperate element of RDD
flatmapRDD = rdd.flatMap(lambda x : x.split(" "))
print("Flat map: ", flatmapRDD.collect())
print("Flat map: ", flatmapRDD.take(3))
# If we use map function to split this, we will get the words splitted but as a single element of RDD
maprdd = rdd.map(lambda x : x.split(" "))
print("\nMap: ",maprdd.collect())
print("Map: ", maprdd.take(3))
# In[35]:
# Now creating key value pair RDD, by mapping each word with key and value.
secondrdd = flatmapRDD.map(lambda word: (word,1))
# In[36]:
secondrdd.take(3)
# In[37]:
# Now we will use reduceKey() function to add up the values with similiar keys(words)
thirdrdd = secondrdd.reduceByKey(lambda word,count : word+count)
thirdrdd.collect()
# In[38]:
# Plotting the chart of the word count
import matplotlib.pyplot as plt
# In[44]:
# Seperating words and counts into two lists..
words=[]
counts=[]
for x in thirdrdd.collect():
words.append(x[0])
counts.append(x[1])
# In[47]:
# Plotting bar chart
plt.bar(words,counts)
|
554b81a4fd49416c21baf3b30fc7f39d4b29860e | gibbson/bootcamp | /thirdday.py | 673 | 3.671875 | 4 | import numpy as np
xa_high = np.loadtxt('data/xa_high_food.csv', comments='#')
xa_low = np.loadtxt('data/xa_low_food.csv', comments='#')
def xa_to_diameter(xa):
"""
Convert an array of cross_sectional areas to diameters with commuensurate units
"""
# Compute diameter from area
# A = pi * d^2 / 4
diameter = np.sqrt(xa * 4 / np.pi)
return diameter
A = np.array([[6.7, 1.3, 0.6, 0.7],
[0.1, 5.5, 0.4, 2.4],
[1.1, 0.8, 4.5, 1.7],
[0.0, 1.5, 3.4, 7.3]])
b = np.array([1.3, 2.3, 3.3, 3.9])
# Print row 1 of A
# Print columns 1 and 3 of A
# Print the values of every entry in A that is Great Than 2
|
91f35ccdb4e4a3dcaf5c05f68af985bb9cd90ae9 | bj730612/Bigdata | /01_Jump_to_Python/Chapter05/185.py | 494 | 3.625 | 4 | class Service:
secret = "영구는 배꼼이 두 개다"
name = ""
def __init__(self,name):
self.name = name
print("맴버변수 %s 를 초기화 하였습니다." %self.name)
def sum(self, a, b):
result = a + b
print("%s님 %s + %s = %s 입니다." %(self.name, a, b, result))
def __del__(self):
print("저희 서비스를 이용해 주셔서 감사합니다.")
input()
pey = Service("홍길동")
input()
pey.sum(1, 1)
input() |
c80d4ce37fd06f5e5b5671f598d285730f3d16ba | wsullivan17/Adoption-Center | /test1.py | 701 | 3.75 | 4 | class Animals:
"""Holds data for each individual animal"""
def __init__(self, animal, age, status):
self.animal = animal
self.age = age
self.status = status
def to_string(self):
return f"{self.animal} : {self.age} : {self.status}"
#dog1 = Animals("b", "c", "d")
#print(dog1.name)
number = 0
animals_list = []
with open("dog_data.txt", "r") as data:
data_line = data.readlines()
for x in data_line:
lines = x.split('_')
animals_list.append(Animals(lines[1], lines[2], lines[3]))
for animal1 in animals_list:
print(animal1.to_string())
print(animals_list[1].to_string())
print(animals_list[1].age)
#print(lines)
|
e99eaca490fbc26c0d341b57513949e7e3e43bf9 | 77fang/sc-projects | /breakout_game/breakout.py | 1,483 | 3.59375 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
YOUR DESCRIPTION HERE
"""
from campy.gui.events.timer import pause
from breakoutgraphics import BreakoutGraphics
from campy.graphics.gobjects import GOval, GRect, GLabel
FRAME_RATE = 1000 / 120 # 120 frames per second.
NUM_LIVES = 3
def main():
graphics = BreakoutGraphics()
lives = NUM_LIVES
# Add animation loop here!
graphics.click_to_start()
while True:
pause(FRAME_RATE)
if graphics.switch: # Switch on.
graphics.ball_on_thing() # Check if ball hit on objects.
graphics.ball_move() # Ball bounce back if it hits wall.
if graphics.get_score() == graphics.get_brick_number(): # If scores are the same as brick numbers.
graphics.stop_win() # Stop ball and print "You Win!"
break
if graphics.ball.y >= graphics.window.height: # If ball falls out of window, lives minus one.
graphics.switch = False
lives -= 1
if lives > 0:
graphics.reset_ball() # Reset ball.
else:
graphics.game_over() # Break if there are no more lives.
break
if __name__ == '__main__':
main() |
fd2692d10d396014b7f99cbd9cb887704b8085dc | expeon07/grid_position | /main.py | 3,447 | 3.90625 | 4 | from typing import Dict
import string
import matplotlib.pyplot as plt
def assign_coordinates(starting_position: tuple, spacing: int) -> Dict:
""" Assigns coordinates to the points
Args:
starting_position (tuple): Coordinates of point A1
spacing (int): Spacing per step on x columns and y rows
Returns:
grid_coordinates (Dict): Dictionary of point names and coordinates
"""
grid_coordinates = {}
for letter in string.ascii_uppercase:
y = int(starting_position[1]) - ((string.ascii_uppercase.index(letter))
* spacing)
if letter == "I":
break
for i in range(1, 13):
x = int(starting_position[0]) + ((i - 1) * spacing)
point_name = letter + str(i)
grid_coordinates[point_name] = (x,y)
# print(grid_coordinates)
return grid_coordinates
def get_location(grid: Dict, point: str) -> tuple:
""" Returns the coordinates of the requested point
Args:
grid (Dict): Dictionary of point names and coordinates
point (str): Point name
Returns:
(x, y) (tuple): Coordinates of the desired points
"""
x, y = grid[point]
return (x, y)
def print_grid(grid: Dict):
""" Displays the grid in a simple graph
Args:
grid (Dict): [description]
Returns: none
"""
# print(grid)
coordinates = []
for coordinate in grid.values():
coordinates.append(coordinate)
plt.scatter(*zip(*coordinates))
for name in grid:
plt.annotate(name, (grid[name][0], grid[name][1]))
plt.show()
if __name__ == "__main__":
point_err_mess = "Value should be an integer in the range [-1000, 1000]."
starting_x_pos = None
while (starting_x_pos == None):
try:
starting_x_pos = int(input("Select starting x position for A1: "))
if (starting_x_pos > 1000) or (starting_x_pos < -1000):
print(point_err_mess)
starting_x_pos = None
except ValueError:
print(point_err_mess)
starting_x_pos = None
starting_y_pos = None
while (starting_y_pos == None):
try:
starting_y_pos = int(input("Select starting y position for A1: "))
if (starting_x_pos > 1000) or (starting_x_pos < -1000):
print(point_err_mess)
starting_y_pos = None
except ValueError:
print(point_err_mess)
starting_y_pos = None
spacing = -1
while (spacing <= 0):
try:
spacing = int(input("Select spacing for x and y: "))
except ValueError:
print("Spacing should be a positive integer.")
spacing = -1
# Make the grid
grid = assign_coordinates((int(starting_x_pos), int(starting_y_pos)),
int(spacing))
# Ask if user wants to show map
show_map = input("Show map? (y/n) ")
if show_map == "y":
print_grid(grid)
# Get location of a desired point
location = (None, None)
while (location == (None, None)):
try:
point = input("Which point do you want to locate in this grid? ")
location = get_location(grid, point)
print(location)
except KeyError:
print("Please enter any point name from A1, A2, A3,..., H12.")
|
698da78ad82dd604b8a703ce18f6a2cd14584a45 | danilsyah/python-learning | /12-If-Elif-Else/Main.py | 1,200 | 3.8125 | 4 | nilai1 = 75
nilai2 = 80
# nesting if
if nilai1 == 75:
print("nilai anda", nilai1)
print("step 1")
if nilai2 == 80:
print("nilai anda", nilai2)
print("step 2")
nilai = 50
if nilai == 75: # equal eksplisit
print("nilai anda :", nilai)
if nilai is 60: # equal
print("nilai anda :", nilai)
if nilai is not 60: # not equal
print("nilai anda bukan 60, tapi :", nilai)
print(40*"=")
nilai = 60
if 80 <= nilai <= 100:
print("nilai anda adalah A")
elif 70 <= nilai <= 80:
print("nilai anda adalah B")
elif 60 <= nilai <= 70:
print("nilai anda adalah C")
elif 50 <= nilai <= 60:
print("nilai anda adalah T, lakukan perbaikan")
else:
print("maaf anda tidak lulus mata kuliah ini")
print(100*"+")
print("Operator Logika untuk List dan string")
print(" ")
gorengan = ["bakwan", "cireng", "gehu", "bala-bala", "tahu"]
beli = "bandros"
if beli in gorengan:
print('Mamang bilang : " ya, saya jual, ', beli, ' "')
if not beli in gorengan:
print('Mamang bilang, " waduh euy saya lagi ga jual ', beli, ' " ')
karakter = "z"
if karakter in beli:
print("ada", karakter, "di ", beli)
else:
print("tidak ada", karakter, "di ", beli)
|
4f91284d77c5d8e9b529d721e29550b68977c838 | mskyberg/Module7 | /fun_with_collections/basic_tuple.py | 1,202 | 4.375 | 4 | """
Program: basic_tuple.py
Author: Michael Skyberg, mskyberg@dmacc.edu
Last date modified: June 2020
Purpose: Demonstrates the use of a basic tuple
"""
def average_scores(*args, **kwargs):
"""
Description: calculates the average of scores and returns a string
:param: *args, score arguments
:param: **kwargs, arguments to include in return string
:returns: returns a string formatted with kwargs and args
:raises keyError: raises an exception
"""
# calculate average of args
average = 0
for arg in args:
average += arg
average = average / (len(args))
# format the string to return with keyword args
return_string = 'Result: '
for key, value in kwargs.items():
return_string += "%s = %s " % (key, value)
return f'{return_string}with current average {average}'
if __name__ == '__main__':
print(average_scores(85, 90, 92, name='Mike', gpa='3.6', course='Python'))
print(average_scores(71, 80, 78, 78, 59, team_name='Wild Cats',
leading_scorer='Jacob', games_remaining='7'))
print(average_scores(94, 97, 99, 100, report='Vacation Review',
start_date='6/17/20', location='Miami'))
|
7c9cbd2dbacc043455fb9fa59fb78e3608290c43 | adusa1019/atcoder | /ABC087/A.py | 182 | 3.578125 | 4 | def solve(string):
x, a, b = map(int, string.split())
return str((x - a) % b)
if __name__ == '__main__':
n = 3
print(solve('\n'.join([input() for _ in range(n)])))
|
f28bb47bc7f43d7c29947a5589920c8ed30dfdb9 | sagudecod97/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 393 | 3.828125 | 4 | #!/usr/bin/python3
import sys
if (__name__ == "__main__"):
argv = sys.argv
i = 1
if (len(argv) == 1):
print("0 arguments.")
elif (len(argv) == 2):
print("1 argument:\n1: {:s}".format(argv[1]))
else:
print("{:d} arguments:".format(len(argv) - 1))
while (i < len(argv)):
print("{:d}: {:s}".format((i), argv[i]))
i += 1
|
752d2010609004e61a8276b2e62e35c913b9a485 | filipov73/python_fundamentals_september_2019 | /07.Data Types and Variables - More Exercises/02. Exchange Integers.py | 138 | 3.53125 | 4 | a = int(input())
b = int(input())
print(f"Before:\na = {a}\nb = {b}")
# a, b = b, a
c = b
b = a
a = c
print(f"After:\na = {a}\nb = {b}")
|
8181aefef00e17576c3fba1f57c400c697c2b0e6 | Niccoryan0/OldPythonProjects | /Hangman/main.py | 3,939 | 3.71875 | 4 | import random
# suits = ['Hearts', 'Diamonds', 'Spades', 'Clovers']
# ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
# values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}
game_on = True
from GameClasses.card import Card
from GameClasses.deck import Deck
from GameClasses.hand import Hand
from GameClasses.chips import Chips
def take_bet(chips):
while True:
try:
print(f'You have: {chips.total} chips')
chips.bet = int(input('How much would you like to bet? '))
except ValueError:
print("Invalid input, please enter an integer")
continue
else:
if chips.bet > chips.total:
print(f'Not enough chips! Your total: {chips.total}')
continue
else:
break
def hit(deck,hand):
hand.add_card(deck.deal())
hand.adjust_for_ace()
def hit_or_stand(deck, hand):
global playing # to control an upcoming while loop
hitorstand = input('Hit or stand? ').lower()
if hitorstand.startswith('h'):
hit(deck,hand)
elif hitorstand.startswith('s'):
playing = False
else:
print('Invalid input, please try again')
def show_some(player, dealer):
print("\nDealer's hand:")
print('<card face down>')
print(*dealer.cards[1:], sep='\n')
print("\nPlayer's hand:", *player.cards, sep='\n')
print("Hand total: ", player.value)
def show_all(player, dealer):
print("\nDealer's hand:", *dealer.cards, sep='\n')
print("Dealer's hand total: ", dealer.value)
print("\nPlayer's hand:", *player.cards, sep='\n')
print("Hand total: ", player.value)
def player_busts(player, chips):
if p_hand.value > 21:
print('\nYou busted!')
chips.lose_bet()
return True
def player_wins(player,dealer,chips):
if 21 >= p_hand.value > d_hand.value:
print('\nYou win!')
chips.win_bet()
def dealer_busts(dealer, chips):
if d_hand.value > 21:
print('\nDealer busted!')
chips.win_bet()
return True
def dealer_wins(player, dealer, chips):
if 21 >= d_hand.value > p_hand.value:
print('\nDealer wins!')
chips.lose_bet()
def tie():
if p_hand == d_hand:
print("It's a tie!")
def replay():
while True:
try:
restart = input('Play again? y/n: ').lower().startswith('y')
except ValueError:
print('Invalid input, please enter y for yes or n for no')
continue
else:
return restart
chips = Chips() # Automatically set to 100 but can be changed, kept outside so it doesnt refresh to 100 every replay
deck = Deck() # Kept outside so that the deck doesnt restock every replay
deck.shuffle()
while True:
print('Welcome to BlackJack!')
if len(deck) == 0:
deck = Deck() # Refreshes deck if it runs out
deck.shuffle()
p_hand = Hand()
p_hand.add_card(deck.deal())
p_hand.add_card(deck.deal())
d_hand = Hand()
d_hand.add_card(deck.deal())
d_hand.add_card(deck.deal())
chips = Chips(chips.total)
take_bet(chips)
show_some(p_hand, d_hand)
playing = True
while playing:
hit_or_stand(deck, p_hand)
show_some(p_hand, d_hand)
if player_busts(p_hand, chips):
break
if d_hand.value <= 16:
hit(deck, d_hand)
if dealer_busts(d_hand, chips):
break
show_all(p_hand, d_hand)
dealer_wins(p_hand, d_hand, chips)
player_wins(p_hand, d_hand, chips)
tie()
print(f'\nYou have: {chips.total} chips')
if chips.total == 0:
print('Out of chips')
break
elif not replay():
break
print('\n\n')
print('Thanks for playing!')
|
39def8c8accd6ad0f726bce6fabca223246c98b7 | jaquepalmeira/programasDiversos | /remove_repetidos.py | 218 | 3.859375 | 4 | def remove_repetidos(x):
y = []
for i in x:
if i not in y:
y.append(i)
return sorted(y)
x=eval('[' + input("Digite os números da sua lista separados por vírgula:")+']')
print (remove_repetidos(x))
|
e3ef1ac0af8b6a9a8c93d56dd0f2581613e04945 | DarrenYee/Monash-Python-Projects- | /sorts.py | 17,805 | 4.21875 | 4 | """
Name: Darren Yee Jer Shien
Student ID: 31237223
FIT2004 Assignment 1
"""
def sort_counting_stable(new_list, column):
'''
Precondition: new_list must have at least one item
This is an a full implementation of the counting sort algorithm which is used to be used in the radix sort
for question 1 of assignment 1.
:param new_list: list of transactions
:param column: current column that we are checking
:return: list sorted according to thr column
Best Case Complexity: O(n+k)
Worst Case Complexity: O(n+k)
Code modified from FIT2004 Tutorial 2
'''
a = 0
base = 10
max_item = new_list[0] % base
for item in new_list:
if item > max_item:
max_item = item
# initialize count array
count_array = [None] * 10
# update count array
for i in range(len(count_array)):
count_array[i] = []
for item in new_list:
a = item % base
count_array[item // (base ** column) % base].append(item)
# update input list
index = 0
for i in range(len(count_array)):
item = i
frequency = count_array[i]
for j in range(len(frequency)):
new_list[index] = count_array[i][j]
index = index + 1
return new_list
def radix_sort(list):
"""
normal radix sort implementation for question 1 of assignment 1
:param list: list of transactions
:return: sorted list of transactions
Best Case Complexity: O(nk) where n is the length of the list and k is the number of digits
Worst Case Complexity: same as Best Case
"""
maximum_value = max(list)
base = 10
col = 0
while maximum_value > 0:
sort_counting_stable(list, col)
col += 1
maximum_value = maximum_value // 10
return list
def best_interval(transactions, t):
"""
Used to find the interval with most transactions
:param transactions: list of transactions
:param t: the length of interval
:return: the starting point of the interval with the most elements available
The usage of each variables are as follows:
lo and hi are used as pointers representing the minimum and maximum value of the interval,
1) best_start and best_end to keep track ofthe current best interval,
2) tracker and tracker1 to keep track of the current amount of element and the amount of elements
in the current best interval respectively,
3) swapped which is a boolean that returns true or false depending if the current transaction
item is more than the hi
4) swap which helps to keep track of which start point of interval we should check for next.
should check for next
Worst case complexity of this function would be O(nt) where n is the number of elements
and t is the length of interval needed
Best case complexity would be O(1) if the list is an empty list. It will loop through the list by using
two pointers (lo and hi) in order to determine which interval has the most elements
"""
#checks if transactions is an empty list and returns 0,0 immediately
if len(transactions) == 0:
return (0, 0)
#performs radix_sort on transactions list to make sure similar items are grouped together
radix_sort(transactions)
lo = transactions[0]
hi = lo + t
best_start = 0
best_end = 0
tracker = 0
tracker1 = 0
swap = 0
i = 0
swapped = False
#while loop that terminates only when it reaches the final element of the list
while i <= len(transactions) - 1:
swapped = False
hi = lo + t
#checks if it is within the range of the current interval that we are checking
if transactions[i] >= lo and transactions[i] <= lo + t:
tracker = tracker + 1
i += 1
else:
#if not within the range, perform the check of best swap
swap += 1
swapped = True
if swapped == True:
if tracker > tracker1:
# if if the current tracker is higher than the current best tracker, update it
best_end = transactions[i - 1]
best_start = best_end - t
tracker1 = tracker
tracker = 0
else:
#else, reset the tracker
tracker = 0
if best_start < 0:
best_start = 0
#update lo with the new starting point of the interval
lo = transactions[swap]
i = swap
#final checker for tracker in order to ensure it is correct
if tracker > tracker1:
best_end = transactions[i - 1]
best_start = best_end - t
tracker1 = tracker
# if tracker one has not been updated, ie all elements are the same, set tracker1 as the current one
if tracker1 == 0 and i > 0:
tracker1 = tracker
best_start = transactions[i - 1] - t
#if everything is the same element, set tracker1 as length of the transactions list
elif tracker1 == 0 and i == 0:
tracker1 = len(transactions)
return (best_start, tracker1)
"""
Name: Darren Yee Jer Shien
Student ID :31237223
Assignment 1 Question 2
"""
def sort_counting_alpha_radix(new_list, column):
'''
Precondition: new_list must have at least one item
Counting sort for alphabets using ord and char
:param new_list = list of words
:param column = the current column that we are tracking
Best Case Complexity: O(n+k) where n = number of elements in list and k = range between largest and smallest
alphabet
Worst Case Complexity: O(n+k) where n = number of elements in list and k = range between largest and smallest
alphabet
Code modified from FIT2004 Tutorial 2
'''
# finding max of list
a = 0
#sets the maximum item
for i in range (len(new_list)):
if len(new_list[i]) >= column+1:
max_item = ord(new_list[i][column])-97
for item in new_list:
if len(item) >= column+1:
item = ord(item[column])-97
if item > max_item:
max_item = item
# initialize count array
count_array = [None] * 26
# update count array
for i in range(len(count_array)):
count_array[i] = []
for item in new_list:
tracker = 0
if len(item) >= column+1:
a = ord(item[column]) - 97
count_array[a].append(item)
tracker = 1
if tracker == 0:
count_array[0].append(item)
# update input list
index = 0
for i in range(len(count_array)):
item = i
frequency = count_array[i]
for j in range(len(frequency)):
if len(new_list[index]) < len(frequency[j]) and index+1 < len(new_list):
new_list[index+1] = new_list[index]
new_list[index] = count_array[i][j]
index = index + 1
return new_list
def sort_counting_alpha(new_list):
'''
Precondition: new_list must have at least one item
:param new_list : current word in the radix sort
Best Case Complexity: O(n+k) where n = number of elements in list and k = range between largest and smallest number
Worst Case Complexity: O(n+k) where n = number of elements in list and k = range between largest and smallest number
'''
ans = []
#finding max of list
if len(new_list) <= 0:
return ans.append(new_list)
max_item = ord(new_list [0])-97
for item in new_list:
if len (item) > 0:
item = ord(item)-97
if item > max_item:
max_item = item
#prints max item
#initialize count array
count_array = [0] * (max_item+1)
#update count array
for item in new_list:
count_array [ord(item)-97] = count_array [ord(item)-97] + 1
#update input list
index = 0
for i in range (len(count_array)):
item = i
frequency = count_array[i]
for j in range (frequency):
ans.append(chr((item)+97))
index = index + 1
return ans
def radix_sort_alpha(list):
"""
used to sort strings using radix sort
:param list: list of words that contain at least one anagram
:return: sorted list of words
Best case complexity = (L1M1 + L2M2) where L1 = number of elements in list 1 M1 = longest string in list 1,
L2 = number of elements in list 2, M2 = longest string in list 2(bounded by radix sort)
Best case complexity = (L1M1 + L2M2) where L1 = number of elements in list 1 M1 = longest string in list 1,
L2 = number of elements in list 2, M2 = longest string in list 2(bounded by radix sort)
"""
maximum_digits = 0
for i in range (len(list)):
if len(list[i]) > maximum_digits:
maximum_digits = len(list[i])
col = maximum_digits - 1
while col >= 0:
sort_counting_alpha_radix(list, col)
col -= 1
return list
def sort_counting(new_list):
'''
Precondition: new_list must have at least one item
Basic counting sort algorithm used to sort the index list based on order.
:param new_list : list of index
Best Case Complexity: O(n+k) where n = number of elements in list and k = range between largest and smallest number
Worst Case Complexity: O(n+k) where n = number of elements in list and k = range between largest and smallest number
'''
# checks if first element is empty string and skips if when setting maximum value
if new_list[0] == "":
max_item = new_list[1]
else:
max_item = new_list[0]
for item in new_list:
if item != "":
if item > max_item:
max_item = item
#initializes count array
count_array = [None] * (max_item+1)
for i in range (len(count_array)):
count_array[i] = []
#checks if item is empty string and automatically appends it to index 0 of count array to ensure it appears first
for item in new_list:
if item == "":
count_array[0].append(item)
else:
count_array[item].append(item)
index = 0
#update input list and return it
for i in range(len(count_array)):
item = i
frequency = count_array[i]
for j in range(len(frequency)):
new_list[index] = count_array[i][j]
index = index + 1
return new_list
def lensort(new_list):
'''
Precondition: new_list must have at least one item
Used to sort the words based on their length, uses a modified version of counting sort
:param new_list : list of words
:return new_list: list of strings sorted according to length
Best Case Complexity: O(n+k) where n = number of elements in list and k = range between largest and smallest number
Worst Case Complexity: O(n+k) where n = number of elements in list and k = range between largest and smallest number
'''
#sets max item according to length of string
max_item = len(new_list[0])
for item in new_list:
if len(item) > max_item:
max_item = len(item)
#initialize count array
count_array = [None] * (max_item+1)
for i in range (len(count_array)):
count_array[i] = []
#update count array
for item in new_list:
count_array [len(item)].append(item)
index = 0
#update input list
for i in range(len(count_array)):
item = i
frequency = count_array[i]
for j in range(len(frequency)):
new_list[index] = count_array[i][j]
index = index + 1
return new_list
def find_anagram (list1,list2):
"""
Used to find the similar words in both list in order to extract the anagrams
:param list1: list 1 from words_with_anagram
:param list2: list2 from words_with_anagrams
:return: the index of the common values in the list
The usage of each variables are as follows:
1) temp is a copy of the list1
2) tester_a and tester_b sets the starting point of the iteration after checking
whether it contains empty string.
3) index is the list we return containing the index of words with anagrams
4) a and b are current items that we are looking at from list1 and list2 respectively
5) iterA and iterB are the two pointers that we use to transverse the lists, they are first
initialized using tester_a and tester_b to start at the item after "" if it exists, if not,
it will start at the first item.
6)tracker will be our exit condition which tracks whether iterA or iterB has reached the end of the list
Best Case Complexity: O(n) where n is the length of either list 1 or list 2 (depending on which is shorter)
Worst Case Complexity: O(n) where n is the length of either list 1 or list 2 (depending on which is shorter)
"""
temp = list1.copy()
tester_a = 0
tester_b = 0
index = []
#checks if list 1 and list 2 contains empty string
for i in range(len(list1)):
if len(list1[i]) <= 0:
tester_a += 1
for i in range(len(list2)):
if len(list2[i]) <= 0:
tester_b += 1
if tester_a and tester_b > 0:
index.append("")
#initializes the first items from list 1 and list 2
a = list1[tester_a]
b = list2[tester_b]
tester = []
iterA = tester_a
iterB = tester_b
tracker = True
# will only terminate if iterA or iterB reaches the maximum length of each list respectively
while tracker == True:
#calls radix sort on the items to check which one is larger
tester= radix_sort_alpha([a,b])
#if it is the same, we append the index of item into the list
if a == b:
index.append(temp.index(list1[iterA]))
iterA += 1
iterB += 1
# if iterA or iterB reaches the end of the list, set tracker to False for loop termination
if iterA == len(list1) or iterB == len(list2):
tracker = False
else:
# if not then we increment both iterA and iterB
a = list1[iterA]
b = list2[iterB]
# checks if the previous the item in list A is the same as the previous one since list1 can share an anagram from list2
elif list1[iterA] == list2[iterB-1]:
index.append(temp.index(list1[iterA])+1)
iterA +=1
if iterA == len(list1):
tracker = False
else:
a = list1[iterA]
#if b is longer than a, then we increment iterA
elif len(a) < len(b):
iterA += 1
if iterA == len(list1):
tracker = False
else:
a = list1[iterA]
# if after we radix sort both values a is smaller than b and a's length is less than or equal to b's length, we increment iterA
elif tester[0] == a and len(a) <= len(b):
iterA += 1
if iterA == len(list1):
tracker = False
else:
a = list1[iterA]
#if all the conditions are not met, then we increment iterB
else:
iterB += 1
if iterB == len(list2):
tracker = False
else:
b = list2[iterB]
return index
def words_with_anagrams (list1,list2):
"""
:param list1: list provided by tester
:param list2: list provided by tester
:return answer : all the words that are anagrams in between list1 and list2
variables that are used as follows:
1) temp is a copy of list1 after counting sort is performed
2) temp1 is a copy of list1 before anything is performed
3) answer is the list where we will store the anagrams
4) index is where we will store the index of anagrams after calling
find_anagrams
Best Case Complexity: O(L1M1+L2M2) where L1 = number of elements in list 1 M1 = longest string in list 1,
L2 = number of elements in list 2, M2 = longest string in list 2(bounded by radix sort)
Worst Case Complexity: O(L1M1+L2M2) where L1 = number of elements in list 1 M1 = longest string in list 1,
L2 = number of elements in list 2, M2 = longest string in list 2(bounded by radix sort)
"""
temp = []
temp1 = list1.copy()
answer = []
index = []
#call counting sort for all items in list1 and 2 and join the outcome together back into the list
#this is to ensure that they are sorted alphabetically
for item in list1:
if len (item) > 0:
list1[list1.index(item)] =("".join(sort_counting_alpha(item)))
else:
list1[list1.index(item)] = list1[list1.index(item)]
temp = list1.copy()
for item in list2:
if len(item) > 0:
list2[list2.index(item)] =("".join(sort_counting_alpha(item)))
#call radix sort for list1 and list2 after they are sorted alphabetically
radix_sort_alpha(list1)
radix_sort_alpha(list2)
#sorts them based on length by using modified counting sort method
lensort(list1)
lensort(list2)
#calls find_anagram method using list1 and list2
index = find_anagram(list1,list2)
#sort the index in order by calling original counting sort algorithm
index = sort_counting(index)
#append the answers by referencing the index of the items from the temp back into temp1
for i in range(len(index)):
# if it is empty string, then we just append it into the answers
if index[i] == "":
answer.append(index[i])
else:
#if not then we will append the item into the answer and set the current item to 0 in order to avoid words with the same anagrams to reference the wrong thing.
answer.append(temp1[temp.index(list1[index[i]])])
temp[temp.index(list1[index[i]])] = 0
return answer |
a8beaf70cc33f1f2935116a27d71948b0d7829bf | chispa73/hello-world | /Change Machine Checkout.py | 2,032 | 3.875 | 4 | #Give correct change in canadian denominations as a cash register with the least number of coins
import decimal
#Value of Canadian denominations
LOONIE = 1
TOONIE = 2
QUARTER = 25
DIME = 10
NICKEL = 5
PENNY = 1
#Ask user to input value of shopping cart
goods_value = decimal.Decimal(input('Please enter the total cost in CAD of goods sold: ')) #used the decimal type
goods_value = goods_value.quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP) #specifying the number of decimal places to use
#Ask user to input cash
tendered_cust = decimal.Decimal(input('Please enter the cash given: '))
tendered_cust = tendered_cust.quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP)
#Break down between dollars and cents
change = str(tendered_cust - goods_value) #turned to a string
split_num = str(change).split('.') #splitting between the decimal
change_value_dollar = int(split_num[0]) #moving each value into it's own variable of dollars and cents
change_value_cents = int(split_num[1])
#Break down the dollars
toonie_total = int(change_value_dollar / TOONIE)
loonie_total = int(change_value_dollar - (toonie_total * TOONIE) / LOONIE)
#Break down coins starting with quarters
cents_needed = int(change_value_cents)
quarters_needed = int(cents_needed / QUARTER)
#dimes
dime_cents_needed = int(cents_needed - (quarters_needed * QUARTER))
dimes_needed = int(dime_cents_needed / DIME)
#nickels
nickel_cents_needed = int(cents_needed - ((quarters_needed * QUARTER) + (dimes_needed * DIME)))
nickels_needed = int(nickel_cents_needed / NICKEL)
#pennies
pennies_cents_needed = int(cents_needed - ((quarters_needed * QUARTER) + (dimes_needed * DIME) + (nickels_needed * NICKEL)))
pennies_needed = int(pennies_cents_needed / PENNY)
print(' Change is $%.2f' %(tendered_cust - goods_value))
print(' We need', toonie_total, 'toonies', loonie_total, 'loonies', quarters_needed, 'quarters,', dimes_needed, 'dimes', nickels_needed, 'nickels', pennies_needed, 'pennies!')
|
4a35d766b71e9471abb77014bbc31caf5eab1ebb | kmgowda/kmg-leetcode-python | /palindrome-permutation/palindrome-permutation.py | 440 | 3.703125 | 4 | // https://leetcode.com/problems/palindrome-permutation
class Solution(object):
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
d= collections.Counter(s)
odd = 0
for cnt in d.values():
if cnt % 2:
odd += 1
if odd > 1:
return False
return True
|
a08009727d95fa01c25f32da1756612cbb69e7f1 | raviqqe/char2image.py | /char2image/__main__.py | 690 | 3.53125 | 4 | import argparse
import json
import sys
from . import char2image
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('document_file', nargs='?',
type=argparse.FileType(), default=sys.stdin)
parser.add_argument('-s', '--size', type=int, default=32)
parser.add_argument('-f', '--font-file', required=True)
return parser.parse_args()
def main():
args = get_args()
print(json.dumps(
char2image.char_to_image_dict(
{char for char in args.document_file.read()},
char2image.filename_to_font(args.font_file, args.size)),
ensure_ascii=False))
if __name__ == '__main__':
main()
|
58f11c5cc8ea4b0138e34902ecfc97676ac54dc2 | hb5105/LabsSem6 | /IT LAB/WEEK4/week4/week4/q2.py | 452 | 3.796875 | 4 | class Pair:
def pairs(self):
flag=0
a=input("enter a list of numbers\n").split(' ')
targ=int(input("enter target value:\n"))
print("the pairs are:")
for i in range(len(a)):
for j in range(i+1,len(a)):
if(int(a[i])+int(a[j])==targ):
flag=1
print(i,",",j)
if(flag==0):
print("no such pair exists")
ob=Pair()
ob.pairs()
|
a22c6fa520b234182e5e6956572eb3219913864a | carlhurst/introduction-to-computer-science | /GUI-Drawing-Different-Shapes/Drawing_Multiple_Squares.py | 708 | 3.796875 | 4 | import time
from graphics import *
import random
import time
# This programme is designed to create a number of squares based on user clicks
# Author Carl Hurst
# Create a window
win = GraphWin("",300,300)
def draw_Square(x,y):
s1 = Rectangle(Point(x,y),Point(x+30,y+30))
s1.setFill("Red")
s1.draw(win)
# for clicks in range(10000):
# click1 = win.getMouse()
# x = click1.getX()
# y = click1.getY()
# draw_Square(x,y)
# click1.draw(win)
start = time.time()
for i in range(10000):
draw_Square(random.randint(10,270),random.randint(10,270))
print(start - time.time())
msg = Text(Point(150,150),"Click anywhere to quit programme")
msg.draw(win)
win.getMouse()
|
32956bd830c62d244645963c5eeacc60f5aade1c | Hemanadh/Python-tutorial | /Class.py | 476 | 3.546875 | 4 | class Dog:
def __init__(self,color,breed):
self.color=color
self.breed=breed
def speak(self):
print("bhou..bhou")
def wish(self,name):
print("hello, " + name)
def hi(self):
print("I am a {} colored {}".format(self.color,self.breed))
tommy = Dog("yellow","lab")
tommy.speak()
tommy.wish("bhaskar")
print(tommy.color)
print(tommy.breed)
print(type(tommy))
print(isinstance(tommy,Dog))
tommy.hi()
|
bfbc6c9747f6d766e5600d584633482d98db9154 | TheSleepingAssassin/CodeFolder | /py/School/FINAL/Practice Worksheet/Q2/app.py | 132 | 4.28125 | 4 | n = int(input("Enter a number: "))
if n % 7 == 0:
print("It is divisible by 7.")
else:
print("It is not divisible by 7.")
|
beb4a9fe7841fa81b5967e6019ec47d1465bc3f0 | jimwh/pydev | /fibonacci.py | 1,308 | 4.375 | 4 | #!/usr/bin/python
# generators are used to generate a series of values
# yield is like the return of generator functions
# the only other thing yield does is ave the "state" of a generator function
# a generator is just a special type of iterator
# like iterators, once can get the next value from a generator using next(),
# for gets values by calling next() implicitly
"""
When we call a normal Python function, execution starts at function's first line and continues
until a return statement, exception, or the end of the function (which is seen as an implicit return None)
is encountered.
Once a function returns control to its caller, that's it.
Any work done by the function and stored in local variables is lost.
A new call to the function creates everything from scratch.
"return" implies that the function is returning control of execution to the point where the function was called.
"yield," however, implies that the transfer of control is temporary and voluntary, and our function expects to
regain it in the future.
"""
def fib(max_num):
a, b = 0, 1
while a < max_num:
# yield pauses a function
#
yield a
a, b = b, a+b
if __name__ == '__main__':
import sys
if sys.argv[1] is not None:
a = list(fib(int(sys.argv[1])))
print(a)
|
16c31d7468e2ff3d226a1055a15f08b4d8c19043 | zhuohuwu0603/interview-algothims | /lecture_basic/Lecture7.Array__Numbers/56. Two Sum.py | 751 | 3.96875 | 4 | '''
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are zero-based.
Example
numbers=[2, 7, 11, 15], target=9
return [0, 1]
Challenge
Either of the following solutions are acceptable:
O(n) Space, O(nlogn) Time
O(n) Space, O(n) Time
'''
class Solution:
def twoSum(self, nums, target):
cache = {}
for i in range(len(nums)):
if target - num[i] in cache:
return [cache[target - num[i]] + 1, i + 1]
cache[nums[i]] = i
return [-1, -1]
|
12ac373f4821c6fdda2bd2da461dfdc815444d99 | paulkoerbitz/pauls_tools | /math.py | 1,711 | 3.859375 | 4 | """Some handy math tools"""
import numpy as np
from scipy import derivative
def diff(f, x, i, n=1, eps=0.01, n_points=3):
"""Takes the i-th derivative of a multi-dimmensional function
"""
def func_for_diff(x_i):
return f(np.concatenate((x[:i],[x_i],x[i+1:])))
x = np.atleast_1d(x)
return derivative(func=func_for_diff, x0=x[i], dx=eps, n=n, order=n_points)
def diff2(f, x, i, j, eps=0.01, n_points=5):
"""Takes the second derivative with respect to function parameters
i and j of a multi-dimensional function"""
x = np.atleast_1d(x)
if i == j:
return diff(f, x, i, 2, eps, n_points)
else:
return diff(lambda z: diff(f, z, i, 1, eps, n_points),\
x, j, 1, eps, n_points)
def grad(f, x, eps=0.01, n_points=3):
x = np.atleast_1d(x)
g = np.zeros_like(x)
for i in range(len(x)):
g[i] = diff(f, x, i, 1, eps, n_points)
return g
def hess(f, x, eps=0.01, n_points=5):
x = np.atleast_1d(x)
d = len(x)
h = np.zeros((d,d))
for i in range(d):
h[i,i] = diff2(f, x, i, i, eps, n_points)
for j in range(i):
h[i,j] = diff2(f, x, i, j, eps, n_points)
h[j,i] = h[i,j]
return h
def shrink_matrix(matrix, factor=0.2):
"""
Shrinks a matrix towards the identity matrix while maintaining the
frobenious matrix norm.
"""
if matrix.ndim != 2:
raise ValueError("shrink_matrix requires a 2d-numpy array!")
n = matrix.shape[0]
if n != matrix.shape[1]:
raise ValueError("shrink_matrix requires a square matrix!")
l = 1.0-factor
return l*matrix\
+ np.sqrt((1.0-l**2)/n)*np.linalg.norm(matrix)*np.eye(n)
|
0bc6d583a5fb3675d79bd0b45154886a677c6bf9 | aamerino/Ejercicios-Iniciacion-Programacion | /21.py | 1,784 | 4.21875 | 4 | # Escribe un programa que solicite por teclado 5 números positivos,
# forzando al usuario a que únicamente introduzca valores positivos.
# A continuación el programa tiene que escribe cuál es el valor más
# pequeño y cuál es el mayor valor de los introducidos por el usuario.
def numMayorMenor(listNum):
for i in listNum:
if i < 0:
return None
numeroMayor = listNum[0]
numeroMenor = listNum[0]
for i in listNum:
if i > numeroMayor:
numeroMayor = i
if i < numeroMenor:
numeroMenor = i
return (numeroMayor, numeroMenor)
# ------------------RECOGIDA DATOS----------------------------
listNum = []
for num in range(1, 6):
print("Introducir numero ", num)
listNum.insert(num, int(input()))
# -------------------SALIDA DATOS-------------------------
if numMayorMenor(listNum) == None:
print("Intrdoduce Solo Numeros Positivos.")
else:
(numeroMayor, numeroMenor) = numMayorMenor(listNum)
print("El Mayor es ", numeroMayor, ". El Menor es ", numeroMenor, ".")
# --------------------CASOS TEST-------------------------
print("···············CASOS TEST··························")
# Caso Normal
listNum = [1, 2, 3, 4, 5]
(numeroMayor, numeroMenor) = numMayorMenor(listNum)
if numeroMayor == 5 and numeroMenor == 1:
print("Caso general Ok")
else:
print("Caso general Fail")
# Caso Negativo
listNum = [1, -2, 3, -4, 5]
if numMayorMenor(listNum) == None:
print("Caso Negativo OK")
else:
print("Caso Negativo Fail")
# Caso numeros iguales
listNum = [5, 5, 5, 5, 5]
(numeroMayor, numeroMenor) = numMayorMenor(listNum)
if numeroMayor == 5 and numeroMenor == 5:
print("Caso igual Ok")
else:
print("Caso igual Fail")
|
77e12af650c5126b385966a785da934be816e2fe | KnightZhang625/Data_Structures_and_Algorithms | /3_2_Union.py | 1,721 | 3.84375 | 4 | class Union(object):
class node(object):
def __init__(self,data,parent):
self.data = data
self.parent = - parent
def __str__(self):
return str(self.data) + ' ' + str(self.parent) + '\n'
def __init__(self):
self.list_1 = []
def add_union(self,single_union):
length = len(single_union)
father_index = len(self.list_1)
father = self.node(single_union[0],length)
self.list_1.append(father)
for _,data in enumerate(single_union[1:]):
self.list_1.append(self.node(data,-father_index))
def find(self,data):
length = len(self.list_1)
i = 0
while i < length:
if self.list_1[i].data == data:
while self.list_1[i].parent >= 0:
i = self.list_1[i].parent
return i
else:
i += 1
return False
def merge(self,n1,n2):
i1 = self.find(n1)
i2 = self.find(n2)
if abs(self.list_1[i1].parent) > abs(self.list_1[i2].parent):
self.list_1[i1].parent += self.list_1[i2].parent
self.list_1[i2].parent = - i1
else:
self.list_1[i2].parent += self.list_1[i1].parent
self.list_1[i1].parent = -i2
if __name__ == '__main__':
u1 = [1,3,5]
u2 = [2,4,6]
u3 = [7,8,9,10]
union = Union()
union.add_union(u1)
union.add_union(u2)
union.add_union(u3)
for index,node in enumerate(union.list_1):
print(str(index),'\t',node)
union.merge(3,8)
print()
for index,node in enumerate(union.list_1):
print(str(index),'\t',node)
|
3bb288529fac9ccfb774167169216b631e14fa5d | bluehat7737/pythonTuts | /47_joinFunction.py | 279 | 4.21875 | 4 | list = [
"C", "C++", "Python", "Java", "JavaScript", "R", "Ruby"
]
for items in list:
print(items+" and", end=" ")
print("other languages.")
# join function
a = " and ".join(list)
print("\n"+a)
a = " , ".join(list)
print("\n"+a)
a = " or ".join(list)
print("\n"+a)
|
a4aea2cc4bf75b03d6d16b73cca916d0d9858ab4 | sdivakarrajesh/Interview-Prep-questions | /Module 3/9/answer-py.py | 549 | 4 | 4 | from math import sqrt
start,end = map(int,input().split())
def isPrime(n):
for i in range(2,int(sqrt(n))):
i = int(i)
if n%i== 0:
return False
return True
def isCircular(n):
length = len(n)
for i in range(0,length):
n = n[1:] + n[0]
if isPrime(int(n)):
continue
else:
return False
return True
if start<=2:
print(2,end=" ")
start= 3
for i in range(start,end+1):
if isPrime(int(i)) and isCircular(str(i)):
print(i,end=" ")
|
a201d99807e53899dee99adddf5549986d9599c2 | gschen/where2go-python-test | /1906101038江来洪/day20191115/训练题_3.py | 187 | 3.65625 | 4 | #小明买了多少罐啤酒.
y = 0
s = 0
while True:
for x in range(y+1):
if x*23+y*19 == 823:
print(x)
s += 1
y += 1
if s != 0:
break |
24a2633d5631df7e7c6d6356fc7c574fda11f00f | flilyday/upgrade | /vervreqests/22.str combination on method.py | 2,301 | 3.875 | 4 | # 22.str combination on method.py
# 0. 기본적인 사용 방법
# String formatting method calls : '메도스 호출'을 통해 문자열 조합하기
# '__{}_{}__'format(value, value) 스타일 문자열 조합
fs = '{0}...{1}...{2}'
ms = fs.format('Robot', 125, 'Box') #.format은 매소드이다.
print(ms)
print('{0}...{1}...{2}'.format('Robot', 125, 'Box'))
print('{2}...{1}...{0}'.format('Robot', 125, 'Box')) #원하는 위치에 따라서 순서를 바꿀 수 있다.
print('{}...{}...{}'.format('Robot', 125, 'Box')) #숫자를 안쓰면 순서에 따라 대입된다.
print('{toy}...{num}...{item}'.format(toy='Robot', num=125, item='Box')) #문자로 지정할 수도 있다.
# 1. 언패킹을 고려하여 인자전달도 가능
my = ['Robot', 125, 'Box']
print('{}...{}...{}'.format(*my))
my = ['Box', (24, 31)]
print('{0[0]}..{0[1]}..{1[0]}..{1[1]}'.format(*my)) #인덱싱 연산을 더해서 다음과 같은 형태의 문자열 조합도 가능
# 2. 딕셔너리 기반의 인덱싱 연산도 가능
d = {'toy': 'Robot', 'price': 3500}
ds = 'toy = {0[toy]}, price = {0[price]}'.format(d)
print(ds)
# 3. 세밀한 문자열 구성 지정
# %[flag][width][.precision]f
print('{0}'.format(3.14))
print('{0:f}'.format(3.14)) #{0:f}이렇게 출력하면 정밀도가 기본 소수점 6짜리로 설정됨
print('{0:d}'.format(3)) #정수로 출력
print('{0:f}'.format(3.14)) #실수로 출력
print('%f' %3.14)
print('{0:f}'.format(3.14))
# 비교
print('%.4f' %3.14) #%뒤에 4
print('{0:.4f}'.format(3.14)) #:뒤에 4
print('%9.4f' %3.14) #%뒤에 .앞에 9 : 빈칸 채우기
print('{0:9.4f}'.format(3.14)) #:뒤에 .앞에 9 : 빈칸 채우기
print('{0:<10.4f}'.format(3.14)) #왼쪽으로 붙임
print('{0:>10.4f}'.format(3.14)) #오른쪽으로 붙임
print('{0:^10.4f}'.format(3.14)) #가운데로 붙임
print('%+d, %+d' %(5, -5)) #부호 출력
print('{0:+d}, {1:+d}'.format(5, -5))
print('{0:+}, {1:+}'.format(5, -5)) #d생략가능
print('{:+}, {:+}'.format(5, -5)) #0,1도 생략가능
print('{0:*^10.4f}'.format(3.14)) #^중앙정렬. *별로 채움
print('{0:+<10}'.format(7)) #<좌측정렬. +플러스로 채움
print('{0:^^10}'.format('hi')) #^중앙정렬. ^꺽쇠로 채움
|
a231eb0e038c0cf9e05c6899b6b69f681ed9fa40 | vin136/lagom | /lagom/runner/base_runner.py | 1,400 | 3.671875 | 4 | from abc import ABC
from abc import abstractmethod
from lagom.envs.vec_env import VecEnv
class BaseRunner(ABC):
r"""Base class for all runners.
Any runner should subclass this class.
A runner is a data collection interface between the agent and the environment.
For each calling of the runner, the agent will take actions and receive observation
in and from an environment for a certain number of trajectories/segments and a certain
number of time steps.
.. note::
By default, the agent handles batched data returned from :class:`VecEnv` type of environment.
And the collected data should use either :class:`Trajectory` or :class:`Segment`.
"""
def __init__(self, config, agent, env):
r"""Initialize the runner.
Args:
config (dict): a dictionary of configurations.
agent (BaseAgent): agent
env (VecEnv): VecEnv type of environment
"""
self.config = config
self.agent = agent
self.env = env
assert isinstance(env, VecEnv), f'expected VecEnv, got {type(env)}'
@abstractmethod
def __call__(self, T):
r"""Run the agent in the environment and collect all necessary interaction data as a batch.
Args:
T (int): number of time steps
"""
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.