blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6b0dad06b9a28d7fe7b8d4502e13e30a798d03c7 | Helen-Sk-2020/JetBr_Simple_Tic_Tac_Toe | /Topics/Loop control statements/Cat cafés/main.py | 259 | 3.8125 | 4 | # import math
cafe_name = []
cats_number = []
while True:
cafe = input()
if cafe == "MEOW":
break
cafe = cafe.split()
cafe_name.append(cafe[0])
cats_number.append(int(cafe[1]))
print(cafe_name[cats_number.index(max(cats_number))])
|
ab99d76921a81c7e506bb3dc0951b7c57501ef06 | codywalter/python-work | /Assignment_Ch06-03_Walter.py | 1,030 | 4.09375 | 4 | import inquirer
import emoji
print("Palindrome Game is an interactive command line application that takes a user's input and checks to see if it is a palindrome.")
def palGame():
userInput = input("Please enter a word: ")
def isPalindrome(word):
return word == word[::-1]
palindromeCheck = isPa... |
27ba79e71c6f8efaa27865f94400cdb36859758d | VitBomm/CSC | /Module1/Bai3/3_4.py | 557 | 3.6875 | 4 | '''
Created on Feb 2, 2017
Trung Tam Tin Hoc - DH KHTN
'''
x = 10
y = 4
print('x = %d, y = %d'%(x,y))
equivelence = x==y
print('x==y is', equivelence)
# equivelence = False
equivelence = x!=y
print('x!=y is', equivelence)
# equivelence = True
equivelence = x>y
print('x>y is', equivelence)
# equivelence = True
x = 8... |
1e793adfeeed5b4441e555317d4cf970f3cccc85 | VitBomm/CSC | /Module1/bai11/11_5.py | 1,078 | 3.578125 | 4 | '''
Created on October 24, 2019
@author: Trung Tâm Tin Học - Trường Đại học Khoa học Tự nhiên TP.HCM
'''
import csv
import os
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
# Học viên xây dựng phương thức đọc nội dung tập tin .CSV
def read_csv_file(filename):
f = open(o... |
9823727fa5eef19a64b9ee87eebc12b5d41fa1f1 | VitBomm/CSC | /Module1/bai8/8_7.py | 417 | 3.671875 | 4 | '''
Created on October 17, 2019
@author: Trung Tâm Tin Học - Trường Đại học Khoa học Tự nhiên TP.HCM
'''
# Xây dựng hàm tính lũy thừa
def exponents(bases,powers):
temp = []
for i in bases:
for j in powers:
temp.append(i**j)
return temp
# In kết quả
print(exponents([2, 3, 4,... |
a31838e3ca4253493aaec295e9bc8bd3f9ff2aaa | VitBomm/CSC | /Module1/Bai5/5_3.py | 180 | 3.734375 | 4 | n = int(input("Nhập n: "))
a = 0
b = 1
print(a)
print(b)
for i in range(n - 2):
if i % 2 == 0:
a = a + b
print(a)
else:
b = b + a
print(b) |
9d043480cac1e66d2d572c5494b0ab42bbe993cc | VitBomm/CSC | /Module1/Bai5/5_5.py | 146 | 3.609375 | 4 | n = input("Nhập chuỗi cần đảo ngược:")
m = n.split(' ')
s = ""
for i in range(len(m)):
s += str(m[i][::-1]) + ' '
print(s.strip()) |
149631ce889f74a12f7f06b3c2ff4796747214bd | VitBomm/CSC | /Module1/baikiemtra/bai_3.py | 1,408 | 3.671875 | 4 | # Tạo danh sách nhân viên kiểu dictionary với key là mã nhân viên,
# value bao gồm các thông tin : tên nhân viên, số điện thoại, lương.
# Cho phép người dùng lần lượt nhập các phần tử cho danh sách cho
# đến khi không muốn nhập nữa
# => Chương trình sẽ thực hiện những công việc sau:
# - Hiển thị danh sách nhân viên.
#... |
91e0b29117d37464d68e0e8929695726fc4e3d64 | VitBomm/CSC | /Module1/baikiemtra/bai_2.py | 1,056 | 3.828125 | 4 | # Tạo list
# Nhập số phần tử trong list
# Cho phép người dùng lần lượt nhập các phần tử cho list cho đến khi
# không muốn nhập nữa
# => Chương trình sẽ thực hiện những công việc sau:
# a/ Đếm tần suất xuất hiện của các phần tử. Chẳng hạn với list gồm
# các phần tử: 12 34 12 34 43 12 5 thì tần suất xuất hiện các phầ... |
63ed0cd1a6c30ae010bd28b373a5e9485c9b3901 | ferry5245/Basic-Coding | /Python learning/Coursera/Vid_Ex/FileRead.py | 413 | 3.640625 | 4 | fname = input("Enter file name: ")
try:
fh = open(fname)
except:
print("Sorry, unable to read file or it doesn't exists.")
quit()
x = 0
total = 0
num = 0
for line in fh:
line = line.strip()
if not line.startswith("X-DSPAM-Confidence:") : continue
pos = line.find("0")
num = float(line[pos:])... |
b6a6ff595b5443b08a1360e92c57151c493691d1 | ferry5245/Basic-Coding | /Python learning/Coursera/Vid_Ex/Function.py | 633 | 4.03125 | 4 | def main():
x = input("Add Number Here : ")
y = input("Add Another : ")
inp = input("Menu:\na. Addition\nb. Subtraction\nc. Division\nd. Multiplication\nWhat do you want to do? ")
if inp == "a" : out = adding(x,y)
elif inp == "b" : out = subtrct(x,y)
elif inp == "c" : out = divis(x,y)
elif i... |
a6392759698c851f079861ee8ae851fcc3cc448a | willoughbys70590/01-recipes | /07_to_grams.py | 830 | 3.703125 | 4 | import csv
# open file
groceries = open('01_ingredients_ml_to_g.csv')
# read data into a list
csv_groceries = csv.reader(groceries)
# create a dictionary to hold the data
food_dictionary = {}
# add the data from the list into the dictionary
# (first item in row is key, next is definition)
for row in csv_groceries:... |
bd6721cc512d2b54803bb8178d911a2f7f5515cf | scikit-learn/scikit-learn | /examples/datasets/plot_random_multilabel_dataset.py | 3,180 | 3.765625 | 4 | """
==============================================
Plot randomly generated multilabel dataset
==============================================
This illustrates the :func:`~sklearn.datasets.make_multilabel_classification`
dataset generator. Each sample consists of counts of two features (up to 50 in
total), which are dif... |
11bb1b289e2c800fa87ab34847465089495ade17 | scikit-learn/scikit-learn | /examples/model_selection/plot_confusion_matrix.py | 2,084 | 4.4375 | 4 | """
================
Confusion matrix
================
Example of confusion matrix usage to evaluate the quality
of the output of a classifier on the iris data set. The
diagonal elements represent the number of points for which
the predicted label is equal to the true label, while
off-diagonal elements are those that ... |
df29af00ca9dda7f9fe4fa15dbfcaa0c18739208 | scikit-learn/scikit-learn | /examples/neighbors/plot_classification.py | 3,142 | 3.984375 | 4 | """
================================
Nearest Neighbors Classification
================================
This example shows how to use :class:`~sklearn.neighbors.KNeighborsClassifier`.
We train such a classifier on the iris dataset and observe the difference of the
decision boundary obtained with regards to the paramete... |
07912459f2c76488fbeb1272e2ffebe1a88f6d6b | scikit-learn/scikit-learn | /examples/applications/plot_species_distribution_modeling.py | 7,763 | 3.5 | 4 | """
=============================
Species distribution modeling
=============================
Modeling species' geographic distributions is an important
problem in conservation biology. In this example, we
model the geographic distribution of two South American
mammals given past observations and 14 environmental
vari... |
492f763201dd967fc10d804615c2f9fd054dae48 | scikit-learn/scikit-learn | /examples/model_selection/plot_det.py | 3,996 | 3.578125 | 4 | """
====================================
Detection error tradeoff (DET) curve
====================================
In this example, we compare two binary classification multi-threshold metrics:
the Receiver Operating Characteristic (ROC) and the Detection Error Tradeoff
(DET). For such purpose, we evaluate two differe... |
a4b30249f2c4f750e8a9ebd3a4d7e6cfcbf992b5 | scikit-learn/scikit-learn | /examples/preprocessing/plot_all_scaling.py | 14,301 | 3.5625 | 4 | """
=============================================================
Compare the effect of different scalers on data with outliers
=============================================================
Feature 0 (median income in a block) and feature 5 (average house occupancy) of
the :ref:`california_housing_dataset` have very
d... |
81bccd24f87cb736ef668075387cfba2c8f5185c | scikit-learn/scikit-learn | /examples/cluster/plot_kmeans_plusplus.py | 1,169 | 4.125 | 4 | """
===========================================================
An example of K-Means++ initialization
===========================================================
An example to show the output of the :func:`sklearn.cluster.kmeans_plusplus`
function for generating initial seeds for clustering.
K-Means++ is used as the... |
a50e3136d57bbe228c3b2a117ff7b4965cf5ec90 | scikit-learn/scikit-learn | /examples/miscellaneous/plot_multilabel.py | 4,057 | 3.921875 | 4 | """
=========================
Multilabel classification
=========================
This example simulates a multi-label document classification problem. The
dataset is generated randomly based on the following process:
- pick the number of labels: n ~ Poisson(n_labels)
- n times, choose a class c: c ~ Multinom... |
18b9627b677851eb43d48ae9af0c50b5a3146527 | scikit-learn/scikit-learn | /examples/linear_model/plot_quantile_regression.py | 11,510 | 3.71875 | 4 | """
===================
Quantile regression
===================
This example illustrates how quantile regression can predict non-trivial
conditional quantiles.
The left figure shows the case when the error distribution is normal,
but has non-constant variance, i.e. with heteroscedasticity.
The right figure shows an ... |
13eb99296be52831902b7a14e9a469fdb4fc7e47 | scikit-learn/scikit-learn | /examples/compose/plot_feature_union.py | 1,925 | 3.8125 | 4 | """
=================================================
Concatenating multiple feature extraction methods
=================================================
In many real-world examples, there are many ways to extract features from a
dataset. Often it is beneficial to combine several methods to obtain good
performance. Th... |
a1dd980a073fc05730088002db26d1cf90da6e9e | scikit-learn/scikit-learn | /examples/applications/plot_digits_denoising.py | 5,205 | 3.6875 | 4 | """
================================
Image denoising using kernel PCA
================================
This example shows how to use :class:`~sklearn.decomposition.KernelPCA` to
denoise images. In short, we take advantage of the approximation function
learned during `fit` to reconstruct the original image.
We will co... |
803cdf0c598a743f8d34ab6eba291c3e443b55c5 | scikit-learn/scikit-learn | /examples/model_selection/plot_underfitting_overfitting.py | 2,680 | 4.375 | 4 | """
============================
Underfitting vs. Overfitting
============================
This example demonstrates the problems of underfitting and overfitting and
how we can use linear regression with polynomial features to approximate
nonlinear functions. The plot shows the function that we want to approximate,
wh... |
b3fea1c06026a2ed69bf6671661a40d87b197fa4 | scikit-learn/scikit-learn | /examples/tree/plot_tree_regression.py | 1,527 | 3.6875 | 4 | """
===================================================================
Decision Tree Regression
===================================================================
A 1D regression with decision tree.
The :ref:`decision trees <tree>` is
used to fit a sine curve with addition noisy observation. As a result, it
learns ... |
94fd4a81942dfca0dae1d6a51d0ae3a2e5b61a5e | scikit-learn/scikit-learn | /examples/preprocessing/plot_target_encoder_cross_val.py | 7,185 | 3.796875 | 4 | """
=======================================
Target Encoder's Internal Cross fitting
=======================================
.. currentmodule:: sklearn.preprocessing
The :class:`TargetEncoder` replaces each category of a categorical feature with
the shrunk mean of the target variable for that category. This method is ... |
fdc9fd3418c0b92c902dc7fb30d8a6aa78bc592a | scikit-learn/scikit-learn | /examples/feature_selection/plot_feature_selection_pipeline.py | 2,768 | 3.875 | 4 | """
==================
Pipeline ANOVA SVM
==================
This example shows how a feature selection can be easily integrated within
a machine learning pipeline.
We also show that you can easily inspect part of the pipeline.
"""
# %%
# We will start by generating a binary classification dataset. Subsequently, we... |
1807549c4410bae974a8d16a7e3965878bd28fb3 | scikit-learn/scikit-learn | /examples/gaussian_process/plot_gpr_noisy.py | 6,481 | 3.5625 | 4 | """
=============================================================
Gaussian process regression (GPR) with noise-level estimation
=============================================================
This example shows the ability of the
:class:`~sklearn.gaussian_process.kernels.WhiteKernel` to estimate the noise
level in the d... |
48b128d1258f5c1c7267fe2d9905885403525259 | scikit-learn/scikit-learn | /examples/ensemble/plot_gradient_boosting_regularization.py | 2,648 | 3.75 | 4 | """
================================
Gradient Boosting regularization
================================
Illustration of the effect of different regularization strategies
for Gradient Boosting. The example is taken from Hastie et al 2009 [1]_.
The loss function used is binomial deviance. Regularization via
shrinkage (`... |
7048b1d8ad68b17f474d61a325070c9fdef31488 | scikit-learn/scikit-learn | /examples/ensemble/plot_gradient_boosting_regression.py | 4,966 | 4.28125 | 4 | """
============================
Gradient Boosting regression
============================
This example demonstrates Gradient Boosting to produce a predictive
model from an ensemble of weak predictive models. Gradient boosting can be used
for regression and classification problems. Here, we will train a model to
tackl... |
90937f02283d527b65f6dab1a20f78904e0ad7d6 | scikit-learn/scikit-learn | /examples/svm/plot_custom_kernel.py | 1,302 | 3.734375 | 4 | """
======================
SVM with custom kernel
======================
Simple usage of Support Vector Machines to classify a sample. It will
plot the decision surface and the support vectors.
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, svm
from sklearn.inspection import De... |
8dcda4cb333200ac049fae5bcb1e153597125b84 | scikit-learn/scikit-learn | /examples/neighbors/plot_lof_novelty_detection.py | 3,560 | 3.796875 | 4 | """
=================================================
Novelty detection with Local Outlier Factor (LOF)
=================================================
The Local Outlier Factor (LOF) algorithm is an unsupervised anomaly detection
method which computes the local density deviation of a given data point with
respect to... |
ab88ed5050c16e547d2822470574d0e40474c3e5 | scikit-learn/scikit-learn | /examples/feature_selection/plot_feature_selection.py | 3,806 | 3.984375 | 4 | """
============================
Univariate Feature Selection
============================
This notebook is an example of using univariate feature selection
to improve classification accuracy on a noisy dataset.
In this example, some noisy (non informative) features are added to
the iris dataset. Support vector machi... |
9ec902702ccda81e0f029fb81c58b42f3de78829 | scikit-learn/scikit-learn | /examples/linear_model/plot_ridge_path.py | 1,972 | 3.890625 | 4 | """
===========================================================
Plot Ridge coefficients as a function of the regularization
===========================================================
Shows the effect of collinearity in the coefficients of an estimator.
.. currentmodule:: sklearn.linear_model
:class:`Ridge` Regressi... |
8ccfdc9ed27467c1ebb23cadd24aaf2da7265b46 | App24/Chat-App | /client_gui_v2.py | 6,600 | 3.59375 | 4 | from tkinter import *
from tkinter.font import *
import socket
import sys
import select
import errno
import sys
class App:
def __init__(self):
self.HEADER_LENGTH=10
self.IP="127.0.0.1"
self.PORT=1234
self.startIPPort()
def popup(self, title,_text,_fg="black"):
toplevel ... |
661c41c3180b7e31b1db2bb053542c948868f3ef | mbcaira/pybank-app | /PyBank.py | 8,329 | 3.875 | 4 | import Currencies
import Account
def check_amount_validity(amount: str) -> bool:
"""
Static method to check whether a given amount is valid for a monetary value
(i.e. cannot be negative or contain letters).
:param amount: String value that will be checked for monetary validity.
:return:... |
6f94989a373d293be00a07244434ff4fb0c973b6 | bakunobu/Certificates | /pirple_python/hw_1.py | 767 | 3.90625 | 4 | """
Homework 1
variables:
==========
Artist: str
My favourite performer
Genre: str
The performer's maing genre
Song: str
Favourite song by the performer
DurationInSeconds: int
Song duration in seconds
Language: str
The language of lyrics
Album: str
The album the song was listed
Year: int
The year the album was released... |
79fb87f0f99b2786cc0fe5522a007b6c6fee258d | RocheJorge/Proyectos-Personales-Python-Github | /num-par-impar.py | 181 | 3.921875 | 4 | # El numero es par o impar
num = int(input("Ingrese un Numero: "))
resto = num%2
if resto == 0:
print("El numero Es par")
else:
print("El numero es impar") |
2c74553296a8d402ef7e9b3a724c8e331f7c7b2d | RocheJorge/Proyectos-Personales-Python-Github | /promedio-notas.py | 260 | 3.84375 | 4 | nota1 = float(input("Ingrese la Nota 1: "))
nota2 = float(input("Ingrese la Nota 2: "))
promedio = (nota1 + nota2) / 2
print("El promedio es: ",promedio)
if promedio >= 60:
print("Aprobo la Materia")
else:
print("Reprobo la Materia") |
e67bc9ccd891ec7a42cf080eb53fcc8c02cbfac0 | RocheJorge/Proyectos-Personales-Python-Github | /ejercicio-eliminar-duplicados-de-una-lista.py | 652 | 4.0625 | 4 |
"""
Con la siguiente lista:
Lista = [1, 2, 3, 4, 5, 1, 6, 7, 9, 4, 5, 1, 8, 4, 1, 5]
a partir de alli, debes desarrollar un codigo que permita eliminar los valores repetidos y muestre en otra lista los elementos que no han sido eliminados, es decir, los que no se repiten
Realizado por Jorge Roche 24743191
"""
print... |
bebb59d443a86f51c5249f929a2fe3b43f3a1c94 | Omega97/omar_utils | /misc/default_dict.py | 558 | 3.875 | 4 |
class DefaultDict(dict):
"""
dict-like object, returns default value if item not in self
"""
def __init__(self, *args, default=0, **kwargs):
self.default = default
super().__init__(*args, **kwargs)
def __getitem__(self, item):
if item in self:
return ... |
584e9472cd96f38433508906e1245a4e9fc17366 | Omega97/omar_utils | /_tests/test_Set.py | 744 | 3.71875 | 4 | from basic.Set import *
def test_1():
assert Set('a') + Set('b') == Set('a', 'b')
assert Set('a', 'b') - Set('b') == Set('a')
assert Set(1, 2) + Set(2, 3) == Set(1, 2, 3)
assert Set(1, 2) - Set(2, 3) == Set(1)
assert Set(1, 2, 3) | Set(3, 4, 5) == Set([i + 1 for i in range(5)])
assert Set(1, 2... |
d46c82d9a0a65cc7ee8aaf59359c822aede6d325 | amkustagi/ds_materials | /pytorch_basics/dataset.py | 3,145 | 4.1875 | 4 | import torch
from torch.utils.data import Dataset
from torchvision import transforms
# To Building data set class Importing Abstract class from the PyTorch
# It is a subclass of data set class
# Initializing the constructor
class toy_set(Dataset):
# Constructors are generally used for instantiating an ... |
5e0bb5223a30f74e9512936e7beef61d91f7fe84 | AramirezTorres/CursoPythonini | /Repositorios/Numeros/Flotantes.py | 507 | 3.984375 | 4 | print(0.1+0.1) #resultado 0.2
print(0.2 + 0.1) #resutado= 0.30000000000000004 porque se genera el numero mas proximo
print (0.3==(0.2+0.1)) #daría como resultado 'falso'
# en cadenas largas de numero se puede separar cada tres digitos con un guion bajo, ejemplo 14_000_000_000.00
x,y,z= 15,25,39 #(genera un grupo de va... |
cfd8c193efec11c40dc1d1f446e8696f6206de76 | AramirezTorres/CursoPythonini | /Repositorios/Hola_Mundo.py | 544 | 3.953125 | 4 | print("hola mundo")
message1="hola mundo"
message2="Adios mundo"
print(message2.upper())
nombre="Atanacio"
apellido="Ramírez"
print(nombre + " " + apellido) #concatenacion de textos
nombre_comleto=f"{nombre} {apellido}" # concatenacion de textos
print(nombre_comleto)
#Limpiar cadena (espacios al inicio o final)
... |
a0b2b7ab0341914e0e5ff08e10ad6215df4d5873 | nikhuff/cs450 | /prove08/neural_net.py | 6,674 | 3.578125 | 4 | import numpy as np
import math
from sklearn import preprocessing
# use to switch between classification and regression
regression = True
class Connection:
def __init__(self, connected_neuron):
self.connected_neuron = connected_neuron
self.weight = np.random.normal()
self.dWeight = 0.0
c... |
b48c482f95c4945a0a4713596b88dc13d49fa94d | songchaogeng/store | /air_conditioning.py | 650 | 3.625 | 4 | class Air_conditioning:
#品牌
__brand=""
def setbrand(self, brand):
self.__brand = brand
def getbrand(self):
return self.__brand
#价格
__price=0
def setprice(self, price):
self.__price = price
def getprice(self):
return self.__price
def open... |
cf3ba649707a4acfde9d8507ef85ed991c1ae3ff | clarkbulleit/bme590hrm | /peak_detect.py | 1,034 | 3.515625 | 4 |
def peak_detect(data, perh=.5, perl=0.015):
""" Detects time locations of peaks
Detection algorithm is sensitive to the input parameters. Different
inputs work better with different ECG traces.
Args:
:param data: Dictionary with lists under keys
"time" and "voltage"
:param per... |
2fdc4c2ad405ca9e20ee8f7ebb0fe6fa3b90e9b3 | etbrow/learn-python | /HillOfBeansGame/HillOfBeansGUI.py | 4,284 | 3.8125 | 4 | from tkinter import *
from tkinter import messagebox
import random
counter = 0
numberOfBeans = 15
def showMessageBox(gameMessage):
messagebox.showinfo(title="Game Event",
message=gameMessage)
def otherTurn():
global numberOfBeans
if random.randint(1, 147)%3 == 0:
... |
698567f328b7c6f159279a79cd1da607990a03be | hawktc/linux | /python/c-days-5.py | 1,147 | 3.9375 | 4 | # help encode chinese
#-*- coding: utf-8 -*-
# import math for mathExercise
import math
# leap year calc
def isLeapYear(year):
"return true if input is leap year, otherwise false"
if ( (year % 4 == 0) & (year % 100 != 0) | (year % 400 == 0) ):
return 1
else:
return 0
# math calc
def mathExercise():
... |
bcbc8a9b9c031160eb89a9e4369485fc26d7acf2 | aderricoyu/puzzle_functions | /puzzle_program.py | 5,360 | 4.1875 | 4 | import puzzle_functions
def get_num_rows(puzzle):
""" (str) -> int
Return the number of rows in puzzle, which is a game board.
>>> get_num_rows('abcd\nefgh\nijkl\n')
3
"""
return puzzle.count('\n')
def get_num_cols(puzzle):
""" (str) -> int
Return the number of ... |
c01892ccff28b54ae141e8c1aa4000624f59b172 | michaelzm/p_euler | /problem12/problem12.py | 2,163 | 3.609375 | 4 | import time
import digits
divisors = 1
#save the number of divisors for each number
arr_nums = []
holder_divisors = []
start_t = time.time()
it_counter = 0
wh_1_counter = 0
wh_2_counter = 0
natural_num = 1
highest_num = 1
hBase = 0
while divisors < 50:
number_time_s = time.time()
arr_nums = []
#add 2 (one for 1 div... |
063c182b5131341adbba01f81c7e017ede0f8803 | michaelzm/p_euler | /problem10/problem10.py | 1,058 | 3.75 | 4 | prime = False
primenumbers = [3,5]
start_n = 1
counter = 2
last_prime = 0
dosearch = True
while dosearch:
prime = True
if start_n % 2 != 0 and start_n % 3 != 0 and start_n % 5 != 0 and start_n != 1:
#pn candidate
for pn in primenumbers:
if start_n... |
9feef21f5b23cf8bcd9fbd019d42fecbf57cbcf3 | michaelzm/p_euler | /problem7/problem7.py | 394 | 3.703125 | 4 | prime = False
primenumbers = [3,5]
start_n = 1
counter = 2
while counter != 10003:
prime = True
if start_n % 2 != 0 and start_n % 3 != 0 and start_n % 5 != 0 and start_n != 1:
#pn candidate
for pn in primenumbers:
if start_n % pn == 0:
prime = False
if not prime:
break
if prime:
primenumbers.a... |
54a36488dec6a3103a370a3dcf0ddeb52c8d79ef | larryokubasu5460/python-for-everybody | /emails.py | 362 | 3.9375 | 4 | inp=input("Enter the name of the file: ")
try:
fh=open(inp)
except:
print("FIle does not exist")
quit()
count=0
for line in fh:
line=line.strip()
if not line.startswith('From '):
continue
count=count+1
word=line.split()
print(word[1])
print("There were {} line wit... |
ceb61c25fcfae63efd50cf2c19d5f2f8b5bc1c33 | larryokubasu5460/python-for-everybody | /grade.py | 739 | 4.34375 | 4 | # Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
# Score Grade
# >= 0.9 A
# >= 0.8 B
# >= 0.7 C
# >= 0.6 D
# < 0.6 F
# If the user enters a value out of range, print a suitable ... |
2ccddc59cb08db3d2eef85dc0dc13f23b7aac89c | DavidBetteridge/AdventOfCode2020 | /Day02/day2.py | 1,317 | 3.71875 | 4 | import re
class Line:
def __init__(self, lower, upper, symbol, password):
self.lower = lower
self.upper = upper
self.symbol = symbol
self.password = password
pattern = re.compile('(?P<lower>[0-9]+)-(?P<upper>[0-9]+) (?P<symbol>[a-z]): (?P<password>[a-z]+)')
lines = open('Day02/day2... |
c325500d85a950fdc5a9d97e779b883a5465de00 | MaximVazyulya/Lesson1 | /foгrth.py | 553 | 3.953125 | 4 | #4. Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
n = input("Введите целое положительное число n= ")
i = len(n)
a = i - 1
q = int(n[a])
while i>1:
if int(n[a]) < int(n[i-2]):
q = int(n[i-2])
... |
dd591382893a0a7d69174d29672303b40e31b5bb | nestorast/Pythonbasic | /main.py | 5,120 | 4.125 | 4 | #menu = """
#Bienvenido al convertidor de monedas
#1- pesos colombianos
#2- pesos argentinos
#3- pesos mexicanos
#"""
#opcion = int(input (menu))
#if opcion == 1:
# pesos = input ("cuantos pesos colombianos tienes? ")
# pesos = float(pesos) ##convierte pesos en una cifra decimal
# valor_dolar = 3875
# dolar... |
2c09b751e43a227af8a3c3e1df1b462041da1d87 | kimym56/42CoTe | /hyjeon/1_prog_bruteforce/2_소수 찾기.py | 964 | 3.609375 | 4 | import math
from itertools import permutations
def is_prime(n):
# 0, 1은 소수가 아님
if n < 2:
return 0
# 2부터 sqrt(n)까지만 나눠보고 나누어 떨어지는 지 확인하면 소수 판별 완료
else:
for i in range(2, int(math.sqrt(n))+1): # 원래 math.sqrt(n)하면 float
if n % i == 0:
return 0
return 1
... |
1c56d8ecb16686185b559a858bdb6a8555977883 | spaceworlds/shiyanlou-code | /calculator.py | 719 | 3.953125 | 4 | ##原始收入,获取用户输入
yssr = int(input('请输入你的薪资:'))
##税后收入
shsr = 0
##应交所得税额
yjsds = 0
#纳税金额
nsje = 0
def calculator(num):
yjsds = num - 5000
if yjsds <= 0 :
nsje = 0
elif 0 < yjsds <= 3000:
nsje = yjsds * 0.03 -0
elif 3000 < yjsds <= 12000:
nsje = yjsds * 0.1 - 210
elif 12000 < yjsds <= 25000:
nsje = yjsds * ... |
cf1064fa1227fbc45d4adf81c55df6632957a6ff | madrabbit2/Exercises_WEEK5 | /ex4_1.py | 990 | 4.15625 | 4 | # tempConvertWarning.py
# A temperature conversion program using an if structure
# to output a weather warning
# written by D.H.,December 2,2004
print "This program will ask you to input the temperature in degrees Fahrenheit"
print "then output the equivalent temperature in degrees Centigrade."
print "The pro... |
5d65b8e8fc9a651cdfe1f2d753041388708df4ce | Briggskm9/Recalls | /Activity 3 Hybercube Katie Briggs.py | 897 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import sys
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.special import gamma
from math import pi
# In[ ]:
# generate the corners of the hypercube
D = input('Enter the dimension of the hypercube: ') # try 10, 100, 1000... |
ee12925e337f42015402a59764982b4ddf9a8e03 | thenickrj/Data-Structures | /Binary Tree/Reverse Level Order Traversal.py | 1,231 | 4.15625 | 4 | # Reverse Level Order Traversal
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def reverseLevelOrder(temp):
h = height(temp)
for i in reversed(range(1, h + 1)):
printGivenLevel(root, i)
# Print nodes at a given le... |
e72f93d85f440ea3b91efc4e0079bed465012672 | aayushkabra1/algo_toolbox_UCSD | /week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py | 886 | 3.953125 | 4 | # Uses python3
import sys
# def fibonacci_sum_naive(n):
# if n <= 1:
# return n
# previous = 0
# current = 1
# sum = 1
# for _ in range(n - 1):
# previous, current = current, previous + current
# sum += current
# return sum % 10
def pisanoPeriod(m):
previo... |
4ff6e63f1635d14b051770a0b6ef7871a9fe8f5d | aayushkabra1/algo_toolbox_UCSD | /Greedy Algorithms/Maximum Salary/maximum_salary.py | 668 | 3.90625 | 4 | # python3
from itertools import permutations
def largest_number(numbers):
digits = []
for num in numbers:
number = int(num)
while number >= 10:
digit = number % 10
digits.append(digit)
number = number // 10
if number < 10:
digits.append(... |
a7d2b6535f0f2f665255a161d6a1ee834ab92968 | gomesp/kids-projects | /lucas-turtle.py | 939 | 3.8125 | 4 | #!/bin/python3
# From: https://projects.raspberrypi.org/en/projects/turtle-race
from turtle import *
from random import randint
speed(0)
penup()
goto(-140, 140)
for step in range(15):
write(step, align='center')
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(20... |
c43d58c0dfee9d7062b11c795ef65f3af338bb23 | prrn-pg/Shojin | /Practice/atcoder/AGC/007/src/a.py | 1,250 | 3.703125 | 4 | # 右と下の両方に#があったら終了だしどちらにもなくても終了
# なんやこのクソみたいな実装は
h, w = map(int, input().split())
table = []
sharp = 0
for _ in range(h):
get = input()
table.append(get)
sharp += get.count("#")
flag = False
pos = [0, 0]
path = 0
while True:
if pos == [h - 1, w - 1]:
path += 1
flag = True
break
... |
0c88c5ccb6438fa545f0325c3e32907792e1d174 | prrn-pg/Shojin | /Practice/atcoder/ABC/042/src/a2.py | 303 | 3.546875 | 4 | # 吸い込んでソートして[5, 5, 7]になるものっていう昔書いたやつがクレバーだった(忘れてた)
# 今回はまっさきに浮かんだやつで....
ok = [[5, 5, 7], [5, 7, 5], [7, 5, 5]]
stdin = list(map(int, input().split()))
print("YES" if stdin in ok else "NO")
|
642409410a66c01817f57818354f13a3a1819d53 | prrn-pg/Shojin | /Practice/AOJ/ALDS1/ALDS1_11/ALDS1_11D/alds1_11d.py | 1,225 | 3.515625 | 4 | # 隣接リストでBFS
# 色分け。
# 色分け、逐次やるんじゃなくて、生成していく。
# しかも「最初は互いに素にして仲間を増やしていく」じゃなくて、
# 「どこの色にも属していないところから仲間を増やしていく」というスタンス
# こうしない場合(互いに素から始める場合)の実装ができなかった
n, m = map(int, input().split())
colors = [0 for _ in range(n)] # 0がどこにも属していない状態ということにする
graph = [[] for _ in range(n)]
for _ in range(m):
s, t = map(int, ... |
24741a1869966fcb80a3502eada93bb0f1ed56cb | prrn-pg/Shojin | /Practice/atcoder/ABC/175/src/a.py | 175 | 3.9375 | 4 | s = list(input())
if s[0] == s[1] == s[2] == "R":
print(3)
elif s[0] == s[1] == "R" or s[1] == s[2] == "R":
print(2)
elif "R" not in s:
print(0)
else:
print(1) |
d9b9009cee8579d885d89c21a0707bc8caf94d41 | prrn-pg/Shojin | /Practice/atcoder/ABC/071/src/_d__dame.py | 943 | 3.546875 | 4 | # 直前が縦にそろっているかどうかで決まりそうだけどわからない
n = int(input())
s = [list(input()), list(input())]
MOD = 10 ** 9 + 7
ans = 1
vertical = False
i = 0
if n == 1:
print(3)
exit()
while i < n:
if i == 0:
if s[0][i] == s[1][i]:
ans = 3
i += 1
vertical = True
else:
... |
a26bcadcca30465f023b4081e4afaea8a110e579 | prrn-pg/Shojin | /Practice/atcoder/ABC/132/src/a.py | 119 | 3.71875 | 4 | s = sorted(input())
if s[0] == s[1] and s[2] == s[3] and len(set(s)) == 2:
print("Yes")
else:
print("No")
|
00f074177baa6f7c424ae744a60017c26a85333a | prrn-pg/Shojin | /Practice/atcoder/ABC/043/src/d.py | 490 | 3.75 | 4 | # 尺取かと思ったけど実装できんな
# あれ?過半数だから成立する場合は3文字だけを抜き取ったどこかで必ず成立するのでは
s = input()
if len(s) == 2:
if s[0] == s[1]:
print(1, 2)
else:
print(-1, -1)
exit()
for i in range(len(s) - 3):
target = s[i : i + 3]
if target[0] == target[1] or target[1] == target[2] or target[2] == target[0]:... |
1918174b962730629bbe25f942120169d45388cb | prrn-pg/Shojin | /templates/Typical/Others/CoordinateCompression/practice01_2D.py | 480 | 3.53125 | 4 | """
input
4
13 25
7 3
11 38
4 50
output
(x, y)を座標圧縮する
"""
n = int(input())
data = []
for _ in range(n):
x, y = list(map(int, input().split()))
data.append((x, y))
print(data)
# (インデックス, 値)で値でソート
datax = sorted(enumerate(list(zip(*data))[0]), key=lambda x:x[1])
datay = sorted(enumerate(list(zip... |
64c0e85949ded94bd06f0295bf6257d67c71ad17 | prrn-pg/Shojin | /Practice/atcoder/ABC/132/src/d.py | 621 | 3.6875 | 4 | # ncrをうまく使う感じ 二項定理は実装がわかんなかったのでググってパクった
from math import factorial
n, k = map(int, input().split())
nn = n - k + 1 # 使える箇所
def ncr(n, r):
res = 1
for i in range(1, r+1):
res = res * (n-i+1)//i
return res
def calc(k):
return [factorial(k)//(factorial(i)*factorial(k-i)) for ... |
879c9ffa028bddb3adc8f6084b20c1b68be4545c | prrn-pg/Shojin | /Practice/atcoder/ABC/128/src/b.py | 411 | 3.65625 | 4 | # 辞書順かつ大きい順(リスト)
n = int(input())
hash = {}
for i in range(n):
s, p = input().split()
p = int(p)
if s in hash.keys():
hash[s].append([i, p])
else:
hash[s] = list()
hash[s].append([i, p])
hash = sorted(hash.items())
for k, v in hash:
vs = sorted(v, key=lambda x:... |
99300b9447b04fa1f2ef853477dcbe5f3f6c806d | prrn-pg/Shojin | /Practice/atcoder/others/keyence2020/src/a.py | 158 | 3.640625 | 4 | # max(h, w)でmin(h, w)の方向に塗りまくる
h, w, n = [int(input()) for _ in range(3)]
x, i = 0, 0
while x < n:
x += max(h, w)
i += 1
print(i)
|
7bd84a3da87b6cf9a5ea5773bf525a2e5e1774a4 | prrn-pg/Shojin | /Practice/atcoder/ABC/012/src/c.py | 244 | 3.625 | 4 | # 九九の合計が問題文から予想できるので流用する やるだけ
n = int(input())
target = 2025 - n
for i in range(1, 10):
for j in range(1, 10):
if i * j == target:
print("{} x {}".format(i, j))
|
7e018a8e574fc523d02d9b9469f77b59223bedcd | prrn-pg/Shojin | /Practice/atcoder/AGC/028/src/_a_dame.py | 896 | 3.5 | 4 | # gcdより長いのは存在しなさそう(勘)なので存在するとしたらgcd
# 実際に試していく
# これだけだとTLEなるのでどっかを効率化する余地がある
n, m = map(int, input().split())
s, t = input(), input()
def lcm(a, b):
if a > b:
return lcm(b, a)
while 0 != a:
a, b = b % a, a
return b
def gcd(a, b):
return (a * b) // lcm(a, b)
u = gcd(n, m)
v = [Non... |
ec281bf09884aa336f35fb9f3812bac98ea79cec | Daniyal963/Programming-Assignment | /Program 1.py | 609 | 3.96875 | 4 | print("Daniyal Ali","18b-096-CS(A)")
print("Programming Excercise")
print("Question no.1")
#Code
import math
a = eval(input("Please enter the value of a: "))
b = eval(input("Please enter the value of b: "))
c = eval(input("Please enter the value of c: "))
x3 = (2*a)
denominator = x3
if denominator == 0:
... |
65a7dc8b7b21d2c278567e9a839aad5e585b9188 | jenchinwang/PythonLearning | /AlphabetInOrder.py | 680 | 4.4375 | 4 | ## This program will find the longest alphabetic letters
## in order inside an user input string. For Example
## "abcdabefiklmasdfuqwh"
## will return "abefiklm". Try it to test it out!
def AlphabetInOrder(s):
str = s[0]
lrg_str = ""
print "The first letter is", s[0]
for i in range(1,len(s)):
... |
2f4f710d2f3dd4e1ed6cb3ef4edf8106f80ac808 | Salman791/ibs-2020-10-application-development-normal-exam | /main.py | 598 | 3.515625 | 4 | from fish import Fish
from aquarium import Aquarium
Clown_fish = Fish("Bob", 12, "Blue", False)
Tang = Fish("Buddy", 13, "Orange", True)
Kong = Fish("Patrick", 14, "Red", False)
aquarium1 = Aquarium()
aquarium1.add_fish([Clown_fish])
aquarium1.add_fish([Tang])
aquarium1.add_fish([Kong])
aquarium2 = Aquarium()
aquar... |
38177e15fec179c2b553ec05bf286391190f2ddc | eng-arvind/python | /method.py | 304 | 3.71875 | 4 | class A:
print("class")
def m():
print("static")
def m1(obj):
print("object")
def m2(objclass):
print("class")
@classmethod
def m3(addrclass):
print("hello")
'''
obj=A()
obj.m1() # A.m1()
obj.m2() # A.m2(obj)
obj.m3() # A.m3(A) '''
|
37251a5055706236bd1f173715c7ebc710ad4c2b | eng-arvind/python | /prime_next.py | 271 | 4 | 4 |
def nextprime(n):
while True:
if(isprime(n+1)):
print(n+1)
break
else:
n +=1
def isprime(n):
for i in range(2,n//2+1):
if n%i==0:
return False
return True
|
6550ca78204a74f83f86d081c6801ec2732b6d8d | eng-arvind/python | /bool.py | 237 | 3.90625 | 4 | n=10
b=True
for i in range(0,n):
b= not(b)
if(b):
print("Even")
else:
print("odd")
#"even" if not n%2 else "odd"
#"even" if not n&1 else "odd"
#"even" if (n^1)&1 else "odd"
#"even" if (n//2)*2==n else "odd"
|
c80c6e7c25ed7a56ed2286d958e6d90a67558ba2 | codenious9/Codes | /Exercise5.py | 341 | 4.375 | 4 | #Write a Python program that prints the string s without the characters located at even indices.
#If the string is empty or only has one character, print it intact.
text = input("Enter the string:- ")
print(text[1::2])
new_text=""
#2nd method
'''
for i in range(len(text)):
if i%2!=0:
new_text+=text[i]
pri... |
e589f2506e39757e175baf2a16c02f4b6b49771e | matheus695p/fraud-detection | /src/analytics/transformations.py | 6,579 | 3.53125 | 4 | import numpy as np
def exponential_features(df, columns):
"""
Agregar polinomial features al dataframe en las columnas mencionadas
Parameters
----------
df : dataframe
variables input.
columns : list
columnas a aplicar.
Returns
-------
df : dataframe
datafra... |
0ff1799628f9a891ccc66526b76415b9d7fdeca6 | jbtayloriii/python-snippets | /Trees/treePrint.py | 3,434 | 3.96875 | 4 | #!/usr/bin/python
import sys
def printTree(root):
indentList = []
getNodeIndentations(root, indentList, 0, 0)
printIndentList(indentList)
#not used, but the idea is built upon in getNodeIndentations.
def getNodeSpace(node):
if node is None:
return 0
valueSpace = len(str(node.value))
leftSpace = getNodeSpace(... |
cb38b6ca56d11145922596bb45a977b0965e6245 | vanlongvl99/buoi5 | /maze.py | 1,621 | 3.59375 | 4 | from copy import deepcopy
from queue import Queue
class point():
def __init__(seft,x,y):
seft.x = x
seft.y = y
def bfs(entry, f, matrix):
curQueue = Queue()
rowVisited = [False for i in range(len(matrix[0]))]
visited = []
for i in range(len(matrix)):
visited.append(deepcopy... |
7398d4d196f8be99b54ababd344a5cfea8d00db3 | rudbog011/Python_10 | /work_10_6.py | 143 | 3.640625 | 4 | print('Введите строку:')
s = input()
num = ''
for i in range(len(s)):
if 48 <= ord(s[i]) <= 57:
num += s[i]
print(num) |
100012ee7d8c6316f79a2f9056f1221938edd399 | vrtineu/learning-python | /variaveis_compostas/listas/ex083.py | 898 | 4.25 | 4 | # Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá análisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.
expressão = str(input('Digite uma expressão: '))
count = 0
# For percorre a expressão inteira buscando '()', se achar... |
2296ba866c43ad865b322dffeaf2e859c629d8c6 | vrtineu/learning-python | /usando_modulos/modulos/ex018.py | 334 | 3.921875 | 4 | # Lê um ângulo e retorna seu seno, cosseno e tangente.
from math import sin, cos, tan, radians
ang = int(input('Digite um ângulo para ver seu seno, cosseno e tangente: '))
print('O ângulo {} tem o seno de {:.2f}, o consseno de {:.2f} e tangente de {:.2f}.'.format(ang, sin(radians(ang)), cos(radians(ang)), tan(radian... |
b4892e71f6d52d62ad521088189d9f665973e181 | vrtineu/learning-python | /lacos_de_repeticao/while/ex059.py | 1,245 | 4.3125 | 4 | # Crie um programa que leia dois valores e mostre um menu na tela:
# [1] Somar
# [2] Multiplicar
# [3] Maior
# [4] Novos números
# [5] Sair do programa
# Seu programa deverá realizar a operação solicitada em cada caso.
num1 = int(input('Digite o primeiro valor: '))
num2 = int(input('Digite o segundo valor: ')... |
36dd64fe563a07ed3e85dd4ee4ee365f61fb6131 | vrtineu/learning-python | /variaveis_compostas/tuplas/ex077.py | 492 | 4.09375 | 4 | # Crie um programa que tenha uma tupla com várias palavras(não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais.
frase = ('aprender', 'python', 'fazendo', 'exercicios', 'praticar',
'desenvolvedor', 'programador', 'curso', 'futuro', 'linguagem')
for palavra in fra... |
f75f875570df81d4a676f35db8cc20d8ed49b1d8 | vrtineu/learning-python | /lacos_de_repeticao/while/ex064.py | 489 | 3.953125 | 4 | # Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles(desconsiderando o flag).
total = num = 0
while num != 999:
num = int(input('D... |
1253c09ddf5d776ff7e6160f2e4940c856e650a3 | vrtineu/learning-python | /modulos/ex112/utilidadescev/moeda/__init__.py | 1,037 | 3.5 | 4 | def aumentar(num=0, taxa=0, format=False):
res = num + ((num * taxa) / 100)
return res if not format else moeda(res)
def diminuir(num=0, taxa=0, format=False):
res = num - ((num * taxa) / 100)
return res if not format else moeda(res)
def dobro(num=0, format=False):
res = num * 2
return res i... |
a2fe05c0ea78c74feb9c7570ed573f9cdfe6493e | vrtineu/learning-python | /lacos_de_repeticao/while/ex070.py | 1,061 | 3.859375 | 4 | # Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar. No final, mostre:
# A) Qual é o total gasto na compra.
# B) Quantos produtos custam mais de R$1000.
# C) Qual é o nome do produto mais barato.
print('~=' * 10)
print(f'{"LOJA SÃO JOSE":-^20}')
... |
899f7099af06444534d517ac06308ea42275cc7b | vrtineu/learning-python | /estruturas_condicionais/ex028.py | 842 | 4.21875 | 4 | # Escreva um programa que faça o computador "pensar" em um número inteiro de 0 e 5 e peça para o usuário descobrir qual foi o número escolhido pelo computador.
# O programa deve escrever na tela se o usuário venceu ou perdeu.
from random import choice
from time import sleep
print('Vou escolher um número de 0 a 5, voc... |
ff44caef6dc0c4d26aa4a2c493e11f5349d22d40 | vrtineu/learning-python | /variaveis_compostas/listas/ex080.py | 906 | 4.21875 | 4 | # Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista, já na posição correta de inserção(sem usar o sort()). No final, mostre a lista ordenada na tela.
valores = list()
for count in range(0, 5):
num = (int(input('Digite um número: ')))
if count == 0:
val... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.