blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
841ebb2d8c2e526f43adbeddde5169f28c84855d | sanketpatel0512/python_class_project | /clean.py | 542 | 3.515625 | 4 |
import pandas as pd
#cleanlinessdata
def BoroClean(y):
cleandata = pd.read_csv("cleanliness.csv",usecols = ['Month', 'Borough', 'Acceptable Streets %', 'Acceptable Sidewalks %'])
cleandata = cleandata.rename(columns = {'Acceptable Streets %': 'clean%','Borough':'boro'})
cleandata['boro']=cleandata['bo... |
f9fce75b7e79c014a21fd8d365e93f069e6e1c99 | sanketpatel0512/python_class_project | /age.py | 370 | 3.5625 | 4 |
import pandas as pd
def BoroAge():
popdata = pd.read_csv("age.csv", usecols = ['Borough','Age','2010','2015'])
popdata = popdata.rename(columns = {'Borough':'boro'})
popdata['boro'] = popdata['boro'].str.upper()
popdata = popdata[~popdata['boro'].isin(['NYC TOTAL'])]
popdata = popdata[~popdata['Age... |
41ac934e1707d6573ecfe86fa8442adb0cc2b7ff | Neirda8282/Tipe | /pwmarduino/pwmarduino/TestPWMv0.py | 1,415 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
"""
Contr�le de la luminosit� d'une LED l'Arduino
� partir d'un PC au moyen du protocole Firmata
Interface graphique (Tkinter)
"""
from tkinter import *
import pyfirmata
pin1 = 2
pin2 = 3
pin3 = 4
port = 'COM27' #windows
#port = '/dev/ttyACM0' #linux
board =... |
7addcc49c0a4d47f13862584874bcb93cb530dc0 | Mahmud-Buet15/Projects | /python/OOP/Snake Game/scoreboard.py | 625 | 3.609375 | 4 | from turtle import Turtle
ALIGNMENT="center"
FONT=("Courier", 18, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score=0
self.goto(0,270)
self.hideturtle()
self.color("white")
self.write(f"Score: {self.score}",ali... |
fdf7bcd8f67cc81eb1f1032caf065feefed992d2 | bhammack/machine-learning | /supervised_learning/algorithms/k_nearest_neighbor.py | 862 | 3.578125 | 4 | from sklearn.neighbors import KNeighborsClassifier
import numpy as np
from . import AbstractLearner
class KNNLearner(AbstractLearner):
def __init__(self):
self.knn_classifier = KNeighborsClassifier(n_neighbors=10)
def classifier(self):
return self.knn_classifier
# For KNN, there are reall... |
cc932e04234c69a33247bec761408d9b647829a5 | VictorIvanMr/Mision_02 | /distanciaPuntos.py | 401 | 3.828125 | 4 | #Víctor Iván Morales Ramos a01377601
#analisis: Crear un algoritmo que calcule la distancia de dos puntos (x1, y1 y x2, y2).
import math
x1 = float(input("Dame la coordenada x1: "))
y1 = float(input("Dame la coordenada y1: "))
x2 = float(input("Dame la coordenada x2: "))
y2 = float(input("Dame la coordenada y2: "))
... |
8d07752c569dd372e6f8c2db6bf74494410b9b5d | fredsonchaves07/book-list | /utils/database.py | 1,406 | 4 | 4 | import sqlite3
books_file = 'books.txt'
def create_book_table():
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS books(name text primary key, author text, read integer)')
connection.commit()
connection.close()
de... |
5d6d8d557279b809dba055dc702c186c0a5abebd | carlson9/KocPython2020 | /in-classMaterial/day4/exception.py | 375 | 4.1875 | 4 | raise Exception
print("I raised an exception!")
raise Exception('I raised an exception!')
try:
print(a)
except NameError:
print("oops name error")
except:
print("oops")
finally:
print("Yes! I did it!")
for i in range(1,10):
if i==5:
print("I found five!")
continue
print("Here is five!")
else:
pr... |
5fdb3d71246fd6d7c94bcb4f7f900d1566acdec7 | oscarzu/Python-Poll-Results | /Pypoll.py | 1,808 | 3.546875 | 4 |
import os
import csv
#Declaring the variables
csvpath = os.path.join("Resources","Election_Data.csv")
Vote_Totals = 0
List_of_Candidates = []
List_of_Votes_Counted = []
Data_File_List = ["Resources/Election_Data.csv"]
#Opening the file and reading it
for file in Data_File_List:
print(csvpath)
with ... |
6b100c2d18461401f3176dacedfafb4f1919a285 | dahcase/Seattle-Mobility-Index | /seamo/preproc/csv_to_sql.py | 949 | 4.03125 | 4 | """
This module takes a data input as a csv file, and converts it to
a sqlite3 dbfile.
"""
import pandas as pd
import sqlite3
import sys
import re
import os
def convert_csv(path, dbfile):
"""
Path is entered as a command-line argument.
"""
conn = sqlite3.connect(dbfile)
# cur =... |
08d47dfcb82b042197b02b7b501add8a843f10e7 | f1025395916/untitled | /pac/24.py | 714 | 3.828125 | 4 | '''
正则使用方法:
-match:从开始位置开始查找,一次匹配
-search:从任何位置查找,一次匹配
-finall:把符合条件的全部查找出来
'''
import re
s = r'([a-z]+)([a-z]+)'
pattern = re.compile(s,re.I) #re.I标识忽略大小写
m = pattern.match("hello world wide web")
all =pattern.findall("hello world wide web")
print(all)
print(type(all))
for i in all:
print(i)
s = m.group(... |
77f8f8cf9fbdc01fbdb3bcf9d1cf1da0f71d7160 | f1025395916/untitled | /12-多线程/04.py | 268 | 3.84375 | 4 | from collections import Iterable
from collections import Iterator
ll =[1,2,3,4,5]
#是可迭代的,但不是迭代器
print(isinstance(ll,Iterable))
print(isinstance(ll,Iterator))
l = [x*x for x in range(5)]
g = (x*x for x in range(5))
print(type(l))
print(type(g)) |
e9516fdad10efbf87d90abd2bf0e558b4e790db2 | f1025395916/untitled | /pac/06.py | 763 | 3.515625 | 4 | from urllib import request,parse
import json
baseurl="https://fanyi.baidu.com/sug"
# 存放模拟form的数据一定是dict格式
data ={
'kw':'girl'
}
# 需要使用parse对data进行编码
data = parse.urlencode(data).encode()
# 我们需要构造一个请求头
headers = {
# 因为使用post,至少应该包含content-length字段
'Content-Length':len(data)
}
rep = request.Request(url=baseur... |
8fda441a1d31dfda3b67f3bdaab5709c36224334 | subham-paul/Quiz-Test-System | /SIGNIN.py | 1,517 | 3.546875 | 4 | # Login.py
import mysql.connector
# Open database connection
db = mysql.connector.connect(user='root', password='',host='127.0.0.1',database='quiz')
# prepare a cursor object using cursor() method
cursor = db.cursor()
try:
print('\n\t\t~:LOGIN PAGE:~')
New=input("\n\t\t ARE YOU NEW USER??? <<<(Type ... |
0c16089c61dc7194a9fb0802387dbdd9fada8fda | mattkim8/Logic | /Matthew_Kim_Assignment_4.py | 507 | 3.703125 | 4 | from fractions import Fraction
##Fraction class automatically reduces fractions
def enum():
print "0"
ls = []
n = 1
d = 1
f = Fraction(n,d)
count = 2
while True:
for i in range(count):
f = Fraction(n,d)
n = i + 1
d = count - i
if f not... |
76cac0ce5b448c1c3d82702d8070b460bcb96931 | LechX/PDXCG_projects | /blackjack/deck.py | 830 | 3.5 | 4 | import random
class Deck:
id = 0
deck_list = []
def __init__(self):
ranks = list("A23456789TJQK")
ranks[ranks.index("T")] = "10"
suits = list("HSCD")
self.cards = []
for i in suits:
for j in ranks:
self.cards.append(j + i)
self.... |
19b6587a9c26924cbf8354c0e1713b5d6db05ad3 | LechX/PDXCG_projects | /week_two_day_five.py | 4,667 | 4.15625 | 4 | '''
# print vowels from a user string using a for loop
user_vowels = input("Please enter your favorite band > ").lower()
vowels = list("aeiouy")
for i in range(0,len(user_vowels)):
if user_vowels[i] not in vowels:
print(user_vowels[i])
else:
continue
# print consonants from a user string usin... |
80c8a329ddc548479eaba93186f8f65c832763c1 | pratikarulkar/Monte-Carlo-Simulation | /Project 2.py | 1,745 | 3.859375 | 4 | import numpy as np
import math
import random
import pandas as pd
import matplotlib.pyplot as plt
##Creating a function to get the point on a circle whose centre is (0,0) and having radius of 1.
def generating_points_on_perimeter_circle():
k=random.choices([1,0,2])[0]
if k==1:
x=random.uniform(-1,1)
... |
66fb96bf4a2de48163c0dd4c1d2aa1f954fe21fc | bryanlimy/calculate-time-on-mars | /julian_date.py | 3,029 | 4.40625 | 4 | def julian_date(day, month, year, hour, minute, second):
'''(int, int, int, int, int, int) -> float
Returns the Julian Date (as used in astronomy), given a Gregorian date and time. If given an invalid date/time, returns None. In the NASA calculations this is known as the JDUT.'''
a = (14 - month)//12
y ... |
d48e0a108d580d38f7534d759944b30379f14ce3 | amrutagaikwad20/Calendar_2020 | /calender.py | 71,131 | 3.953125 | 4 | from tkinter import Tk
from tkinter import Button
from tkinter import Scrollbar
t=Tk()
t.minsize(1500,700)
t.title("Calender 2020")
def january():
January=Button(text="JANUARY",font=("Algerian",25),background="Orange")
January.place(x=500,y=0,width="200",height="70")
sun=Button(text="SUN",fon... |
2ea33d9ddddb918a3489fab0186fe17488c12805 | Constantine19/leetcode | /922-Sort-Array-By-Parity-II.py | 433 | 3.71875 | 4 | def sortArrayByParityII(A):
"""
:type A: List[int]
:rtype: List[int]
"""
odd = 1
even = 0
combined = []
for i in range(len(A)):
combined.append(0)
for i in range(len(A)):
if A[i] % 2 == 0:
combined[even] = A[i]
even += 2
else:
... |
2ff68d9e460387b855a676a7c8c1f0646b101758 | Constantine19/leetcode | /1004-Max-Consecutive-Ones-III.py | 286 | 3.578125 | 4 | def longestOnes(a):
count = 0
result = []
for i in range(len(a)):
if a[i] == 1:
count += 1
else:
result.append(count)
count = 0
return max(result)
a = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
# K = 2
print longestOnes(a)
|
9abf4ee9238f0b612e51526bf54074150fa6524d | Constantine19/leetcode | /058-Length-of-Last-Word.py | 175 | 3.90625 | 4 | def lengthOfLastWord(s):
my_list = s.split()
if len(my_list) <= 0:
return 0
else:
return len(my_list[-1])
s = "Hellou j"
print lengthOfLastWord(s)
|
98e2ad4171682a02c558d00b245a512c71190412 | Constantine19/leetcode | /268-Missing-Number.py | 135 | 3.734375 | 4 | def missingNumber(nums):
n = len(nums) # 5
return n * (n+1) / 2 - sum(nums)
nums = [0, 1, 2, 4, 5]
print missingNumber(nums)
|
156e9d178477dbb770d537ced639272ea6f16d23 | Constantine19/leetcode | /844-Backspace-String-Compare.py | 445 | 3.625 | 4 | def backspaceCompare(S, T):
def process(my_str):
result = []
for i in range(len(my_str)):
if my_str[i] == "#":
if len(result) == 0:
continue
else:
result.pop()
else:
result.append(my_str[i... |
274b2160ffc8c41e5a6aca576e0b23085175ac37 | Constantine19/leetcode | /389-Find-the-Difference.py | 206 | 3.828125 | 4 | def findTheDifference(s, t):
s_set = set(s)
t_set = set(t)
result = ""
for i in t_set - s_set:
result += i
return result
s = "abcd"
t = "abcde"
print findTheDifference(s, t)
|
7dd21306bac85d6d6e00e20f3233befde0564c7c | Constantine19/leetcode | /819-Most-Common-Word.py | 601 | 3.671875 | 4 | def mostCommonWord(paragraph, banned):
#words = paragraph.replace(',', '').replace('.', '').replace("!", "").lower().split()
counts = {}
for i in paragraph.split(','):
print i
# for i in range(len(words)):
# if words[i] not in counts:
# counts[words[i]] = 1
# else... |
fea65472badbeade0825992ec9937ca95410dbbe | stan-alam/Python | /algo/src/BubbleSort.py | 464 | 4 | 4 | #!/usr/bin/python
import sys
def sort(array):
length = len(array)
for i in range(0, length - 1):
for j in range(0, length - 1):
if array[j] > array[ j + 1 ]:
tag = array[j]
array[j] = array[j + 1]
array[j + 1] = tag
def main():
grades = [... |
29f6a4560eb8e0e8dce2188a22a5f960b60a1e76 | CZHerrington/day-2-python | /bonus_challenge_histogram.py | 869 | 4.03125 | 4 | sentence_list = str(input('please enter a sentence: ')).split(' ')
def generate_histogram(sentence):
word_hist_dict = {}
for word in sentence_list:
try:
word_hist_dict[word]
except:
word_hist_dict[word] = 0
finally:
word_hist_dict[word] += 1
retu... |
09d289eae36e1e9e5513e51391e8403060e05f0f | dbolshak/ml | /python-scripts/load_iris.py | 1,601 | 3.671875 | 4 | from sklearn.datasets import load_iris
iris_dataset = load_iris()
'''
The data itself is contained in the target and data fields. data contains the numeric measurements of sepal length, sepal width, petal length, and petal width in a NumPy array
'''
print("dir on iris_dataset: \n{}".format(dir(iris_dataset)))
print("... |
7521bc35afaa483532901803d6da7e1ac6a17b2a | yuvipatil007/python_new | /day_8/day-8-2.py | 446 | 3.53125 | 4 | # Review:
# Create a function called greet().
# Write 3 print statements inside the function.
# Call the greet() function and run your code.
# def greet():
# print("this is function")
# print("this is greet function")
# print("this call from outside")
# greet()
def greet_with(name,location):
print(f"Hello ... |
fd76372728187bd13740d3c237db61671b8b5e4d | taebinjjang/Pre_KSA_Computer_Science_Python | /week3/function/python1.py | 351 | 3.71875 | 4 | import math
def distance(x1, y1, x2, y2):
u = (x2-x1)**2
v = (y2-y1)**2
return math.sqrt(u+v)
def circleArea(radius):
return math.pi * radius**2
def printCircleArea(radius):
print(math.pi * radius**2)
if __name__=='__main__':
a = circleArea(10)
b = distance(0, 0, 3, 4)
printCircleAre... |
55c5f0abb51029823c4e95203187a587a9d37df6 | diana-okrut/by_nesusvet | /medium-kth_largest.py | 770 | 3.90625 | 4 | import heapq
def kth_largest(numbers, k):
"""
See https://leetcode.com/problems/kth-largest-element-in-an-array/
>>> kth_largest([3, 2, 1, 5, 6, 4], 2)
5
>>> kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)
4
>>> kth_largest([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
9
>>> kth_largest([10, 9, ... |
2f02541681935c442b6132e4ea2ad6a25be391d6 | diana-okrut/by_nesusvet | /medium-facebook.py | 1,395 | 4 | 4 | def main(text: str) -> bool:
"""
Implement a function which will check if it is possible to build a valid
palindrome from a sequence of letters. Only permutations are allowed.
>>> main("anna")
True
>>> main("nana")
True
>>> main("nanam")
True
>>> main("dogo")
False... |
ed2fbd0b2fb93871b3056f8508aae1befd44d0e2 | diana-okrut/by_nesusvet | /easy-love-vs-friendship.py | 313 | 3.609375 | 4 | """
https://www.codewars.com/kata/love-vs-friendship/train/python
"""
import string
def words_to_marks(word):
alphabet = {
char: i
for i, char in enumerate(string.ascii_lowercase, start=1)
}
values = [alphabet[letter] for letter in word if letter in alphabet]
return sum(values)
|
22539a3cdb2beba7629a7d01ed1918bb4106b9a6 | realsungyoun/3.1-Informal-Intro-to-Python | /3.+An+informal+introduction+to+Python.py | 7,600 | 4.34375 | 4 |
# coding: utf-8
# # 3.1 Using python as a calculator
# ## 3.1.1. Numbers
# Operators +, -, *, and / are normal, with () used for grouping.
#
#
# In[8]:
2+2
# In[9]:
50 - 5*6
# In[10]:
(50 - 5*6)/4
# In[11]:
8/5 # division always returns a floating point
# Integer numbers have type int, fractional p... |
8a71c83758318114c1ba91c8ff7ea461bc0f9933 | workready/pythonbasic | /sources/t10/t10ej11.py | 235 | 3.546875 | 4 | import numpy as np
A = np.array([[1, 2], [3, 4]])
A
"""
array([[1, 2],
[3, 4]])
"""
# Esto sería un puntero: si cambiamos B, A también cambia
B = A
# Esto sería una copia: si cambiamos B, A no cambia
B = np.copy(A) |
9cd21f87bf6287987e843ec94f090e5da367fbd3 | workready/pythonbasic | /sources/t09/t09ej05.py | 1,275 | 3.890625 | 4 | # Corrutina
def minimize():
try:
# La primera vez que se llame a next(), el generador arrancará y se ejecutará hasta encontrar un yield.
# La llamada a next() es equivalente a send(none), de manera que se guardará None en current,
# y entonces parará, a esperas de la siguiente llamada
... |
027b9c9e4c7e54eff46c9c06dc8836dcea3f1fd0 | workready/pythonbasic | /sources/t07/t07ej19.py | 169 | 3.8125 | 4 | # Ejemplo de uso de expresión lambda en Python
a = [1, 2, 3]
b = [4, 5, 6]
suma_cuadrados = lambda x, y: x**2 + y**2
print([suma_cuadrados(x, y) for x, y in zip(a, b)]) |
270458e2e003680f78a0a3f2f4b17e0978554f1f | workready/pythonbasic | /sources/t03/t03ej18.py | 681 | 3.828125 | 4 | # pop devuelve el último elemento extraído, y clear elimina todos los elementos
a_set = {1, 3, 6, 10, 15, 21, 28, 36, 45}
print(a_set) # {1, 3, 6, 10, 15, 21, 28, 36, 45}
a_set.pop() # 1
a_set.pop() # 3
a_set.clear()
print(a_set) # set()
# Discard y remove se diferencian en que, si el elemento no existe, remo... |
96885ba346fbe52f4a8b06675576076e22754726 | workready/pythonbasic | /sources/t11/t11ej03.py | 224 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.exp(-x ** 2)
x = np.linspace(-1, 3, 100)
plt.plot(x, f(x), color='red', linestyle='', marker='o')
plt.plot(x, 1 - f(x), c='g', ls='--')
plt.show() |
c282e4d0a3c4b12a4bb47981dde76d2685ad00e2 | workready/pythonbasic | /sources/t12/t12ej09.py | 144 | 3.578125 | 4 | import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(3,4), index=['2','4','8'], columns=list('ABCD'))
print(df)
print(df.T) |
fd0db944628970f8771143a1bdfb073edda6faca | workready/pythonbasic | /ejercicios_resueltos/t03/t03ejer05.py | 578 | 3.8125 | 4 | def sumatorio_tope(tope):
"""
Va sumando números naturales hasta llegar al tope.
Ejemplos
--------
>>> sumatorio_tope(9)
6
# 1 + 2 + 3
>>> sumatorio_tope(10)
10 # 1 + 2 + 3 + 4
>>> sumatorio_tope(12)
10 # 1 + 2 + 3 + 4
>>> sumatorio_tope(16)
1... |
901e7a3327f2da3817d48f0cd748031a7361c1ae | workready/pythonbasic | /sources/t06/t06ejer06.py | 824 | 4.1875 | 4 | class Item:
pass # Tu codigo aqui. Estos son los elementos a guardar en las cajas
class Box:
pass # Tu codigo aqui. Esta clase va a actuar como abstracta
class ListBox(Box):
pass # Tu codigo aqui
class DictBox(Box):
pass # Tu codigo aqui
# Esto prueba las clases
i1 = Item("Item 1", 1... |
77cbc8d529d408766074baf0a80db7c5cd479861 | workready/pythonbasic | /sources/t04/t04ej14.py | 1,147 | 4 | 4 | # Construir iterador para generar secuencia de Fibonacci
import itertools
class Fib:
'''Iterador que genera la secuencia de Fibonacci'''
# Constructor
def __init__(self):
self.prev = 0
self.curr = 1
# Esto es llamado cada vez que se llama a iter(Fib). Algo que for hace automáticamente... |
594505fb1c0e2dc163eefd6b23d996f7258a8783 | workready/pythonbasic | /sources/t06/t06ej08.py | 683 | 4.0625 | 4 | # Python añadirá internamente el nombre de la clase delante de __baz
class Foo(object):
def __init__(self):
self.__baz = 42
def foo(self):
print(self.__baz)
# Como el método __init__ empieza por __, en realidad será Bar__init__, y el del padre Foo__init__. Así existen por separado
class Bar(Fo... |
aa3ce5e3f0253d2065b99dd809b0fe29992dd954 | workready/pythonbasic | /sources/t04/t04ej04.py | 297 | 4.28125 | 4 | # Una lista es un iterable
a_list = [1, 2, 3]
for a in a_list:
# Tip: para que print no meta un salto de línea al final de cada llamada, pasarle un segundo argumento end=' '
print (a, end=' ')
# Un string también es un iterable
a_string = "hola"
for a in a_string:
print(a, end=' ') |
f7a033999cdeef6b0b4c523cd03839e7ba7f0b22 | workready/pythonbasic | /sources/t06/t06ejer03.py | 410 | 3.765625 | 4 | class Shape:
pass # Tu codigo aqui
class Rectangle(Shape):
pass # Tu codigo aqui
newRectangle = Rectangle(12, 10)
print(newRectangle.area) # 120
print(newRectangle.perimeter) # 44
newRectangle.width = 5
newRectangle.height = 8
print(newRectangle.area) # 60
print(newRectangle... |
c669dfa12e759faa2498748d22314c604138273c | workready/pythonbasic | /ejercicios_resueltos/t06/t06ejer06.py | 1,689 | 3.875 | 4 | class Item:
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
return "{} => {}".format(self.name, self.value)
class Box:
def add(self, *items):
raise NotImplementedError()
def empty(self):
raise NotImplementedError()
d... |
6c7bf95347870300b8aa50a34f4810ff4da20427 | workready/pythonbasic | /sources/t09/t09ejer01.py | 362 | 3.890625 | 4 | import multiprocessing
# Funcion a ejecutar con multiproceso
def worker(num):
return num*2
# Lista de numeros con los que trabajar
nums = [1,2,3,4,5,6,7,8,9]
values = None
# En values obtendremos el resultado de aplicar worker a la lista, utilizando un pool de 2 procesos
# Tu codigo aqui
assert(values == [2, 4... |
3beae445297c50305023fb275c91f58872facca8 | workready/pythonbasic | /sources/t08/t08ej02.py | 541 | 3.90625 | 4 | class Empleado(object):
"Clase para definir a un empleado"
def __init__(self, nombre, email):
self.nombre = nombre
self.email = email
def getNombre(self):
return self.nombre
jorge = Empleado("Jorge", "jorge@mail.com")
jorge.guapo = "Por supuesto"
# Probando hasattr, getattr, seta... |
5397542b7edb1969c2bb9ee2c3533179a6e4370a | jose-cavalcante/teste | /eq2.py | 559 | 3.96875 | 4 | import math
a=float(input("Digite o valor de a: "))
b=float(input("Digite o valor de b: "))
c=float(input("Digite o valor de c: "))
if a==0:
print("Impossível de calcular, pois a não pode ser zero.")
else:
d=(b**2)-(4*a*c)
if d<0:
print("A equação não tem solução real")
else:
if d==0:
... |
94b26dcd00e1a5ba7e3e4473cb2920cda95f5a14 | nberr/pycaster | /src/data.py | 2,463 | 3.8125 | 4 | # point contains 3 values: x, y, z
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
# comparing two points
def __eq__(self, other):
return (epsilon_eq(self.x, other.x)
and epsilon_eq(self.y, other.y)
and epsilon_eq(self.z, other.z))
# vector ... |
460471be68523b7d92a5e49a17dc9cc032121f1a | Neyaz123/Python | /3.2.py | 414 | 3.921875 | 4 | def summ(x, y, z):
return x+y+z
def proizv(x, y, z):
return x*y*z
X = int(input('Введите первое число: '))
Y = int(input('Введите второе число: '))
Z = float(input('Введите третье число: '))
print('Сумма введенных чисел: ', summ(X, Y, Z))
print('Произведение введенных чисел', proizv(X, Y, Z))
|
1cfb7e5543b30f0f7d2a22779852ade27ece4b5c | PaulJardel/molecule_parser | /molecular/molecule_parser.py | 5,829 | 3.609375 | 4 | from typing import Dict
import re
from molecular.monitoring.log import get_logger
logger = get_logger()
class MoleculeParser:
"""
This class allows to parse molecules, and get the number of atoms that compose it.
It is mainly string operations.
See documentation used : https://docs.python.org/3/lib... |
e32c6fcb9ae8d8f9613f85ab07b69ca50d179619 | owis1998/brute-force-approach | /closest_pair/closest_pair.py | 847 | 3.796875 | 4 | class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def how_far_from(self, point):
if self.x == point.x:
return 0
higher_point, lower_point = (self, point) if self.y > point.y else (point, self)
#Pythagorean theorem
distance = ((higher_point.x - lower_point.x) ** 2 + (higher_point.y - l... |
5dfd71362ded3403b553bc743fab89bab02e2d38 | BluFox2003/RockPaperScissorsGame | /RockPaperScissors.py | 1,684 | 4.28125 | 4 | #This is a Rock Paper Scissors game :)
import random
def aiChoice(): #This function generates the computers choice of Rock, Paper or Scissors
x = random.randint(0,2)
if x == 0:
choice = "rock"
if x == 1:
choice = "paper"
if x == 2:
choice = "scissors"
return choice
def gam... |
3fb1e727b6789e39051ecc514c29f8db0afb5c21 | isrt09/Data-Visualization-using-Python | /Day01/Fill.py | 188 | 3.5625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10)
y1 = 0.08*x**2
y2 = 0.03*x**2
plt.fill_between(x,y1,y2, 'r-')
plt.plot(x,y1, 'r-')
plt.plot(x,y2, 'b-')
plt.show() |
119737821e287b38e186754ab8124f02b745c50d | windanger/Exercise-after-class | /Desktop/Exercise after class/密碼設置強度檢測.py | 1,708 | 3.984375 | 4 | #寫一个密码安全性检查的脚本代码
#低级密码要求:
#1. 密码由单纯的数字或字母组成
#2. 密码长度小于等于8位
#中级密码要求:
#1. 密码必须由数字、字母或特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)任意两种组合
#2. 密码长度不能低于8位
#高级密码要求:
#1.密码必须由数字、字母及特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)三种组合
#2.密码只能由字母开头
#3.密码长度不能低于16位
symbols = '~!@#$%^&*()_=-/,.?<>;:[]{}\|'
number = '123456789'
character = 'abcdefg... |
a5aeeb2e8f0bf153e0ebaa4aaae06ce71ac0539b | windanger/Exercise-after-class | /Desktop/Exercise after class/最大公因數.py | 249 | 3.609375 | 4 | #编写一个函数,利用欧几里得算法(脑补链接)求最大公约数,例如gcd(x, y)
#返回值为参数x和参数y的最大公约数。
def gcd(a,b) :
t = 1
while t==1 :
t = a % b
a , b = b , t
return t
|
e8b613da719dfd651e84ce34b2c1c8ab41849656 | tapatio-123/python-challenge | /PyBank/main.py | 1,776 | 3.796875 | 4 |
import os
import csv
#importing file
budget_csv = os.path.join('..', 'PyBank', 'Resources', 'budget_data.csv')
#read into file
with open(budget_csv) as csvfile:
csvreader = csv.reader(csvfile, delimiter= ",")
csv_header = next(csvreader)
#setting variablbes
total = 0
total_months = 0
total_chan... |
b0d07a7552b88785387c63cc677186fbe47c9c2c | SebastianColorado/DylansBot | /Main.py | 1,329 | 3.5625 | 4 | """Tweets out a random city name + the phrase."""
import csv
import twitter
import os
import random
import time
numRows = 15633
cities = []
with open('cities.csv', 'rt') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
cities.append(row[0])
# Authenticate the twitter bot by ... |
690c1fc35fdd3444d8e27876d9acb99e471b296b | gridl/cracking-the-coding-interview-4th-ed | /chapter-1/1-8-rotated-substring.py | 686 | 4.34375 | 4 | # Assume you have a method isSubstring which checks if one
# word is a substring of another. Given two strings, s1 and
# s2, write code to check if s2 is a rotation of s1 using only
# one call to isSubstring (i.e., "waterbottle" is a rotation of
# "erbottlewat").
#
# What is the minimum size of both strings?
# ... |
bad07562893a7508a001f4be69af6936d9760762 | gridl/cracking-the-coding-interview-4th-ed | /chapter-2/2_1_remove_duplicates.py | 1,113 | 3.765625 | 4 | from linked_list import LinkedList
class ExtLinkedList(LinkedList):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def remove_dup(self):
curr = self.head
if not (curr and curr.next): return
prev = None
elems = set()
while curr:
... |
c381e6e7782819eacd08c3ce44ebc2080c301da3 | kevin-j-chan/cogs18project | /actors.py | 11,648 | 3.546875 | 4 |
# coding: utf-8
# In[4]:
import random
from items import *
from math import floor
# In[5]:
class Player():
def __init__(self, level=1, health=50, strength=5, speed=5):
self.is_alive = True
# Player inventory
self.e_sword = Sword(name="none", value=0, strength=0)
se... |
41cf652afee3550d58f74cd28d7e896513cea42f | hanajhg/pylesson | /pybasic/pybasic_15_fun.py | 14,282 | 4.15625 | 4 | '''
函数
'''
#!/usr/bin/python3
# 计算面积函数
import functools
from urllib import request
def area(width, height):
return width * height
def print_welcome(name):
print("Welcome", name)
print_welcome("Runoob")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))
'''
函数调用
'''
# 定义函数
def print... |
22b2b61964f77e9e343650e16309c0d99df48845 | hanajhg/pylesson | /pybasic/pybasic_6_number.py | 2,607 | 3.796875 | 4 | # Python 数字数据类型用于存储数值。
# 数据类型是不允许改变的,这就意味着如果改变数字数据类型的值,将重新分配内存空间。
# 以下实例在变量赋值时 Number 对象将被创建:
# var1 = 1
# var2 = 10
# 您也可以使用del语句删除一些数字对象的引用。
# del语句的语法是:
# del var1[,var2[,var3[....,varN]]]
# 您可以通过使用del语句删除单个或多个对象的引用,例如:
# del var
# del var_a, var_b
# >>> number = 0xA0F # 十六进制
# >>> number
# 2575
#
# >>> number=0o37... |
861695369e0b660989b3c8629f8073747d4d83a0 | 18616703217/Ibchariot | /xiaoma/lesson1.py | 645 | 3.9375 | 4 | print("判断密码强度:")
import string
#password =input("请输入密码:")
password_strong = 0
strpun = ""
while True:
password =input("请输入密码:")
if len(password) >= 6 :
password_strong += 1
for i in password:
if i.isalnum():
strpun += "1"
elif i in string.punctuation:
strpun... |
837f039ae933a39754aec263ccf6dc194a2fdca0 | nadjetfekir/jeu_allumette | /jeu.py | 2,749 | 3.5625 | 4 | def jeu_ordi(nb_allum, prise_max):
prise=0
s = prise_max + 1
t = (nb_allum - s) % (prise_max + 1)
while (t != 0):
s -= 1
t = (nb_allum - s) % (prise_max + 1)
prise = s - 1
if (prise == 0):
prise = 1
print("l'ordi en prend : ", prise)
return prise
#le ... |
bbe48bd24e69fef525cef8fb2b2281eb87e8fb4a | renowncoder/bcherry | /oldstuff/python/learning/ex3/tfe.py | 815 | 3.75 | 4 | class textfile:
ntfiles = 0 # count of number of textfile objects
def __init__(self,fname):
textfile.ntfiles += 1
self.name = fname #name
self.fh = open(fname) #handle for the file
self.lines = self.fh.readlines()
self.nlines = len(self.lines) #number of lines
self.nwords = 0 #number of words
self.wordc... |
5ffc8cd2a282b9ed5337721bde7b6cfa7117f6c1 | zhaozhekey/Python- | /Day09/代码/07-filter内置类的使用.py | 610 | 3.921875 | 4 | # filter对可迭代对象进行过滤,得到的是一个filter对象
# Python2的时候是内置函数,Python3修改成一个内置类
ages = [12, 23, 30, 17, 16, 22, 19]
# filter可以给定两个参数,第一个参数是函数,第二个参数是可迭代对象
# filter结果是一个filter类型的对象,filter对象也是一个可迭代对象
x = filter(lambda ele: ele > 18, ages)
# print(x) # <filter object at 0x00000288AD545708>
# # for ele in x:
# # print(ele)
print... |
a4527e71036008aeca6ffbc4ef2ddca952cf91f4 | zhaozhekey/Python- | /Day04/代码/05-break和continue.py | 334 | 3.890625 | 4 | #
# i = 0
# while i < 10:
# if i == 5:
# i += 1
# continue
# print(i,end="")
# i += 1
username = input("用户名")
password = input("密码")
while (username !="zz" or password != "123"):
# while not(username =="zz" or password == "123"):
username = input("用户名")
password = input("密码") |
2c4516304358639cea17f4862257cfaa2b748461 | zhaozhekey/Python- | /Day07/代码/05-字典练习二.py | 815 | 4.0625 | 4 | # 输入用户姓名,如果姓名已经存在,提示用户;如果姓名不存在,继续输入年龄,并存入列表中
persons = [
{"name": "zhangsan", "age": 18, "gender": "female"},
{"name": "lisi", "age": 20, "gender": "male"},
{"name": "jack", "age": 30, "gender": "unknow"},
{"name": "kevin", "age": 29, "gender": "female"}
]
# name_input = input("请输入姓名")
#
# for person ... |
ea0dd9a0ac67f205dd8852d29b2db061457d4c6a | zhaozhekey/Python- | /Day09/代码/06-sort方法的使用.py | 971 | 3.828125 | 4 | students = [
{"name": "zhangsan", "age": 18, "score": 98, "height": 180},
{"name": "lisi", "age": 25, "score": 93, "height": 170},
{"name": "jerry", "age": 30, "score": 90, "height": 173},
{"name": "kevin", "age": 30, "score": 90, "height": 176},
{"name": "poter", "age": 27, "score": 88, "height": 1... |
ac828af4ad1b05b9073f125edb56d5d7bb1cc707 | zhaozhekey/Python- | /Day04/代码/04-循环.py | 424 | 3.671875 | 4 | #
# num = 0
# sum = 0
# while num <= 100:
# if num %2 != 0:
# sum += num
# num += 1
# print(sum)
# 内置类range用于生成制定区间的整数序列
# 注意:in的后面必须是一个可迭代对象!!!
# 目前接触的可迭代对象: 字符串、列表、字典、元组、集合、range
# for num in range(0,5):
# print(num)
sum = 0
for num in range(1,101):
sum += num
print(sum) |
b8ef42374e8612fc63201fb35dcfabff91999c7d | zhaozhekey/Python- | /Day11/代码/05-魔法方法.py | 2,086 | 3.828125 | 4 | # 魔法方法也叫魔术方法,是类里的特殊方法
# 特点
# 1.无需手动调用,会在合适的时机自动调用
# 2.这些方法,都是使用__开始,使用__结束
# 3.方法名都是系统规定好的,在何时的时机自己调用
class Person(object):
def __init__(self, name, age):
# 在创建对象时,会自动调用这个方法
print("__init__方法被调用了")
self.name = name
self.age = age
def __del__(self):
# 当对象被销毁时,会自动调用这个方法
... |
c98b4be5ebfaccb676aec4a12ef1c248a14b61c9 | sreehari333/pdf-no-4 | /finding the second largest number.py | 366 | 3.734375 | 4 | list1 = [10, 20, 4, 45, 99]
mx = max(list1[0], list1[1])
secondmax = min(list1[0], list1[1])
n = len(list1)
for i in range(2, n):
if list1[i] > mx:
secondmax = mx
mx = list1[i]
elif list1[i] > secondmax and \
mx != list1[i]:
secondmax = list1[i]
print("Second h... |
439517c3044f848c3d3cdc13b9f60548bb49b4d4 | LasTshaMAN/poetry_scrapper | /processing.py | 515 | 3.765625 | 4 | from collections import Counter
import nltk
from nltk.corpus import stopwords
def text_to_word_count(text):
text = text.lower()
words = nltk.word_tokenize(text)
words = filter_stop_words(words)
return dict(Counter(words).most_common())
def filter_stop_words(words):
# Might use custom list of st... |
2de3e99808500542d25e10bd61fefe9a8f9703d8 | juanfdg/JuanFreireCES22 | /Aula3/Problem_14_11_1_e.py | 777 | 3.59375 | 4 | def bagdiff(xs, ys):
""" bagdiff for the first list."""
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs): # If xs list is finished, we're done
return result
if yi >= len(ys): # If ys list is finished
result.extend(xs[xi:]) # Add the last elements of... |
d89d76b57a914617374ae2be28918b6019c91b82 | juanfdg/JuanFreireCES22 | /Aula3/Problem15_12_4.py | 369 | 3.84375 | 4 | class Point():
def __init__(self, x, y):
self.x = x
self.y = y
# Method wont work when other_point.x - self.x = 0
def get_line_to(self, other_point):
slope = (other_point.y-self.y)/(other_point.x-self.x)
linear_coef = self.y - slope*self.x
return (slope, linear_coef... |
fae94561b78158c49e3aece7739ee839b330e237 | juanfdg/JuanFreireCES22 | /Aula7/ConsumerProducer.py | 1,462 | 3.65625 | 4 | from threading import Thread, Lock
import time
import random
shared_item = 0
itens_done = 0
available = False
class Producer(Thread):
global shared_item
global available
def __init__(self, lock):
Thread.__init__(self)
self.lock = lock
self.produced = False
def run(self):
... |
28e2a37dc3851d46de39dff79db94ffdc81b4d42 | juanfdg/JuanFreireCES22 | /Aula2/Problem4_9_10.py | 325 | 3.640625 | 4 | import turtle
def star(t):
for i in range(5):
t.forward(100)
t.right(144)
wn = turtle.Screen()
wn.bgcolor('lightgreen')
pen = turtle.Pen()
pen.color('purple')
for i in range(5):
star(pen)
pen.forward(100)
pen.penup()
pen.forward(350)
pen.pendown()
pen.right(144)
wn.mainlo... |
dde161338c0e9cd80a6a883fb86abb5cf20c666c | Antares2k16/python_learning | /employee_info.py | 394 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 23 14:49:13 2018
@author: aliao
"""
class Employee():
def __init__(self, first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
def give_raise(self, boos... |
b842b9cfcc54bd719dd8ff1c113a879d81645030 | HANICA/MachineLearningP3 | /ud120-projects-master/datasets_questions/explore_enron_data_6_25_jk.py | 1,337 | 3.703125 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
94a64d991e2bb98e76d3e27c4162982cded2d731 | HANICA/MachineLearningP3 | /ud120-projects-master/svm/svm_author_id_subset_rbf_c_items_37_jk.py | 1,972 | 3.546875 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
J.A. Korten Sept 2018
See: http://scikit-learn.org/stable/modules/svm.html
Excercise 3.47
... |
36d891f703683a78d93e518e080c5964d3756384 | HANICA/MachineLearningP3 | /ud120-projects-master/tools/rescaler_jk.py | 423 | 3.765625 | 4 | #!/usr/bin/python
import numpy
import sys
def featureScaling(arr):
minF = 0
maxF = 0
feature = 0
if len(arr) == 3:
minF = min(arr)
maxF = max(arr)
for item in arr:
if (item != minF) and (item != maxF):
feature = item
rescaledFeature = (featur... |
7d58552ddee2fb969005b372aed4bc75c453d666 | jeffsilverm/GaryCrane | /Jeffs_Phylo_tree.py | 15,161 | 4.09375 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 7 17:19:25 2017
@author: Crane
Modified Tue Feb 7th 20:10 2017
@author: Jeff Silverman, HMC '80
========================================================================
Created on Wed Jul 6 17:55:31 2016
C:\Python34\Phylogenet... |
5c88f6ac529ce9c0c3255805ebaa7743f222bacc | leebecker/InterAnnotatorAgreement | /stats/Agreement.py | 4,324 | 4 | 4 | import math
import unittest
from collections import defaultdict
class Agreement:
"""
Class for computing inter-rater reliability
"""
def __init__(self, rater_responses):
"""
Arguments:
rater_responses -- a list of maps of item labels. ex. [{'item1':1, 'item2':5}, {'item1':2}]... |
1cf8cfebd1827f1120c0b23107aa34831b4d63d5 | nadiavdleer/prograil | /code/classes/trajectory.py | 2,116 | 3.609375 | 4 | class Trajectory:
def __init__(self, start):
"""
trajectory object is a collection of connections
"""
self.start = start
self.end = start
self.connections = []
self.itinerary = [start.name]
self.total_time = 0
self.score = 0
... |
fa2d7a1cf84df832521281ad836c686b6bb78fe3 | qingyuannk/phoenix | /dp/jumpgame.py | 2,117 | 3.78125 | 4 | """
递归动态规划
"""
class Solution(object):
def canJump(self,nums):
if len(nums) == 1:
return True
for i in range(1,nums[0]+1):
if i <= len(nums):
if self.canJump(nums[i:]):
return True
else:
return True
retur... |
331c08ad9a30921c2e24477263065e8d5ee584ef | qingyuannk/phoenix | /sliding_windows/Permutation_in_Sring.py | 1,575 | 3.796875 | 4 | """
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
Example1:
Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains one permutation of s1 ("ba").
... |
db95e99f20fe9d18b38bff2fbff889fe0671d6c1 | nandy23/python-belajar | /jamkedetik.py | 307 | 3.78125 | 4 | print("Konversi jam ke detik")
jam = int(input("Masukan Jam : "))
menit = int(input("Masukan Menit : "))
detik = int(input("Masukan Detik : "))
total_detik = ((jam * 3600) + (menit * 60) + detik)
print(str(jam) + ":" + str(menit) + ":" + str(detik) + " Sama dengan " +
str(total_detik) + " detik")
|
9cd8f12a70e688213149f89dfd4e86e5dff5338f | Zackno23/taskC | /c_2.py | 1,080 | 3.78125 | 4 | import csv
class Customer:
def __init__(self, first_name, family_name, age):
self.first_name = first_name
self.family_name = family_name
self.age = age
def full_name(self):
return f"{self.first_name} {self.family_name}"
def age(self):
return self.age
def entry_... |
22a3d1c71ccdeabae5060cdd52ab9cf2cc147c90 | Carlosterre/Pythonchallenge | /10.py | 2,628 | 3.515625 | 4 | # "len(a[30]) = ?"
# Clickando la vaca: "a = [1, 11, 21, 1211, 111221, ". Es la "Look-and-say sequence"
# 1.- Solucion simple
a = '1'
b = ''
for i in range(0, 30):
j = 0
k = 0
while j < len(a):
while k < len(a) and a[k] == a[j]: k += 1
b += str(k - j) + a[j]
j = k
p... |
79e0416290c99d0225d011e206d5e5d3269ac28b | jeremy-y-walker/nlc-classifier | /NLC.py | 1,953 | 3.515625 | 4 | ########################################################################
# #
# Nearest Local Centroid Classifier #
# Author: Jeremy Walker #
# ... |
26df2cc6b32fe2cb664cd80e0efff6d71995071d | SzymanskiKrzysztof/TicTacToe | /TicTacToeGame.py | 3,330 | 3.921875 | 4 | def start():
print('Welcome to Tic Tac Toe!')
def clear_board():
for i in range(1, 10):
board_map[i] = ''
def display_board(board):
print(f' {board[7]} | {board[8]} | {board[9]} ')
print(f'---------------')
print(f' {board[4]} | {board[5]} | {board[6]} ')
print... |
6cc71c99bec4e3da9a9a61cf65d04af95f4cdf4b | ALuqueM/Trabajo-final-Python | /Trabajo Final/Modulo 1/Scripts/Problema 1.py | 150 | 4.03125 | 4 | y = input('Ingrese por favor su Nombre:')
print('hello, {}.'.format(y))
x = input('Ingrese por favor su Nombre:')
print('hello, {}.'.format(x)) |
6d4ef25c5d3bb2f2225eca4ef1ed864adc896b7d | ZainabMehdee/Separate-Numbers-and-Add-Them-Together | /main.py | 321 | 3.859375 | 4 | # 🚨 Don't change the code below 👇
two_digit_number = input("Type a two digit number: ")
# 🚨 Don't change the code above 👆
####################################
#Write your code below this line 👇
print(type(two_digit_number))
a = int(two_digit_number [0])
b = int(two_digit_number [1])
print (a + b)
|
4cf7bed9b1dabd9b8a0963294fcf5019bb8cdd49 | AlbertGithubHome/Bella | /python/datetime_test.py | 1,074 | 3.6875 | 4 | # datetime test
from datetime import datetime
print(datetime.now())
dt = datetime(2000, 8, 8, 13, 45, 6)
print('dt =',dt)
time_stamp = dt.timestamp()
print('dt.timestamp =', time_stamp)
print('now.timestamp =', datetime.now().timestamp())
now_timestamp = datetime.now().timestamp();
print('now_timestamp =', now_ti... |
f4890c20a78d87556d0136d38d1a1a40ac18c087 | AlbertGithubHome/Bella | /python/list_test.py | 898 | 4.15625 | 4 | #list test
print()
print('list test...')
classmates = ['Michael','Bob', 'Tracy']
print('classmates =', classmates)
print('len(classmates) =', len(classmates))
print('classmates[1] =', classmates[1])
print('classmates[-1] =', classmates[-1])
print(classmates.append('Alert'), classmates)
print(classmates.insert(2,'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.