blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
652b819dee3d37fa01f2e2168dfb03ddce7a4ab2 | rafasapiens/learning | /teste.py | 80 | 3.5625 | 4 | import math
nome=(input("Olá qual seu nome amigo?"))
print("Bem vindo", nome)
|
bccfae1a0c05881a1edad06dc6e836997f7b884d | SILVER-BASHINE/Deep_Learning_Homework | /homework1/neural_net.py | 5,911 | 4.21875 | 4 | from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
class ThreeLayerNet(object):
"""
A three-layer fully-connected neural network. The net has an input dimension of
N, a hidden layer dimension of H, and performs classification over C classes.
We train the network with a softmax loss function and L2 regularization on the
weight matrices. The network uses ReLU nonlinearities after the first and the second fully
connected layers.
In other words, the network has the following architecture:
input - fully connected layer - ReLU - fully connected layer - ReLU - fully connected layer - softmax
The outputs of the third fully-connected layer are the scores for each class.
"""
def __init__(self, input_size, hidden_size, output_size, std=1e-4):
self.params = {}
self.params['W1'] = std * np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = std * np.random.randn(hidden_size, hidden_size)
self.params['b2'] = np.zeros(hidden_size)
self.params['W3'] = std * np.random.randn(hidden_size, output_size)
self.params['b3'] = np.zeros(output_size)
def get_param(self):
return self.params
def loss(self, X, y=None, reg=0.0):
"""
Compute the loss and gradients for a three layer fully connected neural
network.
Inputs:
- X: Input data of shape (N, D). Each X[i] is a training sample.
- y: Vector of training labels. y[i] is the label for X[i], and each y[i] is
an integer in the range 0 <= y[i] < C. This parameter is optional; if it
is not passed then we only return scores, and if it is passed then we
instead return the loss and gradients.
- reg: Regularization strength.
Returns:
If y is None, return a matrix scores of shape (N, C) where scores[i, c] is
the score for class c on input X[i].
If y is not None, instead return a tuple of:
- loss: Loss (data loss and regularization loss) for this batch of training
samples.
- grads: Dictionary mapping parameter names to gradients of those parameters
with respect to the loss function; has the same keys as self.params.
"""
# Unpack variables from the params dictionary
W1, b1 = self.params['W1'], self.params['b1']
W2, b2 = self.params['W2'], self.params['b2']
W3, b3 = self.params['W3'], self.params['b3']
N, D = X.shape
scores = None
T=np.dot(X,W1)+b1
T1=np.maximum(T,0)
T=np.dot(T1,W2)+b2
T2=np.maximum(T,0)
scores=np.dot(T2,W3)+b3
#############################################################################
#############################################################################
# END OF YOUR CODE #
#############################################################################
# If the targets are not given then jump out, we're done
if y is None:
return scores
# Compute the loss
loss = None
#生成全0矩阵
exp_scores=np.exp(scores)
exp_scores/=(np.sum(exp_scores,axis=1).reshape(N,1))
loss=-(1/N)*(np.sum(np.log(exp_scores[np.arange(N),y])))+0.5*reg*np.sum(W1*W1)+0.5*reg*np.sum(W2*W2)+0.5*reg*np.sum(W3*W3)
delta_S=np.zeros_like(exp_scores)
delta_S[range(N),y]+=1
delta_S-=exp_scores
grads = {}
grads['W3']=reg*W3+(-1/N)*np.dot(T2.T,delta_S)
grads['b3']=-(1/N)*np.sum(delta_S,axis=0)
delta_t2=np.zeros_like(T2)
delta_t2[T2>0]=1
grads['W2']=reg*W2+(-1/N)*np.dot(T1.T,np.dot(delta_S,W3.T)*delta_t2)
grads['b2']=(-1/N)*np.sum(np.dot(delta_S,W3.T)*delta_t2,axis=0)
delta_t1 = np.zeros_like(T1)
zhenghe=(np.dot(delta_S,W3.T))*delta_t2
delta_t1[T1>0]=1
grads['W1']=reg*W1+(-1/N)*np.dot(X.T,np.dot(zhenghe,W2.T)*delta_t1)
grads['b1']=(-1/N)*np.sum(np.dot(zhenghe,W2.T)*delta_t1,axis=0)
return loss,grads
def train(self, X, y, X_val, y_val,
learning_rate=1e-3, learning_rate_decay=0.95,
reg=5e-6, num_iters=100,
batch_size=200, verbose=False):
num_train = X.shape[0]
iterations_per_epoch = max(num_train / batch_size, 1)
# Use SGD to optimize the parameters in self.model
loss_history = []
train_acc_history = []
val_acc_history = []
for it in range(num_iters):
r=np.random.choice(num_train,batch_size)
X_batch=X[r,:]
y_batch=y[r]
# Compute loss and gradients using the current minibatch
loss, grads = self.loss(X_batch, y=y_batch, reg=reg)
loss_history.append(loss)
self.params['W1']-=learning_rate*grads['W1']
self.params['W2']-=learning_rate*grads['W2']
self.params['W3']-=learning_rate*grads['W3']
self.params['b1']-=learning_rate*grads['b1']
self.params['b2']-=learning_rate*grads['b2']
self.params['b3']-=learning_rate*grads['b3']
if verbose and it % 100 == 0:
print('iteration %d / %d: loss %f' % (it, num_iters, loss))
# Every epoch, check train and val accuracy and decay learning rate.
if it % iterations_per_epoch == 0:
# Check accuracy
train_acc = (self.predict(X_batch) == y_batch).mean()
val_acc = (self.predict(X_val) == y_val).mean()
train_acc_history.append(train_acc)
val_acc_history.append(val_acc)
# Decay learning rate
learning_rate *= learning_rate_decay
return {
'loss_history': loss_history,
'train_acc_history': train_acc_history,
'val_acc_history': val_acc_history,
}
def predict(self, X):
y_pred = None
score=self.loss(X)
y_pred=np.argmax(score,axis=1)
return y_pred
|
d83adc66c830e781f2746ba439915ed9b09f5385 | geshem14/my_study | /Coursera_2019/Python/week6/week6task6.py | 5,149 | 4.1875 | 4 | # week 6 task 6
# coursera https://www.coursera.org/learn/python
# -osnovy-programmirovaniya/programming/Hs8PB/grazhdanskaia-oborona
"""
текст задания тут 79 символ=>!
Штаб гражданской обороны Тридесятой области решил обновить план спасения на
случай ядерной атаки. Известно, что все n селений Тридесятой области находятся
вдоль одной прямой дороги. Вдоль дороги также расположены m бомбоубежищ, в
которых жители селений могут укрыться на случай ядерной атаки.
Чтобы спасение в случае ядерной тревоги проходило как можно эффективнее,
необходимо для каждого селения определить ближайшее к нему бомбоубежище.
Формат ввода - В первой строке вводится число n - количество селений
(1 <= n <= 100000). Вторая строка содержит n различных целых чисел,
i-е из этих чисел задает расстояние от начала дороги до i-го селения.
В третьей строке входных данных задается число m - количество бомбоубежищ
(1 <= m <= 100000). Четвертая строка содержит m различных целых чисел,
i-е из этих чисел задает расстояние от начала дороги до i-го бомбоубежища.
Все расстояния положительны и не превышают 10⁹. Селение и убежище могут
располагаться в одной точке.
Формат вывода - Выведите n чисел - для каждого селения выведите номер
ближайшего к нему бомбоубежища. Бомбоубежища пронумерованы от 1 до m в том
порядке, в котором они заданы во входных данных.
Указание - Создайте список кортежей из пар (позиция селения, его номер в
исходном списке), а также аналогичный список для бомбоубежищ. Отсортируйте
эти списки.
Перебирайте селения в порядке возрастания.
Для селения ближайшими могут быть два соседних бомбоубежища, среди них надо
выбрать ближайшее. При переходе к следующему селению не обязательно искать
ближайшее бомбоубежище с самого начала. Его можно искать начиная с позиции,
найденной для предыдущего города. Аналогично, не нужно искать подходящее
бомбоубежище до конца списка бомбоубежищ: достаточно найти самое близкое.
Если Вы неэффективно реализуете эту часть, то решение тесты не пройдет.
Для хранения ответа используйте список, где индекс будет номером селения,
а по этому индексу будет запоминаться номер бомбоубежища.
"""
n_place = int(input()) # переменная для количества селений
placeList = sorted(enumerate(map(int, input().split())), key=lambda x: x[1])
m_shelter = int(input()) # переменная для количества бомбоубежищ
shelterList = sorted(enumerate(map(int, input().split())), key=lambda x: x[1])
placeList.sort(key=lambda x: x[1]) # сортировка селений по растоянию
shelterList.sort(key=lambda x: x[1]) # сортировка бомбоубежищ по растоянию
shelterList.append((-1, 10 ** 10)) # дописывание очень удаленного бомб-ща
datePlaces_and_Shelters = [None] * n_place # формирование пустого массива
if m_shelter == 1: # если бомбоубежище одно, то пишем его для всех селений
[print(1) for i in placeList]
else:
j = 0
for i in range(n_place):
tempDistance = abs(shelterList[j][1] - placeList[i][1])
distToNextShelter = abs(shelterList[j + 1][1] - placeList[i][1])
while tempDistance > distToNextShelter:
tempDistance = distToNextShelter
j += 1
distToNextShelter = abs(shelterList[j + 1][1] - placeList[i][1])
datePlaces_and_Shelters[placeList[i][0]] = shelterList[j][0] + 1
print(*datePlaces_and_Shelters)
|
e0a2a5880c99e823d98c573278ea5ab521b34542 | hunterluok/Security | /pythoncode/35_copylinknode.py | 1,020 | 3.796875 | 4 |
from pythoncode.listnode import ListNode
class CopyNode:
def __init__(self):
pass
def copy_node(self, node1, node2, index=1):
if node1 is None:
return node2
if node2 is None:
return node1
if index % 2 == 1:
mergerd = node1
mergerd.nexts = self.copy_node(node1.nexts, node2, index+1)
else:
mergerd = node2
mergerd.nexts = self.copy_node(node1, node2.nexts, index+1)
return mergerd
@staticmethod
def print_value(node):
temp = node
while temp is not None:
print(temp.value)
temp = temp.nexts
if __name__ == "__main__":
my1 = ListNode()
my2 = ListNode()
# 注意这里需要生成 新的my2,尽管与my1中元素的值相同,否则出错。
for i in range(4, 8):
my1.push(i)
my2.push(i)
# my.print_value()
cm = CopyNode()
result = cm.copy_node(my1.head, my2.head)
cm.print_value(result)
|
1486e1cad4880f4842828491e5705c84a53ee98b | mafm9/Problems | /String/frequency.py | 308 | 4 | 4 | inputstring = "Peter piper picked a peck of pickled peppers Peter"
words = inputstring.split()
frequency = [words.count(x) for x in words]
print(frequency)
combine = dict(list(zip(words,frequency)))
longest = max(words,key=len)
print(combine)
print(f"Longest words: {longest}")
print(f"length: {len(longest)}") |
f8cbf756f588ba191c27520050c11d25d40e8c69 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q20_quadrantes.py | 705 | 4.125 | 4 | def main():
angulo = int(input('Digite um ângulo em graus: '))
quadrante = verificar_quadrante(angulo)
if angulo == 0 or angulo == 90 or angulo == 180 or angulo == 270:
print(f'O ângulo {angulo}° está no eixo de intercessão dos quadrantes.')
else:
print(f'O ângulo {angulo}° está no {quadrante} quadrante.')
def verificar_quadrante(angulo):
if angulo % 360 > 0 and angulo % 360 < 90:
return 'primeiro'
elif angulo % 360 > 90 and angulo % 360 < 180:
return 'segundo'
elif angulo % 360 > 180 and angulo % 360 < 270:
return 'terceiro'
elif angulo % 360 > 270 and angulo % 360 < 360:
return 'quarto'
main()
|
8fac0f9a3b7141b1cb3ba090e6cbce4e632cd16a | skyesyesyo/AllDojo | /python/OOP/Reading/inheritance.py | 1,370 | 4.53125 | 5 | # class Parent(object): # inherits from the object class
# parent methods and attributes here
# class Child(Parent): #inherits from Parent class so we define Parent as the first parameter
# parent methods and attributes are implicitly inherited
# child methods and attributes
############################
class Vehicle(object):
"""parent"""
def __init__(self, wheels, capacity, make, model):
self.wheels = wheels
self.capacity = capacity
self.make = make
self.model = model
self.mileage = 0
def drive(self, miles):
self.mileage = self.mileage + miles
return self
def reverse(self, miles):
self.mileage -= miles
return self
########################
class Bike(Vehicle):
"""subclass"""
def vehicle_type(self):
return "Bike_yo"
class Car(Vehicle):
"""subclass"""
def set_wheels(self):
self.wheels = 4
return self
class Airplane(Vehicle):
def fly(self, miles):
self.mileage += miles
return self
######################
v_dodge = Vehicle(4, 8, "dodge", "minivan")
b_Schwinn = Bike(2, 1, "Schwinn", "Paramount")
c_toyota = Car(8, 5, "Toyota", "Matrix")
a_airbus = Airplane(22, 853, "Airbus", "A380")
######################
print v_dodge.make #calling attriubte
v_dodge.drive(10)
print v_dodge.mileage
print b_Schwinn.vehicle_type() #using method
c_toyota.set_wheels()
print c_toyota.wheels
a_airbus.fly(580)
print a_airbus.mileage |
d99071f9c45d3fbf4dd9a4919d2a3c8ac9e36228 | magmax/programming-challenge-2 | /finalists/Ignacio/challenge_11/t11.py | 3,508 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# *** Challenge 11: Descrambler ***
import sys
score_table = { 'A': 1, 'E': 1, 'I': 1, 'L': 1, 'N': 1, 'O': 1, 'R': 1, 'S': 1, 'T': 1, 'U': 1,
'D': 2, 'G': 2,
'B': 3, 'C': 3, 'M': 3, 'P': 3,
'F': 4, 'H': 4, 'V': 4, 'W': 4, 'Y': 4,
'K': 5,
'J': 8, 'X': 8,
'Q': 10, 'Z': 10 }
def count_letters(word):
''' Return a dictionary with keys as letters and the values are the ocurrences of each letter '''
d = {}
for c in word:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
def calculate_score(word):
''' Calculates the score of a word '''
score = 0
for c in word:
score += score_table[c]
return score
if __name__ == '__main__':
# First read all the dictionary and add it to a dictionary using the length of the word for the key
dictionary = {}
f = open('descrambler_wordlist.txt', 'r')
for line in f:
line = line.rstrip()
if len(line) in dictionary:
dictionary[len(line)].append(line)
else:
dictionary[len(line)] = [ line ]
f.close()
num_cases = int(sys.stdin.readline())
for ncase in range(num_cases):
line = sys.stdin.readline().rstrip()
rack, board = line.split()
max_word = ""
max_score = 0
letters_in_board = set(board)
count_rack = count_letters(rack)
max_word_length = len(rack) + 1
for word_length in range(max_word_length, 1, -1):
if word_length not in dictionary:
continue
for word in dictionary[word_length]:
# Is it possible to obtain more points with this word?
score = calculate_score(word)
if score < max_score or (score == max_score and word > max_word):
continue
# Check if it share any letter with the board word
valid_candidate = False
for c in letters_in_board:
if c in word:
valid_candidate = True
break
if not valid_candidate:
continue
# Check if there is a chance to make this word with our rack
count_word = count_letters(word)
for letter in count_word:
if letter in count_rack:
count_word[letter] -= count_rack[letter]
# Sum only the positive values
max_letters_missing = sum(map(lambda x: max(x, 0), count_word.values()));
if max_letters_missing > 1:
continue # We can't use this word
elif max_letters_missing == 1: # We must use the missing letter using one from the board word
missing_letter = [letter for letter, count in count_word.items() if count == 1]
if missing_letter[0] not in board:
continue
# If we have reached this point, the current word is a possible winner
if score > max_score or (score == max_score and word < max_word):
max_score = score
max_word = word
print max_word + " " + str(max_score)
|
bd58f185e8fb9180db548b8865835a73a2f5627c | buxuele/ctf_notes | /snippet/pillow_watermark.py | 637 | 3.671875 | 4 | import sys
from PIL import ImageDraw, ImageFont, Image
"""
add water-mark to an image
"""
def watermark_text(filename,text, pos):
photo = Image.open(filename)
# make the image editable
drawing = ImageDraw.Draw(photo)
black = (3, 8, 12)
font = ImageFont.truetype("/usr/share/fonts/truetype/tlwg/Kinnari-BoldOblique.ttf", 40)
drawing.text(pos, text, fill=black, font=font)
photo.show()
photo.save("newImage" + filename)
if __name__ == '__main__':
img = 'a.jpg'
watermark_text(img,
text='www.mousevspython.com',
pos=(0, 0))
|
1c665ec0fb6c709794a415e3c7f212a728286643 | duchieu307/vuhoangduchieu-fundamentals-c4e13 | /Session04/Homework/exercise2.py | 398 | 3.796875 | 4 | princess = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15,
}
for keys, values in stock.items():
print(keys, values, sep = ': ')
print('price', princess[keys], sep = ': ')
total = 0
for keys, values in princess.items():
price = values * stock[keys]
total = total + price
print(total)
|
19de3be4600da288e42142355c7d5689c2943ed7 | Warwickc3295/CTI110 | /Test2.py | 243 | 3.75 | 4 | import turtle
turtle.speed(10)
turtle.color('hotpink')
turtle.bgcolor('red')
turtle.pensize(2)
size=1
while (True):
for x in range(4):
turtle.forward(size)
turtle.right(60)
size=size + 1
turtle.right(10)
|
6c6f67fb413892046eacf0992c2f1f77df636b61 | idesign0/Programming-Repo | /Python/10.STRINGS/strings.py | 234 | 3.6875 | 4 | ###strings
# 3 ways
x ='xyzeervqrv'
y ="xyevnvz"
z ="""xyzeveqrveq"""
print(len(x)*100)
print(len(y))
print(len(z))
print('max length of above strings')
print(max(len(x),len(y),len(z)))
print(len(x*100))
d=10
print(x + str(d))
|
5a86394ec78fb18a3886a0e080fdd15252e34f5c | javiergr3ybeard/Xtern-Coin | /xterncoin.py | 1,281 | 3.953125 | 4 | #! /usr/bin/python
import random
guessesTaken = 0
getCoins = 0
print('Hello what is your name?')
myName = input()
def main():
global guessesTaken
global getCoins
# Asks which command you want to run.
handleGuess = random.randint(1, 10)
word = input('To make a guess type "guess"\n To look at how many coins you have type "coins"\n To run a look to make guesses for you type "start"').strip().lower()
# Runs the command/s.
if word == "guess":
while guessesTaken < 11:
print('make guess')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess == handleGuess:
getCoins = getCoins + 1
handleGuess = random.randint(1, 10)
print('gooood!')
else:
print('NOPE')
elif word == "coins":
print(myName, 'you have', getCoins)
elif word == "start":
while guessesTaken < 1000:
startGuessing = random.randint(1, 10)
guessesTaken = guessesTaken + 1
if startGuessing == handleGuess:
getCoins = getCoins + 1
handleGuess = random.randint(1, 10)
print('you got a coin!')
else:
print('failed')
elif word == "quit":
return False
else:
print("Command not found")
return True
while main():
pass
|
769db2f78b91deeb0b56612b6c9862242453f5d1 | njenga5/python-problems-and-solutions | /Solutions/problem84.py | 200 | 4.15625 | 4 | '''
Question 84:
Please write a program to shuffle and print the list [3,6,7,8].
Hints:
Use shuffle() function to shuffle a list.
'''
from random import shuffle
s = [3, 6, 7, 8]
shuffle(s)
print(s)
|
4cfa656eef07676dff7b300af5f80322211df8af | christophertrmn/Plot | /daigram.py | 1,146 | 3.90625 | 4 | import math
import itertools
import matplotlib.pyplot as plt
try:
namalegend = []
mulai = int(input("How many trajectories?"))
for x in range(mulai):
namalegend.append("Ball {}".format(x + 1))
initialvelocity = input("Enter the initial velocity for trajectory {} (m/s) ".format(x + 1))
angle = input("Enter the angle of projection for trajectory {} (degrees) ".format(x + 1))
speed_x = float(initialvelocity) * math.cos(math.radians(float(angle)))
speed_y = float(initialvelocity) * math.sin(math.radians(float(angle)))
xcor = list()
ycor = list()
for z in itertools.count():
speedx = speed_x * (z / 1000)
speedy = speed_y * (z / 1000) - 0.5 * 10 * (z / 1000) ** 2
if speedy >= 0:
xcor.append(speedx)
ycor.append(speedy)
else:
break
plt.scatter(xcor, ycor, s =10)
plt.title("Projectile of the ball")
plt.xlabel("X-Coordinate")
plt.ylabel("Y-Coordinate")
plt.legend(namalegend)
plt.show()
except:
print("ERROR PLEASE INPUT VALID INPUT")
|
ac3cd3c40a302a494c86148acc4ab107795676f6 | KareliaConsolidated/CodePython | /Basics/146_Python_Ex_07.py | 694 | 4.0625 | 4 | # SumUp Diagonals
# Write a function called sum_up_diagonals which accepts an N*N list of lists and sums the two main diagonals in the array; the one from the upper left to the lower right, and the one from the upper right to the lower left.
def sum_up_diagonals(arr):
total = 0
for i,val in enumerate(arr):
total += arr[i][i]
total += arr[i][-1-i]
return total
list1 = [
[1,2],
[3,4]
]
list2 = [
[1,2,3],
[4,5,6],
[7,8,9]
]
list3 = [
[4,1,0],
[-1,-1,0],
[0,0,9]
]
list4 = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
]
print(sum_up_diagonals(list1)) # 10
print(sum_up_diagonals(list2)) # 30
print(sum_up_diagonals(list3)) # 11
print(sum_up_diagonals(list4)) # 68 |
03b564a742f5ecddc2da51d14dfb5553d95d9c36 | z3ero/Leetcode | /剑指Offer/21_调整数组顺序使奇数位于偶数前面.py | 1,281 | 3.515625 | 4 | class Solution:
# 思路1: 冒泡排序的思路,前偶后奇交换,O(n**2)
# 思路2: 插入排序的思路
# 使用两个指针,a 指针指向下一个奇数要插入的位置,b指针用来遍历数组
# 每次找到一个奇数,则将[a,b] 统一向后移动一位,复杂度也是 O(n**2)
def reOrderArray_2(self, array):
p1 = 0
p2 = 0
length = len(array)
# 找到第一个偶数(即奇数要插入的位置)
while p1<length and array[p1] & 1:
p1 += 1
p2 = p1
while p2<length:
# 找到第一个奇数
while p2<length and not array[p2] & 1:
p2 += 1
if p2 < length: # 插入第一个奇数,并将[p1:p2]元素后移
tmp = array[p2]
array[p1+1:p2+1] = array[p1:p2]
array[p1] = tmp
p1 += 1
return array
# 思路3: 使用额外空间
# 时间复杂度 O(n),空间复杂度O(n)
def reOrderArray_3(self, array):
eve_arr = filter(lambda x: not x & 1, array) #偶数
odd_arr = filter(lambda x: x & 1, array) #奇数
return odd_arr + eve_arr
sol = Solution()
print(sol.reOrderArray_2([1,2,3,4,5,6,7,8]))
|
39402041515911f37aa7d1955c52b3427c3f644e | stirfrypapi/coding_challenges | /trees_graphs/PrefixTree.py | 1,980 | 3.859375 | 4 | class Node:
def __init__(self, v=None):
self.val = v
self.next = None
self.isWord = False
self.child = None
class List:
def __init__(self):
self.list = [Node() for i in range(26)]
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.words = set()
self.root_list = List()
self.curr_lvl = self.root_list
self.prev_list = None
def ind(self, char):
return ord(char) - 97
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
self.words.add(word)
for i in range(len(word)):
self.curr_lvl.list[self.ind(word[i])] = Node(word[i])
if i == len(word) - 1:
self.curr_lvl.list[self.ind(word[i])].isWord = True
self.prev_list = self.curr_lvl
self.curr_lvl = self.curr_lvl.list[self.ind(word[i])].child
self.prev_list.list[self.ind(word[i])].child = self.curr_lvl
if self.curr_lvl == None and i + 1 < len(word):
self.curr_lvl = List()
self.curr_lvl = self.root_list
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
s = word in self.words
return s
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
start = self.root_list
curr = start
for i in range(len(prefix)):
if curr.list[self.ind(prefix[i])].val != prefix[i]:
return False
curr = curr.list[self.ind(prefix[i])].child
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
if __name__ == '__main__':
t = Trie()
t.insert('apple') |
585a20ec68d1a2e62c0a3964e787bc559bc9ae81 | baahmad/artificial_neural_networks | /lvq2_svm_networks/code/backprop.py | 4,801 | 3.578125 | 4 | from random import seed
from random import random
from random import randrange
from math import exp
from csv import reader
import csv
# Network initialization
def initialize_network(n_inputs, n_hidden, n_outputs):
network = list()
hidden_layer = [{'weights':[random() for i in range (n_inputs + 1)]} \
for i in range(n_hidden)]
network.append(hidden_layer)
output_layer = [{'weights':[random() for i in range(n_hidden + 1)]} \
for i in range (n_outputs)]
network.append(output_layer)
return network
# Neuron activation for an input
def activate(weights, inputs):
activation = weights[-1]
for i in range(len(weights)-1):
activation += weights[i] * inputs[i]
return activation
# Transfer neuron activation (sigmoid)
def transfer(activation):
return 1.0 / (1.0 + exp(-activation))
# Forward propagate input to a network output
def forward_propagate(network, row):
inputs = row
for layer in network:
new_inputs = []
for neuron in layer:
activation = activate(neuron['weights'], inputs)
neuron['output'] = transfer(activation)
new_inputs.append(neuron['output'])
inputs = new_inputs
return inputs
# Calculate the derivative of a neuron output
def transfer_derivative(output):
return output * (1.0 - output)
# Back propagate error and store in the neurons
def backward_propagate_error(network, expected):
for i in reversed(range(len(network))):
layer = network[i]
errors = list()
if i != len(network) -1:
for j in range(len(layer)):
error = 0.0
for neuron in network[i +1]:
error += (neuron['weights'][j] * neuron['delta'])
errors.append(error)
else:
for j in range(len(layer)):
neuron = layer[j]
errors.append(expected[j] - neuron['output'])
for j in range(len(layer)):
neuron = layer[j]
neuron['delta'] = errors[j] * transfer_derivative(neuron['output'])
# Update network weights with error
def update_weights(network, row, l_rate):
for i in range(len(network)):
inputs = row[:-1]
if i != 0:
inputs = [neuron['output'] for neuron in network[i -1]]
for neuron in network[i]:
for j in range(len(inputs)):
neuron['weights'][j] += l_rate * neuron['delta'] * inputs[j]
neuron['weights'][-1] += l_rate * neuron['delta']
# Train a network for a fixed number of epochs
def train_network(network, train, l_rate, n_epoch, n_outputs):
csvData = list()
for epoch in range(n_epoch):
sum_error = 0
for row in train:
outputs = forward_propagate(network, row)
expected = [row[-1]]
sum_error += (expected[0]-outputs[0])**2
backward_propagate_error(network, expected)
update_weights(network, row, l_rate)
satisfied_error = sum_error/len(train)
print('>epoch=%d, lrate=%.3f, error=%.10f' % (epoch, l_rate, sum_error/len(train)))
csvData.append([epoch + 1, sum_error/len(train)])
with open('data.csv', 'w') as csvFile:
writer = csv.writer(csvFile)
writer.writerows(csvData)
csvFile.close()
# Load a CSV file
def load_csv(filename):
dataset = list()
with open(filename, 'rb') as f:
reader = csv.reader(f)
for row in reader:
dataset.append(row)
return dataset
# Convert dataset into integers
def ConvertDataset(dataset):
con_data = list()
for row in dataset:
con_row = list()
for item in row:
if (item =='N'):
con_row.append(0.0)
elif (item == 'O'):
con_row.append(1.0)
else:
con_row.append(float(item))
con_data.append(con_row)
return con_data
# Find the min and max values for each column
def dataset_minmax(dataset):
minmax = list()
stats = [[min(column), max(column)] for column in zip(*dataset)]
return stats
# Rescale dataset columns to the range 0-1
def normalize_dataset(dataset, minmax):
for row in dataset:
for i in range(len(row)-1):
row[i] = (row[i] - minmax[i][0]) / (minmax[i][1] - minmax[i][0])
# Make a prediction with a network
def predict(network, row):
outputs = forward_propagate(network, row)
return outputs.index(max(outputs))
# load and prepare data
seed(1)
filename = 'divorce4.csv'
dataset = load_csv(filename)
dataset = ConvertDataset(dataset)
minmax = dataset_minmax(dataset)
normalize_dataset(dataset, minmax)
n_inputs = len(dataset[0]) - 1
network = initialize_network(n_inputs, 2 * n_inputs, 1)
train_network(network, dataset, .15, 100, 1)
|
ba653316efbffa924d1cdd3dc906243278bba027 | funny860/sosio_software | /problem-1.py | 1,532 | 3.75 | 4 | import re
def check_email(email):
parts = email.split("@")
if(len(parts) != 2):
return False
#check if prefix of string is correct
prefix = parts[0]
sufix = parts[1]
li = ['.','_','-']
#considering only 3 special characters to be acceptable in prefix
if(len(prefix) > 64 and len(prefix) == 0):
return False
# check if first and last characters are not special characters.
if (prefix[0] in li) or (prefix[-1] in li):
return False
k = prefix.split('.')
for each in k:
if each[0] in li or each[-1] in li:
return False
if not(bool(re.match("^[A-Za-z0-9_-]*$",each))):
return False
dot = [i for i, letter in enumerate(prefix) if letter == '.']
hypen = [i for i, letter in enumerate(prefix) if letter == '-']
underscore = [i for i, letter in enumerate(prefix) if letter == '_']
total = dot + hypen + underscore
toatl = sorted(total)
prev = None
for each in total:
if(prev == each - 1):
return False
prev = each
if(len(sufix) > 253 and len(sufix) == 0):
return False
p = sufix.split('.')
if len(p) < 2:
return False
for each in p:
if not(bool(re.match("^[A-Za-z0-9-]*$",each))):
return False
return True
n = int(input("Enter number of emails n:"))
print("Enter each emails one by one. ")
emails = []
for i in range(0,n):
email = input()
emails.append(email)
if check_email(email):
print(email)
|
04accca532e0813f5183340f0cd23b1d5b09d631 | Naveen-kumar01/data-structure-and-algorithms | /pro.py | 601 | 4.03125 | 4 | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def show(self):
print(*self.items,sep="")
s = Stack()
text = input('Please enter the string: ')
for character in text:
if(s.is_empty()):
s.push(character)
elif(s.peek()==character):
s.pop()
else:
s.push(character)
print(s.show())
|
39aafe89c7dec26bf248161d0d286f400253e5b9 | renedekluis/HBO-ICT_python_2B | /Week3/Opdracht2/main.py | 2,019 | 4 | 4 | class ListNode:
def __init__(self,data,next_node):
self.data = data
self.next = next_node
def __repr__(self):
return str(self.data)
class MyCircularLinkedList:
"""
This class creates a looping list of nodes.
"""
def __init__(self):
self.tail = None
def __repr__(self):
"""
This prints the node_list.
Return
------
s : string
string of the node_list
Example
-------
>>> print(mylist)
>>> 5 -> 6
>>> print(myEmptyList)
>>> 'empty list'
"""
s = ''
if not self.tail:
return 'empty list'
current = self.tail.next
if current != None:
s = s + str(current)
current = current.next
while current != self.tail.next:
s = s + " -> " + str(current)
current = current.next
return s
def addLast(self,e):
"""
This function adds a node to the list.
Parameters
----------
e : integer
value to add
Example
-------
>>> addLast(5)
>>> addLast(6)
>>> node_list = 5 -> 6
"""
if not self.tail:
self.tail = ListNode(e,self.tail)
else:
self.tail.next = ListNode(e,self.tail.next)
self.tail = self.tail.next
if not self.tail.next:
self.tail.next = self.tail
def delete(self,e, current = None):
"""
This function removes a function from the node_list.
Parameters
----------
e : integer
value to be removed
Example
-------
>>> node_list = 5 -> 6 -> 7
>>> delete(6)
>>> node_list = 5 -> 7
"""
if not current:
current = self.tail
if current.next.data == e:
current.next = current.next.next
else:
self.delete(e,current.next)
if e == self.tail.data:
self.tail = None
mylist2 = MyCircularLinkedList()
print(mylist2)
mylist2.addLast(1)
mylist2.addLast(2)
mylist2.addLast(3)
mylist2.addLast(4)
mylist2.addLast(5)
print(mylist2)
mylist2.delete(1)
print(mylist2)
mylist2.delete(2)
print(mylist2)
mylist2.delete(3)
print(mylist2)
mylist2.delete(4)
print(mylist2)
mylist2.delete(5)
print(mylist2)
|
6677a61fb5ed34e74aa1b9271e47bdefb0f61d2b | Chenhuaqi6/python_base | /day06/10.10代码/index.py | 574 | 3.765625 | 4 | # s = input('请输入字符串')
# if s:
# print('第一个字符是',s[0])
# print('最后一个字符是',s[-1])
# if len(s) % 2 == 1:
# center = int(len(s) // 2)
# print('中间这个字符是:',s[center])
# else:
# print("您输入的字符串有误")
# 输入字符串 切掉第一个和最后一个
# s = input("请输入一个字符串: ")
# if s:
# print("切片后的字符串", s[1:(len(s)-1)] )
s = input("请输入一行文字: ")
s2 = s[::-1]
if s == s2:
print(s, "是回文")
else:
print(s, "不是回文") |
4575b319560b9dd954dca08faf0ca4b0b71e7c76 | Neptune-Haiwang/MachineLearning_Basics | /算法与数据结构/A2递归/递归应用-探索迷宫.py | 2,067 | 4.15625 | 4 | '''探索迷宫
把迷宫分成行列整齐的方格,区分出墙壁和通道。
即每个方格都有行列位置:矩阵,
采用不同字符来分别代表:墙壁,通道,海龟投放点
'''
class Maze:
def __init__(self, mazeFileName):
rowsInMaze = 0
columnsMaze = 0
self.mazeList = []
mazeFile = open(mazeFileName, 'r')
rowsInMaze = 0
for line in mazeFile:
rowList = []
col = 0
for ch in line[: -1]:
rowList.append(ch)
if ch == 'S':
self.startRow = rowsInMaze
self.startCol = col
col += 1
rowsInMaze += 1
self.mazeList.append(rowList)
columnsMaze = len(rowList)
def searchFrom(maze, startRow, startColumn):
# 1.1 碰到墙壁,返回失败
maze.updatePosition(startRow, startColumn)
if maze[startRow][startColumn] == OBSTACLE:
return False
# 1.2 碰到面包屑(已尝试走过的可以走的点),或者死胡同,返回失败
if (maze[startRow][startColumn] == TRIED) or (maze[startRow][startColumn] == DEAD_END):
return False
# 1.3 碰到了出口, 返回成功
if maze.isExit(startRow, startColumn):
maze.updatePosition(startRow, startColumn, PART_OF_PATH)
return True
# 1.4 撒一下面包屑,继续探索
maze.updatePosition(startRow, startColumn, TRIED)
# 2.1 向北南西东四个方向依次探索,OR操作有短路效应(即一个为TRUE,则后续的不管是啥,结果都为TRUE)
found = searchFrom(maze, startRow-1, startColumn) or searchFrom(maze, startRow+1, startColumn) or \
searchFrom(maze, startRow, startColumn-1) or searchFrom(maze, startRow, startColumn+1)
# 2.2 如果探索成功则标记为当前点,否则标记为死胡同
if found:
maze.updatePosition(startRow, startColumn, PART_OF_PATH)
else:
maze.updatePosition(startRow, startColumn, DEAD_END)
return found
|
e246d0d0c4895be911eb059c6aca170dcfeffe5d | pfsmyth/Cambridge | /code/if.py | 308 | 3.515625 | 4 | # if .. End If
a= 5
b= 4
print("a is", a, "b is",b)
if a > b :
print(a, "is bigger than ", b)
a= 3
b= 4
print("a is", a, "b is",b)
if a > b :
print(a , "is bigger than ", b)
a= 4
b= 4
print("a is", a, "b is",b)
if a == b :
print(a, "is equal to", b)
|
0a1d77ee20ec914f3eb35020211b39c5ad53308f | izzitan/CP1404_practical | /prac_04/list_exercises.py | 1,000 | 4.0625 | 4 | """
Name: Hafidz Izzi Baihaqi
GitHub: https://github.com/izzitan/CP1404_practical
"""
def main():
numbers = []
for i in range(5):
numbers.append(int(input("Number: ")))
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smallest number is {}".format(min(numbers)))
print("The largest number is {}".format(max(numbers)))
print("The average of the numbers is {}".format(sum(numbers) / len(numbers)))
usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface',
'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer',
'bob']
user_valid = False
username = input("Please input your username: ")
for user in usernames:
if username == user:
user_valid = True
if user_valid:
print("Access granted")
else:
print("Access denied")
main()
|
caf8ecba9e06db1d38ce888893d5cc91b19d2cb0 | KamalAres/Infytq | /Infytq/Day7/Exer-35.py | 707 | 3.78125 | 4 | #PF-Exer-35
def count_names(name_list):
count1=0
count2=0
s=[]
#start writing your code here
#Populate the variables: count1 and count2
# Use the below given print statements to display the output
# Also, do not modify them for verification to work
#print("_at -> ",count1)
#print("%at% -> ",count2)
for i in name_list:
if i.find("at")>=0:
count2=count2+1
s=i.split("at")
if len(s[0])==1 and i.endswith("at"):
count1=count1+1
print("_at -> ",count1)
print("%at% -> ",count2)
#Provide different names in the list and test your program
name_list=['at', 'dats']
count_names(name_list)
|
89c5c573833ee71243d3ef7387ab67f810fc23d6 | GeorgiyDemo/FA | /Course_I/Алгоритмы Python/Part1/семинары/pract5/task2.py | 1,898 | 3.90625 | 4 | """
Реализовать создание, запись, чтение и удаление файла с данными о пользователе.
пользователь выбирает действие самостоятельно, а так же указывает путь к размещению файла.
"""
import os
class FileProcessing:
def __init__(self):
select_d = {
"1": self.file_add,
"2": self.file_remove,
"3": self.file_read,
"4": self.file_write,
}
self.file_name = input("Введите название файла для записи -> ")
input_str = ""
while input_str != "0":
input_str = input(
"1. Добавление файла\n2. Удаление файла\n3. Чтение из файла\n4. Запись файла\n0. Выход\n-> "
)
if input_str in select_d:
select_d[input_str]()
elif input_str != "0":
print("Нет введёного пункта меню")
def file_add(self):
f = open(self.file_name, "w")
f.close()
def file_remove(self):
os.remove(self.file_name)
def file_write(self):
"""
Запись исходного выражения в файл
"""
user_info = input("Введите строку для записи -> ")
with open(self.file_name, "w") as f:
f.write(user_info)
def file_read(self):
"""
Чтение файла self.file_name
"""
try:
with open(self.file_name, "r") as f:
print(f.read())
except FileNotFoundError:
print("Ошибка чтения файла. Файла не существует")
if __name__ == "__main__":
FileProcessing()
|
e9c5787e0942eaae24494cbf1217d82f45df6402 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/9ac2cf4b99cb43baa80df9cbb9e59fa3.py | 192 | 3.953125 | 4 | def word_count(string):
frequencies = {}
for word in string.split():
if word in frequencies:
frequencies[word] += 1
else:
frequencies[word] = 1
return frequencies
|
17758714e5ecb76c1339ffa25573e0fecfc02d85 | cvkittler/Machine-Learning-Workspace | /Homework 6/homework6_cvkittler.py | 8,830 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize
NUM_INPUT = 784 # Number of input neurons
NUM_HIDDEN = 40 # Number of hidden neurons
NUM_OUTPUT = 10 # Number of output neurons
NUM_CHECK = 5 # Number of examples on which to check the gradient
# Given a vector w containing all the weights and biased vectors, extract
# and return the individual weights and biases W1, b1, W2, b2.
# This is useful for performing a gradient check with check_grad.
def unpack (w):
constantA = NUM_HIDDEN * NUM_INPUT
W1 = w[:constantA]
constantB = NUM_HIDDEN + constantA
b1 = w[constantA:constantB]
constantC = constantB + NUM_OUTPUT * NUM_HIDDEN
W2 = w[constantB:constantC]
b2 = w[constantC:]
W1 = np.reshape(W1,[NUM_HIDDEN,NUM_INPUT])
W2 = np.reshape(W2,[NUM_OUTPUT,NUM_HIDDEN])
return W1, b1, W2, b2
# Given individual weights and biases W1, b1, W2, b2, concatenate them and
# return a vector w containing all of them.
# This is useful for performing a gradient check with check_grad.
def pack (W1, b1, W2, b2):
return np.append(W1,np.append(b1,np.append(W2,b2)))
# Load the images and labels from a specified dataset (train or test).
def loadData (which):
images = np.load("fashion_mnist_{}_images.npy".format(which))
labels = np.load("fashion_mnist_{}_labels.npy".format(which))
return images, labels
def PC(X, Y, W):
result = np.argmax(calcYHat(X.T, W), axis=0) == np.argmax(Y, axis=1)
return np.sum(result) / result.shape[0]
def calcYHat(_X, _w):
_W1, _b1, _W2, _b2 = unpack(_w)
z1 = (np.dot(_W1 , _X).T + _b1).T
h1 = np.where(z1 > 0, z1, 0)
z2 = (np.dot(_W2 , h1).T + _b2).T
yHat = softmax(z2)
return yHat
#calc the softmax
def softmax(x):
x.astype(np.longdouble)
exp = np.exp(x)
exp_sum = np.sum(exp, axis=0)
return (exp / exp_sum)
# Computes cross entropy for all values in X, Y
def fCE(_X, _Y, _w):
_X = _X.T
yHat = calcYHat(_X, _w)
logYHat = np.log(yHat)
sumLogYHat = np.sum(_Y.T * logYHat)
cost = (-1/_X.shape[1]) * sumLogYHat
return cost
# Given training images X, associated labels Y, and a vector of combined weights
# and bias terms w, compute and return the gradient of fCE. You might
# want to extend this function to return multiple arguments (in which case you
# will also need to modify slightly the gradient check code below).
def gradCE(_X, y, _w):
X = _X.T
W1, b1, W2, b2 = unpack(_w)
z1 = (np.dot(W1 , X).T + b1).T
h1 = np.where(z1 > 0, z1, 0)
z2 = (np.dot(W2 , h1).T + b2).T
yhat = softmax(z2)
yhat_y = yhat - y.T
gT = np.dot(yhat_y.T , W2) * np.where(z1.T >= 0, 1.0, 0.0)
g = gT.T
grad_w2 = np.dot(yhat_y , h1.T)
grad_b2 = np.mean(yhat_y, axis=1)
grad_w1 = np.dot(g , X.T)
grad_b1 = np.mean(g, axis=1)
grad = pack(grad_w1, grad_b1, grad_w2, grad_b2)
return grad
# Given training and testing datasets and an initial set of weights/biases b,
# train the NN.
def train (trainX_, trainY_, testX, testY, _w, L1_coeff = 0.0, L2_coeff = 0.0001, batchSize = 8, numEpochs = 30, learning_rate = 0.01):
numImages = trainX_.shape[0]
if batchSize is None:
batchSize = numImages
# change the order of the examples
newOrder = np.arange(numImages)
np.random.shuffle(newOrder)
X = trainX_[newOrder, :]
Y = trainY_[newOrder, :]
w_past = np.zeros([numEpochs, _w.size])
for EPOCH in range(numEpochs):
for batch_start in range(0, numImages, batchSize):
if(batch_start + batchSize > numImages):
batchSize = numImages - batch_start
xBatch = X[batch_start:batch_start + batchSize,:]
yBatch = Y[batch_start:batch_start + batchSize,:]
gradients = gradCE(xBatch,yBatch, _w)
w1_delta, b1_delta, w2_delta, b2_delta = unpack(gradients)
_w1, _b1, _w2, _b2 = unpack(_w)
_w1 -= learning_rate * w1_delta + L1_coeff * np.sign(_w1) + L2_coeff * _w1
_w2 -= learning_rate * w2_delta + L1_coeff * np.sign(_w2) + L2_coeff * _w2
_b1 -= learning_rate * b1_delta + L1_coeff * np.sign(_b1) + L2_coeff * _b1
_b2 -= learning_rate * b2_delta + L1_coeff * np.sign(_b2) + L2_coeff * _b2
_w = pack (_w1, _b1, _w2, _b2)
w_past[EPOCH] = _w
# print("Epoch:", EPOCH, "Test Score:", PC(testX, testY, _w))
return _w, w_past
def graphData(old_w, X, Y, PERAMS_STRING):
numRecorded = old_w.shape[0]
accuracy = np.zeros(numRecorded)
cross_entropy = np.zeros(numRecorded)
for cur in range(numRecorded):
accuracy[cur] = PC(X,Y,old_w[cur])
cross_entropy[cur] = fCE(X,Y,old_w[cur])
plt.plot(cross_entropy)
plt.ylabel('Loss')
plt.xlabel('Epoch')
title = 'Loss vs Epoch' + PERAMS_STRING
plt.title(title)
fileName = 'plots/' + str(title) + '.jpeg'
plt.savefig(fileName)
plt.show()
plt.plot(accuracy)
plt.ylabel('Percent Correct')
plt.xlabel('Epoch')
title = 'Percent Correct vs Epoch' + PERAMS_STRING
plt.title(title)
fileName = 'plots/' + str(title) + '.jpeg'
plt.savefig(fileName)
plt.show()
def findBestHyperparameters(X, Y, W):
#unused
L1_coeff = np.array([0, 0.00001, 0.0001, 0.001, 0.01])
L2_coeff = np.array([0, 0.00001, 0.0001, 0.001, 0.01])
unitsHiddenLayer = np.array([30,40,50])
#used
batchSize = np.array([16, 32, 64, 128])
bestBatchSize = batchSize[0]
numEpochs = np.array([40, 50, 60])
bestNumEpochs = numEpochs[0]
learning_rate = np.array([0.0001, 0.001, 0.005, 0.01])
best_learning_rate = learning_rate[0]
numImages = trainX.shape[0]
bestPC = 0
for batchSize_ in batchSize:
for numEpochs_ in numEpochs:
for learning_rate_ in learning_rate:
newOrder = np.arange(numImages)
np.random.shuffle(newOrder)
X = X[newOrder, :]
Y = Y[newOrder, :]
X_test = X[:int(numImages * 0.2),:]
X_train = X[int(numImages * 0.2):,:]
Y_test = Y[:int(numImages * 0.2),:]
Y_train = Y[int(numImages * 0.2):,:]
w_found,w_past = train(X_train, Y_train, testX, testY, W, batchSize=batchSize_,numEpochs=numEpochs_,learning_rate=learning_rate_)
titel_add_on = "BatchSize" + str(batchSize_) + "Epochs" + str(numEpochs_) + "LearnRate" + str(learning_rate_)
# graphData(w_past, X_test, Y_test, titel_add_on)
if PC(X_test, Y_test, w_found) > bestPC and fCE(X_test, Y_test, w_found) == fCE(X_test, Y_test, w_found):
print(titel_add_on)
bestBatchSize = batchSize_
bestNumEpochs = numEpochs_
best_learning_rate = learning_rate_
bestW = w_found
bestPC = PC(X_test, Y_test, w_found)
print("Best Hyper Parameters:", " Batch Size: " + str(bestBatchSize) + " Number of Epochs: " + str(bestNumEpochs) + " Learning Rate: " + str(best_learning_rate))
return bestW, titel_add_on
if __name__ == "__main__":
# Load data
if "trainX" not in globals():
trainX, trainY = loadData("train")
testX, testY = loadData("test")
trainX = trainX / 255
testX = testX / 255
n = trainY.size
Y = np.zeros([n, 10])
Y[np.arange(n), trainY] = 1
trainY = Y
n = testY.size
Y = np.zeros([n, 10])
Y[np.arange(n), testY] = 1
testY = Y
# Initialize weights randomly
W1 = 2*(np.random.random(size=(NUM_HIDDEN, NUM_INPUT))/NUM_INPUT**0.5) - 1./NUM_INPUT**0.5
b1 = 0.01 * np.ones(NUM_HIDDEN)
W2 = 2*(np.random.random(size=(NUM_OUTPUT, NUM_HIDDEN))/NUM_HIDDEN**0.5) - 1./NUM_HIDDEN**0.5
b2 = 0.01 * np.ones(NUM_OUTPUT)
# Concatenate all the weights and biases into one vector; this is necessary for check_grad
w = pack(W1, b1, W2, b2)
# Check that the gradient is correct on just a few examples (randomly drawn).
# idxs = np.random.permutation(trainX.shape[0])[0: 1]
# print(scipy.optimize.check_grad(lambda w_: fCE(np.atleast_2d(trainX[idxs,:]), np.atleast_2d(trainY[idxs,:]), w_), \
# lambda w_: gradCE(np.atleast_2d(trainX[idxs,:]), np.atleast_2d(trainY[idxs,:]), w_), \
# w))
# Train the network using SGD.
w,w_past = train(trainX, trainY, testX, testY, w, batchSize=128, numEpochs=40, learning_rate=0.001)
graphData(w_past, trainX, trainY, ' Default')
# UNCOMMENT TO DO HYPER PERAMETER SEARCH
# w_found, titel = findBestHyperparameters(trainX, trainY, w)
# print(PC(testX,testY, w_found))
# print(fCE(testX, testY, w_found))
# graphData(w_found, testX, trainY, titel) |
92ae3ed0edd201b4b383825e5e507ecfab503985 | queensland1990/HuyenNguyen-Fundamental-C4E17 | /SS03/hwcrud3.py | 221 | 3.703125 | 4 | list=["T-shirt","Sweater","Jeans"]
print("Welcome to our shop, what do you want ?")
print("update position: 2")
print("new item ? ",end="")
list[1]="Skirt"
print(list[1])
print("our items: ",end="")
print(*list,sep=", ")
|
72d47ac362edc255e9df31b269c25eaf7b39ef56 | jyates722/Cssi19 | /day7/mystory.py | 415 | 3.875 | 4 | story ="""Clap your hands together,
{0} together
Clap your {1} together,
clap, {2} clap
Clap clap this way,
clap clap that {3},
clap clap all the day,
{4}, clap, clap"""
noun1 = raw_input("Enter an Noun1:")
noun2 = raw_input("Enter an Noun2:")
noun3 = raw_input("Enter an Noun3:")
noun4 = raw_input("Enter an Noun4:")
noun5 = raw_input("Enter an Noun5:")
print story.format(noun1,noun2,noun3,noun4,noun5) |
dde9c69797d2273e4796c542aa46ea280f672522 | Satyavrath/pythonBasics | /stringLength.py | 410 | 4.0625 | 4 | def string_length(name):
count = 0
for string in name:
count += 1
return count
print(string_length("Hello"))
def test_stringLength():
assert string_length("Hello") == 5
assert string_length("myName") == 6
print("The string works fine")
test_stringLength()
# last letter of string
def lastLetter(name):
return name[-1]
print(lastLetter("Hdfasdfasdf"))
|
f8c7257e82d466dee87ddaaefc0b12e3a0a466f9 | HaroldEnrique/web-service | /Test/Test.py | 1,855 | 3.640625 | 4 | import json
import re
import os
class Test:
def __init__(self):
try: # De https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file
if os.path.exists('db.json'):
path='db.json'
elif os.path.exists('/data/db.json'):
path='/data/db.json'
elif os.path.exists('./data/db.json'):
path='./data/db.json'
elif os.path.exists('../data/db.json'):
path='../data/db.json'
else:
raise IOError("No se encuentra 'db.json'")
with open(path) as data_file:
self.datos = json.load(data_file)
except IOError as fallo:
print("Error {:s} leyendo db.json".format( fallo ) )
def todos_datos(self):
return self.datos
def cuantos(self):
return len(self.datos['datos'])
def uno(self,dato_id):
if dato_id > len(self.datos['datos']) or dato_id < 0:
raise IndexError("Índice fuera de rango")
return self.datos['datos'][dato_id]
def nuevo( self, filename, course, date ):
if ( not type(filename) is str):
raise TypeError( "El nombre del fichero debe ser una cadena" )
if ( not type(title) is str):
raise TypeError( "El título del dato debe ser una cadena" )
if not re.match("\d+/\d+\d+", date) :
raise ValueError( "El formato de la fecha es incorrecto" )
existe = list(filter( lambda dato: 'file' in dato and dato['file'] == filename, self.datos['datos'] ))
if len(existe) > 0:
raise ValueError( "Ese fichero ya existe")
self.datos['datos'].append( {'file': filename,
'course': course,
'date': date } )
|
4c18f9ca399dcf6eb9b222bcb945723630b306dd | ericschorling/digital_crafts_python | /python_1/n_to_m.py | 125 | 4 | 4 | n = int(input("give me a number to start at"))
m = int(input("give me a ending number"))
while n <= m:
print(n)
n+=1 |
623938d0d0b872cd839f1d6aacee23825f6e8819 | pedrofrancal/Python | /aprendendo/dicionarios/iterando.py | 615 | 3.515625 | 4 | dados = {'Crossfox': 72832.16, 'DS5': 124549.07, 'Fusca': 150000, 'Jetta Variant': 88078.64, 'Passat': 106161.95}
# o métodos keys() retorna todas as chaves, a gente vai utilizar ele para iterar
for key in dados.keys():
print(dados[key])
# existe metodo para voltar todos os valores tambem
print(dados.values())
# e podemos iterar por itens
for item in dados.items():
print(item)
# podemos desempacotar tambem
for key, value in dados.items():
print(key, value)
# e podemos usar condições
for key, value in dados.items():
if (value > 100000):
print(f'Maior que 100000: '+key, value) |
9bbed30a67e3930b1d42390b58d3c226e8fc684a | zekiahmetbayar/python-learning | /Bolum3_Problemler/mukemmel_sayi.py | 301 | 3.84375 | 4 | sayi = int(input("Merak ettiğiniz sayıyı giriniz : "))
toplam = 0
for i in range(1,sayi):
if (sayi%i == 0):
toplam += i
if(toplam ==sayi):
print(" {} sayısı mükemmel bir sayıdır. ".format(sayi))
else:
print(" {} sayısı mükemmel bir sayı değildir. ".format(sayi)) |
9ab8d5db255ec34cd97ffac259d76b85458bca6d | 2021dbakhmat/greeting | /greeting.py | 267 | 4.125 | 4 | name1 = "Diana"
name2 = "Marl owe"
name3 = "sister"
print(name1)
print(name2)
print("hello, " + name1)
print(len(name2))
print(name2 + " has " + str(len(name2)) + " characters in their name!")
age1 = "16"
print("My" (name3 + " is " + str(len(age1)) + " years old!" )
|
08b6d4380e88010e493c5a8454d7e53f11a4a654 | guydav/minerva | /formal/raquetball.py | 4,392 | 3.609375 | 4 | import random
import tabulate
from utils import *
SERVE_WIN_PROBABILITY = 0.6
OPPONENT_WIN_PROBABILITY = 0.5
PLAY_TO = 21
START_SERVE = True
NUM_TRIALS = 100000
def single_game(p_serve=SERVE_WIN_PROBABILITY, p_opponent=OPPONENT_WIN_PROBABILITY, play_to=PLAY_TO,
start_serve=START_SERVE):
my_score = 0
opponent_score = 0
current_serve = start_serve
while my_score < play_to and opponent_score < play_to:
point = random.random()
if current_serve:
if point < p_serve:
my_score += 1
else:
current_serve = False
else:
if point < p_opponent:
opponent_score += 1
else:
current_serve = True
return int(my_score == play_to)
def trial_generator(num_trials=NUM_TRIALS):
for i in xrange(num_trials):
yield single_game()
def run_simulation():
my_total = sum(trial_generator())
print 'The simulated winning percentage is {p:.3}%'.format(p=float(my_total)*100/NUM_TRIALS)
def build_table(p_win=SERVE_WIN_PROBABILITY, p_loss=OPPONENT_WIN_PROBABILITY, play_to=PLAY_TO,
start_serve=START_SERVE):
result = []
for r in xrange(play_to + 1):
row = []
result.append(row)
for c in xrange(play_to + 1):
row.append({True: 0, False: 0})
result[0][0][True] = 1
result[0][0][False] = 1
frontier = PriorityQueue()
visited = set()
frontier.put((1, 0), 0)
frontier.put((0, 1), 0)
while frontier:
current = frontier.get()
if current in visited:
continue
visited.add(current)
row, col = current
p_current_win = 0
p_current_loss = 0
if row == 0:
# first row, can only win to get here
p_current_win = result[row][col - 1][True] * p_win
elif col == 0:
# first column, can only lose to get here
if row == 1:
# First loss, edge-case for starting on serve
p_current_loss = result[row - 1][col][False] * (1 - p_win)
else:
p_current_loss = result[row - 1][col][False] * (1 - p_loss)
elif row == play_to and col == play_to:
# The score 21-21 is impossible
pass
elif col == play_to:
# last column, can only win to get here
p_current_win = result[row][col - 1][True] * p_win
p_current_win += result[row][col - 1][False] * p_loss
elif row == play_to:
# last row, can only lose to get here
p_current_loss = result[row - 1][col][True] * (1 - p_win)
p_current_loss += result[row - 1][col][False] * (1 - p_loss)
else:
# coming from a win
p_current_win = result[row][col -1][True] * p_win
p_current_win += result[row][col -1][False] * p_loss
# coming from a loss
p_current_loss = result[row - 1][col][True] * (1 - p_win)
p_current_loss += result[row - 1][col][False] * (1 - p_loss)
result[row][col][True] = p_current_win
result[row][col][False] = p_current_loss
if row < play_to:
next_row = (row + 1, col)
frontier.put(next_row, sum(next_row))
if col < play_to:
next_col = (row, col + 1)
frontier.put(next_col, sum(next_col))
return result
def print_table():
table = build_table()
table_to_print = []
row_num = 0
for row in table:
table_to_print.append([row_num] + ['{p_w:.4f}|{p_l:.4f}'.format(p_w=col[True], p_l=col[False]) for col in row])
row_num += 1
header_row = ['***'] + range(22)
print tabulate.tabulate(table_to_print, headers=header_row)
total_win_p = sum([row[21][True] for row in table])
total_loss_p = sum([col[False] for col in table[21]])
print 'The total win probability is {p:.4f}'.format(p=total_win_p)
print 'The total loss probability is {p:.4f}'.format(p=total_loss_p)
print 'The overall win probability is {p:.4f}'.format(p=(total_win_p / (total_win_p + total_loss_p)))
print 'The overall loss probability is {p:.4f}'.format(p=(total_loss_p / (total_win_p + total_loss_p)))
def main():
run_simulation()
# print_table()
if __name__ == '__main__':
main()
|
28aa8f52e2c8a4fbd73bbf3946f677cc88e848a4 | zepetto7065/study_codingTest | /12주차/문제/지혜수_10870_피보나치수5.py | 187 | 3.828125 | 4 | def fibo(n):
a = 0
b = 1
c = 0
for _ in range(n-1):
c = a + b
a, b = b, c
return c
N = int(input())
if N == 0:
print(0)
elif N == 1:
print(1)
else:
print(fibo(N)) |
059a2de356024b80d7004c6f37a431417d26c27d | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_1_neat/16_0_1_Mauro_a.py | 369 | 3.5625 | 4 | def read_int():
return int(raw_input())
def solve(N):
if N == 0:
return "INSOMNIA"
seen = set()
n = 0
while True:
n += N
ans = n
seen.update(set(str(n)))
if len(seen) == 10:
return ans
for case in range(read_int()):
N = read_int()
ans = solve(N)
print "Case #%d: %s" % (case+1, ans)
|
3ed138814ce0b262a3944cb6db1079af7ba100b8 | emersonsemidio/python | /Desafio.73.py | 349 | 3.921875 | 4 | Times = ('São Paulo ', 'Flamengo ', 'Atlético-Mg ', 'Palmeiras ', 'Grêmio ', 'Fluminense ')
print('-=' *20)
print('Os 5 primeiros são ',end = '')
for c in range(0,5):
print(Times[c],end='')
print('')
print('-=' *20)
print(f'Os 4 últimos são {Times[2:]}')
print('-=' *20)
print(f'O time que em 3° é o {Times[2]}')
print('-=' *20)
|
d82f726d464e9fc14261a9b059d6429eb89fd720 | kla0629/Backjoon | /2588.py | 515 | 3.734375 | 4 | """
(세 자리 수) × (세 자리 수)는 다음과 같은 과정을 통하여 이루어진다.
(1)과 (2)위치에 들어갈 세 자리 자연수가 주어질 때 (3), (4), (5), (6)위치에 들어갈 값을 구하는 프로그램을 작성하시오.
"""
a = int(input())
b = int(input())
if 100 <= a < 1000 and 100 <= b < 1000:
b_100 = int(b/100)
b_10 = int(b/10 - b_100*10)
b_1 = int(b - b_100*100 - b_10*10)
print(a*b_1)
print(a*b_10)
print(a*b_100)
print(a*b) |
e98c075bd6df705c448082eda088c9040fe0d964 | gaurav-dalvi/codeninja | /python/CharSort.py | 759 | 3.75 | 4 | # Sort array of chars, ASCII only.
# Input : String of chars , terminated by newline of NULL
# Output: Sorted set of chars. You can overwrite array.
# Desired complexity : O(n) with constant space
def sortCharacters(inString):
inputList = list(inString)
asciiMap = [0] * 256
for i in xrange(len(inputList)):
count = asciiMap[ord(inputList[i])]
asciiMap[ord(inputList[i])] = count + 1
# stroing input in array
index = 0
for i in xrange(256):
if asciiMap[i] > 0:
for j in xrange(asciiMap[i]):
inputList[index] = chr(i)
index = index + 1
return ''.join(inputList)
if __name__ == '__main__':
inString = 'afrslfirew'
print sortCharacters(inString)
|
a366ab030f405824d432fce15d6b96c2a72f23bb | gadoid/PythonNote | /Day1.py | 3,179 | 4.1875 | 4 | # int 整型
# 可以用 int() 强制转换为整型
float_number=1.1
print(int(float_number))
str_info="a"
# 进制
# 0b 2进制 0o 八进制 默认十进制 0x 十六进制
result=0b101+0o17+10+0x1D
print(result)
# 对其
#5 右对齐5位
#-5 左对齐 5位
print("%5d"%(result),"aaa")
print("%-5d"%(result),"aaa")
#float 浮点型
#转换整型为浮点型
int_number=2
print(float(int_number))
# .+数字打印固定位数小数
print("%5.8f"%(int_number))
# 字符串型
# 由单、双引号括起来的任意文本
print("hello world")
#可以用Unicode 数值表示
a= u"Hello world"
print("\150\145\154\154\157\40\167\157\162\154\144")
#跨行输出 三个单/双 引号
print("""hello
world""")
#字符串支持切片
hello = "hello world"
print(hello[:6])
print(hello[6:])
#布尔值 数值True\False 或其他可转换值
# 如0,1
print(bool(0),bool(1))
# 如非空、空
print(bool(" "),bool(None),bool(""))
# 运算式结果
print(bool(1>2),bool(1<2))
# 变量命名
# 支持的元素 大小写字母、数字、下划线 不能用数字开头
# 大小写敏感 不要和自带关键子冲突
# 驼峰命名法
def ApplePie():
print("This is a apple pie")
ApplePie()
# 小驼峰命名法
def applePie():
print("This is a apple pie")
applePie()
#PEP8
# 用小写字母拼写,多个单词用下划线连接
# 受保护的实例属性用单个下划线开头
# 私有的实例属性用两个下划线开头
# Python 变量声明
# Python_variable
Python_variable="variable"
print(Python_variable)
#Type函数检查变量类型
print(type(Python_variable))
Python_variable=1
print(type(Python_variable))
#变量运算
Python_int=8
Python_float=8.1
print(Python_float+Python_int)
Python_str="a"
try:
print(Python_int+Python_str)
except TypeError:
print("TypeError")
#强制转换函数
# float()
# str()
# chr()
# int()
# bool()
# ord()
print(ord("h"))
print(chr(0o150))
#变量传值
content="通过%+类型传递参数"
print("%s"%(content))
# 通过format函数
content="通过format函数"
#print("{content}".format())
#简化
print(f"{content}")
#直接使用变量连结
content="直接使用变量连接"
print("print"+content)
#运算符
# 切片,左闭右开[]
list1= [1,2,3,4,5]
list2=list1
list3=list1[:]
print(id(list1),id(list2),id(list3))
import copy
list4=copy.deepcopy(list1)
print(id(list4))
#切片参数 [:,2,-1]
print(list1[-1::1])
#乘方
print(2**2)
#取反
print(-0b101)
#取余、整除
print(8%3,8//3)
#左移 右移
print(8>>1,8<<1)
print(0b100,0b1000,0b10000)
#按位与
print(5&8)
print(0b1100&0b100)
# >= <= < >
# 不等于 !=
# is、not is 比较内存地址
list1 =[1,2,3,4,5]
list2 = list1.copy()
list4 = list1
list3 = list1[:]
print(bool(list1 is list2),bool(list1 is list4),bool(list1 is list3))
# in not in 比较元素信息,不比较内存地址
list1 = [1,2,3]
list2 = [1,2,3,4,[1,2,3]]
list3 = [1,2,3,list1]
print(bool(list1 in list3),bool(list1 in list2))
#not or and 逻辑运算符
if not "b" or "a" and "b" :
print('ok')
if "a" or "b" and not "b" :
print("ok")
print('not ok')
#复合运算
number = 16
while number > 0:
number>>=1
print(number)
|
d9d8e95badf13bd1a561853ab9e815fd5353d3cb | liu-yuxin98/Python | /chapter6/6.2.py | 248 | 3.96875 | 4 | def sumDigits(number):
sum=0
if number<0:
number=-1*number
else:
number=number
while number != 0:
sum = sum + number % 10
number = (number - number % 10) / 10
return sum
print(sumDigits(-12345))
|
15f1893b4eb06b3d5f230c80c4225cced42ad593 | andresscode/coursera-cs-math-specialization | /math-thinking-cs/week-04/prime_conjecture.py | 236 | 3.578125 | 4 | def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def solve():
for i in range(1, 1000001):
num = i ** 2 + i + 41
if not is_prime(num):
return num
return -1
print(solve())
|
a6a61dcbb4ed002e75e26f999f14173aa6ff9638 | icole/MITx-6.00.1x | /problem-set-2/problem1.py | 563 | 3.78125 | 4 | balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
totalPayment = 0
for i in range(1, 13):
print "Month: " + str(i)
minimumPayment = balance * monthlyPaymentRate
totalPayment += minimumPayment
print "Minimum monthly payment: %.2f" % minimumPayment
remainingBalance = balance - minimumPayment
remainingBalance += (remainingBalance * annualInterestRate)/12
print "Remaining balance: %.2f" % remainingBalance
balance = remainingBalance
print "Total paid: %.2f" % totalPayment
print "Remaining balance: %.2f" % balance
|
389ba775b135edee5a487b0b8c4791ee66dd3da9 | Davidxswang/leetcode | /easy/1370-Increasing Decreasing String.py | 2,323 | 3.890625 | 4 | """
https://leetcode.com/problems/increasing-decreasing-string/
Given a string s. You should re-order the string using the following algorithm:
Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append it.
Repeat step 2 until you cannot pick more characters.
Pick the largest character from s and append it to the result.
Pick the largest character from s which is smaller than the last appended character to the result and append it.
Repeat step 5 until you cannot pick more characters.
Repeat the steps from 1 to 6 until you pick all characters from s.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return the result string after sorting s with this algorithm.
Example 1:
Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
Example 2:
Input: s = "rat"
Output: "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.
Example 3:
Input: s = "leetcode"
Output: "cdelotee"
Example 4:
Input: s = "ggggggg"
Output: "ggggggg"
Example 5:
Input: s = "spo"
Output: "ops"
Constraints:
1 <= s.length <= 500
s contains only lower-case English letters.
"""
# time complexity: O(n), space complexity: O(1)
class Solution:
def sortString(self, s: str) -> str:
freq = [0] * 26
for letter in s:
freq[ord(letter)-ord('a')] += 1
length = len(s)
result = ''
while length > 0:
for i in range(len(freq)):
if freq[i] > 0:
result += chr(ord('a') + i)
freq[i] -= 1
length -= 1
for i in range(len(freq)-1, -1, -1):
if freq[i] > 0:
result += chr(ord('a') + i)
freq[i] -= 1
length -= 1
return result
|
62c99807a59d0cb31c2bc0d0e7bd184a09872590 | didi1215/leetcode | /leetcode/leetcode/editor/cn2/[剑指 Offer 22]链表中倒数第k个节点.py | 1,154 | 3.65625 | 4 | # 输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。
#
# 例如,一个链表有 6 个节点,从头节点开始,它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。
#
#
#
# 示例:
#
#
# 给定一个链表: 1->2->3->4->5, 和 k = 2.
#
# 返回链表 4->5.
# Related Topics 链表 双指针
# 👍 218 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
# 快慢指针
former, latter = head, head
for i in range(k):
# former和latter相差k
former = former.next
while former:
# former = null时跳出
former, latter = former.next, latter.next
return latter
# leetcode submit region end(Prohibit modification and deletion)
|
fe487327c7a3595f0d6722e6cfd2214cc8048b05 | C-Probert/python | /decimal.py | 980 | 4 | 4 | #!/usr/bin/python
import sys
hexmap = {0:'0', 1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}
#function handles conversion of binary and hex.
#val is the decimal number and divnum is the number to divide by.
def convert_number(val, divnum):
quotient, remainder = divmod( val, divnum )
while quotient != 0:
yield remainder
quotient, remainder = divmod( quotient, divnum )
yield remainder
return
if len(sys.argv) == 2:
int_string = sys.argv[1]
dec = 0
try:
dec = int(int_string)
except ValueError:
sys.exit('Could not parse input to int')
hexval = ''
for val in convert_number(dec,16):
hexval = hexmap[val] + hexval
print 'hex: {0}'.format(hexval),
binaryval = ''
for val in convert_number(dec,2):
binaryval = str(val) + binaryval
print 'binary: {0}'.format(binaryval)
else:
print 'No argument was given'
|
24c377e51a2f279e6ddfe039fc3fbeef0a1a02c6 | taisei5i7/Python_learnigdebris | /3.7.2/panic my answer.py | 378 | 4.0625 | 4 | phrase = "Don't panic!"
plist = list(phrase)
print(phrase)
print(plist)
target = ["o", "n", "t", "a", "p"]
word = plist
found = []
for letter in word:
if letter in target:
if letter not in found:
found.append(letter)
plist = found
found.remove("a")
found.insert(2, " ")
found.insert(4, "a")
new_phrase = ''.join(plist)
print(plist)
print(new_phrase)
|
5d55ba16d3527c01c2176632d6d01312381e4ebe | cryp2knight/numerical-methods-notebooks | /notebooks/montecarlo.py | 1,980 | 3.953125 | 4 | # EXERCISE 1
from numpy.random import rand
from math import sqrt
def estimate_pi_with_monte_carlo(n=1000):
inside_points = 0
for _ in range(n):
x = rand()
y = rand()
distance = sqrt(x**2 + y**2)
if distance < 1:
inside_points += 1
return 4 * (inside_points / n)
# estimate of PI with 1000 points
print('Pi estimate:', estimate_pi_with_monte_carlo())
#EXERCISE 2
from numpy.random import rand
# parabolas
p1 = lambda x: x**3
p2 = lambda x: 2*x - x**2
# upperbound is 1, lowerbound is 0
def estimate_area_bounded_by_p1_and_p2(n=10000,l=0,u=1):
p1_sum = 0
p2_sum = 0
for _ in range(n):
x = rand()
p1_sum += p1(x)
p2_sum += p2(x)
p1_area = ((u - l)/n) * p1_sum
p2_area = ((u - l)/n) * p2_sum
return p2_area - p1_area
print(estimate_area_bounded_by_p1_and_p2())
#HIT AND MISS
def estimate_area_bounded_by_p1_and_p2_using_proportion(n=10000):
inside_points = 0
for _ in range(n):
x = rand()
y = rand()
y_p1 = p1(x)
y_p2 = p2(x)
if y > y_p1 and y < y_p2:
inside_points += 1
return inside_points / n
print(estimate_area_bounded_by_p1_and_p2_using_proportion())
# Efficiency
# Both monte carlo algorithm run on O(n) where n is the number
# of random data points, first approcah needs extra computation
# but proportion method may slow down depending on the rand function
# Overall, the proportion method is faster if we will not consider
# the random number generation function
#EXERCISE 3
from numpy.random import uniform
def estimate_volume_of_ellipsoid(n=10000):
box_volume = 14*4*10
ellipsoid = lambda x,y,z: x**2/49 + y**2/4 + z**2/25
count = 0
for _ in range(n):
x = uniform(-7, 7, 1)
y = uniform(-2, 2, 1)
z = uniform(-5, 5, 1)
if ellipsoid(x,y,z) <= 1:
count += 1
return box_volume * (count/n)
print(estimate_volume_of_ellipsoid())
|
ded3511c3cfc1a61ce9dd684eedb8e39a2bcf052 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4366/codes/1734_2504.py | 325 | 3.796875 | 4 | quant1=int(input("digite a quantidade inicial de copias:"))
quant2=int(input("digite a quantidade inicial de leucocitos:"))
p1=int(input("digite o percentual1:"))
p2=int(input("digite o percentual2:"))
p1=p1/100
p2=p2/100
t=0
while(2*quant1>quant2):
quant1=quant1+quant1*p1
quant2=quant2+quant2*p2
t=t+1
print(t)
|
426e26c9437d937cda71942ecf1195e1eacad9b2 | skipter/Programming-Basics-Python | /Exam 01.12.2018/01.School Supplies.py | 297 | 3.75 | 4 | pencil = int(input())
pen = int(input())
liquid = float(input())
discount = int(input())
pencip_price = pencil * 5.80
pen_price = pen * 7.20
liquid_price = liquid * 1.20
materials = pencipPrice + penPrice + preparatPrice
total = materials - ((materials * discount) / 100)
print(f"{total:.3f}")
|
117ef5751de8e4c5f8f691aafaa906fd501350e5 | lincolnjohnny/py4e | /2_Python_Data_Structures/Week_5/ex_09_04.py | 973 | 3.796875 | 4 | # Write a program to read through the mbox-short.txt and figure out who has sent the greatest number
# of mail messages.
# The program looks for 'From ' lines and takes the second word of those lines as the person
# who sent the mail.
# The program creates a Python dictionary that maps the sender's mail address to a count of the
# number of times they appear in the file.
# After the dictionary is produced, the program reads through the dictionary using a
# maximum loop to find the most prolific committer.
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
email = dict()
for line in handle :
line.rstrip()
if not line.startswith('From ') :
continue
words = line.split()
email[words[1]] = email.get(words[1],0) + 1
bigkey = None
bigvalue = None
for key,value in email.items() :
if bigvalue is None or value > bigvalue :
bigkey = key
bigvalue = value
print(bigkey, bigvalue) |
9d8066dd96b54af5bee1bd08f7ddea26e2ce6bde | Jackerdelta/VillagerTradePriceCheck | /PriceChecker.py | 2,586 | 3.59375 | 4 | import decimal
from decimal import *
class main:
def __init__(self,item_to_offer,item_for_trade,calculation_type,average_item_per_block,price_of_block,price_per_stack_in_shop,margin_desired):
setcontext(Context(prec=5))
self.item_to_offer=Decimal(item_to_offer)
self.item_for_trade=Decimal(item_for_trade)
self.calculation_type=calculation_type
self.average_item_per_block=average_item_per_block
self.price_of_block=Decimal(price_of_block)
self.price_per_stack_in_shop=Decimal(price_per_stack_in_shop)
self.margin_desired=Decimal(margin_desired)
def calculate(self):
if self.calculation_type=="/":
print "--------------------------------"
price_per_item=self.price_of_block/self.average_item_per_block
print "Price per item: ",Decimal(price_per_item)
print "--------------------------------"
trade_ratio=self.item_to_offer/self.item_for_trade*64
print "Trade Ratio:",Decimal(trade_ratio)
print "--------------------------------"
final_int=1+price_per_item
final_equation=trade_ratio*final_int
print "Price per stack:",Decimal(final_equation)
print "--------------------------------"
profit_made=self.price_per_stack_in_shop-final_equation
print "Profit Made:",Decimal(profit_made)
print "--------------------------------"
calculate_margin=Decimal(self.price_per_stack_in_shop*self.margin_desired)
if profit_made<calculate_margin:
print "WARNING: You will lose money with a margin of ",Decimal(self.margin_desired),"%"
else:
print "Success! Margin has been met!"
print "--------------------------------"
def set_parameters():
item_to_offer=int(raw_input("How many Emeralds you offer: "))
item_for_trade=int(raw_input("How many items you are getting: "))
average_item_per_block=int(raw_input("If you mined this block with a Fortune Pickaxe how many item(s) would you get?: "))
price_of_block=Decimal(raw_input("Cost of block on RenMX shop:" ))
price_per_stack_in_shop=Decimal(raw_input("Cost of stack of this item on RenMX shop:"))
margin_desired=Decimal(raw_input("Margin Desired (decimal): "))
this=main(item_to_offer,item_for_trade,"/",average_item_per_block,price_of_block,price_per_stack_in_shop,margin_desired)
this.calculate()
#this=main(1,2,"/",4,3)
#this.calculate()
set_parameters()
|
1544c510f19b813837db7c9d4884521287b35986 | nortonacosta/Exercicios_Loops | /ex15.py | 104 | 3.875 | 4 | n = int(input('Digite um npumero ímpar: '))
for i in range(0, n):
if i % 2 == 1:
print(i)
|
f7972ebd14b6cf5f0bdda54d43409740203aeb00 | SirSanewa/rekrutacja | /app.py | 7,568 | 3.546875 | 4 | from sqlalchemy import func, desc
from models import Person
from session import session_creator
import argparse
from datetime import datetime
def percentage(number, total):
"""
Calculates and returns percentage value from given number and total amount.
:param number: int
:param total: int
:return: percentage: int
"""
result = (number * 100) / total
if result.is_integer():
return int(result)
return result
def gender_proportions():
"""
Prints gender proportions of db population.
:return:
"""
total_rows = sql_session.query(Person) \
.count()
men = sql_session.query(Person) \
.filter(Person.gender == "male") \
.count()
women = sql_session.query(Person) \
.filter(Person.gender == "female") \
.count()
men_percent = percentage(men, total_rows)
women_percent = percentage(women, total_rows)
print(f"Gender proportions are: \n\t-{men_percent}% men({men} total)\n\t-{women_percent}% women({women} total).")
def average_age(option="total"):
"""
Prints average age depending on option chosen from {'total', 'male', 'female'}. Default 'total'.
Raises Value Error if option other then allowed.
:param option: str, default 'total'
:return:
"""
populations = {"total", "male", "female"}
if option not in populations:
raise ValueError("Used unsupported population")
if option == "total":
age_avg = sql_session.query(func.avg(Person.age)) \
.scalar()
else:
age_avg = sql_session.query(func.avg(Person.age)) \
.filter(Person.gender == option) \
.scalar()
if age_avg.is_integer():
age_avg = int(age_avg)
else:
age_avg = round(age_avg, 2)
print(f"Average age for the selected population({option}) is {age_avg} years.")
def sqlalch_count_grouped(attribute, amount):
"""
Counts grouped rows from db by given attribute.
:param attribute: class: sqlalchemy.orm.attributes.InstrumentedAttribute
:param amount: int
:return: result: list
"""
result = sql_session.query(attribute, func.count(attribute).label("quantity")) \
.group_by(attribute) \
.order_by(desc("quantity")) \
.limit(amount) \
.all()
return result
def most_common_cities(amount):
"""
Prints number of most common cities from db with number they appear. Used sqlalch_count_grouped().
:param amount: int
:return:
"""
popular_cities = sqlalch_count_grouped(Person.city, amount)
print(f"Lista {amount} najczęściej występujących miast:")
for city, count in popular_cities:
print(f"\tMiasto: {city} - wystąpiło {count} razy")
def most_common_pw(amount):
"""
Prints number of most common passwords from db with number they appear. Used sqlalch_count_grouped().
:param amount: int
:return:
"""
common_pw = sqlalch_count_grouped(Person.password, amount)
print(f"Lista {amount} najczęściej występujących haseł:")
for pw, count in common_pw:
print(f"\tHasło: '{pw}' - użyto {count} razy")
def str_to_datetime(date_str, date_type=None):
"""
Converts date string to datetime object.
:param date_type: str
:param date_str: str
:return: datetime object
"""
if date_type is None:
date_str += "T00:00:00.000Z"
elif date_type == "end":
date_str += "T23:59:59.999Z"
return datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
def born_between(str_start, str_end):
"""
Prints all people (firstnames, lastnames and d.o.b.) from db that were born between given dates.
Dates are given as string and converted to datetime with str_to_datetime(). Raises ValueError if start date is
bigger then end date.
:param str_start: str
:param str_end: str
:return:
"""
date_start = str_to_datetime(str_start)
date_end = str_to_datetime(str_end, date_type="end")
if date_start > date_end:
raise ValueError("Wprowadzono niepoprawne daty")
results = sql_session.query(Person) \
.filter(Person.dob >= date_start) \
.filter(Person.dob <= date_end) \
.order_by(Person.dob) \
.all()
print(f"Liczba {len(results)} osób urodzonych pomiędzy {str_start} a {str_end}:")
for person in results:
print(f"\t- {person.firstname} {person.lastname}, date of birth: {datetime.strftime(person.dob, '%Y-%m-%d')}")
def password_safety_score(password):
"""
Calculates password's safety and returns score as an int.
:param password: str
:return: score int
"""
pts = 0
str_func_list = [
{"function": str.islower, "points": 1},
{"function": str.isupper, "points": 2},
{"function": str.isdigit, "points": 1},
]
for element in str_func_list:
if sum(map(element["function"], password)) >= 1:
pts += element["points"]
if len(password) >= 8:
pts += 5
if not str.isalnum(password):
pts += 3
return pts
def safest_password():
"""
Uses password_safety_score() to print the most secure password from db and it's score.
:return:
"""
result = sql_session.query(Person.password).all()
best_result = max((password_safety_score(row.password), row.password) for row in result)
best_score = best_result[0]
best_password = best_result[1]
print(f"Najbezpieczniejsze hasło zdobyło {best_score} punktów i brzmi: '{best_password}'.")
def main():
"""
Creates parser, collects arguments and runs appropriate functions.
:return:
"""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="born_between")
dates_parser = subparsers.add_parser("born_between", help="Return all people born between given dates")
dates_parser.add_argument("-s", "--start_date", action="store", metavar="", required=True,
help="Start date in format YYYY-MM-DD for born_between")
dates_parser.add_argument("-e", "--end_date", action="store", metavar="", required=True,
help="End date in format YYYY-MM-DD for born_between")
parser.add_argument("-g", "--gender_proportion", action="store_true",
help="Returns gender proportions of the population")
parser.add_argument("-a", "--average_age", choices=["total", "male", "female"], const="total", nargs="?",
help="Returns average age of the selected population from [male, female, total]. Default total")
parser.add_argument("-c", "--common_cities", metavar="",
help="Returns number of most common cities")
parser.add_argument("-p", "--common_password", metavar="",
help="Returns number of most common password")
parser.add_argument("-s", "--safest_password", action="store_true",
help="Returns the safest password")
args = parser.parse_args()
if args.gender_proportion:
gender_proportions()
if args.average_age:
average_age(args.average_age)
if args.common_cities:
most_common_cities(args.common_cities)
if args.common_password:
most_common_pw(args.common_password)
if args.safest_password:
safest_password()
if args.born_between:
if args.start_date and args.end_date:
born_between(args.start_date, args.end_date)
if __name__ == "__main__":
sql_session = session_creator()
main()
|
0d7eae12c763142b4c1c04f5b91b5b6513f6ade5 | emilybee3/Flask-Madlibs | /madlibs.py | 3,293 | 3.65625 | 4 | from random import choice, randint#gets the choice function from random library
from flask import Flask, render_template, request
#importing the class Flask and the functions render_template and request from flask
# "__name__" is a special Python variable for the name of the current module
# Flask wants to know this to know what any imported things are relative to.
app = Flask(__name__)
#app is an instance of the class Flask
@app.route('/')
# route to handle the landing page of a website.
def start_here():
return "Hi! This is the home page."
# route to display a simple web page
@app.route('/hello')#links the function say_hello to the url extension /hello
def say_hello():
return render_template("hello.html")
#displays hello.html webpage which asks for: user name
@app.route('/greet')#links the function greet_person to the url extension /greet
def greet_person():#starts function greet_person
player = request.args.get("person")
#uses .get function to get the user input from the form in which greet is assigned to the form action(hello.html)
AWESOMENESS = [
'awesome', 'terrific', 'fantastic', 'neato', 'fantabulous', 'wowza', 'oh-so-not-meh',
'brilliant', 'ducky', 'coolio', 'incredible', 'wonderful', 'smashing', 'lovely']
#list of compliments used by comliments variable
compliment = choice(AWESOMENESS)
#randomly chooses a word from the list Awesome and assigns it to variable compliments
return render_template("compliment.html", person=player, compliment=compliment)
#displays compliment.html page passing in these arguments to the value attribute on that page
@app.route('/game')
def show_game_form():
# name = request.args.get("yesno")
value = request.args.get("yesno")
player = request.args.get("person")
if value == "no":
AWESOMENESS = [
'awesome', 'terrific', 'fantastic', 'neato', 'fantabulous', 'wowza', 'oh-so-not-meh',
'brilliant', 'ducky', 'coolio', 'incredible', 'wonderful', 'smashing', 'lovely']
compliment = choice(AWESOMENESS)
return render_template("goodbye.html", person=player, compliment=compliment)
else:
return render_template("game.html", person=player)
@app.route('/goodbye')
def goodbye():
player = request.args.get("person")
#value = request.args.get("")
AWESOMENESS = [
'awesome', 'terrific', 'fantastic', 'neato', 'fantabulous', 'wowza', 'oh-so-not-meh',
'brilliant', 'ducky', 'coolio', 'incredible', 'wonderful', 'smashing', 'lovely']
compliment = choice(AWESOMENESS)
return render_template("goodbye.html", person=player, compliment=compliment)
@app.route('/madlib')
def show_madlib():
noun_value = request.args.get("noun")
color_value = request.args.get("color")
adjective_value = request.args.get("adjective")
player = request.args.get("person")
story = randint(1,4)
return render_template("madlib.html", person=player, story=story,
noun=noun_value, color=color_value,
adjective=adjective_value)
if __name__ == '__main__':
# debug=True gives us error messages in the browser and also "reloads" our web app
# if we change the code.
app.run(debug=True)
|
a27ecb0e07e8cb284ee3226b6f63d954b1aae65f | mnxtr/Leetcode | /Arrays/Two_Sum_Sorted.py | 1,126 | 4 | 4 | # Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
# Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.
# You may assume that each input would have exactly one solution and you may not use the same element twice.
# Example 1:
# Input: numbers = [2,7,11,15], target = 9
# Output: [1,2]
# Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
# Leetcode 167: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
# Difficulty: Easy
# Solution: Modify left and right pointers based on the size of the target relative to the sum of nums[l] and nums[r]
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l, r = 0, len(numbers) - 1
while l < r:
if numbers[l] + numbers[r] == target:
return [l + 1, r + 1]
elif numbers[l] + numbers[r] > target:
r -= 1
else:
l += 1
return []
# Time Complexity: O(N)
# Space Complexity: O(1)
|
b64e1c78d84ca3679a5c82cd72adf7f90149fa70 | talianassi921/python-practice | /Questions/capitalize_first_letter.py | 165 | 3.90625 | 4 | def capitalize_first_letter(sentence):
return " ".join([x[0].upper()+x[1:] for x in sentence.split(" ")])
print(capitalize_first_letter("talia is really cool")) |
bad62e9fc395ade1c58a834ea1136b0abe778d7c | Praful-a/Python-Programming | /Lists/list_methods.py | 4,679 | 4.875 | 5 | # # You can learn more :- https://www.programiz.com/python-programming/methods/list
# append :- The append() method adds an item to the end of the list.
animals = ['cat', 'dog', 'rabbit']
animals.append('guinea pig')
print(animals)
extend: - The extend() extends the list by adding all items of a list(passed as an argument) to the end.
# language list
language = ['French', 'English', 'German']
# another list of language
language1 = ['Spanish', 'Portuguese']
language.extend(language1)
# Extended List
print('Language List: ', language)
# language list
language = ['French', 'English', 'German']
# language tuple
language_tuple = ('Spanish', 'Portuguese')
# language set
language_set = {'Chinese', 'Japanese'}
# appending element of language tuple
language.extend(language_tuple)
print('New Language List: ', language)
# appending element of language set
language.extend(language_set)
print('Newest Language List: ', language)
insert: - The insert() method inserts an element to the list at a given index.
# vowel list
vowel = ['a', 'e', 'i', 'u']
# inserting element to list at 4th position
vowel.insert(3, 'o')
print('Updated List: ', vowel)
mixed_list = [{1, 2}, [5, 6, 7]]
# number tuple
number_tuple = (3, 4)
# inserting tuple to the list
mixed_list.insert(1, number_tuple)
print('Updated List: ', mixed_list)
remove: - The remove() method removes the first matching element(which is passed as an argument) from the list.
# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']
# 'rabbit' is removed
animals.remove('rabbit')
# Updated animals List
print('Updated animals list: ', animals)
# animals list
animals = ['cat', 'dog', 'dog', 'guinea pig', 'dog']
# 'dog' is removed
animals.remove('dog')
# Updated animals list
print('Updated animals list: ', animals)
# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']
# Deleting 'fish' element
animals.remove('fish')
# Updated animals List
print('Updated animals list: ', animals)
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e'
index = vowels.index('e')
print('The index of e:', index)
# index of the first 'i'
index = vowels.index('i')
print('The index of i:', index)
# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']
# 'p' doesn't exist in the list
index = vowels.index('p')
print('The index of p:', index)
# random list
random = ['a', ('a', 'b'), [3, 4]]
# index of ('a', 'b')
index = random.index(('a', 'b'))
print("The index of ('a', 'b'):", index)
# index of [3, 4]
index = random.index([3, 4])
print("The index of [3, 4]:", index)
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# count element 'i'
count = vowels.count('i')
# print count
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
# print count
print('The count of p is:', count)
# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]
# count element ('a', 'b')
count = random.count(('a', 'b'))
# print count
print("The count of ('a', 'b') is:", count)
# count element [3, 4]
count = random.count([3, 4])
# print count
print("The count of [3, 4] is:", count)
# programming languages list
languages = ['Python', 'Java', 'C++', 'French', 'C']
# remove and return the 4th item
return_value = languages.pop(3)
print('Return Value:', return_value)
# Updated List
print('Updated List:', languages)
# programming languages list
languages = ['Python', 'Java', 'C++', 'Ruby', 'C']
# remove and return the last item
print('When index is not passed:')
print('Return Value:', languages.pop())
print('Updated List:', languages)
# remove and return the last item
print('\nWhen -1 is passed:')
print('Return Value:', languages.pop(-1))
print('Updated List:', languages)
# remove and return the third last item
print('\nWhen -3 is passed:')
print('Return Value:', languages.pop(-3))
print('Updated List:', languages)
# Operating System List
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)
# List Reverse
os.reverse()
# updated list
print('Updated List:', os)
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
old_list = [1, 2, 3]
new_list = old_list
# add element to list
new_list.append('a')
print('New List:', new_list)
print('Old List:', old_list)
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
list.clear()
print('List:', list)
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
del list[:]
print('List:', list)
|
719a526d2f8055676deceb068d545ac8667c661a | seatable/seatable-api-python | /seatable_api/column.py | 11,418 | 3.671875 | 4 | from datetime import datetime
from .constants import ColumnTypes
# Set the null list to distinguish the pure none and the number 0 or 0.00, which is
# a critical real value in number type column.
NULL_LIST = ['', [], None]
# Column Value related classes handle the compare computation of the table data
class ColumnValue(object):
"""
This is for the computation of the comparison between the input value and cell value from table
such as >, <, =, >=, <=, !=, which is supposed to fit different column types
"""
def __init__(self, column_value, column_type=None):
self.column_value = column_value
self.column_type = column_type
def equal(self, value):
if value == '':
return self.column_value in NULL_LIST
return self.column_value == value
def unequal(self, value):
if value == '':
return self.column_value not in NULL_LIST
return self.column_value != value
def greater_equal_than(self, value):
raise ValueError("%s type column does not support the query method '%s'" % (self.column_type, '>='))
def greater_than(self, value):
raise ValueError("%s type column does not support the query method '%s'" % (self.column_type, '>'))
def less_equal_than(self, value):
raise ValueError("%s type column does not support the query method '%s'" % (self.column_type, '<='))
def less_than(self, value):
raise ValueError("%s type column does not support the query method '%s'" % (self.column_type, '<'))
def like(self, value):
'''fuzzy search'''
raise ValueError("%s type column does not support the query method '%s'" % (self.column_type, 'like'))
class StringColumnValue(ColumnValue):
"""
the return data of string column value is type of string, including column type of
text, creator, single-select, url, email,....., and support the computation of
= ,!=, and like(fuzzy search)
"""
def like(self, value):
if "%" in value:
column_value = self.column_value or ""
# 1. abc% pattern, start with abc
if value[0] != '%' and value[-1] == '%':
start = value[:-1]
return column_value.startswith(start)
# 2. %abc pattern, end with abc
elif value[0] == '%' and value[-1] != '%':
end = value[1:]
return column_value.endswith(end)
# 3. %abc% pattern, contains abc
elif value[0] == '%' and value[-1] == '%':
middle = value[1:-1]
return middle in column_value
# 4. a%b pattern, start with a and end with b
else:
value_split_list = value.split('%')
start = value_split_list[0]
end = value_split_list[-1]
return column_value.startswith(start) and column_value.endswith(end)
else:
raise ValueError('There is no patterns found in "like" phrases')
class NumberDateColumnValue(ColumnValue):
"""
the returned data of number-date-column is digit number, or datetime obj, including the
type of number, ctime, date, mtime, support the computation of =, > ,< ,>=, <=, !=
"""
def greater_equal_than(self, value):
if value == "":
self.raise_error()
return self.column_value >= value if self.column_value not in NULL_LIST else False
def greater_than(self, value):
if value == "":
self.raise_error()
return self.column_value > value if self.column_value not in NULL_LIST else False
def less_equal_than(self, value):
if value == "":
self.raise_error()
return self.column_value <= value if self.column_value not in NULL_LIST else False
def less_than(self, value):
if value == "":
self.raise_error()
return self.column_value < value if self.column_value not in NULL_LIST else False
def raise_error(self):
raise ValueError("""The token ">", ">=", "<", "<=" does not support the null query string "".""")
class ListColumnValue(ColumnValue):
"""
the returned data of list-column value is a list like data structure, including the
type of multiple-select, image, collaborator and so on, support the computation of
=, != which should be decided by in or not in expression
"""
def equal(self, value):
if not value:
return self.column_value in NULL_LIST
column_value = self.column_value or []
return value in column_value
def unequal(self, value):
if not value:
return self.column_value not in NULL_LIST
column_value = self.column_value or []
return value not in column_value
class BoolColumnValue(ColumnValue):
"""
the returned data of bool-column value is should be True or False, such as check-box
type column. If the value from table shows None, treat it as False
"""
def equal(self, value):
return bool(self.column_value) == value
def unequal(self, value):
return bool(self.column_value) != value
# Column related class handle the treatment of both input value inputted by users by using
# the query statements, and the value in table displayed in different data structure in
# varies types of columns
class BaseColumn(object):
def parse_input_value(self, value):
return value
def parse_table_value(self, value):
return ColumnValue(value)
class TextColumn(BaseColumn):
def __init__(self):
self.column_type = ColumnTypes.TEXT.value
def __str__(self):
return "SeaTable Text Column"
def parse_table_value(self, value):
return StringColumnValue(value, self.column_type)
class LongTextColumn(TextColumn):
def __init__(self):
super(LongTextColumn, self).__init__()
self.column_type = ColumnTypes.LONG_TEXT.value
def __str__(self):
return "SeaTable Long Text Column"
def parse_table_value(self, value):
value = value.strip('\n')
return StringColumnValue(value, self.column_type)
class NumberColumn(BaseColumn):
def __init__(self):
self.column_type = ColumnTypes.NUMBER.value
def __str__(self):
return "SeaTable Number Column"
def parse_input_value(self, value):
if value == "":
return value
if '.' in value:
value = float(value)
else:
try:
value = int(value)
except:
self.raise_input_error(value)
return value
def parse_table_value(self, value):
return NumberDateColumnValue(value, self.column_type)
def raise_input_error(self, value):
raise ValueError("""%s type column does not support the query string as "%s",
please use "" or digital numbers
""" % (self.column_type, value))
class DateColumn(BaseColumn):
def __init__(self):
self.column_type = ColumnTypes.DATE.value
def __str__(self):
return "SeaTable Date Column"
def parse_input_value(self, time_str):
if not time_str:
return ""
try:
time_str_list = time_str.split(' ')
datetime_obj = None
if len(time_str_list) == 1:
ymd = time_str_list[0]
datetime_obj = datetime.strptime(ymd, '%Y-%m-%d')
elif len(time_str_list) == 2:
h, m, s = 0, 0, 0
ymd, hms_str = time_str_list
hms_str_list = hms_str.split(':')
if len(hms_str_list) == 1:
h = hms_str_list[0]
elif len(hms_str_list) == 2:
h, m = hms_str_list
elif len(hms_str_list) == 3:
h, m, s = hms_str_list
datetime_obj = datetime.strptime("%s %s" % (
ymd, "%s:%s:%s" % (h, m, s)), '%Y-%m-%d %H:%M:%S')
return datetime_obj
except:
return self.raise_error(time_str)
def parse_table_value(self, time_str):
return NumberDateColumnValue(self.parse_input_value(time_str), self.column_type)
def raise_error(self, value):
raise ValueError(""" %s type column does not support the query string as "%s",
the supported query string pattern like:
"YYYY-MM-DD" or
"YYYY-MM-DD hh" or
"YYYY-MM-DD hh:mm" or
"YYYY-MM-DD hh:mm:ss" or
""" % (self.column_type, value))
class CTimeColumn(DateColumn):
def __init__(self):
super(CTimeColumn, self).__init__()
self.column_type = ColumnTypes.CTIME.value
def __str__(self):
return "SeaTable CTime Column"
def get_local_time(self, time_str):
utc_time = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S.%f+00:00')
delta2utc = datetime.now() - datetime.utcnow()
local_time = utc_time + delta2utc
return local_time
def parse_table_value(self, time_str):
return NumberDateColumnValue(self.get_local_time(time_str), self.column_type)
class MTimeColumn(CTimeColumn):
def __init__(self):
super(MTimeColumn, self).__init__()
self.column_type = ColumnTypes.MTIME.value
def __str__(self):
return "SeaTable MTime Column"
def parse_table_value(self, time_str):
return NumberDateColumnValue(super(MTimeColumn, self).get_local_time(time_str), self.column_type)
class CheckBoxColumn(BaseColumn):
def __init__(self):
super(CheckBoxColumn, self).__init__()
self.column_type = ColumnTypes.CHECKBOX.value
def __str__(self):
return "SeaTable Checkbox Column"
def parse_input_value(self, value):
if not value:
return False
elif value.lower() == 'true':
return True
elif value.lower() == 'false':
return False
else:
self.raise_error(value)
def parse_table_value(self, value):
return BoolColumnValue(value, self.column_type)
def raise_error(self, value):
raise ValueError(""" %s type column does not support the query string as "%s",
the supported query string pattern like:
"true" or "false", case insensitive
""" % (self.column_type, value))
class MultiSelectColumn(BaseColumn):
def __init__(self):
super(MultiSelectColumn, self).__init__()
self.column_type = ColumnTypes.MULTIPLE_SELECT.value
def parse_table_value(self, value):
return ListColumnValue(value, self.column_type)
COLUMN_MAP = {
ColumnTypes.NUMBER.value: NumberColumn(), # 1. number type
ColumnTypes.DATE.value: DateColumn(), # 2. date type
ColumnTypes.CTIME.value: CTimeColumn(), # 3. ctime type, create time
ColumnTypes.MTIME.value: MTimeColumn(), # 4. mtime type, modify time
ColumnTypes.CHECKBOX.value: CheckBoxColumn(), # 5. checkbox type
ColumnTypes.TEXT.value: TextColumn(), # 6. text type
ColumnTypes.MULTIPLE_SELECT.value: MultiSelectColumn(), # 7. multi-select type
ColumnTypes.LONG_TEXT.value: LongTextColumn(), # 8. long-text type
}
def get_column_by_type(column_type):
return COLUMN_MAP.get(column_type, TextColumn())
|
f034abade681f231cec2b7dd1e815c5dd567e203 | Guitaristchris809/Payday-Calc | /PP1.0.py | 434 | 3.59375 | 4 | cash = float(17.50)
hours = float(raw_input("Hours worked in the past two weeks? ")) # def hours
def payment(): # calc reg pay
return hours * cash
def over():
if hours > 80:
OT = (hours - 80) * 8.75 # calc overtime hours
return OT
else:
OT = 0
return OT
def final():
return payment() + over()
print "Congrats! You've earned", final() , " dollars this pay period."
|
de2807b02f8a6f829875f26608af8300056e36f0 | simonzhang0428/Book_Think_Python | /File.py | 2,559 | 3.546875 | 4 | # infile = open('test.txt')
# with open('test.txt') as infile:
# for line in infile:
# line = line.rstrip()
# words = line.split()
# for word in words:
# word = word.rstrip(".,?!")
# print(word)
#
# using with, no need to close file
# infile.close()
# input_string = "United State: 3000"
# result = input_string.rsplit(":", 1)
# print(result)
import os
def has_no_e(word):
for char in word:
if char == 'e':
return False
return True
def avoids(word, forbidden):
for char in word:
if char in forbidden:
return False
return True
def uses_only(word, allowed):
for char in word:
if char not in allowed:
return False
return True
def uses_all(word, required):
for char in required:
if char not in word:
return False
return True
# reduction to precious solved problem
# return uses_only(required, word)
def is_abecedarian(word):
previous = word[0]
for char in word:
if char < previous:
return False
previous = char
return True
def is_abecedarian2(word):
if len(word) <= 1:
return True
if word[0] > word[1]:
return False
return is_abecedarian2(word[1:])
def is_abecedarian3(word):
i = 0
while i < len(word)-1:
if word[i] > word[i+1]:
return False
i += 1
return True
fin = open('words.txt')
cwd = os.getcwd()
abspath = os.path.abspath('File.py')
print(cwd)
print(abspath)
print(os.listdir(cwd))
# for line in fin:
# word = line.strip()
# if len(word) > 20:
# print(word)
# count, total = 0, 0
# for line in fin:
# word = line.strip()
# total += 1
# if has_no_e(word):
# print(word)
# count += 1
#
# print('without \'e\' percentage:', round(count / total, 3))
# count = 0
# forbidden = input('Enter forbidden letters: ')
# for line in fin:
# word = line.strip()
# if avoids(word, forbidden):
# print(word)
# count += 1
#
# print('without {} count is {}'.format(forbidden, count))
# count = 0
# allowed = input('Enter allowed letters: ')
# for line in fin:
# word = line.strip()
# if uses_only(word, allowed):
# print(word)
# count += 1
#
# print('only use {} count is {}'.format(allowed, count))
count = 0
for line in fin:
word = line.strip()
if is_abecedarian(word):
# print(word)
count += 1
print('abecedarian word count is', count)
fin.close()
|
edaa0a584a79471d7c5a0c5057f188fd0b0f7bfd | lucianofalmeida/Desafios_Python | /desafio050.py | 167 | 4.0625 | 4 | pessoas = ['rodrigo','rafael','guilherme','pedro','greyce','check','dark']
print(pessoas[-3:])
#o resultado são os 3 ultimos elementos da lista de forma negativa
|
67421d01436e1320ddb5c2e16c5f6c09a6bda7fb | jeremysherriff/HTPC-Manager | /libs/sqlobject/util/csvexport.py | 6,758 | 3.5625 | 4 | """
Exports a SQLObject class (possibly annotated) to a CSV file.
"""
import os
import csv
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import sqlobject
__all__ = ['export_csv', 'export_csv_zip']
def export_csv(soClass, select=None, writer=None, connection=None,
orderBy=None):
"""
Export the SQLObject class ``soClass`` to a CSV file.
``soClass`` can also be a SelectResult object, as returned by
``.select()``. If it is a class, all objects will be retrieved,
ordered by ``orderBy`` if given, or the ``.csvOrderBy`` attribute
if present (but csvOrderBy will only be applied when no select
result is given).
You can also pass in select results (or simply a list of
instances) in ``select`` -- if you have a list of objects (not a
SelectResult instance, as produced by ``.select()``) then you must
pass it in with ``select`` and pass the class in as the first
argument.
``writer`` is a ``csv.writer()`` object, or a file-like object.
If not given, the string of the file will be returned.
Uses ``connection`` as the data source, if given, otherwise the
default connection.
Columns can be annotated with ``.csvTitle`` attributes, which will
form the attributes of the columns, or 'title' (secondarily), or
if nothing then the column attribute name.
If a column has a ``.noCSV`` attribute which is true, then the
column will be suppressed.
Additionally a class can have an ``.extraCSVColumns`` attribute,
which should be a list of strings/tuples. If a tuple, it should
be like ``(attribute, title)``, otherwise it is the attribute,
which will also be the title. These will be appended to the end
of the CSV file; the attribute will be retrieved from instances.
Also a ``.csvColumnOrder`` attribute can be on the class, which is
the string names of attributes in the order they should be
presented.
"""
return_fileobj = None
if not writer:
return_fileobj = StringIO()
writer = csv.writer(return_fileobj)
elif not hasattr(writer, 'writerow'):
writer = csv.writer(writer)
if isinstance(soClass, sqlobject.SQLObject.SelectResultsClass):
assert select is None, (
"You cannot pass in a select argument (%r) and a SelectResult argument (%r) for soClass"
% (select, soClass))
select = soClass
soClass = select.sourceClass
elif select is None:
select = soClass.select()
if getattr(soClass, 'csvOrderBy', None):
select = select.orderBy(soClass.csvOrderBy)
if orderBy:
select = select.orderBy(orderBy)
if connection:
select = select.connection(connection)
_actually_export_csv(soClass, select, writer)
if return_fileobj:
# They didn't pass any writer or file object in, so we return
# the string result:
return return_fileobj.getvalue()
def _actually_export_csv(soClass, select, writer):
attributes, titles = _find_columns(soClass)
writer.writerow(titles)
for soInstance in select:
row = [getattr(soInstance, attr)
for attr in attributes]
writer.writerow(row)
def _find_columns(soClass):
order = []
attrs = {}
for col in soClass.sqlmeta.columnList:
if getattr(col, 'noCSV', False):
continue
order.append(col.name)
title = col.name
if hasattr(col, 'csvTitle'):
title = col.csvTitle
elif getattr(col, 'title', None) is not None:
title = col.title
attrs[col.name] = title
for attrDesc in getattr(soClass, 'extraCSVColumns', []):
if isinstance(attrDesc, (list, tuple)):
attr, title = attrDesc
else:
attr = title = attrDesc
order.append(attr)
attrs[attr] = title
if hasattr(soClass, 'csvColumnOrder'):
oldOrder = order
order = soClass.csvColumnOrder
for attr in order:
if attr not in oldOrder:
raise KeyError(
"Attribute %r in csvColumnOrder (on class %r) does not exist as a column or in .extraCSVColumns (I have: %r)"
% (attr, soClass, oldOrder))
oldOrder.remove(attr)
order.extend(oldOrder)
titles = [attrs[attr] for attr in order]
return order, titles
def export_csv_zip(soClasses, file=None, zip=None, filename_prefix='',
connection=None):
"""
Export several SQLObject classes into a .zip file. Each
item in the ``soClasses`` list may be a SQLObject class,
select result, or ``(soClass, select)`` tuple.
Each file in the zip will be named after the class name (with
``.csv`` appended), or using the filename in the ``.csvFilename``
attribute.
If ``file`` is given, the zip will be written to that. ``file``
may be a string (a filename) or a file-like object. If not given,
a string will be returnd.
If ``zip`` is given, then the files will be written to that zip
file.
All filenames will be prefixed with ``filename_prefix`` (which may
be a directory name, for instance).
"""
import zipfile
close_file_when_finished = False
close_zip_when_finished = True
return_when_finished = False
if file:
if isinstance(file, basestring):
close_when_finished = True
file = open(file, 'wb')
elif zip:
close_zip_when_finished = False
else:
return_when_finished = True
file = StringIO()
if not zip:
zip = zipfile.ZipFile(file, mode='w')
try:
_actually_export_classes(soClasses, zip, filename_prefix,
connection)
finally:
if close_zip_when_finished:
zip.close()
if close_file_when_finished:
file.close()
if return_when_finished:
return file.getvalue()
def _actually_export_classes(soClasses, zip, filename_prefix,
connection):
for classDesc in soClasses:
if isinstance(classDesc, (tuple, list)):
soClass, select = classDesc
elif isinstance(classDesc, sqlobject.SQLObject.SelectResultsClass):
select = classDesc
soClass = select.sourceClass
else:
soClass = classDesc
select = None
filename = getattr(soClass, 'csvFilename', soClass.__name__)
if not os.path.splitext(filename)[1]:
filename += '.csv'
filename = filename_prefix + filename
zip.writestr(filename,
export_csv(soClass, select, connection=connection))
|
97e2b9ec37e22b245ad3a8698b537f3f92a25b01 | samhuynhle/insertion_sort_python | /insertionsort.py | 417 | 3.921875 | 4 | testlist1 = [8,9,10,2,3,6,4,5,1,7]
def insertion_sort(some_list):
count = 0
for x in range(1, len(some_list), 1):
for j in range(x, 0, -1):
if some_list[x-j] > some_list[x]:
count += 1
some_list[x], some_list[x-j] = some_list[x-j], some_list[x]
print(count)
print(some_list)
insertion_sort(testlist1)
# this is Sam's insertion sort code: 08/05/2019 |
a9e0695375429d465a19cc6ea233269159424818 | vipmunot/Data-Analysis-using-Python | /Python Programming Beginner/Customizing Functions and Debugging Errors-61.py | 3,286 | 3.890625 | 4 | ## 3. Optional Arguments ##
# Default code
def tokenize(text_string, special_characters, clean=False):
if clean == True:
cleaned_story = clean_text(text_string, special_characters)
story_tokens = cleaned_story.split(" ")
else:
story_tokens = text_string.split(" ")
return(story_tokens)
clean_chars = [",", ".", "'", ";", "\n"]
tokenized_story = []
tokenized_vocabulary = []
misspelled_words = []
tokenized_story = tokenize(story_string, clean_chars, clean=True)
tokenized_vocabulary = tokenize(vocabulary, clean_chars, clean=False)
for item in tokenized_story:
if item not in tokenized_vocabulary:
misspelled_words.append(item)
## 5. Practice: Creating a More Compact Spell Checker ##
def clean_text(text_string, special_characters):
cleaned_string = text_string
for string in special_characters:
cleaned_string = cleaned_string.replace(string, "")
cleaned_string = cleaned_string.lower()
return(cleaned_string)
def tokenize(text_string, special_characters, clean=False):
cleaned_text = text_string
if clean:
cleaned_text = clean_text(text_string, special_characters)
tokens = cleaned_text.split(" ")
return(tokens)
def spell_check(vocabulary_file,text_file,special_characters=[",",".","'",";","\n"]):
misspelled_words = []
voca = open(vocabulary_file).read()
txt = open(text_file).read()
tokenized_vocabulary = tokenize(voca,special_characters,clean=False)
tokenized_text = tokenize(txt,special_characters,clean=True)
for item in tokenized_text:
if item not in tokenized_vocabulary and item != '':
misspelled_words.append(item)
return(misspelled_words)
final_misspelled_words = []
final_misspelled_words = spell_check('dictionary.txt','story.txt')
print(final_misspelled_words)
## 7. Syntax Errors ##
def spell_check(vocabulary_file, text_file, special_characters=[",",".","'",";","\n"]):
misspelled_words = []
vocabulary = open(vocabulary_file).read()
text = open(text_file.read()
tokenized_vocabulary = tokenize(vocabulary, special_characters= special_characters,clean = False)
tokenized_text = tokenize(text, special_characters, True)
for ts in tokenized_text:
if ts not in tokenized_vocabulary and ts != '':
misspelled_words.append(ts)
return(misspelled_words)
final_misspelled_words = spell_check(vocabulary_file="dictionary.txt", text_file="story.txt")
print(final_misspelled_words)
## 9. TypeError and ValueError ##
forty_two = 42
forty_two + float("42")
str("guardians")
## 11. Traceback ##
def spell_check(vocabulary_file, text_file, special_characters=[",",".","'",";","\n"]):
misspelled_words = []
vocabulary = open(vocabulary_file).read()
# Add ending parentheses.
text = open(text_file).read()
# Fix indentation.
tokenized_vocabulary = tokenize(vocabulary, special_characters)
tokenized_text = tokenize(text, special_characters, True)
for ts in tokenized_text:
if ts not in tokenized_vocabulary and ts != '':
misspelled_words.append(ts)
return(misspelled_words)
final_misspelled_words = spell_check(vocabulary_file="dictionary.txt", text_file="story.txt")
print(final_misspelled_words) |
a72ddb7ef6141a6bc96295149a0fed0dc241b4e8 | jasmine95dn/flask_best_worst_scaling | /tests/unit/test_models.py | 3,625 | 3.5625 | 4 | '''
Unit Tests for models.py
'''
def test_new_user(new_user):
"""
GIVEN a User model
WHEN a new User is created
THEN check
1. if username, email, password are defined correctly
2. if password is stored as hashed password, not plaintext
3. if get_id() returns a string in form 'user:<user_id>'
"""
### 1.
assert new_user.username == 'jung'
assert new_user.email == 'abc@abc.de'
assert new_user.password != '12345678'
### 2.
assert new_user.check_password('12345678')
assert not new_user.check_password('12345679')
### 3.
assert new_user.get_id() == "user:12"
def test_new_annotator(new_annotator):
"""
GIVEN an Annotator model
WHEN a new Annotator is created
THEN check
1. if keyword is stored correctly
2. if get_id() returns a string in form 'annotator:<annotator_id>'
"""
### 1.
assert new_annotator.keyword == 'ax7832ljf'
### 2.
assert new_annotator.get_id() == "annotator:3"
def test_new_project(new_user, new_project, new_batch, new_tuple, new_item, new_annotator, new_data):
"""
GIVEN an existing User
WHEN this User uploads a new Project and choose option 1 with local system
THEN check
1. if all field are stored correctly
2. if all relationships are defined correctly
"""
### 1.
## table Project
assert new_project.name == 'test'
assert new_project.description == 'this is a test'
assert new_project.anno_number == 5
assert new_project.best_def == 'best'
assert new_project.worst_def == 'worst'
assert new_project.n_items == 10
assert new_project.p_name == 'test'
assert not new_project.mturk
## table Batch
assert new_batch.size == 1
## table Tuple - no extra information, so no test
## table Item
assert new_item.item == 'A'
## table Data
assert new_data.best_id == 1
assert new_data.worst_id == 2
### 2.
## new_user-new_project has one-to-many relationship
new_project.user = new_user
assert new_project in new_user.projects
## new_project-new_batch has one-to-many relationship
new_batch.project = new_project
assert new_batch in new_project.batches
## new_tuple-new_items has many-to-many relationship
new_tuple.items.append(new_item)
assert new_item in new_tuple.items
assert new_tuple in new_item.tuples
## new_project-new_annotator has one-to-many relationship
new_annotator.project = new_project
assert new_annotator in new_project.annotators
## new_annotator-new_data has one-to-many relationship
new_data.annotator = new_annotator
assert new_data in new_annotator.datas
## new_tuple-new_data has one-to-many relationship
new_data.tuple_ = new_tuple
assert new_data in new_tuple.datas
## new_annotator-new_batch has many-to-many relationship
new_annotator.batches.append(new_batch)
assert new_batch in new_annotator.batches
assert new_annotator in new_batch.annotators
def test_new_project_mturk(new_project_mturk, new_batch_mturk):
"""
GIVEN an existing User
WHEN this User uploads a new Project and choose option 2 with Mechanical Turk
THEN check
1. if all field are stored correctly
2. this works the same like test_new_project() -> no extra test
"""
### 1.
## table Project
assert new_project_mturk.name == 'test'
assert new_project_mturk.description == 'this is a test'
assert new_project_mturk.anno_number == 5
assert new_project_mturk.best_def == 'best'
assert new_project_mturk.worst_def == 'worst'
assert new_project_mturk.n_items == 10
assert new_project_mturk.p_name == 'test'
assert new_project_mturk.mturk
## table Batch
assert new_batch_mturk.size == 1
assert new_batch_mturk.keyword == 'ax7832ljf'
assert new_batch_mturk.hit_id == 'AID12897679'
|
218484d4b63e6887c56234d3e188e841cc5ffe61 | atharva07/python-files | /problem2.py | 590 | 4.03125 | 4 | # initializng list
test_list = [3,5,6,2,34,43,54]
print("checking if 5 is present or not (using loop) : ")
# checking if 5 exist or not
for i in test_list:
if(i == 5):
print("element exist")
if (5 in test_list):
print('yes')
else:
print('no')
from bisect import bisect_left
test_set_list = [1,3,6,5,3,4]
test_set_bisect = [1,3,6,5,3,4]
print('checking if 4 is present or not (using set)')
test_set_list = set(test_set_list)
if 4 in test_set_list:
print('yes')
# checking using sort
test_set_bisect.sort()
if bisect_left(test_set_bisect, 4):
print('yes')
|
f27c240d7154135c24249bbc49926e6f121e087f | narin-anongchai/RescueMaze | /docs/tutorials/Vision/step3_letter_detection.py | 4,430 | 3.640625 | 4 | """
Example OpenCV letter detection
Written by Fatemeh Pahlevan Aghababa, Amirreza Kabiri, MohammadHossein Goharinejad - 2020
"""
# if you haven't install opencv yet, please type "pip install opencv-python" in your terminal/command line.
import cv2
import numpy
import matplotlib.pyplot as plt
def find_victim_big(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Here, the matter is straight forward. If pixel value is greater than a threshold value,
# it is assigned one value (may be white), else it is assigned another value (may be black).
#The function used is cv2.threshold. First argument is the source image, which should be a grayscale image.
# Second argument is the threshold value which is used to classify the pixel values.
# Third argument is the maxVal which represents the value to be given if pixel value is more than
# (sometimes less than) the threshold value. OpenCV provides different styles of thresholding and
# it is decided by the fourth parameter of the function. Different types are:
# cv2.THRESH_BINARY
# cv2.THRESH_BINARY_INV
# cv2.THRESH_TRUNC
# cv2.THRESH_TOZERO
# cv2.THRESH_TOZERO_INV
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
# Contours can be explained simply as a curve joining all the continuous points (along the boundary),
# having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition.
contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
#bound the images
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
i=0
victims=[]
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
#following if statement is to ignore the noises and save the images which are of normal size(character)
#In order to write more general code, than specifying the dimensions as 100,
# number of characters should be divided by word dimension
if w>100 and w<130 and h>100 and h<130:
#save individual images
victims.append((x,y,h,w))
i=i+1
return victims
def find_victim(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Here, the matter is straight forward. If pixel value is greater than a threshold value,
# it is assigned one value (may be white), else it is assigned another value (may be black).
#The function used is cv2.threshold. First argument is the source image, which should be a grayscale image.
# Second argument is the threshold value which is used to classify the pixel values.
# Third argument is the maxVal which represents the value to be given if pixel value is more than
# (sometimes less than) the threshold value. OpenCV provides different styles of thresholding and
# it is decided by the fourth parameter of the function. Different types are:
# cv2.THRESH_BINARY
# cv2.THRESH_BINARY_INV
# cv2.THRESH_TRUNC
# cv2.THRESH_TOZERO
# cv2.THRESH_TOZERO_INV
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
# Contours can be explained simply as a curve joining all the continuous points (along the boundary),
# having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition.
contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
#bound the images
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
i=0
victims=[]
img_h,img_w = img.shape
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
#following if statement is to ignore the noises and save the images which are of normal size(character)
#In order to write more general code, than specifying the dimensions as 100,
# number of characters should be divided by word dimension
if (img_w - w)<20 or (img_h - h)<20:
continue
if w<20 or h<20:
continue
#save individual images
victims.append((x,y,h,w))
print((x,y,h,w))
i=i+1
print(len(victims))
return victims
img = cv2.imread('img/vision.png') # Read image file
print("Vision image size: ", img.shape) #(860, 1321, 3)
victims = find_victim_big(img)
if len(victims)> 0:
x,y,h,w = victims[0]
img = cv2.rectangle(img, (x,y), (x+w,y+h), color=(255, 0, 0), thickness=4)
else:
print("No victim found!")
plt.subplot(111), plt.imshow(img, cmap='gray'), plt.title('Victim') # Plot the Image
plt.show() # Show the plotter window (You should see the image in a new window now)
|
839d9a1cb0947df9a423ccdf4872bf35cc7d5e54 | skreynolds/RoboND_Code | /06_deepLearning/01_introNN/15_simpleNN/simple.py | 368 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 06:55:23 2017
@author: Shane Reynolds
"""
import numpy as np
def sigmoid(x):
# TODO: Implement sigmoid function
return 1/(1+np.exp(-x))
inputs = np.array([0.7, -0.3])
weights = np.array([0.1, 0.8])
bias = -0.1
# TODO: Calculate the output
output = sigmoid(sum(inputs*weights)+bias)
print('Output:')
print(output) |
fa6b2a341e522d5e252a60ad4493b4d7fbd6e8f0 | harishdasari1595/Personal_projects | /Algorithms and Datastructure/linked_list/swap_kth_node_from_end.py | 2,550 | 4.15625 | 4 | import sys
#Class for creating a node of a linked list
class node:
def __init__(self, info):
self.info = info
self.next = None
class LinkedList:
def __init__(self):
#At start the head is pointing to None
self.head = None
def display(self):
print ("#"*50)
temp = self.head
#print (msg)
while (temp):
print(temp.info)
temp = temp.next
#Method for inserting new node at the beginning
def insert_at_beginning(self, data):
#Creating the new node temp
self.temp = node(data)
#Check for a empty linked list
if self.head is None:
self.head = self.temp
return
#Pointing the next of the new node to the head node
self.temp.next = self.head
#Pointing the head to the new inserted node
self.head = self.temp
def swap_kth_node_fromend(self, n, k):
#Creating a dummy node for handling the boundary case
dummynode = node(0)
dummynode.next = self.head
#Creating the required pointer and pointing to dummy node
first_pointer = self.head
second_pointer = self.head
temp_pointer = self.head
if ((1 <= n <= 10^5) and (1 <= k < n)):
if self.head is None:
return "String is empty"
for i in range (k):
first_pointer = first_pointer.next
while first_pointer is not None:
first_pointer = first_pointer.next
second_pointer = second_pointer.next
temp_pointer = temp_pointer.next
# print ("first pointer value is {} ".format(first_pointer))
# print ("second pointer value is {} ".format(second_pointer.info))
# print ("Temp pointer value is {} ".format(temp_pointer.info))
# print ("*"*50)
temp = second_pointer.info
knext_value = second_pointer.next.info
second_pointer.info = knext_value
second_pointer.next.info = temp
return dummynode.next
if __name__ == '__main__':
llist = LinkedList()
n = int(input("How many nodes do you want in the linked list: "))
for i in range(n):
llist.insert_at_beginning(int(input("Please enter the {} element ".format(i))))
llist.display()
llist.swap_kth_node_fromend(n, 3)
llist.display()
|
ce4de4da06874ce0bf862bb7c30a49d7e9a40f2b | reckful88/learning-python | /lianxi_alist.py | 669 | 3.953125 | 4 | #-*- coding:utf-8 -*-
#####求一个列表中最大的元素######
#def alist(n):
# a = n[0]
# for x in n:
# if x > a:
# a = x
# return a
def maxmin(n):
maxs = n[0]
mins = n[0]
for x in n:
if maxs < x:
maxs = x
if maxs > x:
mins = x
maxmin([1,2,3,4,5,6])
print max, mins
'''
In [26]: numbers = [4,3,6,1,7]
In [27]: maxs = numbers[0]
In [28]: mins = numbers[0]
In [29]: for x in numbers:
....: if maxs > x:
....: maxs = x
....: if mins < x:
....: mins = x ....:
In [30]: print maxs,mins
1 7
'''
|
aed4bc972a196867dc7b695a14be9a862a3c6fb3 | ravalrupalj/BrainTeasers | /Edabit/The_Frugal_Gen.py | 1,281 | 4.09375 | 4 | #The Frugal Gentleman
#Atticus has been invited to a dinner party, and he decides to purchase a bottle of wine. However, he has little knowledge of how to choose a good bottle. Being a very frugal gentleman (yet disliking looking like a cheapskate), he decides to use a very simple rule. In any selection of two or more wines, he will always buy the second-cheapest.
#Given a list of wine dictionaries, write a function that returns the name of the wine he will buy for the party. If given an empty list, return None. If given a list of only one, Atticus will buy that wine.
def chosen_wine(wines):
l=[]
for i in wines:
l.append(i['price']) # #get value of price in first dict of wines
posi=sorted(l)
for i in wines:
if len(posi) > 1:
if i['price']==posi[1]:
return i['name']
elif len(posi)==1:
return i['name']
else:
return None
print(chosen_wine([
{ "name": "Wine A", "price": 8.99 },
{ "name": "Wine 32", "price": 13.99 },
{ "name": "Wine 9", "price": 10.99 }]))
#➞ "Wine 9"
print(chosen_wine([{ "name": "Wine A", "price": 8.99 }]))
#➞ "Wine A"
print(chosen_wine([]))
#➞ None
#Notes
#All wines will be different prices, so there is no confusion in the ordering. |
096fd2e2f6e463f1b707a3ba007079ab829033a3 | rengoo/hello-world | /helloworld.py | 564 | 3.65625 | 4 | # This Program says hello
import random # Importiert Modul; Alternative ist from, womit man sich das Prefix spart
print('Hello')
myName = input("Eingabe?")
def caseselect(answer):
if answer == 1:
return 'lol'
elif answer == 2:
return 'jolo'
def myfunctionawesomefunction():
print("You have called me")
for i in range(5):
print("Stinrg und Zahl" + str(i))
i = 0
while i < 15:
# print("Noch mehr Zahlen" + str(i))
i = i + 1
print("Zufallszahl " + str(random.randint(1,10)))
myfunctionawesomefunction()
caseselect(1)
|
e4bedd235221c712ccfa3d1ebfd1c960061d9b1b | felipe-basina/python | /codigos/verifica_total_caracteres.py | 393 | 3.5625 | 4 | # Verifica o total de caracteres diferentes
# para que seja possivel criar um anagrama, a partir de duas metades,
# de uma determinada palavra
from collections import Counter
s = "hhpddlnnsjfoyxpciioigvjqzfbpllssuj"
if len(s)%2 == 1:
print "-1"
print Counter(s[0:len(s)/2])
print Counter(s[len(s)/2:])
temp = Counter(s[0:len(s)/2]) - Counter(s[len(s)/2:])
print temp
print sum(temp.values())
|
2ab52b08d731acc1df2368c72dd69262595ece52 | Totoro2205/python-rush-tasks | /level-1/task-1/task-1-15-1.py | 170 | 3.828125 | 4 | #!/usr/bin/env python3
#coding: utf-8
"""
pythonic way
"""
a = 1
b = 2
print('a = {}, b = {}'.format(a, b))
tmp = a
a = b
b = tmp
print('a = {}, b = {}'.format(a, b))
|
aff367252204147b02afc4ee0bd3b19574ded47d | rafaelperazzo/programacao-web | /moodledata/vpl_data/482/usersdata/348/110214/submittedfiles/Av2_Parte4.py | 365 | 3.953125 | 4 | # -*- coding: utf-8 -*-
m = int(input('informe as linhas: '))
n = int(input('informe as colunas: '))
matriz = []
for i in range (m):
linhas = []
for j in range (n):
linhas.append(int(input('informe os elementos: ')))
matriz.append(linhas)
print(matriz)
for i in range (m-1,-1,-1):
for j in range (n-1,-1,-1):
matriz[i][j]
|
9c719e27b4949ef3233c228045820d0f206904e0 | SoniaSanchezSoto/Python-practice | /numeroMaximo.py | 216 | 3.921875 | 4 | def num_max (a, b, c):
if a > b and a > c:
print (a)
elif b > a and b > c:
print (b)
elif c > a and c > b:
print (c)
else:
print ("Son Iguales")
num_max(1,2,3) |
51580829d3cb4e41be32d27413f5b3d3678b6be6 | agnaka/CEV-Python-Exercicios | /Pacote-download/Exercicios/ex086.py | 759 | 3.75 | 4 | matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0,3):
for c in range(0, 3):
matriz[l][c] = int(input(f'Digite um valor para [{l}, {c}]'))
print('-=' * 30)
for l in range(0,3):
for c in range(0,3):
print(f'[{matriz[l][c]:^5}]', end = '')
print()
print()
print('FIM')
'''lista = [[], [], [], [], [], [], [], [], []]
for n in range(0,3):
lista[n].append(int(input(f'Digite um valor para [0, {n}]: ')))
for n in range(3,6):
lista[n].append(int(input(f'Digite um valor para [1, {n-3}]: ')))
for n in range(6,9):
lista[n].append(int(input(f'Digite um valor para [2, {n-6}]: ')))
print('-=' * 30)
print(f'{lista[0]}{lista[1]}{lista[2]}\n{lista[3]}{lista[4]}{lista[5]}\n'
f'{lista[6]}{lista[7]}{lista[8]}')'''
|
8a54287b6778d50690e5004f1e9e4c6afb74068c | vektorelpython/Python17Temel | /Ornek2.py | 738 | 3.578125 | 4 | # a = 1
# b = 1
# bolum = 0
# for i in range(0,100):
# c = a+b
# print(c)
# b,a = c,b
# if bolum == a/b:
# print(i)
# break
# else:
# bolum = a/b
metin = "Aç raporunu koy okunur o parça"
# metin = metin.replace(" ","").lower()
# print(metin)
# print(len(metin)//2)
# print(metin[:len(metin)//2])
# print(metin[(len(metin)//2)+1:][::-1])
# if metin[:len(metin)//2] == metin[(len(metin)//2)+1:][::-1]:
# print("Doğru")
def palindrom(metin):
return metin.replace(" ","").lower()[:len(metin.replace(" ","").lower())//2] == \
metin.replace(" ","").lower()[(len(metin.replace(" ","").lower())//2)+1:][::-1]
if palindrom(input("Cümleyi yazınız")):
print("Cümle palindrom")
|
4086b49cf8e65c224e7f16e74cfc4c3144b719e2 | Orcha02/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 255 | 3.90625 | 4 | #!/usr/bin/python3
for num1 in range(10):
for num2 in range(10):
if num1 == 8 and num2 == 9:
print("{0:d}{1:d}\n".format(num1, num2), end="")
elif (num1 < num2):
print("{0:d}{1:d}".format(num1, num2), end=", ")
|
122579eccc6ccea8dd34ecb29b3309f825ddba8d | yinhuax/leet_code | /datastructure/my_sorted/Select_sort.py | 585 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Mike
# @Contact : 597290963@qq.com
# @Time : 2021/2/9 12:03
# @File : Select_sort.py
class Select_sort(object):
def select_sort(self, alist):
n = len(alist)
for i in range(n - 1):
min_index = i
for j in range(i + 1, n):
if alist[j] < alist[min_index]:
min_index = j
alist[min_index], alist[i] = alist[i], alist[min_index]
return alist
if __name__ == '__main__':
print(Select_sort().select_sort([1, 2, 6, 5, 7, 0, 9]))
|
7ade61b9c4203df975feb291bd3fd28bbd296f5b | wk8/noble-words | /knight_solver.py | 1,536 | 3.703125 | 4 | class KnightSolver(object):
def __init__(self, grid, dictionary_root):
self._grid = grid
self._root = dictionary_root
def find_longest_words(self):
'''
Returns a list of the longest words from the dictionary found
in the grid; i.e. all words in the returned list have the same
length.
'''
current_words = []
current_lengths = 0
for i in range(self._grid.height):
for j in range(self._grid.width):
current_words, current_lengths = self._find_longest_words_rec(
i, j, self._root, '', current_words, current_lengths)
return current_words
# returns the list of the longest words starting from i, j
def _find_longest_words_rec(self, i, j, node, word, words, lengths):
letter = self._grid.get(i, j)
new_node = node.get(letter)
if new_node is None:
return words, lengths
new_word = word + letter
if new_node.is_word and len(new_word) >= lengths:
if len(new_word) == lengths:
words.append(new_word)
else:
words = [new_word]
lengths = len(new_word)
for new_i, new_j in self._grid.knight_moves(i, j):
words, lengths = self._find_longest_words_rec(new_i, new_j,
new_node, new_word,
words, lengths)
return words, lengths
|
7d2a45f0a81adeaecd6e894068e7cd1930a86e7c | GouravSardana/sorting_algos | /selection_sort.py | 624 | 4 | 4 | def selection_sort(lst):
n = len(lst)
for i in range(n): # to loop throught through all the elments within the list
smallest_index = i # let the index for smallest element be initially i
for j in range(i+1, n): # loop from i + 1 to n
if(lst[j] < lst[smallest_index]): # if any element is less than lst[smallest_index]
smallest_index = j # then smallest index becomes the new index
# swapping the elements (swapping 2 nos operation)
temp = lst[smallest_index]
lst[smallest_index] = lst[i]
lst[i] = temp
return lst # return sorted list
l=list(map(int, input().split())
print(selection_sort(l))
|
ae1c4128b0b1b60bad1174cfe0357a762fd05c96 | GabrieLima-dev/Coursera | /bhaskara.py | 563 | 3.828125 | 4 | import math
a = float(input("Digite o valor de a: "))
b = float(input("Digite o valor de b: "))
c = float(input("Digite o valor de c: "))
delta = b ** 2 - 4 * a * c
if delta == 0:
raiz_1 = (-b + math.sqrt(delta))/(2 * a)
print("a raiz desta equação é", raiz_1)
else:
if delta < 0:
print("esta equação não possui raízes reais")
else:
raiz_1 = (-b + math.sqrt(delta))/(2 * a)
raiz_2 = (-b - math.sqrt(delta))/(2 * a)
a = (raiz_1, raiz_2)
print("as raízes da equação são", min(a), "e", max(a))
|
c794653e7610a9f0ad3aaaf3523a7dabef36973b | Javier-cyber-Wx/Farenheit-a-celcius | /algoritmo 1/primer programa.py | 249 | 3.9375 | 4 | def fahrenheit_a_celsius(f):
return (f - 32) / 1.8
f = float(input("Ingresa los grados Fahrenheit: "))
c = fahrenheit_a_celsius(f)
print(f"Los {f} grados Fahrenheit son {c} grados celsius")
input("Presione una tecla para finalizar....")
|
3458b4dccb86827584d2aab063135ca98909ebe3 | CharlieX1701/NatureConnect | /readQuotes.py | 627 | 3.859375 | 4 | ''''
The purpose of this program is to read in a file containing inspirational
quotes, clean the data, and then randomly select a quote from this file
and print it for the user.
'''
import random
#read in quotes data, clean it, write out to file
def readQuotes():
filename = 'quotes.csv'
infile = open(filename, 'r')
data = infile.read()
infile.close()
data = data.replace(',', ': ')
data = data.replace('"', '')
data = data.split(',')
outFile = 'allQuotes.txt'
outVar = open(outFile, 'w')
for i in data:
outVar.write(str(i))
outVar.close()
readQuotes()
|
78cbc3b097352947ed9c537c5b3959899fa55a0e | jennyChing/onlineJudge | /11408.py | 1,722 | 3.875 | 4 | '''
Primes
11408 - Count DePrimes
Input
Each line contains a and b in the format ‘a b’. 2 ≤ a ≤ 5000000. a ≤ b ≤ 5000000. Input is terminated by a line containing ‘0’.
Output
Each line should contain the number of DePrimes for the corresponding test case. Explanation: In Test Case 2, take 10. Its Prime Factors are 2 and 5. Sum of Prime Factors is 7, which is a prime. So, 10 is a DePrime.
1. a < i < b; 2. i = prime * prime; 3. prime + prime = prime
'''
import math
# only go through prime numbers smaller then n^1/2:
# go through prime numbers under 1000000^1/2 to bulid a list, and cross out multiples of prime numbers one by one. Those not crossed out are prime numbers
# primes within (1000000^1/2)
def prime():
isPrime = [True for _ in range(5000000)] # 2 * i + 1= n
isPrime[0], isPrime[1] = False, False
buff = set()
for i in range(len(isPrime)):
if isPrime[i]:
buff.add(i)
for j in range(i * i, len(isPrime), i):
isPrime[j] = False
return buff
if __name__ == '__main__':
primes = prime()
sortedPrimes = sorted(primes)
while True:
try:
n = input()
if n == '0':
break
a, b = list(map(int, n.split()))
dePrimes = []
for i in range(a, b + 1):
factors = []
for p1 in sortedPrimes:
if p1 < b + 1:
p2 = i / p1
if p2 % 1 == 0:
factors.append(p1)
if sum(factors)in primes:
dePrimes.append(i)
print(len(dePrimes))
except(EOFError):
break
|
6dcc80c5091f79e68902b1b2d01fd88de26c599b | hyc121110/LeetCodeProblems | /Others/gardenNoAdj.py | 1,240 | 4.25 | 4 | '''
You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.
paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
Also, there is no garden that has more than 3 paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.
'''
# Greedily paint nodes one by one.
# Because there is no node that has more than 3 neighbors,
# always one possible color to choose.
def gardenNoAdj(N, paths):
res = [0] * N
G = [[] for i in range(N)]
for x, y in paths:
G[x - 1].append(y - 1)
G[y - 1].append(x - 1)
for i in range(N):
temp = {1, 2, 3, 4} - {res[j] for j in G[i]}
res[i] = temp.pop()
return res
print(gardenNoAdj(N=4, paths=[[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]))
print(gardenNoAdj(N=4, paths=[[1,2],[3,4]]))
print(gardenNoAdj(N=4, paths=[[1,2],[2,3],[3,1]]))
print(gardenNoAdj(N=5, paths=[[1,2],[2,3],[3,4],[4,5],[1,5]]))
|
166c9b0763f36d5631f1acd1140f22d61210ac6c | patmorin/lhp | /lhp_demo.py | 6,220 | 3.515625 | 4 | #!/usr/bin/python3
import sys
import time
import random
import itertools
import matplotlib.pyplot as plt
import scipy.spatial
import lhp
def triangulate(points):
n = len(points)
dt = scipy.spatial.Delaunay(points)
assert(dt.npoints == n)
assert(len(dt.convex_hull) == 3)
assert(dt.nsimplex == 2*n - 5)
succ = [dict() for _ in range(n)]
for t in dt.simplices:
for i in range(3):
succ[t[i]][t[(i+1)%3]] = t[(i+2)%3]
# don't forget the outer face
of = list(set(itertools.chain.from_iterable(dt.convex_hull)))
if of[1] in succ[of[0]]:
of = of[::-1]
for i in range(3):
succ[of[i]][of[(i+1)%3]] = of[(i+2)%3]
return succ, of
######################################################################
# Boring routines to build a "random" triangulation
######################################################################
def make_triangulation(n, data_type):
print("Generating points")
if data_type == 0:
# Use a set of n-3 random points
points = [(-1.5,-1.5), (-1.5,3), (3,-1.5)] \
+ [random_point() for _ in range(n-3)]
elif data_type == 1:
# Use a set of n-3 collinear points
points = [(-1.5,-1.5), (-1.5,3), (3,-1.5)] \
+ [(-1 + i/(n-3), -1 + i/(n-3)) for i in range(n-3)]
elif data_type == 2:
points = [(0, 0), (1,1), (1,0)] \
+ [(random.random(), random.random()) for _ in range(n-3)]
for i in range(n):
(x, y) = points[i]
if x < y:
points[i] = (y, x)
else:
raise ValueError("Invalid argument for data_type")
n = len(points)
# random.shuffle(points)
print("Computing Delaunay triangulation")
succ, outer_face = triangulate(points)
return succ, points, outer_face
""" Generate a random point in the unit circle """
def random_point():
while 1 < 2:
x = 2*random.random()-1
y = 2*random.random()-1
if x**2 + y**2 < 1:
return (x, y)
""" Convert a triangle-based adjacency representation into an adjacency-list representation """
def succ2al(succ):
al = list()
for sd in succ:
al.append(list())
v0 = next(iter(sd))
v = v0
while True: # emulating do ... while v != v0
al[-1].append(v)
v = sd[v]
if v == v0: break
return al
def usage():
print("Computes a tripod decomposition of a Delaunay triangulation")
print("Usage: {} [-h] [-c] [-r] [-y] [-w] [-b] [-nv] <n>".format(sys.argv[0]))
print(" -h show this message")
print(" -c use collinear points")
print(" -y use random points in triangle")
print(" -r use random points in disk (default)")
print(" -w use O(n log n) time algorithm (default)")
print(" -b use O(n^2) time algorithm (usually faster)")
print(" -nv don't verify correctness of results")
print(" <n> the number of points to use (default = 10)")
if __name__ == "__main__":
n = 0
data_type = 0
worst_case = True
verify = True
for arg in sys.argv[1:]:
if arg == '-h':
usage()
elif arg == '-r':
data_type = 0 # random
elif arg == '-c':
data_type = 1 # collinear
elif arg == '-y':
data_type = 2 # random in triangle (like rbox y)
elif arg == '-w':
worst_case = True
elif arg == '-b':
worst_case = False
elif arg == '-nv':
verify = False
else:
n = int(arg)
if n <= 0:
usage()
sys.exit(-1)
s = ["random", "collinear", "uniform"][data_type]
print("Generating {} point set of size {}".format(s, n))
succ, points, outer_face = make_triangulation(n, data_type)
n = len(succ)
m = sum([len(x) for x in succ]) // 2
print("n = ", n, " m = ", m)
assert(m == 3*n - 6)
s = ["O(n^2)", "O(n log n)"][worst_case]
s2 = ["", " and verifying results"][verify]
print("Using {} algorithm{}...".format(s, s2), end='')
sys.stdout.flush()
start = time.time_ns()
tp = lhp.tripod_partition(succ, outer_face, worst_case, verify)
stop = time.time_ns()
print("done")
print("Elapsed time: {}s".format((stop-start)*1e-9))
if n > 500:
print("Not displaying results since n = {} > 500".format(n))
sys.exit(0)
# Draw graph
for v in range(len(succ)):
for w in succ[v]:
plt.plot([points[v][0], points[w][0]], [points[v][1], points[w][1]], color='gray', lw=0.2)
for v in range(n):
plt.plot(points[v][0], points[v][1], color="red", lw=1, marker='o',
markersize=min(8,180/n))
cmap = ['red', 'darkgreen', 'blue', 'orange', 'ghostwhite']
fmap = ['mistyrose', 'lightgreen', 'lightblue', 'moccasin', 'ghostwhite']
# Draw tripods
tripod_colours = tp.colour_tripods()
for i in range(1, len(tp.tripods)):
tripod = tp.tripods[i]
c = tripod_colours[i]
# Draw legs
for path in tripod:
x = [points[v][0] for v in path]
y = [points[v][1] for v in path]
plt.plot(x, y, color=cmap[c], lw=2)
tau = [tripod[i][0] for i in range(3)]
# Draw and label Sperner triangle
x = [points[v][0] for v in tau]
y = [points[v][1] for v in tau]
if n <= 100:
plt.fill(x, y, facecolor=fmap[c], lw=0)
x = sum(x)/3
y = sum(y)/3
if n < 250:
plt.text(x, y, str(i), horizontalalignment='center',
verticalalignment='center', fontsize=min(10,500/n))
tau2 = sum([tripod[j][:-1][:1] for j in range(3)], [])
if tau2:
tau2.append(tau2[0])
x = [points[v][0] for v in tau2]
y = [points[v][1] for v in tau2]
plt.plot(x, y, color=cmap[c], lw=2)
for v in range(n):
t = tp.tripod_map[v][0]
c = cmap[tripod_colours[t]]
plt.plot(points[v][0], points[v][1], color=c, lw=1, marker='o',
markersize=min(8,400/n))
plt.axis('off')
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
|
77cc8c1d0eda809026c68048bb9047ba24505f76 | kain21/Lesson | /4.py | 73 | 3.578125 | 4 | a = 2
b = int(input("Введите значение b: "))
print (a + b) |
5d84378f660cd0098b7dcb58325b34b728a7e520 | Noe-ZM28/Curso-Python | /Flujo/Iteracion/while/While_4.py | 542 | 4.0625 | 4 | while (True):
print("*************************")
print("**Selecciona una opcion**")
print("*************************")
print("""1) Saludar
2) Sumar 2 numeros
3) Salir""")
print("<: ")
opcion = input()
if opcion == '1':
print("Hola:D")
elif opcion == '2':
a = float(input("Ingrese un numero: "))
b = float(input("Ingrese otro numero: "))
print("El resultado es: " ,a+b)
elif opcion == '3':
print("Adios:D")
break
else:
print("opcion incorrecta")
|
6238c68b588c229c61f5e972d771cf9e626681c2 | tri-llionaire/tri-llionaire.github.io | /numbers.py | 759 | 3.5625 | 4 | #GUESS A NUMBER THAT'S BEEN RANDOMLY GENERATED
import random, time
find = random.randint(0, 9999999)
x = 0
t = 0
s = int(input('how many seconds to try: '))
guesses = []
start = time.time()
while (time.time() - start) < s:
guess = random.randint(0, 9999999)
'''while guess in guesses:
t += 1
guess = random.randint(0, 999999)
guesses.append(guess)'''
x += 1
if guess == find:
print('match: {}'.format(guess))
break
end = time.time()
second = str(x)
use = second[::-1]
i = 0
new = ''
for y in use:
if (i % 3) == 0:
new = new + ','
i += 1
new = new + y
second = new[::-1][:-1]
print('tried {} times in {}s'.format(second, str(end - start)[:5]))
#print('attempted {} duplicates'.format(t))
|
052f50f4923856f1460e8bad879c8a7b9e5c4887 | muellerjo/COVID-2019-Plots | /00_ETL-Python/02_add-population and KPIs.py | 2,561 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#After the Union of the CSVs, we will add the population of the countries to the completed dataset
#First we load the dataset with the numbers of world population
import pandas as pd
import numpy as np
#Load the CSVs
covid_cases = pd.read_csv ('../01_ETLOutput-CSV/01-data-grouped.csv')
population = pd.read_csv ('../worldpopulation/data.csv')
#------------------------------------------------------------------------------------
# ADDING DATA OF POPULATION
#------------------------------------------------------------------------------------
#Replace country names, because they er different in the population file
population["name"]= population["name"].replace('China', "Mainland China")
population["name"]= population["name"].replace('United States', "US")
#Merging both data
df = pd.merge(covid_cases,
population[['name', 'pop2020']],
left_on='country',
right_on='name',
how='left')
print("Dataframe of merged Data:")
print(df.head())
#-----------------------------------------------------------------------------------
#Calculate KPIs
print("\n \n \n Calculating KPIs \n")
#-----------------------------------------------------------------------------------
df['PercentOfPopulationConfirmedDecimal'] = (df.Confirmed/(df.pop2020*1000))
df['PercentOfPopulationConfirmed'] = df.PercentOfPopulationConfirmedDecimal*100
#df['confirmed_per_Thousand'] = df.Confirmed/(df.pop2020)
df['MortalityDecimal'] = df.Deaths / (df.Confirmed)
df['MortalityPercent'] = df.MortalityDecimal*100
#df['% Death'] = (df.mortality_percent/(df.pop2020*1000))*100
df['active'] = df.Confirmed - (np.nan_to_num(df.Recovered))
df['PercentOfPopulationActiveDecimal'] = (df.Confirmed - (np.nan_to_num(df.Recovered)))/(df.pop2020*1000)
df['PercentOfPopulationActive'] = df.PercentOfPopulationConfirmedDecimal*100
df['PercentOfPopulationRecoveredDecimal'] = df.Recovered/(df.pop2020*1000)
df['PercentOfPopulationRecovered'] = df.PercentOfPopulationRecoveredDecimal*100
print("\n \n \n Dataframe of merged Data after calculation of KPIs: \n")
print(df.head())
#-----------------------------------------------------------------------------------
# Save CSV
#-----------------------------------------------------------------------------------
#Save to csv-file
print("\n Saving to CSV.............................................................\n")
df.to_csv('../01_ETLOutput-CSV/02-data-grouped-population.csv')
df.head()
# In[ ]:
|
0f83199c73619f818b356c7593d9e17bb505cc7c | brendanstuff/wisconsin | /pixelartclass.py | 2,224 | 3.59375 | 4 | from turtle import Turtle
t = Turtle()
size = 20
row = 5
blue = 3
t.st()
for i in range(row):
t.begin_fill()
for j in range(4):
t.forward(size)
t.right(90)
t.end_fill()
t.forward(size)
t.back(size * row)
t.setpos(t.xcor(), t.ycor() + size)
# Next row
t.begin_fill()
for i in range(4):
t.forward(size)
t.right(90)
t.forward(size)
t.end_fill()
# 3 blue squares
t.color("blue")
for i in range(blue):
t.begin_fill()
for j in range(4):
t.forward(size)
t.right(90)
t.end_fill()
t.forward(size)
# 1 black square
t.color("black")
t.begin_fill()
for i in range(4):
t.forward(size)
t.right(90)
t.forward(size)
t.end_fill()
t.setpos(t.xcor() - (size * row), t.ycor())
t.setpos(t.xcor(), t.ycor() + size)
t.begin_fill()
for i in range(4):
t.forward(size)
t.right(90)
t.forward(size)
t.end_fill()
# 3 blue squares
t.color("blue")
for i in range(blue):
t.begin_fill()
for j in range(4):
t.forward(size)
t.right(90)
t.end_fill()
t.forward(size)
# 1 black square
t.color("black")
t.begin_fill()
for i in range(4):
t.forward(size)
t.right(90)
t.forward(size)
t.end_fill()
t.setpos(t.xcor() - (size * row), t.ycor())
t.setpos(t.xcor(), t.ycor() + size)
t.begin_fill()
for i in range(4):
t.forward(size)
t.right(90)
t.forward(size)
t.end_fill()
# 3 blue squares
t.color("blue")
for i in range(blue):
t.begin_fill()
for j in range(4):
t.forward(size)
t.right(90)
t.end_fill()
t.forward(size)
# 1 black square
t.color("black")
t.begin_fill()
for i in range(4):
t.forward(size)
t.right(90)
t.forward(size)
t.end_fill()
t.setpos(t.xcor() - (size * row), t.ycor())
t.setpos(t.xcor(), t.ycor() + size)
for i in range(row):
t.begin_fill()
for j in range(4):
t.forward(size)
t.right(90)
t.end_fill()
t.forward(size)
t.back(size * row)
t.setpos(t.xcor(), t.ycor() + size)
t.ht() |
a077dcdf767fcfbb67b1d575fc421169733b9987 | humbertoperdomo/practices | /python/PythonCrashCourse/PartI/Chapter05/hello_admin.py | 375 | 3.90625 | 4 | #!/usr/bin/python3
#users = ['anonymous', 'webmaster', 'admin', 'dbadmin', 'humberto']
users = []
if users:
for user in users:
if user == 'admin':
print("Hello " + user + ", would you like to see a status report?")
else:
print("Hello " + user + ", thank you for logging in again.")
else:
print("We need to find some users!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.