blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
a679a5448777fd29b5615ae51eec64711df6d8a4 | flyingsilverfin/SpotMix | /tools/training_data_db.py | 1,127 | 3.671875 | 4 | import sqlite3
class SimilarityBoundsException(Exception):
pass
class TrackSimilarityDb():
def __init__(self, db_file_path):
self._conn = sqlite3.connect(db_file_path)
self._create_tables()
def _create_tables(self):
""" Create a three column table - track id 1 (text), track id 2 (text), similarity (int between 0 and 9) """
self._conn.execute("CREATE TABLE IF NOT EXISTS track_similarity (track_id_1 TEXT NOT NULL, track_id_2 TEXT NOT NULL, similarity INTEGER, PRIMARY KEY (track_id_1, track_id_2));")
def add(self, track_id_1, track_id_2, similarity):
if similarity < 0 or similarity > 9:
raise SimilarityBoundsException("Similarity must be between 0 and 9 inclusive")
self._conn.execute("INSERT INTO track_similarity VALUES (?, ?, ?)", [track_id_1, track_id_2, similarity])
self._conn.commit()
def get_all_similarities(self):
c = self._conn.cursor()
triples = []
for id1, id2, sim in c.execute("SELECT * FROM track_similarity"):
triples.append((id1, id2, sim))
return triples
|
fc2d4a0139ec3a882240d34fa9266ed5fc05f7d6 | mattvenn/python-workshop | /tutorial/quiz.py | 814 | 4.09375 | 4 | total_questions = 2
current_question = 1
score = 0
#introduction
print "welcome to Matt's quiz!"
print "there are", total_questions, "questions in the quiz"
#function to ask the questions and get the answers
def ask_question(question,answer):
print "-" * 20
print "question", current_question, "of", total_questions
guess = raw_input(question + "? ")
#make the answers lower case before comparing them
if guess.lower() == answer.lower():
print "well done!"
return True
else:
print "better luck next time!"
return False
if ask_question("what is 5+2","7"):
score += 1
current_question += 1
if ask_question("what the capital of France","Paris"):
score += 1
current_question += 1
print "that's it!"
print "you got", score, "out of", total_questions
|
02731bbd7b58eb575d7c2801654dbff8e6544f78 | Oshini99/python-turtle-graphics | /makingCircleUsingSquaresRapidWay.py | 275 | 3.65625 | 4 | import turtle
my_turtle = turtle.Turtle()
my_turtle.speed(0)
def makingSquare(lenght,angle):
for i in range(4):
my_turtle.forward(lenght)
my_turtle.right(angle)
for i in range(150):
makingSquare(100,90)
my_turtle.right(11)
|
2ef5180201911778dc816fd0ad05288459ace580 | wuhao2/Python_learning | /数据结构及其应用/Python_datastruct_implement/queue.py | 1,281 | 4.0625 | 4 | # _*_ coding: utf-8 _*_
__author__ = 'bobby'
__data__ = '2017/6/4 15:41 '
# 队列的实现
class Queue(object):
def __init__(qu, size):
qu.queue = []
qu.size = size
qu.head = -1
qu.tail = -1
def Empty(qu):
if qu.head == qu.tail:
return True
else:
return False
def Full(qu):
if qu.tail - qu.head == qu.size:
return True
else:
return False
# 入队列
def enQueue(qu, content):
if qu.Full():
print("Queue is Full!")
else:
qu.queue.append(content)
qu.tail += 1
# 出队列
def outQueue(qu):
if qu.Empty():
print("Queue is Empty!")
else:
qu.queue.remove(qu.queue[0]) # 始终从队列的头部出来
qu.head += 1
# 输出队列中的内容
def getQueueData(self):
return self.queue
q = Queue(7)
print("queue is empty or not:", q.Empty())
print("********************入队列之后**********************")
q.enQueue("wuhao")
q.enQueue("wushibing")
q.enQueue(5)
q.enQueue(8)
print(q.getQueueData())
print("********************出队列之后**********************")
q.outQueue()
q.outQueue()
print(q.getQueueData())
|
fcf734b6ae7b329acecb8237ffd3a796d0133162 | kayvera/python_practice | /array/hashtable.py | 398 | 3.8125 | 4 | # hash table should always be top of mind for a possible solution
dict = {}
dict['a'] = 1
dict['b'] = 2
dict['c'] = 3
print(dict)
print(dict['a'])
for k in dict.keys():
print(dict[k])
for k, v in dict.items():
print(k, ' :', v)
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {k: v for k, v in zip(keys, values)}
print(hash)
arr = [0, 1, 2, 3, 4]
newHash = list(map(hash, arr))
|
88f86cc3ad6edab68be2677052309c495932aab0 | nicaibuzhao/day05 | /06-字典的使用.py | 231 | 4.40625 | 4 | # 练习1:定义一个字典类型的变量,输出及查看类型
dic = {"name":"张三","age":123,"sex":"男"}
# 练习2:根据key(age) 使用中括号和get方式字典中的value值
print(dic["name"])
print(dic.get("age")) |
d4b3ec7c4609d35042b8452f11b58329e262643a | petervel/Euler | /problems_026-050/problem30.py | 394 | 3.71875 | 4 | #!/usr/bin/python
__author__ = 'peter.vel'
def digits(number):
number = str(number)
list = []
for i in number:
list.append(int(i))
return list
def is_sum_of_fifths(number):
sum = 0
for i in digits(number):
sum += pow(i, 5)
return number == sum
def main():
sum = 0
for i in range(10, 1000000):
if is_sum_of_fifths(i):
print("* {0}".format(i))
sum += i
print(sum)
main() |
171d30a31f5008e5d7cb727b19d0a0f5d43c7a30 | billkd24/python | /conditions.py | 185 | 4.03125 | 4 | age = int (input("Please enter your age:"))
if age >= 18:
print ("Elgible to Drive")
else:
print ("Not elgible to Drive")
print (f"Please come back after {18-age} years.")
|
dec5d647b9225b0a2863702d69e45118cd17e4cf | w1033834071/qz2 | /oldboy/day04/homework.py | 709 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding -*-
#列出商品 选商品
# li = ['手机','电脑','鼠标垫','游艇']
# for i,j in enumerate(li):
# print(i+1,j)
# num = int(input("num:"))
# if num > 0 and num <= len(li):
# good = li[num-1]
# print(good)
# else:
# print('商品不存在')
dic = {
"河北":{
"石家庄":["鹿泉","真诚","元氏"],
"邯郸":["永年","涉县","磁县"]
},
"河南":{
"郑州":["1","2","3"],
"开封":["4","5","6"]
}
}
#循环输出所有的省
for p in dic:
print(p)
str1 = input("请输入省份:")
for c in dic[str1]:
print(c)
str2 = input("请输入城市:")
for d in dic[str1][str2]:
print(d)
|
bf9c33fed299a2db57b9729f82624aa3ca5cb6d9 | vidyasagarr7/DataStructures-Algos | /Karumanchi/Trees/DeepestNode.py | 1,022 | 3.859375 | 4 | import queue
from BinaryTree import BinaryTree
def deepest_node(root):
if root is None:
return
else:
que = queue.Queue()
que.put(root)
node = None
while not que.empty():
node = que.get()
if node.get_left():
que.put(node.get_left())
if node.get_right():
que.put(node.get_right())
return node.data
### REVISIT THIS #######
def delete_node(root):
if root is None:
return
else:
que=queue.Queue()
que.put(root)
if not que.empty():
node = que.get()
if node.get_left():
que.put(node.get_left())
if node.get_right():
que.put(node.get_right())
root.data,node.data=node.data,root.data
del node
if __name__=="__main__":
tree = BinaryTree()
for i in range(1,10):
tree.add_node(i)
print(deepest_node(tree.root))
delete_node(tree.root)
tree.level_order() |
aba41e2227f1e73dff66cf5266477c443932f607 | yaelBrown/pythonSandbox | /usefulPythonFiles/mathHomework.py | 122 | 3.6875 | 4 | import math
def func(a):
return math.pow(a,2) - (6 * a) + 5
for x in range(-2,6):
aa = func(x)
print(f"{x} {aa}") |
c0c7f66a0d9ee3566934c0801f4a0d33f9c735cb | korwil/lessons | /python/p_lesson_6/task2.py | 1,288 | 3.734375 | 4 | # Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
# Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными.
# Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
# Использовать формулу: длина * ширина * масса асфальта для покрытия одного кв метра дороги асфальтом,
# толщиной в 1 см * чи сло см толщины полотна. Проверить работу метода.
# Например: 20м * 5000м * 25кг * 5см = 12500 т
class Road:
def __init__(self, length, width):
self._length = length
self._width = width
def get_mass(self, a, b):
result = self._length * self._width * a * b
t = 'кг'
if result >= 1000:
result = result/1000
t = 'т'
return result, t
r = Road(20, 5000)
res, t = r.get_mass(25, 5)
print(res, t)
|
c5b9670f2f8ea047289d554c524f97dfd9bb2031 | twsq/car-velocity-estimation | /recurrent_cnn_polished_yury.py | 11,485 | 3.78125 | 4 | from scipy import misc
import json
import numpy as np
import sys
'''
Implementation of recurrent CNN for predicting velocity. The network first computes
features by applying a CNN to every frame that is put in as input (currently last 5 frames
of each sequence) and then uses these features as input into a recurrent neural network with
1 LSTM hidden layer.
Inspired by this paper:
Donahue et al. (2015), Long-term Recurrent Convolutional Networks for
Visual Recognition and Description
A warning: The training and test data take a lot of memory, which could lead to running out of
RAM (unless your computer has a lot of RAM (like 16 GB or something like that). Also, at least for my
computer, the network takes quite a long time to train (something like 10 minutes an epoch).
'''
# Code should be put in a folder containing the benchmark_velocity folder
file_prefix = "./benchmark_velocity/clips/"
'''
Below code is used to process a random half of the data as training data.
Can modify it to add various amounts of padding to the bounding boxes since
the bounding box of a car might change for different frames.
'''
size = 200
startOver = True
train_sequences_resized = []
train_velocities = []
if startOver:
# Shuffle indices of data samples randomly (in case samples are ordered in some way)
random_indices = np.random.permutation(range(1, 247))
# Save random shuffling (useful later for extracting test set)
np.save("rcnn_shuffled_indices", random_indices)
# Use half of data for training
for i in range(123):
sys.stdout.write('\rProcessing training data: {0}'.format(i))
# Open annotation file
annotation_file = file_prefix + "{0:0=3d}".format(random_indices[i]) + "/annotation.json"
with open(annotation_file) as json_data:
annotations = json.load(json_data)
# Extract bounding boxes and velocities of cars
bboxes = []
for j in range(len(annotations)):
bbox = annotations[j]['bbox']
# Add margin to bounding boxes
# horiz_margin = 0.05 * (bbox['bottom'] - bbox['top'])
# vert_margin = 0.05 * (bbox['right'] - bbox['left'])
horiz_margin = 0
vert_margin = 0
bboxes.append((int(bbox['top'] - horiz_margin), int(bbox['bottom'] + horiz_margin), int(bbox['left'] - vert_margin), int(bbox['right'] + vert_margin)))
# Extract velocity
train_velocities.append(annotations[j]['velocity'])
image_folder = file_prefix + "{0:0=3d}".format(random_indices[i]) + "/img/"
# Loop over bounding box for each car in sequence for current example
for bbox in bboxes:
# List of cropped frames in a sequence
sequence_cropped = []
# Loop over each frame of example
for j in range(55, 60):
# Read in frame, crop it to bounding box, resize image to size by size (input image size to InceptionV3 CNN)
image = image_folder + "{0:0=3d}".format(j + 1) +".jpg"
image_data = misc.imread(image, mode = 'RGB')
frame = np.zeros_like(image_data)
frame[bbox[0]: bbox[1], bbox[2]:bbox[3]] = image_data[bbox[0]: bbox[1], bbox[2]:bbox[3]]
image_cropped = misc.imresize(frame, (size, size))
sequence_cropped.append(image_cropped)
# Add sequence of cropped frames corresponding to a given car as an example sequence
train_sequences_resized.append(sequence_cropped)
print()
print()
train_sequences_resized = np.array(train_sequences_resized)
train_velocities = np.array(train_velocities)
np.save("rcnn_train_images_merged_resized_shuffle.npy", train_sequences_resized)
np.save("rcnn_train_velocities_shuffle.npy", train_velocities)
else:
# Load saved preprocessed training data (array of sequences of cropped frames corresponding to a car) and saved velocities
# Currently use last 5 frames of each sequence as input
random_indices = np.load("rcnn_shuffled_indices.npy")
train_sequences_resized = np.load("rcnn_train_images_merged_resized_shuffle.npy")[:, :, :, :]
train_velocities = np.load("rcnn_train_velocities_shuffle.npy")
import tensorflow as tf
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D, Lambda, Input
from keras import backend as K
from keras.models import load_model
from keras.layers.wrappers import TimeDistributed
from keras.layers.recurrent import LSTM
# set learning phase to 0 (this is necessary for the code to work due to batch normalization
# layers in the InceptionV3 network)
# See https://github.com/fchollet/keras/issues/5934 for more details.
K.set_learning_phase(0)
# create the base pre-trained model (InceptionV3 pretrained on ImageNet)
# The base model was obtained from here:
# https://keras.io/applications/.
input = Input(shape=(None, size, size, 3), name='input')
base_model = InceptionV3(weights='imagenet', include_top=False)
# Apply TimeDistributed wrapper to InceptionV3 model. This way, the same InceptionV3
# network is applied to every frame in a given input sequence.
# Documentation for TimeDistributed wrapper: https://keras.io/layers/wrappers/
# I think in order to wrap the whole base_model with the TimeDistributed wrapper, a Lambda layer
# is needed (see https://gist.github.com/alfiya400/9d3bf303966f87a3c2aa92a0a0a54662)
cnn_time_model = TimeDistributed(Lambda(lambda x: base_model(x)))
cnn_time_output = cnn_time_model(input)
# Add a global spatial average pooling layer wrapped with TimeDistributed wrapper
cnn_time = TimeDistributed(GlobalAveragePooling2D())(cnn_time_output)
# Add a fully-connected layer again wrapped with TimeDistributed wrapper
rcnn_model = TimeDistributed(Dense(512, activation='relu'))(cnn_time)
# Add LSTM hidden layer that takes as input features from the previous fully-connected
# layer wrapped with TimeDistributed wrapper
rcnn_model = LSTM(128)(rcnn_model)
# Add fully connected layer
rcnn_model = Dense(64, activation='relu')(rcnn_model)
# Output layer that predicts both components of velocity
rcnn_model = Dense(2)(rcnn_model)
# this is the model we will train
model = Model(inputs=[input], outputs=rcnn_model)
# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in base_model.layers:
layer.trainable = False
model.summary()
# compile the model (should be done *after* setting layers to non-trainable)
model.compile(optimizer='rmsprop', loss='mean_squared_error')
# train the model on the new data for a few epochs
model.fit(train_sequences_resized, train_velocities, epochs=10)
# at this point, the top layers are well trained and we can start fine-tuning
# convolutional layers from inception V3. We will freeze the bottom N layers
# and train the remaining top layers.
# let's visualize layer names and layer indices to see how many layers
# we should freeze:
#for i, layer in enumerate(base_model.layers):
# print(i, layer.name)
# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 172 layers and unfreeze the rest:
for layer in model.layers[:172]:
layer.trainable = False
for layer in model.layers[172:]:
layer.trainable = True
# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='mean_squared_error')
# we train our model again (this time fine-tuning the top 2 inception blocks
# alongside the top Dense layers
model.fit(train_sequences_resized, train_velocities, epochs=5)
# Save weights of model (due to the Lambda layer, saving
# the whole model with model.save and loading model with load_model doesn't work)
model.save_weights("rcnn_velocity_estimator_shuffled.h5")
# Predict velocities for training data and evaluate model on training data
train_predicted_velocities = model.predict(train_sequences_resized)
np.save("rcnn_train_predicted_velocities_shuffle.npy", train_predicted_velocities)
print(model.evaluate(train_sequences_resized, train_velocities))
print(np.sum(np.square(train_velocities - train_predicted_velocities)) / np.sum(np.square(train_velocities)))
'''
Below code (currently commented out) can be used to process other half of the data
as test data. Can modify it to add various amounts of padding to the bounding boxes since
the bounding box of a car might change for different frames.
'''
test_sequences_resized = []
test_velocities = []
if startOver:
# Use other half of data for testing
for i in range(123, 246):
sys.stdout.write('\rProcessing test data: {0}'.format(i))
# Open annotation file
annotation_file = file_prefix + "{0:0=3d}".format(random_indices[i]) + "/annotation.json"
with open(annotation_file) as json_data:
annotations = json.load(json_data)
# Extract bounding boxes and velocities of cars
bboxes = []
for j in range(len(annotations)):
bbox = annotations[j]['bbox']
# horiz_margin = 0.05 * (bbox['bottom'] - bbox['top'])
# vert_margin = 0.05 * (bbox['right'] - bbox['left'])
horiz_margin = 0
vert_margin = 0
bboxes.append((int(bbox['top'] - horiz_margin), int(bbox['bottom'] + horiz_margin), int(bbox['left'] - vert_margin), int(bbox['right'] + vert_margin)))
test_velocities.append(annotations[j]['velocity'])
image_folder = file_prefix + "{0:0=3d}".format(random_indices[i]) + "/img/"
images = []
# Loop over bounding boxes for current example
for bbox in bboxes:
sequence_cropped = []
# Loop over each frame of example
for j in range(55, 60):
# Read in frame, crop it to bounding box
image = image_folder + "{0:0=3d}".format(j + 1) +".jpg"
image_data = misc.imread(image, mode = 'RGB')
frame = np.zeros_like(image_data)
frame[bbox[0]: bbox[1], bbox[2]:bbox[3]] = image_data[bbox[0]: bbox[1], bbox[2]:bbox[3]]
image_cropped = misc.imresize(frame, (size, size))
sequence_cropped.append(image_cropped)
test_sequences_resized.append(sequence_cropped)
print()
print()
test_sequences_resized = np.array(test_sequences_resized)
test_velocities = np.array(test_velocities)
np.save("rcnn_test_images_merged_resized_shuffle.npy", test_sequences_resized)
np.save("rcnn_test_velocities_shuffle.npy", test_velocities)
else:
# Load saved preprocessed test data (array of sequences of cropped frames corresponding to a car) and saved velocities
# Currently use last 5 frames of sequence as input
test_sequences_resized = np.load("rcnn_test_images_merged_resized_shuffle.npy")[:, -5:, :, :]
test_velocities = np.load("rcnn_test_velocities_shuffle.npy")
# Predict velocities for test data and evaluate model on test data
print(model.evaluate(test_sequences_resized, test_velocities))
predicted_velocities = model.predict(test_sequences_resized)
np.save("rcnn_predicted_velocities_shuffle.npy", predicted_velocities)
print(np.sum(np.square(test_velocities - predicted_velocities)) / np.sum(np.square(test_velocities)))
|
57e1d8dd720a11286d178e660c3d61cf9e0e5933 | mgbrouli/Controle.Estoque | /main.py | 2,891 | 3.8125 | 4 | #não esta totalmente funcional, falta realmente criar alguns comandos e no futuro aprender a criar bancos de dados externos para salvar os arquivos
bebidas = []
pereciveis = []
naoPereciveis = []
def cadastro():
while True:
lista = {}
lista.clear()
lista['produto'] = str(input('Digite o nome do produto: '))
lista['quantidade'] = int(input('Quantidade: '))
pb = float(input('Preço bruto R$: '))
lista['pBruto'] = pb
pcent = int(input('Porcentagem do lucro: '))
lista['porcentagem'] = pcent
lista['lucro'] = ((pb*pcent)/100)+pb
print('''Qual o tipo de produto
[1] Bebidas Alcoolicas.
[2] Produtos perecivel.
[3] Produtos Não pereciveis.
''')
tipo = int(input('Digite aqui a opção desejada: '))
if tipo == 1:
bebidas.append(lista.copy())
elif tipo == 2:
pereciveis.append(lista.copy())
elif tipo == 3:
lista['validade'] = int(input('Data de validade (digite apenas o mes): '))
naoPereciveis.append(lista.copy())
resp = str(input('Quer continuar o cadastro [S/N]: ')).upper().strip()[0]
while resp not in 'SN':
resp = str(input('Quer continuar o cadastro [S/N]: ')).upper().strip()[0]
if resp == 'N':
break
def alterar():
print('''Qual o tipo de produto
[1] Bebidas Alcoolicas.
[2] Produtos perecivel.
[3] Produtos Não pereciveis.
''')
resp = int(input('Digite sua opção em numeros: '))
while resp >= 4:
resp = int(input('Digite sua opção em numeros: '))
if resp == 1:
for i in bebidas:
for k, v in i.items():
print(f'{k}: {v}')
elif resp == 2:
for i in pereciveis:
for k, v in i.items():
print(f'{k}: {v}')
elif resp == 3:
for i in naoPereciveis:
for k, v in i.items():
print(f'{k}: {v}')
print('--'*30)
print(f'{">>>PROGRAMA DE CONTROLE DE ESTOQUE v1.0<<<":^60}')
print(f'{"crado por Welligton":^60}')
print('--'*30)
while True:
print('''\033[1;33mEscolha sua opção digitando as opções em valor numerico:\033[m
\033[1;32m[1]\033[m Para cadastrar produtos:
\033[1;32m[2]\033[m Para Alterar o produtos cadastrados:
\033[1;32m[0]\033[m Para sair do programa:\033[m
''')
print('--' * 30)
opcao = int(input('\033[1;33mDigite aqui a opção: \033[m'))
while opcao >= 3:
opcao = int(input('\033[1;33mDigite aqui a opção: \033[m'))
if opcao == 0:
break
elif opcao == 1:
cadastro()
elif opcao == 2:
alterar()
print(bebidas)
print(pereciveis)
print(naoPereciveis)
|
558c9fd9aed5fc8ce6d7bed02344e7dcea6e43ce | thezaza101/Python-Code-Snippets | /other/p/SIT742A1/A1P1.py | 5,516 | 3.828125 | 4 | import pandas as pd
'''The first task is to read the json file as a Pandas DataFrame and delete the rows
which contain invalid values in the attributes of “points” and “price”.'''
df = pd.read_json('datasets//wine.json')
df = df.dropna(subset=['points', 'price'])
'''what are the 10 varieties of wine which receives the highest number of reviews?'''
dfTop10MostReviews = df['variety'].value_counts()[:10]
print("Q1:")
print(dfTop10MostReviews)
print('\n')
'''which varieties of wine having the average price less than 20, with the average points at least 90?'''
averagePoints = df.groupby('variety', as_index=False)['points'].mean()
averagePoints = averagePoints.loc[averagePoints['points']>=90]
averagePrice = df.groupby('variety', as_index=False)['price'].mean()
averagePrice = averagePrice.loc[averagePrice['price']<20]
q2 = pd.merge(averagePrice, averagePoints, on='variety')
print("Q2:")
print(q2)
print('\n')
'''
In addition, you need to group all reviews by different countries and generate a statistic
table, and save as a csv file named “statisticByState.csv”. The table must have four
columns:
Country – listing the unique country name.
Variety – listing the varieties receiving the most reviews in that country.
AvgPoint – listing the average point (rounded to 2 decimal places) of wine in that
country
AvgPrice – listing the average price (rounded to 2 decimal places) of wine in that country
'''
countryList = df['country'].drop_duplicates().to_frame()
dfTopReviews = df.groupby('country')['variety'].value_counts()
dfTopReviews = dfTopReviews.to_frame()
dfTopReviews.columns = ['Var_count']
dfTopReviews = dfTopReviews.reset_index(inplace=False)
dfTopReviews = dfTopReviews.set_index(['country', 'variety'],drop=False, inplace=False)
dfTopReviews = dfTopReviews.drop_duplicates(subset='country', keep='first', inplace=False)
averagePointsCt = df.groupby('country', as_index=False)['points'].mean().round(2)
averagePriceCt = df.groupby('country', as_index=False)['price'].mean().round(2)
ss = pd.merge(countryList,dfTopReviews,on='country')
ss = pd.merge(ss,averagePointsCt,on='country')
ss = pd.merge(ss,averagePriceCt,on='country')
ss = ss[['country','variety','points','price']]
ss.to_csv('datasets//StatisticByStateSP.csv')
print("Q3:")
print("See 'datasets//StatisticByStateSP.csv' for more...")
print(ss)
'''In this task, you are required to write Python code to extract keywords from the
“description” column of the json data, used to redesign the wine menu for Hotel
TULIP.
You need to generate two txt files:'''
import re
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.probability import *
from itertools import chain
#from tqdm import tqdm
import codecs
with open('datasets//stopwords.txt') as f:
stop_words = f.read().splitlines()
stop_words = set(stop_words)
'''HighFreq.txt This file contains the frequent unigrams that appear in more than 5000
reviews (one row in the dataframe is one review).'''
# write your code here
# define your tokenize
descData = df["description"]
def removeStopWords(stopWords, txt):
newtxt = ' '.join([word for word in txt.split() if word not in stopWords])
return newtxt
tokenizer = RegexpTokenizer(r"\w+(?:[-']\w+)?")
# remove stop words and tokenize each review
tokenized_Reviews = list((tokenizer.tokenize(removeStopWords(stop_words,review)) for review in descData))
# flatten the list of lists into a single list and also make everything lowercase
tokenized_words = [item.lower() for sublist in tokenized_Reviews for item in sublist]
# get the frequency distribution
fd = FreqDist(tokenized_words)
# select words with > 5000 frequency
fiveKOrMore = list(filter(lambda x: x[1]>5000,fd.items()))
# sort the list by the word
fiveKOrMore.sort(key=lambda tup: tup[0])
topCommonWords = list((word[0] for word in fiveKOrMore))
with open('datasets//HighFreq.txt', 'w') as f:
for item in topCommonWords:
f.write("%s\n" % item)
'''Shirazkey.txt This file contains the key unigrams with tf-idf score higher than 0:4.
To reduce the runtime, first you need to extract the description from the variety of
“Shiraz”, and then calculate tf-idf score for the unigrams in these descriptions
only.'''
# select 'description' from 'variety' eqaul to 'Shiraz'
descDataShiraz = df[df["variety"]=="Shiraz"]["description"]
# remove stop words and tokenize each review
tokenized_Reviews_Shiraz = list((tokenizer.tokenize(removeStopWords(stop_words,review.lower())) for review in descData))
idgen = (str(x) for x in range(0,len(tokenized_Reviews_Shiraz)))
doclist_Shiraz = {next(idgen):review for review in tokenized_Reviews_Shiraz}
# use TfidfVectorizer to calculate TF-IDF score
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(analyzer='word', stop_words = 'english')
tfs = tfidf.fit_transform([' '.join(value) for value in doclist_Shiraz.values()])
print(tfs.shape)
# find words with TF-IDF score >0.4 and sort them
vocab = tfidf.get_feature_names()
tfidfScores = list(zip(vocab, tfs.toarray()[0]))
'''
temparry = tfs[:,0]
temparry = temparry.toarray()
for word, weight in zip(vocab, temparry):
if weight > 0.4:
print (word, ":", weight)
'''
# Print the list
for item in tfidfScores:
if item[1] > 0.0:
print (item[0], ":", item[1])
# save your table to 'key_Shiraz.txt'
with open('datasets//key_Shiraz.txt', 'w') as f:
for item in tfidfScores:
if item[1] > 0.4:
f.write("%s\n" % item[0]) |
925512bdd8868822aa354e61f13a70e76a252e43 | tramxme/CodeEval | /Medium/PredictTheNumber.py | 542 | 3.53125 | 4 | import sys, re
def doStuff(num):
seq = [0,1]
while(num > len(seq)):
addSeq = seq[len(seq)//2:]
for n in seq[:len(seq)//2]:
if n == 0: addSeq.append(1)
elif n == 1: addSeq.append(2)
elif n == 2: addSeq.append(0)
seq.extend(addSeq)
print(seq[num])
return
def main(file_name):
fileName = open(file_name, 'r')
for line in fileName.readlines():
line = re.sub(r'\n','', line)
doStuff(int(line))
if __name__ == '__main__':
main(sys.argv[1])
|
438aad130f2b87a3faa16391282f9ece3fdc4c35 | wtripp/udacity-cs215-intro-algorithms | /final/final-3_weighted_graph.py | 1,984 | 4.15625 | 4 | #
# In lecture, we took the bipartite Marvel graph,
# where edges went between characters and the comics
# books they appeared in, and created a weighted graph
# with edges between characters where the weight was the
# number of comic books in which they both appeared.
#
# In this assignment, determine the weights between
# comic book characters by giving the probability
# that a randomly chosen comic book containing one of
# the characters will also contain the other
#
marvel = cPickle.load(open("final-3_smallG.pkl"))
characters = cPickle.load(open("final-3_smallChr.pkl"))
def create_weighted_graph(bipartiteG, characters):
G = {}
for char in characters:
for other_char in characters:
if char == other_char:
continue
char_set = set(bipartiteG[char])
other_char_set = set(bipartiteG[other_char])
A_and_B = len(char_set.intersection(other_char_set))
A_or_B = (len(char_set) + len(other_char_set)) - A_and_B
if G.get(char) is None:
G[char] = {other_char: None}
if A_and_B > 0.0:
G[char][other_char] = (0.0 + A_and_B) / A_or_B
else:
G[char][other_char] = None
return G
######
#
# Test
def test():
bipartiteG = {'charA':{'comicB':1, 'comicC':1},
'charB':{'comicB':1, 'comicD':1},
'charC':{'comicD':1},
'comicB':{'charA':1, 'charB':1},
'comicC':{'charA':1},
'comicD': {'charC':1, 'charB':1}}
G = create_weighted_graph(bipartiteG, ['charA', 'charB', 'charC'])
# three comics contain charA or charB
# charA and charB are together in one of them
assert G['charA']['charB'] == 1.0 / 3
assert G['charA'].get('charA') == None
assert G['charA'].get('charC') == None
def test2():
G = create_weighted_graph(marvel, characters)
|
e80853e568d3b11e2fe6ab68fa0a0fff3728e396 | goncalossantos/Algorithms | /Challenges/CCI/Chapter 01/rotate_matrix_inplace.py | 1,970 | 3.96875 | 4 | class Rotation():
def rotate(self, i, j):
return (j, self.N - i -1)
def __init__(self, i, j, N):
self.N = N
self.get_coordinates_to_rotate(i, j)
def get_coordinates_to_rotate(self, i, j):
self.top = (i,j)
self.right = self.rotate(i,j)
self.bottom = self.rotate(*self.right)
self.left = self.rotate(*self.bottom)
def apply_rotation(matrix, rotation):
tmp = matrix[rotation.top[0]][rotation.top[1]]
matrix[rotation.top[0]][rotation.top[1]] = matrix[rotation.left[0]][rotation.left[1]]
matrix[rotation.left[0]][rotation.left[1]] = matrix[rotation.bottom[0]][rotation.bottom[1]]
matrix[rotation.bottom[0]][rotation.bottom[1]] = matrix[rotation.right[0]][rotation.right[1]]
matrix[rotation.right[0]][rotation.right[1]] = tmp
return matrix
def rotate_matrix(matrix):
"""Rotates a matrix 90 degrees
Iterates through a matrix to rotate it in place.
Arguments:
matrix {list of lists} -- contains the matrix of ints
Returns:
[list of lists] -- rotated matrix
"""
N = len(matrix)
# We only need to go to the middle row
for i in range(N/2):
# We only need to to the inside columns
for j in range(i,N-i-1):
rotation = Rotation(i, j, N)
matrix = apply_rotation(matrix, rotation)
return matrix
def print_matrix(matrix):
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in matrix]))
def test_matrix():
test_2 = ([[1, 2], [3, 4]] , [[3, 1], [4, 2]])
test_3 = ([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[7, 4, 1], [8, 5, 2], [9, 6, 3]])
test_4 = (
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]],
[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]],
)
for test in [test_2, test_3, test_4]:
result = rotate_matrix(test[0])
assert result == test[1]
test_matrix() |
91e830c34984c65e3e6b19dffbad9fcc16d56669 | Deeklogu/Codek | /fact.py | 70 | 3.5625 | 4 | import math
s=int(input("enter any number"))
print(math.factorial(s))
|
75fc2b455bd9dd48d7b20fa2981fee1f2a49706a | anthonynolan/coding-for-schools | /grades.py | 331 | 4.03125 | 4 | # Get the input
english = input("What grade did you get in English?")
maths = input("What grade did you get in Maths?")
computers = input("What grade did you get in Computers?")
# Change them all to integers
a = int(english)
b = int(maths)
c = int(computers)
print("Your average grade is " + str((int(a) + int(b) + int(c)) / 3))
|
e321a91b066fc6ee8367ebf7fcef27925284d184 | scobbyy2k3/python-challenge | /pyPoll/main.py | 2,104 | 3.875 | 4 | #import modules
import os
import csv
election_data = "Resources/election_data.csv"
# list names of candidates
candidates = []
# number of votes for each candidate
num_votes = []
# total number of votes
total_votes = 0
# percentage of total votes for each candidate
percent_votes = []
with open(election_data, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
csv_header = next(csvreader)
for row in csvreader:
# Count the total number of votes
total_votes += 1
# Set the candidate names to candidatelist
if row[2] not in candidates:
candidates.append(row[2])
index = candidates.index(row[2])
num_votes.append(1)
else:
index = candidates.index(row[2])
num_votes[index] += 1
# total vote count per candidate
for votes in num_votes:
percentage = (votes/total_votes) * 100
percentage = round(percentage)
percentage = "%.3f%%" % percentage
percent_votes.append(percentage)
# winner
winner = max(num_votes)
index = num_votes.index(winner)
winning_candidate = candidates[index]
# Election results
print("Election Results")
print("--------------------------")
print(f"Total Votes: {str(total_votes)}")
print("--------------------------")
for i in range(len(candidates)):
print(f"{candidates[i]}: {str(percent_votes[i])} ({str(num_votes[i])})")
print("--------------------------")
print(f"Winner: {winning_candidate}")
print("--------------------------")
#output to txt file
# Name white file
write_election_datacsv = f"pyPoll_results.txt"
text = open("write_election_datacsv", mode = 'w')
text.write("Election Results\n")
text.write("---------------------------------------\n")
text.write(str(f"Total Votes: {str(total_votes)}\n"))
text.write("---------------------------------------\n")
for i in range(len(candidates)):
text.write("---------------------------------------\n")
text.write(str(f"Winner: {winning_candidate}"))
text.write("---------------------------------------\n")
|
4de807dc7ea0381d03bd98d0c77d4b3a24933b33 | gaurav-dwivedi/mypracticecodes | /Fibonacci 4 methods.py | 692 | 3.65625 | 4 | def fib1(n):
a, b = 0, 1
for i in range(n):
print(a)
a, b = b, a + b
def fib2(n):
if n == 0:
return 0
if n == 1:
return 1
return fib2(n - 1) + fib2(n - 2)
def fib3(n):
c = 0
a, b = 0, 1
while True:
if c > n: return
yield a
a, b = b, a + b
c += 1
def fib4(n):
a, b = 0, 1
for i in range(n):
nex = a + b
if i <= 1:
print(i)
else:
print(nex)
a, b = b, nex
print('Method 1:')
fib1(5)
print('Method 2:')
for i in range(5):
print(fib2(i))
print('Method 3:')
n = fib3(5)
for i in n:
print(i)
print('Method 4:')
fib4(5)
|
eb6cec76feb86c1601ba06c931c67b268127ee4c | ChetnaRajput/Python-Basics-Day1-2 | /2-factorials.py | 377 | 4.25 | 4 | """
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
"""
n = int(input("Enter a number to calculate factorial:"))
fact = 1
for i in range(1,n+1):
fact *=i
print(fact)
|
bd828f4715855be2470be81b9d7fd53e48867f3e | Datatu/datascience | /datascience/assignment3/multiply.py | 966 | 3.90625 | 4 | import MapReduce
import sys
"""
Implementation of Matrix multiplication in MapReduce
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
value = record
if(value[0]=='a'):
for i in range(0,5):
mr.emit_intermediate(str(value[1])+" "+str(i),value)
else:
for j in range(0,5):
mr.emit_intermediate(str(j)+" "+str(value[2]),value)
def reducer(key, list_of_values):
total=0
lista=[0]*5
listb=[0]*5
print key
print list_of_values
print " "
for v in list_of_values:
if (v[0]=='a'):
lista[v[2]]=v[3]
else:
listb[v[1]]=v[3]
for j in range(0,5):
total+=lista[j]*listb[j]
mr.emit((int(key[0]),int(key[2]),total))
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
8813fb2506743db415d641b129ed3c7cc3464d38 | ybillchen/Simple-Examples-Keras | /Keras_linear_fitting.py | 1,406 | 3.578125 | 4 | # 'Keras_linear_fitting' is used to fit linear data with one layer
# created by Bill
from tensorflow import keras as kr
import numpy as np
import matplotlib.pyplot as plt
# generate data and add random noise
x = np.linspace(-1, 1, 200)
np.random.shuffle(x)
y = 0.5 * x + 2 + np.random.normal(0, 0.05, (200, ))
# uncomment to show data
# plt.plot(x, y, '^b', markersize = 4.0)
# plt.show()
x_train, y_train = x[: 160], y[: 160] # training set
x_test, y_test = x[160 :], y[160 :] # testing set
# initialize model
model = kr.Sequential()
model.add(kr.layers.Dense(units = 1, input_dim = 1)) # add input layer (also output layer)
model.compile(loss = 'mse', optimizer = 'sgd') # set loss function and optimizer
# training
print('Begin Training')
for step in range(301): # repeat 301 times
cost = model.train_on_batch(x_train, y_train)
if step % 100 == 0:
print('Loss: ', cost)
print('End Training\n')
# testing
print('Begin Testing')
cost = model.evaluate(x_test, y_test, batch_size = 40)
print('Loss:', cost)
print('End Testing')
# print weight and bias
W, b = model.layers[0].get_weights()
print('Weight=', W, '\nBias=', b)
# uncomment to show fitting result
# x = np.sort(x)
# y_predict = model.predict(x)
# plt.plot(x_test, y_test, '^b', markersize = 4.0)
# plt.plot(x, y_predict, 'r')
# plt.axis([-1.1, 1.1, -1.1, 1.1])
# plt.show() |
942a2cab78d72c9dd2b8e58d7f035a0d54370dfd | mahiradayal/foundations | /homework_2/homework-2-part1-dayal.py | 1,315 | 4.15625 | 4 | # Mahira Dayal
# Oct 30, 2020
# Homework 2, Part 1
# Part One: Lists
Numbers = [22, 90, 0, -10, 3, 22, 48]
print(len (Numbers))
print(Numbers[3])
print(Numbers[1]+Numbers[3])
print(sorted(Numbers, reverse=True) [1])
print(Numbers [-1])
print((sum (Numbers))/2)
import statistics
# I didn't want to add and divide, thought this was quicker.
if (statistics.mean(Numbers))>(statistics.median(Numbers)):
print ("Mean is larger")
else:
print ("Median is larger")
#Part One: Dictionaries
movie = {
'title': 'The Parent Trap',
'year': '1998',
'director': 'Nancy Meyers'
}
print("My favorite movie is", movie['title'], "which was released in", movie['year'], "and was directed by", movie['director'])
movie['budget'] = 15500000
movie['revenue'] = 92000000
print ("The difference between revenue and budget is $",movie['revenue']-movie['budget'])
if movie['budget']>movie['revenue']:
print ("That was a bad investment")
elif movie['revenue']>(5*movie['budget']):
print ("That was a great investment")
else:
print("That was an okay investment")
population = {
'Manhattan': 1.6,
'Brooklyn': 2.6,
'Bronx': 1.4,
'Queens': 2.3,
'Staten Island': 0.5
}
print (population['Brooklyn'])
print (sum(population.values()))
print ((population['Manhattan']/(sum(population.values())))*100, "%")
|
7e52cf50f97a380fd642400ed77ac5c0e6e9706a | LukeBrazil/fs-imm-2021 | /python_week_1/day1/fizzBuzz.py | 324 | 4.15625 | 4 | number = int(input('Please enter a number: '))
def fizzBuzz(number):
if number % 3 == 0 and number % 5 == 0:
print('FizzBuzz')
elif number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
print('Buzz')
else:
print(f'Number does not fit requirements: {number}')
fizzBuzz(number) |
88871276907ca035324a4bfb0e4f06cb2064c79a | sakshigoyal58/Python | /PythonDictionary.py | 321 | 3.90625 | 4 | dictionary = {"name" :"sakshi", "name" : "varnit"}
print(dictionary) #wont give error but will take the last one only
dic1 = {"name" : "sakshi", "age" : 23}
for i in dic1:
print(dic1[i])
tuple= (1,2,1,1)
print(sorted(tuple))
x=10
y=x
y=12
z=12
if id(z) == id(y):
print("yes")
else:
print("No")
#pull request |
a7a0128e77c0b50df320cc4e38977228e8d8c997 | Shisan-xd/testPy | /python_work/day3_三目运算符.py | 415 | 3.71875 | 4 | """
语法:
条件成立执行表达式 if 条件 else 条件不成立执行表达式
"""
a = 8
b = 2
c = a if a > b else b # 判断a是否大于b,a大于b则执行a变量赋值给c,否则执行b赋值给c
print(c)
# 需求:有两个变量,比较大小 如果变量1 大于 变量2 执行 变量1 - 变量2 否则 变量2 - 变量1
aa = 91
bb = 90
cc = aa - bb if aa > bb else bb - aa
print(cc)
|
9dccb72e337bcc49f565112437d2ac3b37f0ce77 | traviswu0910/Intern_Project | /News_try_and_delete_redundant.py | 609 | 3.578125 | 4 | #抓贅字用,修正清洗資料用
#也可看時間序列變化
import pickle
import pandas as pd
with open('top_news_keys','rb')as f:
data = pickle.load(f)
def show_key_words_with_score():
total_date = pd.date_range('20180101','20200708',freq='d')
total_date = total_date.strftime('%Y%m%d')
for date in total_date:
try:
print(date)
print(data[date][:3])
except:
print('This day is wrong:',date)
pass
return()
def show_only_key_words():
for i in data:
for x,y in data[i][:3]:
print(x)
return()
if __name__ == '__main__':
# show_only_key_words()
show_key_words_with_score() |
fad1ab671b20db6e864fcb4901309182543fc4bf | XuJunhao-jiaojiao/Time | /2级python资料/Python部分/上机练习/2/2.2.py | 97 | 3.578125 | 4 | N=input("请输入一段文字:")
i=0
for l in range(len(N)):
print(N[i])
i=i+1
|
1bcede79f3cf143f12089e1b6987aea4be497fc2 | Aiyane/aiyane-LeetCode | /1-50/搜索旋转排序数组.py | 1,556 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 搜索旋转排序数组.py
"""
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
"""
"""
思路:取中间数字,分四种情况
"""
__author__ = 'Aiyane'
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l = len(nums)
i = 0
j = l-1
while i <= j:
m = (i + j) // 2
if nums[m] == target:
return m
if nums[i] <= nums[m]:
if nums[i] <= target < nums[m]:
j = m -1
else:
i = m + 1
else:
if nums[m] < target <= nums[j]:
i = m + 1
else:
j = m - 1
return -1
def main():
sol = Solution()
print(sol.search([4,5,6,7,0,1,2], 0))
print(sol.search([4,5,6,7,0,1,2], 3))
print(sol.search([], 3))
print(sol.search([1], 1))
print(sol.search([1], 2))
if __name__ == '__main__':
main() |
4e3e9e8d4cd97f98eedbf41beb1c653245f87669 | crab-a/hw02 | /statistics.py | 673 | 4.28125 | 4 | def mean(values):
"""
calculate the mean of all values in the iterable 'values'
:param values: iterable containing numbers(int/float/double)
:return: the mean
"""
total = sum(values)
length = len(values)
return total / length
def median(values):
"""
calculate the median of all values in the iterable 'values'
:param values: iterable containing numbers(int/float/double)
:return: the median
"""
length = len(values)
sorted_values = sorted(values)
med = 0
if length % 2:
return sorted_values[int(length / 2)]
return (sorted_values[int(length / 2)] + sorted_values[int((length / 2)) - 1]) / 2
|
c891f30f12fc1e48b967817380b5b2cae4338e27 | pascal19821003/python | /study/tutorial/runoob/7.py | 1,234 | 4.3125 | 4 | #Python 列表(List)
#https://www.runoob.com/python/python-lists.html
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
print("============================")
#list = [] ## 空列表
#list.append('Google') ## 使用 append() 添加元素
#list.append('Runoob')
#print (list)
print("============================")
list1 = ['physics', 'chemistry', 1997, 2000]
print (list1)
del list1[2]
print ("After deleting value at index 2 : ")
print (list1)
print("============================")
L=["Google", "Runoob", 'Taobao']
print(L[2])
print(L[-2])
print(L[1:])
print("============================")
print(len([1, 2, 3]))
print([1, 2, 3] + [4, 5, 6])
print(['Hi!'] * 4)
print(3 in [1, 2, 3])
for x in [1,2,3]: print (x)
print("===============list=============")
aTuple=( 'xyz', 'zara', 'abc')
aList=list(aTuple)
print("列表元素:", aList)
print("============================")
aList=[123, 'xyz', 123, 'zara','abc']
aList.append(2009)
print("Updated List: ", aList)
print("count of 123: ", aList.count(123))
print(aList.index('zara'))
aList.insert(3, "hhh")
print(aList)
aList.pop(-1)
print(aList)
aList.reverse()
print(aList)
|
d86868b1c56b0028c414efb13f74ade56c5ddb99 | Hassan-Sher/DS-Labs | /Quick Sort.py | 485 | 3.921875 | 4 | def quicksort(A,low,high):
if low < high:
p = partition(A,low,high)
quicksort(A,low,p-1)
quicksort(A,p+1,high)
def partition(A,low,high):
i = low-1
pivot = A[high]
for j in range(low,high):
if A[j] <= pivot:
i = i+1
A[i],A[j] = A[j],A[i]
A[i+1],A[high] = A[high],A[i+1]
return i+1
A = [5,3,4,1,2,6,7]
print("Original Array",A)
quicksort(A,0,len(A)-1)
print("Sorted Array",A)
|
2d06b1366e0745be87a9ad997f745d6235ea5b3f | jbelo-pro/CoffeeMachine | /Problems/Game over/task.py | 229 | 3.671875 | 4 | scores = input().split()
# put your python code here
i = 0
c = 0
for score in scores:
if score == 'C':
c += 1
else:
i += 1
if i == 3:
break
print('You won' if i < 3 else 'Game over')
print(c)
|
e342707bbb1ff14024589b2a8944cdf8df57124c | kumbhani/pingpong | /solution_bitmapXOR2.py | 1,170 | 4.0625 | 4 | '''
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
'''
class Solution(object):
def missingNumber(self, nums):
'''
:type nums: List[int]
:rtyp: int
There are two approaches as hinted by the tags on leetcode.
1. Math - Missing number would be the difference between
the sum of n number minus sum of elements in in nums array
2. Bit Manipulation - Using XOR, we set x1 as an accumulator like you mentioned for the elements in nums
then x2 is set to 1 and then ran all the way to n. The remaining bits in x1 and x2 when XORed gives the
missing number
'''
if not nums:
return 0
x1 = nums[0]
x2 = 1
n = len(nums)
for i in xrange(1, n):
x1 ^= nums[i]
for i in xrange(2, n+1):
x2 ^= i
return (x1 ^ x2)
|
619ec1b6a2c44dceffe8f2c9497f6e6193dd1686 | dinabseiso/HW10 | /seventeen2.py | 4,812 | 3.671875 | 4 | #! usr/bin/env python
# seventeen2.py
### Import here
from random import randint
### Body
def draws(file):
with open(file) as fin1:
future_draws = fin1.readlines()
return future_draws
def play_game(file):
"""This function initiates the game. For this particular game, there will be
17 marbles in a jar. Turns between the user and the CPU are taken in grabbing
marbles from the jar, and this will continue for as long as there are marbles
in the jar.
Because the user always goes first, a value is returned for the number of
marbles left after the user grabs 1-3 marble/s. The values have already been
read from a file in a variable future_draws, which recognizes line breaks.
An empty list winner is instantiated for future appending/record-keeping of
who has won.
Each line (aka game) in future_draws is read as a string, including commas. Instead, a list
of draws would be prefered, so that we could step through the user choices for
as long as there are marbles in the jar.
There is a check for whether there are no marbles remaining, and if so the game
ends and the computer wins. If not, the CPU takes its turn. If the CPU grabs the
last marble, then the user wins. If not, then...
Repeat until there are no marbles left.
"""
winner = []
future_draws = draws(file)
for line in future_draws:
marbles_in_jar = 17
marbles_in_jar_after_user = 17
line_string = line.split(",")
while marbles_in_jar > 0 and marbles_in_jar_after_user > 0:
for draw in line_string:
marbles_in_jar_after_user = your_turn(marbles_in_jar, draw)
if marbles_in_jar_after_user == 0:
winner.append("P2")
break
marbles_in_jar = cpu_turn(marbles_in_jar_after_user)
if marbles_in_jar == 0:
winner.append("P1")
break
results(future_draws, winner)
def your_turn(marbles_in_jar, future_draws):
""" This was not entirely necessary, but because I already implemented it previously
I figured it would be good to have here as well. It takes in the input from the
user explicitly and verifies that the input is valid. If it is not, it iterates again.
Returns the number of marbles left in the jar for the CPU to evaluate.
"""
your_turn = True
while your_turn == True:
for draws in future_draws:
draws = draws.split(",")
for grab in draws:
your_turn, grabbed = check_valid_input(grab, marbles_in_jar)
marbles_in_jar -= grabbed
return marbles_in_jar
def cpu_turn(marbles_in_jar):
""" The computer grabs a random integer between 1 and 3, unless taking that quantity
is impossible (for example, attempting to grab 3 marbles when only 2 exist). In that
case, the CPU will take only two.
It is printed to the console the number of marbles the CPU took. The number of marbles
remaining is then computed, printed, and returned for evaluating into the next turn of
the user.
"""
computer_grab = randint(1, min(3, marbles_in_jar))
marbles_in_jar -= computer_grab
return marbles_in_jar
def check_valid_input(grabbed, marbles_in_jar):
""" This function checks a few possible inputs that would not allow the script to run
as it should. For example, if the input is not an integer value, if the user tries to
grab more than three marbles, if the user tries to grab no marbles, and if the user
tries to grab more marbles than there are in the jar, they will be asked to try again.
Something additionally covered here is for the number of marbles grabbed to equal the
number of marbles remaining if the predetermined grab-value is more than the number
of marbles left in the jar.
Until proper input is received, the loop will continue (see your_turn() and cpu_turn()
for the while loop that contains this function.)
"""
try:
grabbed = int(grabbed)
if grabbed > 3:
raise ValueError("Don't be greedy! Try again!")
elif grabbed == 0:
raise ValueError("Nice try. Try again!")
elif marbles_in_jar - grabbed < 0:
grabbed = marbles_in_jar
except Exception:
print("Sorry, that is not a valid option. Try again! ")
return True, grabbed
your_turn = False
return your_turn, grabbed
def results(future_draws, winner):
with open("seventeen2_output.txt", "w") as fin2:
game_number = 1
winner_index = 0
for options in future_draws:
options = options.strip()
options = options.replace(",","-")
the_winner = winner[winner_index]
fin2.write("Game #{}. Play sequence: {}. Winner: {} \n".format(game_number, options, the_winner))
game_number += 1
winner_index += 1
player_one_wins = winner.count("P1")
player_two_wins = winner.count("P2")
fin2.write("Player 1 won {} times; Player 2 won {} times.".format(player_one_wins, player_two_wins))
### Define main()
def main():
play_game("seventeen2_input.txt")
## Boilerplate
if __name__ == "__main__":
main() |
e25aa025141e8d1fabd276df4054e0bd7a348f1c | jaychan09070339/Python_Basic | /practice_1/ABCD_Z.py | 132 | 3.828125 | 4 | #!/usr/bin/python
word="A"
num=ord(word)
count=0
while count<=25:
print(word,end="")
num+=1
word=chr(num)
count+=1
|
402794a866d092d623be988b2358ed1285e7c26b | aambrioso1/Effective_Python | /Item42.py | 5,410 | 3.875 | 4 | #!/usr/bin/env PYTHONHASHSEED=1234 python3
"""
Item 42: Prefer Public Attributes Over Private Ones
"""
# Reproduce book environment
import random
random.seed(1234)
import logging # Used for exception handling
from pprint import pprint
from sys import stdout as STDOUT
# Write all output to a temporary directory
import atexit
import gc
import io
import os
import tempfile
TEST_DIR = tempfile.TemporaryDirectory()
atexit.register(TEST_DIR.cleanup)
# Make sure Windows processes exit cleanly
OLD_CWD = os.getcwd()
atexit.register(lambda: os.chdir(OLD_CWD))
os.chdir(TEST_DIR.name)
def close_open_files():
everything = gc.get_objects()
for obj in everything:
if isinstance(obj, io.IOBase):
obj.close()
atexit.register(close_open_files)
"""
There are only two types of visibility in Python for class attributes: public and private
Some things to remember:
Private atrributes are not rigorously enforced.
Use the documentation for protected fields rather than trying to control access with private
attributes.
Use private attributes only to control naming conflicts.
Document protected fields carefully.
"""
# Example 1: Indicate a private field by prefixed it with a double underscore.
class MyObject:
def __init__(self):
self.public_field = 5
self.__private_field = 10
def get_private_field(self):
return self.__private_field
# Example 2: Public attributes can be directly accessed by anyone
foo = MyObject()
assert foo.public_field == 5
# Example 3: Note that the foo class has access to its own private field
assert foo.get_private_field() == 10
# Example 4: You cannot access a private field directly from outside the class.
try:
foo.__private_field
except:
logging.exception('Expected')
else:
assert False
# Example 5
class MyOtherObject:
def __init__(self):
self.__private_field = 71
@classmethod
def get_private_field_of_instance(cls, instance):
return instance.__private_field
bar = MyOtherObject()
assert MyOtherObject.get_private_field_of_instance(bar) == 71
# Example 6: A subclass cannot access its parent class's private fields
try:
class MyParentObject:
def __init__(self):
self.__private_field = 71
class MyChildObject(MyParentObject):
def get_private_field(self):
return self.__private_field
baz = MyChildObject()
baz.get_private_field()
except:
logging.exception('Expected')
else:
assert False
# Example 7: Note that the reason that the subclass access to a private field fails
# is that the field is prefix with the name of the class it was created in.
# Understanding this makes it is to access a parent class's private field if you need to.
assert baz._MyParentObject__private_field == 71
# Example 8: Shows how the private fiels attributes are stored
print(baz.__dict__)
# Example 9
class MyStringClass:
def __init__(self, value):
self.__value = value
def get_value(self):
return str(self.__value)
foo = MyStringClass(5)
assert foo.get_value() == '5'
# Example 10
class MyIntegerSubclass(MyStringClass):
def get_value(self):
return int(self._MyStringClass__value)
foo = MyIntegerSubclass('5')
assert foo.get_value() == 5
# Example 11
class MyBaseClass:
def __init__(self, value):
self.__value = value
def get_value(self):
return self.__value
class MyStringClass(MyBaseClass):
def get_value(self):
return str(super().get_value()) # Updated
class MyIntegerSubclass(MyStringClass):
def get_value(self):
return int(self._MyStringClass__value) # Not updated
# Example 12: Problem with private field renamed by subclasses.
try:
foo = MyIntegerSubclass(5)
foo.get_value()
except:
logging.exception('Expected')
else:
assert False
# Example 13
class MyStringClass:
def __init__(self, value):
# This stores the user-supplied value for the object.
# It should be coercible to a string. Once assigned in
# the object it should be treated as immutable.
self._value = value
def get_value(self):
return str(self._value)
class MyIntegerSubclass(MyStringClass):
def get_value(self):
return self._value
foo = MyIntegerSubclass(5)
assert foo.get_value() == 5
# Example 14: Use private fields only when you are concerned that names will conflict because a
# particular name is commonly used.
class ApiClass:
def __init__(self):
self._value = 5
def get(self):
return self._value
class Child(ApiClass):
def __init__(self):
super().__init__()
self._value = 'hello' # Conflicts
# Example 15: Use the double underscore and a private attribute to avoid a nameing conflict.
# This can be useful when working with unknown API's and common using common names.
a = Child()
print(f'{a.get()} and {a._value} should be different')
class ApiClass:
def __init__(self):
self.__value = 5 # double underscore
def get(self):
return self.__value
class Child(ApiClass):
def __init__(self):
super().__init__()
self._value = 'hello' # Conflicts
a = Child()
print(f'{a.get()} and {a._value} should be different')
# We can access the "private" attribute directly.
print(f'a._ApiClass__value is {a._ApiClass__value} just like a.get()!') |
46c3db3ca5a7bc31051b203406aaaabb3fd1eca0 | NoGroceries/python2021 | /tutorial/numbers.py | 457 | 4.09375 | 4 | # Division (/) always returns a float
print(17 / 3)
print(17 // 3) # 商
print(17 % 3) # 余数
print(4 * 3.75 - 1) # 混合类型时,会将int转换为float
# In interactive mode, the last printed expression is assigned to the variable _
# >>> 8/5
# 1.6
# >>> print(_)
# 1.6
# Python strings cannot be changed — they are immutable.
language = "Python"
print(language[0])
language[0] = 'J' # TypeError: 'str' object does not support item assignment
|
f2f47058972d2b0616d9ddec2133bd5efc334d46 | NiuNiu-jupiter/Leetcode | /137. Single NumberII.py | 1,965 | 3.75 | 4 | """
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99
数组为[2,2,2,3],一共有四个元素,进行四次循环。
第一次循环,b=(0000^0010)&1111=0010=2,a=(0000^0010)&1101=0000=0
第二次循环,b=(0010^0010)&1111=0000=0,a=(0000^0010)&1111=0010=2
第三次循环,b=(0000^0010)&1101=0000=0,a=(0010^0010)&1111=0000=0
第四次循环,b=(0000^0011)&1111=0011=3,a=(0000^0011)&1100=0000=0
某个值nums[i]第一次出现的时候,b把它记录了下来,这时候a=0;接着第二次出现的时候,b被清空了,记录到了a里面;接着第三次出现的时候,b和a都被清空了。
如果一个数组中,所有的元素除了一个特殊的只出现一次,其他都出现了三次,那么根据我们刚刚观察到的结论,最后这个特殊元素必定会被记录在b中。
那么这次我们同样利用异或运算,看能不能设计出一种变换的方法让a和b按照上述变换规则,进行转换。
b=0时碰到x,就变成x;b=x时再碰到x,就变成0,这个不就是异或吗?所以我们也许可以设计b=b xor x。
但是当b=0时再再碰到x,这时候b还是要为0,但这时候不同的是a=x,而前两种情况都是a=0。所以我们可以设计成:b=(b xor x)&~a
同样道理,我们可以设计出:a=(a xor x)&~b
"""
def singleNumber(nums):
a,b = 0, 0
for num in nums:
b = (b ^ num) & ~a # when the third nums[i] coming, b need to be 1 again, but at this time previous nums[i] in a, so & ~a can set b to 1.
a = (a ^ num) & ~b
return b
|
1a0b2059b961d67244c732ea18fbc0c2102e22c0 | trevornagaba/titanic_spyder | /app.py | 7,373 | 3.5625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
# %matplotlib inline
# Import train data
train_df=pd.read_csv("data/train.csv")
train_df.head()
# Determine percentage of missing data
def missingdata(data):
total = data.isnull().sum().sort_values(ascending = False)
percent = (data.isnull().sum()/data.isnull().count()*100).sort_values(ascending = False)
ms=pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
ms= ms[ms["Percent"] > 0]
f,ax =plt.subplots(figsize=(8,6))
plt.xticks(rotation='90')
fig=sns.barplot(ms.index, ms["Percent"],color="green",alpha=0.8)
plt.xlabel('Features', fontsize=15)
plt.ylabel('Percent of missing values', fontsize=15)
plt.title('Percent missing data by feature', fontsize=15)
return ms
missingdata(train_df)
def cleandata(train_df, param1, param2, param_drop):
# Fill empty fields
# Find a way to automate the selection of these empty fields
train_df[param1].fillna(train_df[param1].mode()[0], inplace = True)
train_df[param2].fillna(train_df[param2].median(), inplace = True)
drop_column = [param_drop]
train_df.drop(drop_column, axis=1, inplace = True)
print('check the nan value in data')
print(train_df.isnull().sum())
dataset = train_df
# Create a new feature Familysize based on number if siblings and parch
dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1
# Define function to extract titles from passenger names
import re
def get_title(name):
title_search = re.search(' ([A-Za-z]+)\.', name)
# If the title exists, extract and return it.
if title_search:
return title_search.group(1)
return ""
# Create a new feature Title, containing the titles of passenger names
dataset['Title'] = dataset['Name'].apply(get_title)
# Group all non-common titles into one single grouping "Rare"
dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col','Don',
'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')
dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')
dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')
# Group age and fare features into bins
dataset['Age_bin'] = pd.cut(dataset['Age'], bins=[0,14,20,40,120], labels=['Children','Teenage','Adult','Elder'])
dataset['Fare_bin'] = pd.cut(dataset['Fare'], bins=[0,7.91,14.45,31,120], labels=['Low_fare','median_fare', 'Average_fare','high_fare'])
# Drop columns
traindf=train_df
drop_column = ['Age','Fare','Name','Ticket']
dataset.drop(drop_column, axis=1, inplace = True)
drop_column = ['PassengerId']
traindf.drop(drop_column, axis=1, inplace = True)
traindf = pd.get_dummies(traindf, columns = ["Sex","Title","Age_bin","Embarked","Fare_bin"],
prefix=["Sex","Title","Age_type","Em_type","Fare_type"])
return traindf
traindf = cleandata(train_df, 'Embarked', 'Age', 'Cabin')
# Plot heat to illustrate correlation and identify unessential features
sns.heatmap(traindf.corr(),annot=True,cmap='RdYlGn',linewidths=0.2)
#data.corr()-->correlation matrix
fig=plt.gcf()
fig.set_size_inches(20,12)
plt.show()
# Import sklearn and split data into train and test set
from sklearn.model_selection import train_test_split #for split the data
from sklearn.metrics import accuracy_score #for accuracy_score
from sklearn.model_selection import KFold #for K-fold cross validation
from sklearn.model_selection import cross_val_score #score evaluation
from sklearn.model_selection import cross_val_predict #prediction
from sklearn.metrics import confusion_matrix #for confusion matrix
all_features = traindf.drop("Survived",axis=1)
Targeted_feature = traindf["Survived"]
# X_train,X_test,y_train,y_test = train_test_split(all_features,Targeted_feature,test_size=1,random_state=42)
# X_train.shape,X_test.shape,y_train.shape,y_test.shape
# Fit and test data
from sklearn.ensemble import RandomForestClassifier
#model = RandomForestClassifier(criterion='gini', n_estimators=700,
# min_samples_split=10,min_samples_leaf=1,
# max_features='auto',oob_score=True,
# random_state=1,n_jobs=-1)
model = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
max_depth=None, max_features='auto', max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=800,
n_jobs=None, oob_score=False, random_state=None,
verbose=0, warm_start=False)
model.fit(all_features, Targeted_feature)
#prediction_rm=model.predict(X_test)
#print('--------------The Accuracy of the model----------------------------')
#print('The accuracy of the Random Forest Classifier is', round(accuracy_score(prediction_rm,y_test)*100,2))
#kfold = KFold(n_splits=10, random_state=22) # k=10, split the data into 10 equal parts
#result_rm=cross_val_score(model,all_features,Targeted_feature,cv=10,scoring='accuracy')
#print('The cross validated score for Random Forest Classifier is:',round(result_rm.mean()*100,2))
#y_pred = cross_val_predict(model,all_features,Targeted_feature,cv=10)
#sns.heatmap(confusion_matrix(Targeted_feature,y_pred),annot=True,fmt='3.0f',cmap="summer")
#plt.title('Confusion_matrix', y=1.05, size=15)
# Import data
test_df=pd.read_csv("data/test.csv")
test_df.head()
missingdata(test_df)
testdf = cleandata(test_df, 'Fare', 'Age', 'Cabin')
# Plot heat to illustrate correlation and identify unessential features
sns.heatmap(testdf.corr(),annot=True,cmap='RdYlGn',linewidths=0.2)
#data.corr()-->correlation matrix
fig=plt.gcf()
fig.set_size_inches(20,12)
plt.show()
prediction_rm=model.predict(testdf)
np.savetxt("submission.csv", prediction_rm, delimiter=",")
# Optimizing the model using GridSearch and the RandomForest Classifier
from sklearn.model_selection import GridSearchCV
# Random Forest Classifier Parameters tunning
model = RandomForestClassifier()
n_estim=range(100,1000,100)
## Search grid for optimal parameters
param_grid = {"n_estimators" :n_estim}
model_rf = GridSearchCV(model,param_grid = param_grid, cv=5, scoring="accuracy", n_jobs= 4, verbose = 1)
model_rf.fit(all_features, Targeted_feature)
# Best score
print(model_rf.best_score_)
#best estimator
model_rf.best_estimator_
#model = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
# max_depth=None, max_features='auto', max_leaf_nodes=None,
# min_impurity_decrease=0.0, min_impurity_split=None,
# min_samples_leaf=1, min_samples_split=2,
# min_weight_fraction_leaf=0.0, n_estimators=800,
# n_jobs=None, oob_score=False, random_state=None,
# verbose=0, warm_start=False)
#
#model.fit(all_features, Targeted_feature) |
535e4bea1b336ba5c31d7a5e1930601de1e8a519 | prakash4531/Python_basics2 | /11_Text_Alignments.py | 1,003 | 4.3125 | 4 |
# -*- coding: utf-8 -*-
"""
Problem No: 11 (Text Alignments)
"User enter the text (0 < len < 20) and alignment (left, center, right).
print the aligned out put and by adding - to make alignment"
Formula:
-Left:
>>> print 'Praveen'.ljust(width,'-')
Praveen----------
-Right
>>> print 'Praveen'.rjust(width,'-')
----------Praveen
-Center
>>> print 'Praveen'.center(width,'-')
-----Praveen-----
Example:
Input:
String: Praveen
Alignment: center
output: -----Praveen-----
"""
string = input('Enter your text here: ')
alignment = input('Enter your alignment here: ')
print("Thea original string is : \n", string, "\n")
width = 20
left = string.ljust(width, '-')
right = string.rjust(width, '-')
center = string.center(width, '-')
if alignment == 'left':
print(left)
elif alignment == 'right':
print(right)
elif alignment == 'center':
print(center)
else:
print("Please write the alignment input from left,right and center: ")
|
a882d4466d05b55b925e04735602dc860ba6787a | harinisridhar1310/Guvi | /fibonnaic.py | 124 | 3.671875 | 4 | #harini
a=int(input())
first=0
second=1
for i in range(0,a):
print(second)
third=first+second
first=second
second=third
|
19576cdb776a951310d6625b07473defb0d5e77e | JaredLGillespie/OpenKattis | /Python/boundingrobots.py | 755 | 3.828125 | 4 | # https://open.kattis.com/problems/boundingrobots
def walk_think(x, y, c, v):
if c == 'u':
return x, y + v
if c == 'r':
return x + v, y
if c == 'd':
return x, y - v
return x - v, y
def walk_actual(w, l, x, y, c, v):
x, y = walk_think(x, y, c, v)
return min(max(0, x), w - 1), min(max(0, y), l - 1)
w, l = map(int, input().split())
while w != 0 and l != 0:
n = int(input())
tx, ty, ax, ay = 0, 0, 0, 0
for _ in range(n):
c, v = input().split()
tx, ty = walk_think(tx, ty, c, int(v))
ax, ay = walk_actual(w, l, ax, ay, c, int(v))
print('Robot thinks %s %s' % (tx, ty))
print('Actually at %s %s' % (ax, ay))
print()
w, l = map(int, input().split())
|
5c9a63b08723cad8c03ef299631ae75942f60b4e | hdjsjyl/LeetcodeFB | /29.py | 1,324 | 3.78125 | 4 | """
29. Divide Two Integers
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = truncate(-2.33333..) = -2.
"""
## binary search, TC: O(logn)
## bit operation: << means *2, >> means /2
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend == 0:
return 0
flag = 1
if dividend < 0:
flag *= -1
dividend *= -1
if divisor < 0:
flag *= -1
divisor *= -1
ant = 0
while dividend >= divisor:
cnt = 1
while dividend >= divisor << cnt:
cnt += 1
ant += 1 << cnt - 1
dividend -= divisor << cnt - 1
res = ant * flag
if res > 2 ** 31 - 1:
return 2 ** 31 - 1
elif res < -1 * 2 ** 31:
return -1 * 2 ** 31
return ant * flag
|
8d1239b00f976c1bf180daf2d41b4a5186703eba | blue0712/blue | /demo25.py | 553 | 3.78125 | 4 | day_of_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
lengthArray = []
for d in day_of_week:
lengthArray.append(len(d))
print(lengthArray)
print([len(d) for d in day_of_week])
print([d for d in day_of_week if len(d) > 6])
x1, x2, x3, x4, x5, x6, x7 = day_of_week
print(x1, x3, x5)
print(x2, x4, x6, x7)
number_list = [3, 1, 4, 1, 5, 9, 26, 83, 42, 0, 100, 83, 99]
over30 = sorted(d**2 for d in number_list if d>30)
print(over30)
under50 = sorted((e for e in number_list if e < 50),reverse=True)
print(under50) |
13d9c525a9785751ba2978c7cf6ef943e4fab247 | sethdeane16/projecteuler | /027.py | 665 | 3.5 | 4 | import resources.pef as pef
import time
"""
https://projecteuler.net/problem=27
8.877437829971313
"""
def main():
maxn = 0
answer = 0
for a in range(-1000,1001):
for b in range(-1000,1000):
streak = 0
for n in range(80):
if pef.is_prime(n**2 + (n*a) + b):
streak += 1
else:
break
if maxn <= n:
maxn = n
answer = a * b
return answer
if __name__ == "__main__":
start_time = time.time()
answer = main()
end_time = time.time()
pef.answer(answer, end_time - start_time)
|
7d9f770c4c89d81a98cd3af70b8811948e573a8a | sreeharisreddy/MachineLearning | /RandomForestClassificationExample.py | 2,059 | 3.53125 | 4 | # Loading the library with the iris dataset
from sklearn.datasets import load_iris
# Loading scikit's randomforest classifier library
from sklearn.ensemble import RandomForestClassifier
#loading pandas
import pandas as pd
#loading numpy
import numpy as np
#seeting random seed
np.random.seed(0)
#creating an object called iris with the iris data
iris = load_iris()
#print(iris)
#craeting a data frame with foure featur variables
df = pd.DataFrame(iris.data,columns=iris.feature_names)
#df.head()
#Adding a new column for the species name
df['species'] = pd.Categorical.from_codes(iris.target,iris.target_names)
#Creating the Test and Train data randomly
df['is_train'] = np.random.uniform(0,1,len(df)) <= .75
df.head()
#Creating adataframe with test rows and training rows
train,test = df[df['is_train']==True], df[df['is_train']==False]
#Show the number of observations for the test and training dataframes
print('Numbe of observations in the training dataset:',len(train))
print('Numbe of observations in the test dataset:',len(test))
#Creating the list of the feature column's names
features = df.columns[:4]
print(features)
#Converting each species into digits
y=pd.factorize(train['species'])[0]
#Creating Random ForestClassifier
clf = RandomForestClassifier(n_jobs=2,random_state=0)
#Training the classifier
clf.fit(train[features],y)
#Applying the trained classifier to the test
clf.predict(test[features])
#Viewing the predicted probabilities of the first 10 observations
clf.predict_proba(test[features])[0:10]
#mapping names for thr plans for each plant class
preds = iris.target_names[clf.predict(test[features])]
#view thr predicted species for the first five observations
preds[0:5]
#view the Actual species for the five first observation
test['species'].head()
#creating confusion matrix
pd.crosstab(test['species'],preds,rownames=['Actual Species'],colnames=['Predicted Species'])
#Predicting for new dataset
preds = iris.target_names[clf.predict( [[9.0,3.6,7.4,7.0],[5.0,3.6,1.4,2.0]])]
preds |
9beea0207e8a6961b8c014f83e6dbeac51ba0388 | adjmunro/origin-srs | /data/scripts/AddEntry.py | 3,160 | 3.71875 | 4 | class WordList:
def __init__(self, filename, n_cols):
self.filename = filename + '.txt' if '.txt' not in filename else filename
self.n_cols = n_cols
self.elements = {}
self.other_files = {}
self.other_keys = []
self.read()
self.add()
def add(self):
n = 0
while n < self.n_cols:
while n == 0:
key = input(f'(key) 0: ')
if key == '':
n += 1
continue
if key in self.elements:
v = input(
f"Key '{key}' already exists in this file!\n{key} -> {self.elements[key]}\nEnter a new value (single column), or 'x' to cancel.")
if v != 'x':
self.elements[key] = [v]
continue
if key in self.other_keys:
filename, value = self.find(key)
if input(
f"Key '{key}' found in '{filename}'!\n{key} -> {value}\nEnter 'y' if you still wish to add this key.") != 'y':
continue
self.elements.update({key: []})
for key in self.elements.keys():
if '' in self.elements[key]:
self.elements[key].remove('')
if len(self.elements[key]) >= self.n_cols - 1:
continue
elem = input(f'({n}) [{key}] -> ')
if elem == '':
n = self.n_cols
break
self.elements[key].append(elem.replace(',', ';'))
n += 1
self.write()
def find(self, key):
for f, i in self.other_files.items():
if key in i:
return (f, i[key])
return None
def read(self):
if os.path.exists(self.filename):
print('Adding to existing file')
with open(self.filename, 'r', encoding='UTF-8') as f:
temp = [i.split(',') for i in f.read().split('\n') if i != '']
self.elements = {i[0]: i[1:] for i in temp}
for filename in os.listdir():
if filename == self.filename or '.txt' not in filename:
continue
print(f'Scanning {filename}')
with open(filename, 'r', encoding='UTF-8') as f:
temp = [i.split(',') for i in f.read().split('\n') if i != '']
self.other_files.update({filename: {i[0]: i[1:] for i in temp}})
self.other_keys += self.other_files[filename].keys()
def write(self):
with open(self.filename, 'w', encoding='UTF-8') as f:
f.write('\n'.join([','.join([k] + v) for k, v in self.elements.items()]))
if __name__ == "__main__":
import os
filename = input('Enter filename: ')
while filename == '':
filename = input('Enter filename: ')
n_cols = input('Enter max number of columns: ')
while not n_cols.isdigit():
print(f'"{n_cols}" is invalid!')
n_cols = input('Enter max number of columns: ')
WordList(filename, int(n_cols))
|
9afc83208c7522872bda29d23ca1cd6e1d848b98 | Zerpha-Rova/draw | /line1.py | 333 | 3.65625 | 4 | import turtle as td
from turtle import Turtle as turt
z = -1
wn = td.Screen()
bob = turt()
def line(a,b): ###a=(x1, y1) b=(x2,y2)
bob.penup()
bob.goto(a)
bob.pendown()
bob.goto(b)
bob.penup()
line((70,-50),(110,55))
q = 66
w = (q, q*z)
v = (q*z, q)
line(w,v)
'''u = (((10,100*z),bob.ycor()), (w))
line(u)'''
wn.mainloop() |
d5dcc719a6146820a70050797f69c02416abb223 | simonada/AI-Projects | /ANN/Networks.py | 14,787 | 3.546875 | 4 | import numpy as np
import random
verbose = False
monitor_test = True
l1_regularization = False
class Network(object):
def __init__(self, sizes, activationFcns, test_data):
"""
:param: sizes: a list containing the number of neurons in the respective layers of the network.
See project description.
"""
self.num_layers = len(sizes)
self.sizes = sizes
self.activation_functions = activationFcns
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x)
for x, y in zip(sizes[:-1], sizes[1:])]
self.test_data = test_data
def inference(self, x):
"""
:param: x: input of ANN
:return: the output of ANN with input x, a 1-D array
"""
# print('Original input', x)
# print('Number of layers', len(self.weights))
L = len(self.weights)
W = self.weights
B = self.biases
activation = x
for layer in range(1, L + 1):
# print('Layer Input', input_z.shape)
# flatten the dimensions of the biases, otherwise the sum is not pointwise
hidden_layer = (np.dot(W[layer - 1], activation)) + B[layer - 1] # .ravel()
activation = self.activation_functions[layer](hidden_layer)
if verbose:
print('Weights', W[layer - 1], 'biases', B[layer - 1])
print('Input after weighting', hidden_layer.shape, hidden_layer)
print('Input after activation', activation)
# print('Final output', input_z)
return activation
def training(self, trainData, T, n, alpha, validationData=None, lmbda = 0):
"""
trains the ANN with training dataset using stochastic gradient descent
:param trainData: a list of tuples (x, y) representing the training inputs and the desired outputs.
:param T: total number of iteration
:param n: size of mini-batches
:param alpha: learning rate
"""
self.N = len(trainData) # needed for Regularization
epochs = []
training_accuracy = []
validation_accuracy = []
max_validation_score = 0
count_epochs_without_improvement = 0
testing_accuracy = []
for iterations in range(T):
print('Epoch', iterations)
epochs.append(iterations)
batches = self.splitTrainData(trainData, n)
print('Batches', len(batches))
# Epoch = iteration over the whole data set
for batch in batches:
self.updateWeights(batch, alpha, lmbda)
if validationData:
val_accuracy = self.evaluate(validationData)
print("Performance on validation data: {0} / {1} ({2})".format(val_accuracy, len(validationData),
val_accuracy / len(validationData)))
validation_accuracy.append((val_accuracy / len(validationData) * 100))
if val_accuracy > max_validation_score:
max_validation_score = val_accuracy
count_epochs_without_improvement = 0
else:
count_epochs_without_improvement += 1
if count_epochs_without_improvement == 10:
print('Early stopping after ten epochs no improvement in accuracy.')
print('Max accuracy', max_validation_score)
print('Epochs', epochs)
return validation_accuracy, training_accuracy, testing_accuracy
training_accuracy.append((self.evaluate(trainData) / len(trainData)) * 100)
if monitor_test:
testing_accuracy.append((self.evaluate(self.test_data) / len(self.test_data)) * 100)
# print()
# print('Performance statistics')
# print('Epochs', epochs)
# print('Training acc')
# print(training_accuracy)
# print('Validation acc')
# print(validation_accuracy)
return validation_accuracy, training_accuracy, testing_accuracy
def splitTrainData(self, trainData, n):
random.shuffle(trainData)
batches = [trainData[k:k + n] for k in range(0, len(trainData), n)]
return batches
def updateWeights(self, batch, alpha, lmbda = 0):
"""
called by 'training', update the weights and biases of the ANN
:param batch: mini-batch, a list of pair (x, y)
:param alpha: learning rate
"""
biases_aggregated_updates = []
weights_aggregated_updates = []
batch_size = len(batch)
# 1. Prepare to aggregate the gradients computed for each sample in the mini-batch
# aggregated into an list of array of the same dimensions as the original weights and biases
# initialized with zeros
for w in self.weights:
weights_aggregated_updates.append(np.zeros(w.shape))
for b in self.biases:
biases_aggregated_updates.append(np.zeros(b.shape))
for x, y in batch:
delta_nabla_w, delta_nabla_b = self.backprop(x, y)
# zip them together to be able to iterate over them pair wise and update the W and B layer by layer
weights_pairs = zip(weights_aggregated_updates, delta_nabla_w)
biases_pairs = zip(biases_aggregated_updates, delta_nabla_b)
biases_aggregated_updates = [batch_bias + sample_bias_delta for batch_bias, sample_bias_delta in
biases_pairs]
weights_aggregated_updates = [batch_weigths + sample_weights_delta for batch_weigths, sample_weights_delta
in weights_pairs]
# Final Batch update
weights_final_pairs = zip(self.weights, weights_aggregated_updates)
biases_final_pairs = zip(self.biases, biases_aggregated_updates)
updated_weights = []
updated_biases = []
# Average the updates by dividing the learning rate by the number of samples in the mini batch
alpha = (alpha / batch_size)
for old_weights, batch_gradients_weights in weights_final_pairs:
if l1_regularization:
#print('Performing L1 regularization:')
regularized_weights = old_weights - alpha * (lmbda/self.N)*np.sign(old_weights) # if reg term is zero, the results are the same as if no reg. is applied
else:
regularized_weights = old_weights * (1 - alpha * (lmbda/self.N)) # if reg term is zero, the results are the same as if no reg. is applied
updated_weights.append(regularized_weights - alpha * batch_gradients_weights)
for old_biases, batch_gradients_biases in biases_final_pairs:
updated_biases.append(old_biases - alpha * batch_gradients_biases)
self.weights = updated_weights
self.biases = updated_biases
def backprop(self, x, y):
"""
called by 'updateWeights'
:param: (x, y): a tuple of batch in 'updateWeights'
:return: a tuple (nablaW, nablaB) representing the gradient of the empirical risk for an instance x, y
nablaW and nablaB follow the same structure as self.weights and self.biases
"""
W = self.weights
nr_layers = len(W)
# Data structure for the final outputs
gradients_weights = []
gradients_biases = []
for w in self.weights:
gradients_weights.append(np.zeros(w.shape))
for b in self.biases:
gradients_biases.append(np.zeros(b.shape))
layers_activations, layers_outputs = self.forward_pass(x)
# First step get loss derivatives of the final layer
# Matrix to store the deltas for each layer, should have a shape dependent on
# the number of HL and the number of nodes in each HL
prediction = layers_activations[-1]
last_layer_outputs = layers_outputs[-1]
if self.activation_functions[-1].__name__ == "sigmoid":
last_layer_output_derivatives = sigmoid_prime(last_layer_outputs)
elif self.activation_functions[-1].__name__ == "tanh":
last_layer_output_derivatives = tanh_prime(last_layer_outputs)
elif self.activation_functions[-1].__name__ == "relu":
last_layer_output_derivatives = relu_prime(last_layer_outputs)
elif self.activation_functions[-1].__name__ == "leaky_relu":
last_layer_output_derivatives = leaky_relu_prime(last_layer_outputs)
last_layer_delta = dSquaredLoss(prediction, y) * last_layer_output_derivatives
if verbose:
print('Squared loss derivatives', dSquaredLoss(prediction, y))
print('Z last layer derivatives', last_layer_output_derivatives)
print('Deltas last layer', last_layer_delta)
# Next compute the derivatives w.r.t. to the errors at each layer, i.e. by how much does each node contribute
# logic for delta = weights of layer above * delta of layer above dot sigmoid derivative of node output?
layers_deltas = np.zeros(nr_layers, dtype=object)
layers_deltas[-1] = last_layer_delta
# Compute the deltas for each layer based on the deltas of the layer above it (iterate backwards)
for layer in range(nr_layers - 2, -1, -1):
w_previous_layer = W[layer + 1]
deltas_previous_layer = layers_deltas[layer + 1]
error_contributions_per_node = np.dot(w_previous_layer.T, deltas_previous_layer)
if self.activation_functions[layer + 1].__name__ == "sigmoid":
slope_derivatives_per_node = sigmoid_prime(layers_outputs[layer])
elif self.activation_functions[layer + 1].__name__ == "tanh":
slope_derivatives_per_node = tanh_prime(layers_outputs[layer])
elif self.activation_functions[layer + 1].__name__ == "relu":
slope_derivatives_per_node = relu_prime(layers_outputs[layer])
elif self.activation_functions[layer + 1].__name__ == "leaky_relu":
slope_derivatives_per_node = leaky_relu_prime(layers_outputs[layer])
layer_delta = error_contributions_per_node * slope_derivatives_per_node
layers_deltas[layer] = layer_delta
# Final step, computing the deltas for weights updates at each layer
for i in range(nr_layers):
# weights
activation = layers_activations[i]
delta = layers_deltas[i]
gradient_w = np.dot(delta, activation.T)
gradients_weights[i] = gradient_w
gradients_biases = layers_deltas
return (gradients_weights, gradients_biases)
def forward_pass(self, x):
W = self.weights
B = self.biases
L = len(W)
# print('---Forward pass---')
activation = x
activations_array = [x] # the first activation is the input itself
function_outputs_array = []
for layer in range(1, L + 1):
hidden_layer_output = (np.dot(W[layer - 1], activation)) + B[layer - 1] # .ravel()
function_outputs_array.append(hidden_layer_output)
activation = self.activation_functions[layer](hidden_layer_output)
activations_array.append(activation)
return activations_array, function_outputs_array
def evaluate(self, data):
"""
:param data: dataset, a list of tuples (x, y) representing the training inputs and the desired outputs.
:return: the number of correct predictions of the current ANN on the input dataset.
The prediction of the ANN is taken as the argmax of its output
"""
accuracy = 0
count = 0
for x, y in data:
count += 1
probabilities = self.inference(x)
max_probability_class_id = probabilities.argmax(axis=0)
# check if prediction matches the target
if y[max_probability_class_id] == 1:
accuracy += 1
return accuracy
# activation functions together with their derivative functions:
def dSquaredLoss(a, y):
"""
:param a: vector of activations output from the network
:param y: the corresponding correct label
:return: the vector of partial derivatives of the squared loss with respect to the output activations
"""
# assuming that we measure the L(a, y) by sum(1/2*square(y_i - a_i)) for all i parameters, so that the two cancels out
# for each partial derivation L/a_i we have 1/2*square(a_j -y_j) = 0 where j != i
# partial derivation for a single 1/2*square(a_i -y_i) = 1/2 * 2 * (y_i - a_i) * -1 = a_i - y_i
# (a_i - y_i) gives the contribution of the final output per node to the total error
return (a - y) # * a_derivatives
def squaredLoss(x, y):
print('prediction', x)
print('target', y)
return np.sum(np.square(x - y))
def sigmoid(z):
"""The sigmoid function"""
return 1.0 / (1.0 + np.exp(-z))
def sigmoid_prime(z):
"""Derivative of the sigmoid function"""
return sigmoid(z) * (1 - sigmoid(z))
def tanh(z):
return (1.0 - np.exp(-2 * z)) / (1.0 + np.exp(-2 * z))
def tanh_prime(z):
return 1 - np.square(tanh(z))
def relu(z):
return np.maximum(z, 0)
def relu_prime(z):
return (z > 0) * 1 # if the element is greater than zero, it'll be set to one, otherwise zero
def leaky_relu(z):
# if value above 0, keep the value, else replace value with beta * value
beta = 0.01
return np.where(z > 0, z, - beta * z)
def leaky_relu_prime(z):
beta = 0.01
dz = np.ones_like(z)
dz[z < 0] = - beta
return dz
def main():
# ref. for the example: https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/
print('Running Networks example')
net = Network([2, 2, 2])
sample_weigths_l1 = np.array([[0.15, 0.25],
[0.2, 0.30]])
sample_weigths_l2 = np.array([[0.40, 0.50],
[0.45, 0.55]])
net.weights[0] = sample_weigths_l1
net.weights[1] = sample_weigths_l2
net.biases[0] = np.array([[0.35], [0.35]])
net.biases[1] = np.array([[0.60], [0.60]])
x = np.array([0.05, 0.10]) # input
y = np.array([0.01, 0.99]) # target
nablaW, nablaB = net.backprop(x, y)
print('Weights')
print(nablaW)
print('Biases')
print(nablaB)
# for i in range(10):
# nablaW, nablaB = net.backprop(x, y)
# print(nablaW)
# net.weights -= 0.5 * nablaW
# net.biases -= 0.5 * nablaB
if __name__ == '__main__':
main()
|
da721234e24fc476a24ac93d5216948697ba03fe | arfsufpe/scheduler | /scheduler.py | 6,438 | 3.640625 | 4 | '''
Created on 12 de jan de 2020
@author: Rodrigo
'''
from __future__ import print_function
from ortools.sat.python import cp_model
# Each volunteer has a predefined job to do and also predefined is his total number of shifts during the whole month
# for example John is a volunteer (John is a senior) and he's going to take 7 shifts during the whole month
# since John is a senior he might be designated to work as a one of the three jobs:
# (supervisor, report operator, team member)
# Albert is a senior and he's going to take 5 shifts during the whole month as a (supervisor or report operator or team member)
# Alfred is a driver and he's going to take 4 shifts during the whole month as a driver
# (driver can work as driver or team member)
# same reasoning applies to the other volunteers.
# the input is a dictionary with the total of shifts during the month and the corresponding type of volunteer and its rank:
# volunteers{'Name'} = (type of volunteer, total number of shifts in a month, rank)
# volunteers{'John'} = (senior,7, 0)
# volunteers{'Albert'} = (senior, 5,10)
# volunteers{'Alfred'} = (driver,4, 12)
# volunteers{'Layse'} = (report operator assistant,5, 13)
# volunteers{'Mia'} = (supervisor assistant, 8, 51)
# volunteers{'Jim'} = (team member, 8,56)
# SHIFT (in a single shift we have the following jobs):
# 1 - seniors can work as
# supervisor (required - only 1 is enough)
# OR report operator (required - 1 or 2)
# 2 operators is preferable for the case we have a day with 4 teams
# in the case we run out of senior volunteers it is possible to have
# only one report operator
# OR team member (in case all all others - supervisor or report operator 'chair'- are busy already)
# 2 - supervisors' assistant can work as (supervisor assistant OR team member)
# (desirable - can be 0 in the case we don't have enough volunteers)
# 3 - report operators' assistant can work as (report operator assistant OR team member)
# [required*](only one is necessary no matter we have 1 or 2 report operators)
# 4 - drivers can work as (drivers OR team member)
# 5 - ordinary volunteers can work as (team member)
# TEAM
# 1 - each team is responsible for 1 of the 12 police facilities for that shift
# 2 - each team is composed of ordinary volunteers and a driver (minimum of 2 [ 1 driver + 1 team member],
# maximum of 4 [ 1 driver + 3 team member])
# in a week there are two shifts of 12 hours each
# from Mondays to Fridays there is only the second shift (from 7pm to 7am)(no one works at shift 1)
# on Saturdays there are two shifts (one from 7am to 7pm and another from 7pm to 7am (of Sunday)(there are workers on shift 1 and 2)
# on Sundays there is only one shift from 9am to 9pm (workers on shift 1 only)
#what to do: create a schedule for the volunteers for the whole month for all shifts for all 12 police facilities
# Facility constraints:
# there are 12 facilities which will 'place' the operation
# for the the whole month in each facility there must be at least two teams placed on that facility every weekend(Friday, Saturday, Sunday)
# the teams should be evenly (as even as possible) distributed among the facilities during the whole month
# at Fridays, Saturdays and Sundays the total number of teams associated to the facility must be a minimum of 3 and maximum of 4 (if we have enough volunteers)
# from Monday to Thursday there must be at least on team member associated to a facility
# Volunteers constraints
# there is a rank among seniors and the ones with higher rank must work as a supervisor
# (seniors with higher rank should work as supervisor first, then report operator and finally team member)
# there must be at least one day off after a shift
# the shifts of every volunteer should be evenly (as even as possible)distributed for the whole month
# for every volunteer the number of shifts must be equal to the total number of shifts passed as input
# The following information is a complement of the information above (just to make it clear)
# There are these types of volunteers:
# seniors - preferably can be assigned to supervisor OR report operator
# in the case where all the supervisor's job or report operator's job are full
# it is possible for seniors to compose the team
# There is a rank in the senior subgroup and the ones with higher rank must take the supervisor's job first
# then the report operator next and finally a team member
# senior's assistant - a list of volunteers for the specific service
# report operators' assistant - a subgroup of volunteers whose job is to assist the report operator
# team members - the remaining volunteers
# team - composed of ordinary volunteers and a driver
# each team must be assigned to one of the 12 police facilities for the day
# drivers - each team must have one driver (subgroup of volunteers allowed to drive)
def main():
#Data.
num_days = 29
num_shifts = 2
num_facilities = 12
num_supervisors = 20
num_supervisor_assistants = 15
num_report_operators = 20
num_report_operator_assistants = 15
num_drivers = 15
num_team_members = 100 # will be a member of a team
all_days = range(num_days)
all_shifts = range(num_shifts)
all_facilities = range(num_facilities)
all_supervisors = range(num_supervisors)
all_supervisor_assistants = range(num_supervisor_assistants)
all_report_operators = range(num_report_operators)
all_report_operator_assistants = range(num_report_operator_assistants)
all_drivers = range(num_drivers)
all_team_members = range(num_team_members)
# Creates the model.
model = cp_model.CpModel()
# Creates shift variables.
# shifts[(v, d, s, j,t,f)]: volunteer 'v' works on shift 's' on day 'd' doing the 'j' job on team 't' associated to facility 'f'.
shifts = {}
if __name__ == '__main__':
pass |
c78718b0e1afcb6f9d8b11bfe4f905f606135bb8 | V-Plum/ITEA | /lesson_2/homework_2.py | 310 | 3.71875 | 4 | def main():
# Get number
n = int(input("Enter number: "))
# Calculate result
n1 = n + 1
n2 = n - 1
result = n1 ** 2 - n2 ** 2
# display result
print(f"Різниця добутків чисел n+1 та n-1 дорівнює: {result}")
if __name__ == "__main__":
main()
|
b8e176885d95a609f35beb603c8159c22c0f0045 | archerckk/PyTest | /Ar_Script/ar_286_循环分支练习.py | 1,432 | 3.8125 | 4 | """
今天习题:
习题一:
1 用while语句的2种方法输出数字:1到10
2 用for语句和continue 输出结果:1 3 5 7 9
习题二:假设有列表
a = [1,2,3,4,5,6]
1 用for if else 的方法查找数字8是否在列表a里,如果在的话,输出字符串'find',如果不存在的话,
输出字符串'not find'
2 用while语句操作上面的列表a,输出下面结果:
[2,3,4,5,6,7]
"""
# 练习1 用while语句的2种方法输出数字:1到10
print('练习1方法1结果展示:')
x = 1
while True:
print(x)
x += 1
if x > 10:
break
print('练习1方法2结果展示:')
x = 1
while x < 11:
print(x)
x += 1
# 练习2 用for语句和continue 输出结果:1 3 5 7 9
print('练习2结果展示:')
x = 1
for i in range(1, 10, 2):
print(i)
print('练习2方法2结果展示:')
for i in range(1, 10):
if i % 2 == 1:
print(i)
# 练习3 用for if else 的方法查找数字8是否在列表a里,如果在的话,输出字符串'find',如果不存在的话,输出字符串'not find'
print('练习3结果展示:')
a = [1, 2, 3, 4, 5, 6]
for i in a:
if 8 in a:
print('find')
break
else:
print('not find')
# 练习4 2 用while语句操作上面的列表a,输出下面结果:[2,3,4,5,6,7]
print('练习4结果展示:')
a = [1, 2, 3, 4, 5, 6]
while True:
del a[0]
a.append(7)
break
print(a)
|
ec0ea09be5bc48eca7c73a2736fc813c0245b554 | jpieczar/Euler | /Python/twelve.py | 458 | 3.8125 | 4 | from itertools import accumulate, count
from math import sqrt
def count_factors(num):
sum_ = 2 * sum(num % i == 0 for i in range(1, int(sqrt(num)) + 1))
return sum_
def triangular_numbers():
yield from accumulate(count())
def main():
for triangle_nr in triangular_numbers():
if count_factors(triangle_nr) > 500:
return triangle_nr
if __name__ == "__main__":
answer = main()
if answer:
print(answer) |
c39c9220965bcbb75f947043243cf7d6c21bdd5a | bhanurangani/code-days-ml-code100 | /code/day-2/4.Loops/WhileLoop/WhileLoop.py | 74 | 3.875 | 4 | #this is how while loop is used
i=1
while i < 6 :
print(i)
i += 1 |
d2356e0091cc32fc97af06942f69e653d3753640 | MatthewC221/Algorithms | /license_format.py | 964 | 3.703125 | 4 | # Leetcode: https://leetcode.com/problems/license-key-formatting/description/
# Some of these questions are hella weird to be honest. Quite straight forward, be careful of edge cases.
# Realise there's an elegant way to find out the length of the first group. If you have 8 chars and groups of 3, your first group
# is length 2. That's why start = len(S) % K makes sense.
class Solution(object):
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
S = S.upper()
S = S.replace('-', '')
ret = ""
start = len(S)%K
if (start != 0):
for i in xrange(0, start):
ret += S[i]
if (i != len(S)-1): ret += "-"
count = 0
for i in xrange(start, len(S)):
if (count%K == 0 and count != 0): ret += "-"
ret += S[i]
count += 1
return ret
|
a2f38fe8698ad7ded399dbf26dc8dfd1bd8f46bd | jardellx/arcade | /base/181/solver.py | 142 | 3.578125 | 4 | words = input().split(" ")
cont = 0
for w in words:
try:
value = int(w)
cont += value
except:
pass
print(cont) |
e0aaab68845ea2081e62013339c84e4b37d9cb0a | DandyCV/LITS | /Lesson05.py | 720 | 3.625 | 4 | def check_float(s):
if '.' in s:
return True
else:
return False
s = '5.8'
print (check_float(s))
def decor(func):
def inner(*args, **kw):
print('\n')
func()
print('\n')
return inner
@decor
def smart_input():
numbers = input('Введіть кілька чисел через пробіл ')
numbers_list = numbers.split()
max = float('-inf')
for n in numbers_list:
num = int(n)
if num > max:
max = num
print('Максимальне число = ',max)
#def max_input():
#print(max(map(int,input().split())))
smart_input()
|
cfd1602fc6dbc6fc1adfd299bbfeb8db31bc3f34 | Nicolaks/prime-number | /prime-number-master/programm/prime-0.1.py | 930 | 3.96875 | 4 | import os
from math import *
# Function return true if a number is prime.
def is_prime(n):
for i in range(2, int(sqrt(n)+1)):
if n%i == 0:
return False
return True
# Create a while, with a top number, and check if the number
# is prime ans after put him in file.
def launch():
n = int(input("What number should I go up to ? "))
for p in range(2, n+1):
if is_prime(p):
print(p)
prime_file = open("prime", "a")
prime_file.write(str(p) + " " + str(is_prime(p)) + "\n")
prime_file.close()
# Convert bytes.
def convert_bytes(num):
global res
res = num / 1024.0
return res
# Allow to see the size of a file.
def file_size(file_path):
if os.path.isfile(file_path):
file_info = os.stat(file_path)
return convert_bytes(file_info.st_size)
# Main function who launch all the program.
def main():
launch()
file_path = "prime"
marks = str(int(file_size(file_path)))
print(marks + " ko")
main()
|
2c2423a260c44bfb8c3583863789811a4682cd14 | brookslybrand/CS303E | /CodingBat/Logic-1/in1to10.py | 261 | 3.625 | 4 |
# coding: utf-8
# In[129]:
def in1to10(n, outside_mode):
'''
return True if between 1 and 10 inclusive, or
outside those numbers if outside_mode = True
'''
return ( (not outside_mode and 1 <= n <= 10) or (outside_mode and (n <= 1 or n >= 10) ) )
|
f9f6e29dd029f32c0c80e1c53aba796e2a62e90c | efficacy/aoc2020 | /day14/day14.py | 3,680 | 3.59375 | 4 | import re
import math
BITS = 36
MAX = 0b111111111111111111111111111111111111
def invert(x):
return MAX - x
def double(values, bit):
# print("double:",values,bit)
ret = []
for value in values:
# print("considering:",value)
zero = value & invert(bit)
one = zero | bit
ret.append(zero)
ret.append(one)
# print("appended:",ret)
return ret
class Cpu:
def __init__(self):
self.enable = 0
self.value = 0
self.mem = {}
def __str__(self):
return "mask:"+str(self.enable)+","+str(self.value)+"\n mem:"+str(self.mem)
def set_mask(self, mask):
nbits = len(mask)
if not nbits == BITS:
raise(Exception("mask must be 36 bits, was",nbits))
# print("set_mask:", mask)
e = ''
v = ''
for i in range(BITS):
c = mask[i]
if c == 'X':
e += '0'
v += '0'
else:
e += '1'
v += c
self.enable = int(e,2)
self.value = int(v,2)
def apply_mask(self, value):
a = self.enable & self.value
b = (invert(self.enable)) & value
ret = a | b
# print("apply mask e:",self.enable,"v:",self.value,"a:",a,"b:",b,"->",ret)
return ret
def apply_mask2(self, value):
floaters = invert(self.enable)
# print("apply mask 2 e:",format(self.enable,'b'),"f:",format(floaters,'b'),"v:",self.value,"i",value)
base = self.value | value
ret = [base]
for i in range(BITS):
bit = int(math.pow(2,i))
if (floaters & bit):
ret = double(ret, bit)
# print("after double:", ret)
# raise(Exception("huh"))
# print("apply mask 2 e:",self.enable,"v:",self.value,"->",ret)
return ret
def put(self, addr, value):
# print("put:",addr,':=',value)
if value > 0:
self.mem[addr] = value
else:
self.mem.pop(addr, None)
def set_value(self, addr, value, qpart):
if (qpart == 1):
masked = self.apply_mask(value)
self.put(addr, masked)
else:
masked = self.apply_mask2(addr)
for a in masked:
self.put(a, value)
return masked
def count_memory(self):
ret = 0
for loc in self.mem:
ret += self.mem[loc]
return ret
# return all possible combinations of bits where mask is 0
def splurge(mask,value, input):
pass
def solve(qpart, filename='input.txt'):
print("Part " + str(qpart))
with open(filename, 'r') as f:
lines = f.read().splitlines()
cpu = Cpu()
for line in lines:
possible = re.match("mask = ([01X]{36})", line)
if possible:
mask = possible.group(1)
cpu.set_mask(mask)
print("set mask: ",mask)
continue
possible = re.match("mem\[(\d+)\] = (\d+)", line)
if possible:
addr,value = possible.groups()
masked = cpu.set_value(int(addr),int(value), qpart)
print("set addr:",addr,"value:",value,"->",masked)
continue
print("unknown line: " + line)
# print(cpu)
print("result:",cpu.count_memory())
if __name__ == '__main__':
# solve(1, "test1.txt")
# solve(1)
# cpu = Cpu()
# cpu.set_mask('000000000000000000000000000000000X0X')
# v = 0xF
# print('app1',cpu.apply_mask(v))
# print('app2',cpu.apply_mask2(v))
# solve(2, "test2.txt")
# solve(2, "test3.txt")
# solve(2, "test1.txt")
solve(2) |
0ee18bd49d1d04a1eb865bee71c7d6963d7f6117 | kawaiiblitz/Introduction-to-Computer-Science-Python | /IteracionRecursion.py | 1,859 | 4.03125 | 4 | ###################################### Iteración y Recursión ######################################
# Solución Iterativa - Multiplicación #
def mult_iter(a,b):
result = 0
while b > 0:
result += a
b -= 1
return result # Cuando salga del while manda el resultado #
mult_iter(3,3)
# Factorial por recursión #
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
factorial (4)
# Factorial por iteración #
def factorial_iter(n):
prod = 1
for i in range (1, n+1):
prod *= i
return prod
factorial_iter(4)
# Potencia de un número usando recursión #
def iterPower(base, exp):
result = 1
while exp > 0:
result *= base
exp -= 1
return result
iterPower(2, 4)
# Potencia de un número usando iteración no x ** x
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
if exp <= 0 :
return 1
else :
return base * iterPower(base,exp-1)
#Una vez completado el ciclo o el if, se va regresando pasos atrás #
iterPower(2, 4)
# Torres de Hanoi #
def printMove(fr, to):
print('move from' + str(fr) + 'to' + str(to))
def Towers(n,fr,to,spare):
if n == 1:
printMove(fr,to)
else:
Towers(n-1, fr, spare, to)
Towers(1, fr, to, spare)
Towers(n-1, spare, to, fr)
print(Towers(4, 'P1','P2','P3'))
# Máximo Común Divisor iteración #
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
minimo = min(a,b)
if a % minimo = 0 and
|
131b39c139ee96c367634e002383b8c4ccd0d220 | davorgraj/SluzbenaVozila | /main.py | 1,453 | 3.78125 | 4 | # -*- coding: utf-8 -*-
from Vehicles import Vehicle, add_new_vehicle, list_all_vehicles, edit_number_of_kilometers_or_date_service, delete_vehicle, save_vehicles_in_txt
def main():
print "Dobrodošl v programu za urejanje vaših avtomobilov"
print ""
vehicles = []
while True:
print ""
print "Izberite opcijo:"
print "a) Dodajte novo vozilo"
print "b) Ogled seznama vozil"
print "c) Uredite število prevoženih kilometrov ali datum servisa."
print "d) Izbrišite vozilo iz seznama."
print "e) Shrani vozila v txt datoteko."
print ""
selection = raw_input("Izberite opcijo (a, b, c, d or e): ")
print ""
if selection.lower() == "a":
add_new_vehicle(vehicles)
elif selection.lower() == "b":
list_all_vehicles(vehicles)
elif selection.lower() == "c":
if not vehicles:
print "Nimate vozil v vašem seznamu."
else:
edit_number_of_kilometers_or_date_service(vehicles)
elif selection.lower() == "d":
if not vehicles:
print "Nimate vozil v vašem seznamu."
else:
delete_vehicle(vehicles)
elif selection.lower() == "e":
save_vehicles_in_txt(vehicles)
else:
print "Niste izprali pravilne opcije. Poskusite ponovno"
if __name__ == "__main__":
main()
|
6e2f2468dd4f5dffa7392d34d3860f943a8924e2 | florije1988/manman | /learn/005.py | 226 | 3.515625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'manman'
"""
求 2/1+3/2+5/3+8/5+13/8.....前20项之和?
"""
a = 1.0
b = 2.0
sum = 0
c = 0
for i in range(0, 20):
sum = sum + b/a
c = a + b
a = b
b = c
print(sum)
|
22cd43a4045dd296910b52e4485660aafa89ba53 | irenatrend/Data_Analyst_Nanodegree_Udacity | /Data_Wrangling_With_Mongo_DB/Final Project/AdditionalDataExploration.py | 2,689 | 3.5625 | 4 | #!/usr/bin/env python
import pprint
def get_db(db_name):
from pymongo import MongoClient
client = MongoClient('localhost:27017')
database = client[db_name]
return database
if __name__ == '__main__':
db = get_db('cities')
# Count different Amenities
print "Count different Amenities:"
pprint.pprint(db.miami_fl.aggregate(([
{"$group": {"_id": "$amenity", "count": {"$sum": 1}}},
{"$sort": {"count": -1}}]))['result'])
# Top 10 appearing amenities
print "Top 10 appearing amenities:"
pprint.pprint(db.miami_fl.aggregate([{"$match": {"amenity": {"$exists": 1}}},
{"$group": {"_id": "$amenity", "count": {"$sum": 1}}},
{"$sort": {"count": -1}},
{"$limit": 10}])['result'])
# Number of cafes
print "Number of cafes:", db.miami_fl.find({"amenity": "cafe"}).count()
# Number of Dunkin Donuts
print "Number of Dunkin Donuts:", db.miami_fl.find({"name": "Dunkin Donuts"}).count()
# Number of shops
print "Number of shops:", db.miami_fl.find({"shop": {"$exists": "true"}}).count()
# Restaurant's name, the food they serve, contact number and opening hours
print "Restaurants:"
pprint.pprint(db.miami_fl.aggregate([
{'$match': {'amenity': 'restaurant', 'name': {'$exists': 1}}},
{'$project': {'_id': '$name', 'cuisine': '$cuisine', 'contact': '$phone', 'opening_hours': '$opening_hours'}}])
['result'])
# Nightclubs, phone contact and opening hours
print "Nightclubs:"
pprint.pprint(db.miami_fl.aggregate([
{'$match': {'amenity': 'nightclub', 'name': {'$exists': 1}}},
{'$project': {'_id': '$name', 'contact': '$phone', 'opening_hours': '$opening_hours'}}])['result'])
# Biggest religion (no surprise here)
print "Biggest religion:"
pprint.pprint(db.miami_fl.aggregate([
{"$match": {"amenity": {"$exists": 1}, "amenity": "place_of_worship"}},
{"$group": {"_id": "$religion", "count": {"$sum": 1}}},
{"$sort": {"count": -1}},
{"$limit": 1}])['result'])
# Most popular cuisines
print "Top 5 most popular cuisines:"
pprint.pprint(db.miami_fl.aggregate([
{"$match": {"amenity": {"$exists": 1}, "amenity": "restaurant"}},
{"$group": {"_id": "$cuisine", "count": {"$sum": 1}}},
{"$sort": {"count": -1}},
{"$limit": 5}])['result']) |
9221e4f9d26162f25cb37cd9f20045ea35170084 | Charleso19/Python3-Text-Adventure-ex45 | /ex45m.py | 12,242 | 3.78125 | 4 | # As well as built-in modules, I have imported two self-made modules,
# mainly to shorten the current python file and improve readabiltiy
from sys import exit
from random import randint, randrange, choice
from math import sqrt
from textwrap import dedent
from entity_module import CreateEntity
from attack_module import Attack
class Blackboard(object):
"""
This class is to display the controls of the game. I have named it as a
blackboard, as the centre of the game (i.e. the HouseRoom), has a blackboard
on the wall that displays the controls.
"""
def view_controls(self):
print(dedent("""
DIRECTIONS:
• 'north'
• 'east'
• 'south'
• 'west'
ACTIONS:
• 'check case': Checks the trophy case
• 'examine'/'look': Examines the object
• 'attack': Attacks an enemy
• 'stats': View player's stats
"""))
class TreasureCase(object):
"""
The TreasureCase is styled in a composition format; i.e. the HouseRoom
has-a TreasureCase. I thought this composition format made more sense.
N.B. a possible annoyance is that the user must initiate the check_case
method below in order to win the game.
"""
treasure = []
def check_case(self):
print("Checking treasure in case...")
print("You have the following treasure:")
for i in TreasureCase.treasure:
print(f"• {i}")
if len(TreasureCase.treasure) >= 3:
return 'end_room'
else:
pass
class HouseRoom(object):
"""
This is the main central hub of the game, it is where the game starts and
where access to all other rooms are available.
"""
def __init__(self):
"""
I've set this so that the HouseRoom has-a treasure-case and has-a
blackboard. It seemed easier to work with this way.
"""
self.treasure_case = TreasureCase()
self.controls = Blackboard()
def activate(self, player, troll):
"""
This is basically the same as the enter() function from exercise 43.
The Engine object below however passes the player and troll
(CreateEntity()) objects to every room's activate, often unnecessarily;
perhaps there is a better way to do this.
"""
print(dedent("""
A short sharp sound crackles through the air. Groggy you awake,
slowly; a pale cold light shines through cracks in the ceiling
above you.
What do you do?
"""))
answer = input("> ")
if answer == 'north':
return 'troll_room'
elif answer == 'east':
return 'death_room'
elif answer == 'south':
return 'gallery_room'
elif answer == 'west':
print(dedent("""
The door is locked.
"""))
return 'house_room'
elif ("examine" in answer) or ("look" in answer):
print(dedent("""
The room is dreary and unintersting. However, in the corner
lies a beautifully displayed treasure case.
"""))
return 'house_room'
elif answer == 'stats':
player.view_entity()
return 'house_room'
elif answer == 'attack':
print(dedent("""
In a wild frenzy you pace around the house and attack the
various inanimate objects like a loon. Eventually you knock
into the trophy case, causing a vase on top to fall and break
upon your head.
"""))
return 'house_room'
elif answer == 'check case':
var = self.treasure_case.check_case()
if var:
return var
elif not var:
return 'house_room'
else:
raise Exception("ERROR HERE OWEN")
elif answer == 'controls' or answer == 'help':
print(dedent("""
On the far side of the wall, a blackboard is poorly pinned to
the crumbling wall. On it there are various scribbles, as
follows:
"""))
self.controls.view_controls()
return 'house_room'
else:
print("\nSorry, I didn't quite get that.")
return 'house_room'
class CollectTreasure(object):
"""
This class is perhaps more of a function than a class, perhaps I could
have made this into a module, or included it as a method in the TrollRoom
class instead.
"""
def activate(self, player, troll):
print(dedent("""
Congratulations, the troll is dead! Behind his corpse looms a
shiny diamond. You pick it up and head south back to the house.
After which, you add it to the Treasure Case.
"""))
TreasureCase.treasure.append('Shiny diamond')
return 'house_room'
class TrollRoom(object):
"""
This is the room where the player fights the only enemy in the
game. I've split this across the Troll Room and an Attack module. This is
so in the future, I can add more enemies that have an attack sequence via
the Attack module, rather than only the troll having it.
"""
def __init__(self):
"""
Used composition style again here. The TrollRoom class has-a Attack
class
"""
self.attack_sequence = Attack()
def activate(self, player, troll):
print(dedent("""
You walk north through a pitch-black hole. Before you towers a
massive troll like monster, teeth snarling and a mean-looking
axe.
"""))
answer2 = input("> ")
if (answer2 == 'north' or answer2 == 'east') or (answer2 == 'west'):
print(dedent("""
The troll blocks all of your escape routes, however, a quick move
south may save you."""))
return 'troll_room'
# Added a luck element here just to make it more intersting
elif answer2 == 'south':
luck = randint(1,2)
if luck == 1:
print(dedent("""
You decide to retreat, however the Troll has had his weat-a-bix
this morning and out steps you. Before you've even turned
around, the troll swings his axe and your head tumbles to
the floor.
"""))
return 'death_room'
else:
print(dedent("""
The troll seems to anticipate your intentions and cut off
your angle of retreat. Luckily, he slips on a
precariously placed banana skin, buying you precious
seconds to escape.
"""))
return 'house_room'
# If I had coded the attack sequence here, I believe the TrollRoom
# class would be too long, and decrease readability. Outsourcing it to
# a different class (or in this case, a module) stops this issue.
elif answer2 == 'attack':
# The Attack module returns a result for us to use and it is
# assigned to var, this is then returned back to the engine.
var = self.attack_sequence.activate(player, troll)
return var
else:
print("\nSorry, I didn't quite get that.")
return 'troll_room'
class GalleryRoom(object):
"""
This room is nice and simple and borderline lazy. The user must
access this room first before attacking the troll, otherwise, the user
dies.
"""
def activate(self, player, troll):
if player.inventory == {} and TreasureCase.treasure == []:
# I have created this if-else statement so that the user can only
# get the treasure and items once; without it a user could enter
# this room twice and win the game without facing the Troll.
print(dedent("""
You discover one Golden Coin and a Silver Jewel Encrusted Crown.
Moreover, on the walls, you discover a sword and shield.
You decide to take everything, and return to the House.
"""))
# The use of random intergers means the attack_sequence will be
# slighlty different every time, however, see the attack_module
# file for a note on a bug.
player.inventory['Sword'] = randrange(10, 41, 10)
player.inventory['Shield'] = randrange(10, 41, 10)
TreasureCase.treasure.append('Golden Coin')
TreasureCase.treasure.append('Silver Jewel Encrused Crown')
return 'house_room'
else:
print(dedent("""
You have already colleced the Sword, Shield, and two
treasures; there are no more items here for you.
"""))
return 'house_room'
class EndRoom(object):
""" Quite simply ends the game once the user has won."""
def activate(self, player, troll):
print(dedent("""
Congratulations! You won!
"""))
exit(0)
class DeathRoom(object):
"""A classic death scene/room; very similiar to ex.43 version."""
def activate(self, player, troll):
death_quotes = [
"You're dead. You're not very good at this, are you?",
"You're dead. Honestly, what did you expect?",
"You're dead. My 80 year old gran' can play better than this.",
"You're dead. Not much of a surprise is it?",
"You're dead. Surprise surprise...",
"You're dead, bucko.",
]
# A simpiier version of the ex43's version of choosing a random quote
# from the list above; however one should take the time to understand
# ex43's version.
print(choice(death_quotes))
exit(0)
class Map(object):
"""A simple Map that the engine uses to navigate through the script."""
# Unsure of class is needed for such a simple bit of code.
# The use of a dictionary here ensure that only one instance of each class
# is stored. Some other ways kept producing new instances.
rooms = {
'house_room': HouseRoom(),
'troll_room': TrollRoom(),
'gallery_room': GalleryRoom(),
'end_room': EndRoom(),
'death_room': DeathRoom(),
'collect_treasure': CollectTreasure(),
}
class Engine(object):
"""
The engine here is the driving force of the entire programme.
It is based on ex43's design, however I believe it is slightly simplier
"""
def __init__(self):
"""
Once again I have used a composition format here. The engine has-a
map of the game/script that it needs to run, it also has-a two entites
that it needs to pass certain classess, in order for the attack
sequence to work.
"""
self.game_map = Map()
self.player = CreateEntity()
self.troll = CreateEntity()
def run_engine(self):
current_room = self.game_map.rooms.get('house_room')
final_room = self.game_map.rooms.get('end_room')
while current_room != final_room:
next_room = current_room.activate(self.player, self.troll)
current_room = self.game_map.rooms.get(next_room)
current_room.activate(self.player, self.troll)
engine_obj = Engine()
engine_obj.run_engine()
|
d54e601375118780dfd2572e3618c119d25188f1 | gitter-badger/pymanopt | /pymanopt/solvers/steepest_descent.py | 3,161 | 3.609375 | 4 | """
Module containing steepest descent (gradient descent) algorithm based on
steepestdescent.m from the manopt MATLAB package.
"""
import time
from pymanopt.solvers import linesearch
from pymanopt.solvers.solver import Solver
class SteepestDescent(Solver):
def __init__(self, ownlinesearch=None, *args, **kwargs):
super(SteepestDescent, self).__init__(*args, **kwargs)
if ownlinesearch is None:
self._searcher = linesearch.LineSearch()
else:
self._searcher = ownlinesearch
# Function to solve optimisation problem using steepest descent.
def solve(self, problem, x=None):
"""
Perform optimization using gradient descent with linesearch.
This method first computes the gradient (derivative) of obj
w.r.t. arg, and then optimizes by moving in the direction of
steepest descent (which is the opposite direction to the gradient).
Arguments:
- problem
Pymanopt problem setup using the Problem class, this must
have a .man attribute specifying the manifold to optimize
over, as well as a cost and enough information to compute
the gradient of that cost.
- x=None
Optional parameter. Starting point on the manifold. If none
then a starting point will be randomly generated.
Returns:
- x
Local minimum of obj, or if algorithm terminated before
convergence x will be the point at which it terminated.
"""
man = problem.man
# Compile the objective function and compute and compile its
# gradient.
if self._verbosity >= 1:
print("Computing gradient and compiling...")
problem.prepare(need_grad=True)
objective = problem.cost
gradient = problem.grad
# If no starting point is specified, generate one at random.
if x is None:
x = man.rand()
if self._verbosity >= 1:
print("Optimizing...")
# Initialize iteration counter and timer
iter = 0
time0 = time.time()
if self._verbosity >= 2:
print(" iter\t\t cost val\t grad. norm")
while True:
# Calculate new cost, grad and gradnorm
cost = objective(x)
grad = gradient(x)
gradnorm = man.norm(x, grad)
iter = iter + 1
if self._verbosity >= 2:
print("%5d\t%+.16e\t%.8e" % (iter, cost, gradnorm))
# Descent direction is minus the gradient
desc_dir = -grad
# Perform line-search
step_size, x = self._searcher.search(objective, man, x, desc_dir,
cost, -gradnorm**2)
stop_reason = self._check_stopping_criterion(
time0, stepsize=step_size, gradnorm=gradnorm, iter=iter)
if stop_reason:
if self._verbosity >= 1:
print(stop_reason)
print('')
break
return x
|
025faad9007cb7b8db2ee7234749047d501320f8 | kMatejak/recruitment-tasks-gdansk | /ZADANIE_2_missing_numbers.py | 612 | 3.828125 | 4 | def missing_numbers(m: list, n: int) -> list:
data = {number: None for number in range(1, n + 1)}
missing_numbers = list()
for x in m:
data.update({x: 1})
for number in data:
if data[number]:
continue
else:
missing_numbers.append(number)
return missing_numbers
if __name__ == '__main__':
m = [2, 3, 7, 4, 9]
n = 10
mn = missing_numbers(m, n)
print(f"\nDla danego zbioru m = {m}")
print(f"brakujące liczby w tym zbiorze z ciągu liczb 1..{n} to:")
for x in mn:
print(f"{x}", end=", ")
print()
print()
|
fcbfd8faaad28f4bc7f554d8f1e3fe0b409e8a8d | rafaelperazzo/programacao-web | /moodledata/vpl_data/34/usersdata/83/13869/submittedfiles/moedas.py | 403 | 3.859375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a=input('Digite o valor de a: ')
b=input('Digite o valor de b: ')
c=input('Digite o valor de c: ')
if a>=b :
w=c//a
r=(c%a)//b
if (c%a)%b==0 :
print (w)
print (r)
else :
print ('N')
else :
r=c//b
w=(c%b)//a
if (c%b)%a==0 :
print (w)
print (r)
else :
print ('N')
|
9c4292fd7559a9ef782a9f1cc52cfe5dbcda8716 | elrion018/CS_study | /beakjoon_PS/no1874.py | 769 | 3.546875 | 4 | n = int(input())
stack = [0]
num = 0
arr_1 = []
arr_2 = []
for _ in range(n):
_input = int(input())
if stack[-1] < _input and _input not in arr_1:
while stack[-1] < _input:
num += 1
if num not in arr_1:
stack.append(num)
arr_2.append("+")
arr_1.append(stack.pop())
arr_2.append("-")
elif stack[-1] == _input and _input not in arr_1:
arr_1.append(stack.pop())
arr_2.append("-")
elif stack[-1] > _input and _input not in arr_1:
while stack[-1] > _input:
arr_1.append(stack.pop())
arr_2.append("-")
else:
arr_1.append("NO")
break
if "NO" in arr_1:
print("NO")
else:
for i in arr_2:
print(i)
|
90a31b9be41e4ba7eef5244f99ab8b5c327e6b25 | adylshanov/Home_Work_Adylshanov | /number_system.py | 2,605 | 3.65625 | 4 | '''
Модуль перевода в разные системы исчисления
'''
__all__ = [
'dec2bin',
'dec2oct',
'dec2hex',
'bin2dec',
'oct2dec',
'hex2dec'
]
def dec2bin(number):
"""Переводит из десятиричной системы в двоичную"""
return code(number, 2)
def dec2oct(number):
"""Переводит из десятиричной системы в восьмеричную"""
return code(number, 8)
def dec2hex(number):
"""Переводит из десятиричной системы в шестнадцатиричную"""
return code(number, 16)
def code(number, sysnum):
""" Функция перевода десятичного числа в sysnum систему исчисления """
rez = ''
while (number >= 1):
if (number%sysnum >= 10):
rez = ifinhex(number%sysnum) + rez
else :
rez = str(number%sysnum) + rez
number = number//sysnum
return str(rez)
def bin2dec(number):
"""Переводит из двоичной системы в десятиричную"""
return decode(number, 2)
def oct2dec(number):
"""Переводит из восьмеричной системы в десятиричную"""
return decode(number, 8)
def hex2dec(number):
"""Переводит из шестнадцатеричную системы в десятиричную"""
return decode(number, 16)
def decode(number, sysnum):
""" Функция перевода числа из sysnum систем исчисления в десятиричную """
tx = str(number)
tx = tx[::-1]
rez = 0
for i in range(len(tx)):
if tx[i].isalpha() == True:
rez += int(ifouthex(tx[i])) * (sysnum ** (i))
else :
rez += int(tx[i]) * (sysnum ** (i))
return int(rez)
def ifouthex(char):
""" замена буквы на число в системе исчисления больше десятичной """
if char == 'a':
return 10
elif char == 'b':
return 11
elif char == 'c':
return 12
elif char == 'd':
return 13
elif char == 'e':
return 14
elif char == 'f':
return 15
def ifinhex(char):
""" вставка символа буквы в систему исчисления больше десятичной """
if char == 10 :
return 'a'
elif char == 11:
return 'b'
elif char == 12:
return 'c'
elif char == 13:
return 'd'
elif char == 14:
return 'e'
elif char == 15:
return 'f'
if __name__ == '__main__' :
print(dec2bin(250))
print(dec2oct(493))
print(dec2hex(11259375))
print(bin2dec(dec2bin(250)))
print(oct2dec(dec2oct(493)))
print(hex2dec(dec2hex(11259375)))
|
087f25ccdae50bc5d7ecb2ec9acfeac082026593 | James-Lee1/Unit_5-02 | /unit_5-02-1.py | 662 | 4.4375 | 4 | # Created by : James Lee
# Created on : 13 Nov. 2017
# Created for : ICS3UR
# This program shows the largest number in an array
def find_highest_value(arrays = []):
# Finds the highst value in am array
value_number_in_array = 0
for value in arrays:
if value_number_in_array < value:
value_number_in_array = value
else:
value_number_in_array = value_number_in_array
return value_number_in_array
array = [5,4,7,9,3,10]
find_highest_value(array)
max_value = find_highest_value(array)
print("The max value of the array is: " + str(max_value))
|
b72f97f2746a06e18c4f6faf1838fc68de46e853 | kurund/edx-mit-compscience-python | /bsearch.py | 778 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 2 22:45:31 2017
@author: kurund
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
if len(aStr) == 0:
return False
elif char == aStr:
return True
elif len(aStr) == 1:
return False
half = int(len(aStr)/2)
if half < 0:
return False
elif char == aStr[half]:
return True
elif char < aStr[half]:
return isIn(char, aStr[0:half])
elif char > aStr[half]:
return isIn(char, aStr[half:])
#print(isIn('a', 'halloo'))
#print(isIn('e', 'bdvv'))
#print(isIn('s', 'm')) |
b36580b261d1a705b3e1c32bc3eb543ca2f51631 | blackmoses67/programming-portfolio | /programming/percentcalc.py | 2,347 | 3.53125 | 4 | def main():
#all variables
pts = 0
shotsMade = 0
shotsTaken = 0
reb = 0
ast = 0
stl = 0
blk = 0
mins = 0
games = 1
#start the loop
while games <= 82:
print "\n"
#points per game
p = float(raw_input("Enter Points: "))
pts += p
PPG = pts / games
print "Player scored", p, "Points in this game"
print "Player has scored", pts, "Points this season"
print "Player averages", PPG, "Points per game"
print "\n"
#field goal percentage
sm = float(raw_input("Enter shots made: "))
st = float(raw_input("Enter shots taken: "))
print "\n"
shotsMade += sm
shotsTaken += st
print "He has made", shotsMade, "this season"
print "He has taken", shotsTaken, "this season"
print "\n"
gameFGP = sm / st
seasonFGP = shotsMade / shotsTaken
print "The player shot", gameFGP, "percent in this game"
print "The player averages", seasonFGP, "this season"
print "\n"
#rebounds per game
r = float(raw_input("Enter Rebounds: "))
reb += r
RPG = reb / games
print "Player got", r, "Rebounds in this game"
print "Player has gotten", reb, "Rebounds this season"
print "Player averages", RPG, "Rebounds per game"
print "\n"
#assists per game
a = float(raw_input("Enter Assists: "))
ast += a
APG = ast / games
print "Player got", a, "Assists in this game"
print "Player has gotten", ast, "Assists this season"
print "Player averages", APG, "Assists per game"
print "\n"
#steals
s = float(raw_input("Enter Steals: "))
stl += s
SPG = stl / games
print "Player got", s, "Steals in this game"
print "Player has gotten", stl, "Steals this season"
print "Player averages", SPG, "Steals per game"
print "\n"
#blocks
b = float(raw_input("Enter Blocks: "))
blk += b
BPG = blk / games
print "Player got", b, "Blocks in this game"
print "Player has gotten", blk, "Blocks this season"
print "Player averages", BPG, "Blocks per game"
print "\n"
#minutes
m = float(raw_input("Enter minutes played: "))
mins += m
MPG = mins / games
print "Player played", m, "Minutes this game"
print "Player averages", MPG, "Minutes per game"
print "\n"
#add to the counter
games += 1
#break the loop
print "Are you finished?"
end = raw_input("end or no: ")
if end == "end":
break
#end the program very pleasantly
print "the season has ended"
main() |
b589cd6ab904a0883979716a31cc1578731bdf66 | younkyounghwan/python_class | /lab5_2.py | 847 | 3.8125 | 4 | """
쳅터: day 5
주제: 함수
문제:
문자열의 듀플을 매개변수로 받아서, 해당 문자열들을 ','로 한 줄에 연결하여 출력하는 함수 print_sting을 정의한다.
소프트웨어공학과, 정보통신공학과, 글로컬it학과, 컴퓨터공학과를요소로 가지는 튜플을 매개변수로 해서 print_string을 호출한다.
작성자:윤경환
작성일: 18 10 02
"""
def print_string(a): #함수 정의
# 연결된 문자열을 반환
for i in range(0,len(a)): #반복문
print(a[i], end="") #출력
if i != len(a): #콤마 넣기
print(end=", ") #콤마를 넣기
a = ("소프트웨어공학과", "정보통신공학과", "글로컬it학과", "컴퓨터공학과") #문자열 정의
print_string(a) #함수 호출
#문자열 합으로 도출하는 것 연습하기 |
220e861d868f7d01123ef0416133df59901a1c34 | jknsware/python-crash-course | /chapter_6/person.py | 597 | 4.03125 | 4 | people = []
person = {
'first_name': 'jason',
'last_name': 'ware',
'age': '42',
'city': 'cedar park',
}
people.append(person)
person = {
'first_name': 'stuart',
'last_name': 'ware',
'age': '39',
'city': 'liberty hill',
}
people.append(person)
person = {
'first_name': 'chad',
'last_name': 'ware',
'age': '37',
'city': 'euless',
}
people.append(person)
for person in people:
name = f"{person['first_name'].title()} {person['last_name'].title()}"
age = person['age']
city = person['city'].title()
print(f"{name}, of {city}, is {age} years old.")
|
1c241fbc085dcb4ff4df6a7d090f3bac75f69b3f | RobertEJohnson/python-intro | /conditionals.py | 175 | 3.546875 | 4 |
if 3 > 2:
print('The rules of the universe still apply')
elif 2 > 3:
print('I am a 47 foot tall purple platypus bear')
else:
print('How did you even get here?')
|
46c5f93235e2d3f9da0efccab452d7ab29a4e060 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_118/2790.py | 481 | 3.671875 | 4 | from numpy import sqrt,ceil,floor
def palind(n):
if ceil(n)!=floor(n):
return False
n=int(n)
if str(n)==str(n)[::-1]:
return True
return False
def count_palind(a,b):
count=0
for i in range(a,b+1):
if palind(i) and palind(sqrt(i)):
count=count+1
return count
if __name__=='__main__':
fp=open("input.txt")
T=int(fp.readline())
for i in range(0,T):
x=fp.readline().strip().split()
a=int(x[0])
b=int(x[1])
print "Case #"+str(i+1)+":",count_palind(a,b)
|
9d4969927009e8492c75ef3c9e088cb2910b4c42 | HankDa/UCD_S1_Python_Assignment | /p6_19209435_08Oct/p6p5.py | 1,081 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 15:47:46 2020
@author: Hank.Da
"""
"""
#pseudocode
if enter password == correct password:
print('You have successfully logged in')
else:
print('password incorrect')
print('Plz enter correct passwaord three times')
for loop 3 times:
if enter password == correct password:
count of correct password +=1
if count of correct password ==3:
print('You have successfully logged in')
else:
print('You have been denied access.')
"""
password_default = '1234abcd'
count = 0
pw_input = input('plz enter password:')
if pw_input == password_default:
print('You have successfully logged in')
else:
print('password incorrect')
print('Plz enter correct passwaord three times')
for i in range(3):
pw_input = input('plz enter password:')
if pw_input == password_default:
count += 1
if count==3:
print('You have successfully logged in')
else:
print('You have been denied access.')
|
7b80c75808d3a73e75db0dfeaa0e7cbd0f6e4671 | Rishika1983/Python-code-practice | /mumber.py | 223 | 4.1875 | 4 | #The program takes a number n and computes n+nn+nnn
n = int( input('enter your number'))
num = ''
total = 0
for i in range(0,n+1):
num = num + str(n)
print (num)
total = total + int(num)
print(total) |
37879554ca69ceec2c2b1e5c49b2ad93e0e5788a | jdee77/100DaysOfPython | /Day-02/codes/leapyear.py | 427 | 4.28125 | 4 | print("LEAP YEAR")
year = int(input("Enter the year :"))
leapYear = False
# a year is leap year if its evenly divisible by 4
# except evenly divisible by 100
# unless not divisible by 400
if year % 100 == 0:
if year % 400 == 0:
leapYear = True
else:
if year % 4 == 0:
leapYear = True
if leapYear:
print(f"{year} is leap year.")
else:
print(f"{year} is not a leap year.") |
06b43121f55062f22988a5b9411f16234b2dd4c9 | pankajdahilkar/python_codes | /gender.py | 402 | 3.921875 | 4 | import csv
name = input("Enter your name ")
with open("Female.csv",'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader :
for field in row :
if field == name:
print(name,"is girl")
break
else : print("not found")
|
ddc06a5b1e493fa6a87bf83aeb93ca25e6784a80 | bespontoff/checkio | /solutions/Blizzard/palindromic_palindrome.py | 780 | 3.828125 | 4 | #!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run palindromic-palindrome
# Write a palindromic program with acheckio(s)function that checks whethers(a string) is a palindrome.
#
# For this task, using "#" is forbidden.
#
# You can use other methods for the function's definition (for example a lambda). The test will try to run the function "checkio" from your code.
#
# The example of the palindromic code:
#
#
# checkio=lambda x: x#x :x adbmal=oikcehc
# However, in your code, you can not use "#".
#
# Input:A text as a string.
#
# Output:Palindrome or not as a boolean.
#
# Precondition:1<|text| ≤ 20
# The text contains only ASCII letters in lowercase.
#
#
# END_DESC
def checkio(s):
return s == s[::-1]
#checkio = lambda s: |
03e98da48b534616b82afb084c7016ff9d225af6 | RAVE-V/python-programs | /matrix and transpose.py | 486 | 3.953125 | 4 | list1=[[1,1,1],[2,2,2],[1,1,1]]
list2=[[1,1,1],[1,1,1],[1,1,1]]
#list3=[[0,0,0],[0,0,0],[0,0,0]]
for k in range(3):
print '|',
for l in range(3):
print list1[k][l],
print '|\n'
print'*********'
f=0
for i in range(3):
for j in range(3):
list2[i][j]=list1[j][i]
print 'The tranpose :'
for m in range(3):
print '|',
for n in range(3):
print list2[m][n],
print '|\n'
|
59a1e376ae8bf470a623070f71eca6ea2d2791e4 | InesTeudjio/FirstPythonProgram | /ex3.py | 238 | 4.40625 | 4 | # 3. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
new_string = string [:2] + string[-2:]
print(new_string) |
94c8681ed44e9da010bedd0d54c9d219e0fc6a2e | the-nans/py_repo_4gb | /lesson_4/lesson4_cw6.py | 2,974 | 3.53125 | 4 | """
Реализовать два небольших скрипта:
а) итератор, генерирующий целые числа, начиная с указанного,
б) итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл не должен
быть бесконечным. Необходимо предусмотреть условие его завершения.
Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл. Во втором
также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено.
"""
from itertools import count, cycle
from sys import argv
def iter1(start, fin):
"""
итератор, генерирующий целые числа, начиная с указанного
:return: список целых чисел начиная со start и до fin
"""
for i in range(start, fin+1):
yield i
def iter2(user_list, fin):
"""
итератор, повторяющий элементы некоторого списка, определенного заранее
:return: список, состоящий из элементов входящего списка, повторённых fin раз
"""
result = []
c = 0
for i in cycle(user_list):
c += 1
result.append(i)
if c <= fin*len(user_list):
yield result
else:
break
iteration = "Вводите аргументы правильно"
if int(argv[1]) == 1:
try:
arg_start = int(argv[2])
arg_end = int(argv[3])
iteration = iter1(arg_start, arg_end)
while True:
print(next(iteration))
except ValueError:
print('Аргументы должны быть целыми числами!')
except IndexError:
print('Минимум три аргумента!')
except StopIteration:
print("Конец")
elif int(argv[1]) == 2:
try:
arg_end = int(argv[2])
arg_start_list = argv[3::]
iteration = iter2(arg_start_list or ["No list defined"], arg_end or 1)
while True:
print(next(iteration))
except IndexError:
print('Минимум три аргумента!')
except StopIteration:
print("Конец")
else:
print("lesson4_cw6.py [1 <начало отсчета> <конец последовательности>|2 <множество, "
"через пробел> <кол-во повторений>] ")
|
a2b465ed58bee8e0c11fe4697d7ee694ac3670a6 | guardeivid/aiuta | /Lenguajes/Python/Curso/90-Geolocalizacion.py | 1,291 | 3.625 | 4 | #!/usr/bin/env python 3
# -*- coding: utf-8 -*-
# instalar
# pip install geopy
#
"""
from geopy.geocoders import Nominatim
punto = "22.1577057, -102.2731303"
geolocation = Nominatim()
result = geolocation.reverse(punto)
print result.address # direccion
print(result.latitude, result.longitude)
print result.raw # json
#-------------------------------
from geopy.geocoders import GoogleV3
geolocation = GoogleV3()
try:
result = geolocation.reverse(punto)
#print str(result[0]).encode('utf-8')
print u' '.join((result[0])).encode('utf-8').strip()
print (result[0]) # direccion
except Exception as e:
print e
#a = "Pabellón de Arteaga, Aguascalientes, 20620, México"
#print a.decode('unicode-escape')
# si da error de timeout,
# aumentar el valor de la variable DEFAULT_TIMEOUT = 1
# en python/lib/site-package/geopy/geocoders/base-py
"""
#########################################################
#otra manera
# pip install geocoder
#
import geocoder
#latlon = geocoder.google("San Diego, California")
#print ("San Diego, California", latlon.latlng)
# reverse
#direccion = geocoder.google([45.1221, 54.1212], method="reverse")
#print direccion.city, direccion.state_long, direccion.country_long
postal_zip = geocoder.google("300 Post Street, San Francisco, CA")
print postal_zip.postal |
99a4f752e7924393936cb57d4a38153024c9089d | johanqr/python_basico_2_2019 | /Tarea5/Ejemplo.py | 1,258 | 3.8125 | 4 | # Misc classes
class misc:
def __repr__(self):
# return the clase name
return self.__class__.__name__
def __str__(self):
# return the clase name
return self.__class__.__name__
class Animal(misc):
def __init__(self, especie):
self.especie = especie
def reproducirse(self):
print(f'El {self} está reproduciendose')
def comer(self):
print(f'El {self} está comiendo')
def crecer(self):
print(f'El {self} está creciendo')
def nacer(self):
print(f'El {self} está naciendo')
def morir(self):
print(f'El {self} está muriendo')
class Mono(Animal):
def __init__(self):
super().__init__(especie='Mono')
self.cola = True
def jugar(self):
print(f'El {self.especie} está jugando')
def mueve_la_cola(self):
print(f'El {self.especie} mueve la cola')
class Humano(Mono):
def __init__(self):
self.especie = 'Humano'
self.cola = False
def mueve_la_cola(self):
if not self.cola:
print(f'El {self.especie} no tiene cola')
else:
print(f'El {self.especie} tiene cola')
yo = Humano()
print(yo) |
244244432e2911b854fb56d9e5f4acf33a39d2f6 | preetha-mani/IBMLabs | /Calculator.py | 292 | 4 | 4 | first=int(input("enter a first number:"))
second=int(input("enter a second number:"))
add=(first+second)
sub=(first-second)
div=(first/second)
mul=(first*second)
print("The addition is",add)
print("The Subtraction is",sub)
print("The multiplication is",mul)
print("The division",div) |
fc9c76f8a4106e82a687adbabf688476306a179f | wasp-lahis/PED-1s2020 | /lab_06/lab06.py | 1,011 | 3.609375 | 4 | percurso = 33
qtd_nivel_0 = 0
qtd_nivel_1 = 0
qtd_nivel_2 = 0
tempo = 0
tempo_medio = 0.
max_velocidade = 0.
min_velocidade = 1000
soma_tempo = 0
cont = 0
tempo = float(input())
while tempo != -1:
if tempo < 180:
qtd_nivel_0 +=1
elif tempo >= 180 and tempo < 240:
qtd_nivel_1 +=1
elif tempo >= 240:
qtd_nivel_2 +=1
tempo_min = tempo/60
velocidade = percurso/tempo_min
if velocidade > max_velocidade:
max_velocidade = velocidade
if velocidade < min_velocidade:
min_velocidade = velocidade
soma_tempo += tempo
cont += 1
tempo = int(input())
tempo_medio = soma_tempo/cont
print("Caracois no nivel 0:", qtd_nivel_0)
print("Caracois no nivel 1:", qtd_nivel_1)
print("Caracois no nivel 2:", qtd_nivel_2)
print("Tempo medio:", round(tempo_medio,1), "s")
print("Velocidade maxima:", round(max_velocidade,1), "cm/min")
print("Velocidade minima:", round(min_velocidade,1), "cm/min")
|
1b2d60ddb87afd52191b3a699003657830bde59d | jannekai/project-euler | /061.py | 741 | 3.53125 | 4 | from collections import OrderedDict
import time
import math
from euler import *
start = time.time()
def triangle(n): return int(n*(n+1)/2)
def square(n): return int(n*n)
def pentagonal(n): return int(n*(3*n-1)/2)
def hexagonal(n): return int(n*(2*n-1))
def heptagonal(n): return int(n*(5*n-3)/2)
def octagonal(n): return int(n*(3*n-2))
i = 1
triangles = []
squares = []
pentagonals = []
heptagonals = []
octagonals = []
while True:
i += 1
break
i = 0
d = OrderedDict()
while True:
i += 1
t = triangle(i)
s = square(i)
p = pentagonal(i)
h = hexagonal(i)
o = octagonal(i)
end = time.time() - start
print ("Total time was " + str(end)+ " seconds")
|
cf68801c5aae8c1e5a2182f226e583b0966a36d9 | jaeminjung/algoexpert | /productSum.py | 476 | 3.78125 | 4 | def helpf(array, depth):
ans = 0
while array:
first = array.pop(0)
if type(first) != list:
ans += first * depth
else:
ans += helpf(first, depth + 1)
return ans
def productSum(array):
# Write your code here.
ans = 0
depth = 1
while array:
first = array.pop(0)
if type(first) != list:
ans += first * depth
else:
ans += helpf(first, depth + 1)
return ans
print(productSum([5, 2, [7, -1], 3, [6, [-13, 8], 4]])) # 12 |
1eb3bede29decc9d40711569f48172c5a9702489 | BharathiSundaravadivel/Practise_Python | /cal_age.py | 1,692 | 4.25 | 4 | '''
-Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
-
-Extras:
-
-Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
-Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button)
'''
from datetime import date
def caluclateCentYear(curr_age,name,num):
diff_in_age = 100 - curr_age
curr_year=int(date.today().year)
cent_age = curr_year + diff_in_age
if (num==0):
print("Number Cannot be Zero")
return
else:
printNum(num,name,cent_age)
printNumMultLine(num,name,cent_age)
return
def printNum(number,name,cent_age):
print ("\nPrinting "+str(num)+" Times\n")
print (("Hello "+name+", You will turn Hundred in " + str(cent_age)+"\n")*number)
print("Printed the Lines "+": "+str(number) + " times\n")
def printNumMultLine(number,name,cent_age):
print ("\nPrinting "+str(num)+" Times, Split into Multiple Lines\n")
print (("Hello "+name+",\nYou will turn Hundred in\n" + str(cent_age)+"\n")*number)
print("Printed the Lines "+": "+str(number) + " times, spit into Multiple Lines")
name = input("Enter your Name:")
cur_age = int(input("Enter Your Age:"))
num =int(input("Enter a number:"))
caluclateCentYear(cur_age,name,num)
|
8f308473e75c57c93ee878ee2466277507ae2e79 | Hidayattullah/first_repo | /Example1.py | 141 | 4.0625 | 4 | #Simple example
a = 10
b = 50
if a > b:
print("A more than B")
print(a-b)
else:
print("B more or equal A")
print(b-a)
print("The End") |
1413ee82b38c2178cc0429cd9e755ec8fd3ca370 | DeepaShrinidhiPandurangi/Problem_Solving | /Rosalind/Formatting_FASTA_files/Remove_empty_lines.py | 454 | 3.734375 | 4 | # Remove empty lines from the file
openfile = open("L3_char.txt")
contents = openfile.read()
#print(read)
new_contents = []
for line in contents:
# Strip whitespace, should leave nothing if empty line was just "\n"
if not line.strip():
continue
# We got something, save it
else:
new_contents.append(line)
for i,j in enumerate(new_contents):
if j in L:
print("",end="")
else:
print(j,end="")
|
e59fafae44068ba3e52fc104e26454939c334833 | arsummers/python-data-structures-and-algorithms | /data-structures/graph/graph.py | 791 | 3.671875 | 4 | class Graph:
def __init__(self):
self._vertices = []
def add_vertex(self, value):
vert = Vertex(value)
self._vertices.append(vert)
return vert
def get_vertices(self):
return self._vertices or None
def add_edge(self, vert1, vert2, weight=0):
if vert1 in self._vertices and vert2 in self._vertices:
vert1.neighbors.append(Edge(vert2, weight))
def get_neighbors(self, vertex):
return vertex.neighbors
def __len__(self):
return len(self._vertices)
class Edge:
def __init__(self, vertex, weight=0):
self.vertex = vertex
self.weight = weight
class Vertex:
def __init__(self, value):
self.value = value
self.neighbors = []
self.visited = False |
4aff5328f4d32d46d8fb0273caee126b40bbb844 | andrewrosss/rake-spacy | /rake_spacy/aggregators.py | 1,247 | 3.546875 | 4 | from abc import ABC
from abc import abstractmethod
from typing import List
import numpy as np
class BaseAggregator(ABC):
@abstractmethod
def __call__(self, scores: List[float]) -> float:
"""Reduces a list of numbers to a single number.
Args:
scores (List[float]): The numbers over which to perform the reduction.
Returns:
float: The result.
"""
pass
class SumAggregator(BaseAggregator):
def __call__(self, scores: List[float]) -> float:
return sum(scores)
class MeanAggregator(BaseAggregator):
def __call__(self, scores: List[float]) -> float:
return sum(scores) / len(scores)
class PenalizedNormAggregator(BaseAggregator):
def __init__(self, max_len_before_penalization: int = 5):
self.max_len_before_penalization = max_len_before_penalization
def __call__(self, scores: List[float]) -> float:
N = np.linalg.norm(scores)
D = len(
[s for s in scores if s != 0]
) # omit ignoreable words from length penalty
# if there are 4 or fewer non-stop words, don't penalize
D = 1 if (1 <= D <= self.max_len_before_penalization) else D
return float(N / D) if D != 0 else 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.