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 |
|---|---|---|---|---|---|---|
5fbb6fad65cab887d9a8061f108bba0631388b8d | DMarchezini/UriOnlineJudge-Python | /Uri1036.py | 543 | 3.84375 | 4 | """
Exemplos de Entrada Exemplos de Saída
10.0 20.1 5.1
R1 = -0.29788
R2 = -1.71212
0.0 20.0 5.0
Impossivel calcular
10.3 203.0 5.0
R1 = -0.02466
R2 = -19.68408
10.0 3.0 5.0
Impossivel calcular
"""
variaveis = input().split(" ")
a, b, c = variaveis
a = float(a)
b = float(b)
c = float(c)
if a == 0 or (b ** 2 - (4*a*c... |
440ce870c626ba92489478877535f03bfc88943d | Mahedi250/Artificial-Intelligence | /Encryption/Encryption.py | 2,217 | 3.890625 | 4 | securityCode = {}
matrixList = []
encodedMatrix = []
pattern = [
[1,2,3],
[1,1,2],
[0,1,2]
]
#This method with Initialize the securityCode like 'A':1, 'B':2... 'Z':26
def initializeCode():
code = 1
for i in range(65,91):
securityCode[chr(i)] = code
code += 1
#This method will find th... |
d00c5dd8c996aaed2784a30a925122bee2a4ac9d | rafaeljordaojardim/python- | /basics/exceptions.py | 1,891 | 4.25 | 4 | # try / Except / Else / Finally
for i in range(5):
try:
print(i / 0)
except ZeroDivisionError as e:
print(e, "---> division by 0 is not allowed")
for i in range(5):
try:
print(i / 0)
except NameError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is no... |
20bfa38708e9d8d75096cf8e60b48874eb9030f1 | rafaeljordaojardim/python- | /advanced/itertools.py | 703 | 3.65625 | 4 |
from itertools import *
list1 = [1, 2, 3, 'a', 'b', 'c']
list2 = [101,102, 103, 'X', 'Y']
# chain get sequences and chains then together
a = chain(list1, list2)
for i in chain(list1, list2):
print(i)
list(chain(list1, list2))
# first value is the starting and the second is the step
count(10, 2.5)
for i in cou... |
700af91613cd9a2ee6667615f5a08e59f9d2da62 | MrPer4ik/pythoniasa19fall | /assignment01a.py | 1,490 | 4 | 4 | """
Assignment 1-A
==============
Write fuction that generates the text below; use at least variables and f-strings.
For those who are already familiar with Python – write the best code you can to conform to the Zen of Python.
"""
def poem():
result = ''
base = [["the house that Jack built", "lay in"],
... |
b5920d757099c82a445968a3ec820256906846e3 | Ericmanh/cac_ham_python | /CacHamToanHoc/ham_time.py | 235 | 3.796875 | 4 | # Hàm time gồm clock và time
from time import clock
print("enter your name:", end="")
start_time =clock()
name = input()
print("nhập name")
elapsed = clock() - start_time
print(name, "it took you", elapsed ,"second to repond")
|
7521cbf4b76c785fe8d0b78e837fba5cdf41cce1 | evanlihou/msu-cse231 | /clock.py | 1,436 | 4.4375 | 4 | """
A clock class.
"""
class Time():
"""
A class to represent time
"""
def __init__(self, __hour=0, __min=0, __sec=0):
"""Constructs the time class.
Keyword Arguments:
__hour {int} -- hours of the time (default: {0})
__min {int} -- minutes of the time... |
f5d77a708522b6febacc4c1e43704d1c63a2d07d | evanlihou/msu-cse231 | /proj01.py | 1,123 | 4.3125 | 4 | ###########################################################
# Project #1
#
# Algorithm
# Prompt for rods (float)
# Run conversions to other units
# Print those conversions
###########################################################
# Constants
ROD = 5.0292 # meters
FURLONG = 40 # rods
MILE = 1609.34 # me... |
9578905a36441641c14596aa6d262cb1be5fa3cd | hazalozbey/python | /modüller.py | 928 | 3.96875 | 4 | #def selamla():
# print("merhaba")
# print("nasılsınız")
# print(selamla())
# def selamla1(isim):
# print("isminiz:",isim)
# print(selamla1("hazal"))
#def toplama(a,b,c):
# print("toplamları",a+b+c)
#print(toplama(1,2,3))
#def faktöriyel(sayi):
# faktöriyel=1
# if(sayi==0 or sayi==1):
# ... |
3d6946467c554af43e10a93431ef883565fd72cf | mtmmy/Leetcode | /Python/0149_MaxPointsOnALine/maxPoints.py | 1,425 | 3.5625 | 4 | import unittest
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
class Solution:
def maxPoints(self, points):
"""
:type points: List[Point]
:rtype: int
"""
result, n = 0, len(points)
for i in range(n):
d... |
aa08c36318b4408b995ce281c712eb84b2c1fbd7 | mtmmy/Leetcode | /Python/0941_ValidMountainArray/validMountainArray.py | 555 | 3.546875 | 4 | class Solution:
def validMountainArray(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if not A or len(A) < 3:
return False
if A[0] > A[1] or A[-2] < A[-1]:
return False
peak = False
for i in range(0, len(A) ... |
d03418d26f95655d92cfa4116a826b8e9ecedd33 | mtmmy/Leetcode | /Python/0316_RemoveDuplicateLetters/removeDuplicateLetters.py | 542 | 3.53125 | 4 | from collections import Counter
class Solution:
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
freq = Counter(s)
visited, stack = set(), []
for c in s:
freq[c] -= 1
if c not in visited:
... |
11e2f25abb2ac470a3c9b11fe41735fd2e3fc8aa | mtmmy/Leetcode | /Python/0426_ConvertBinarySearchTreeToSortedDoublyLinkedList/treeToDoublyList.py | 864 | 3.734375 | 4 | class Node:
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.cur = None
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root:
return None
... |
4751e0618f128de48568312d32e7c346715b682a | mtmmy/Leetcode | /Python/0059_SpiralMatrix2/generate_matrix.py | 1,102 | 3.59375 | 4 | class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
result = [[0] * n for _ in range(n)]
nowWidth = n
nowHeight = n
x = 0
y = 0
num = 1
while nowWidth > 0 and nowHeight > 0:
if n... |
c2237fb7188c293ecff36d8874cd7aa3cc336e12 | mtmmy/Leetcode | /Python/0721_AccountsMerge/accountsMerge.py | 3,210 | 3.65625 | 4 | import unittest
class Solution:
def accountsMerge(self, accounts):
"""
:type accounts: List[List[str]]
:rtype: List[List[str]]
"""
def find(s, root):
return s if root[s] == s else find(root[s], root)
result = []
root = {}
own... |
54499ce3bff30fe820f3656956695b8f1d18dfb8 | mtmmy/Leetcode | /Python/0535_EncodeAndDecodeTinyURL/Codec.py | 866 | 3.5625 | 4 | import string
import random
class Codec:
def __init__(self):
self.shortToLong = {}
self.longToShort = {}
def randomString(self):
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6))
def encode(self, longUrl):
"""Encodes a URL to a shortened... |
618959b86074b58d1d86d9ed8ffcf1cac0ecb7b6 | mtmmy/Leetcode | /Python/0075_SortColors/sortColors.py | 635 | 3.890625 | 4 | class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
red, blue = 0, len(nums) - 1
i = 0
while i <= blue:
if nums[i] == 0:
nums[red], nums[i] = n... |
000577b788c7e90def08197606d74da889e05165 | mtmmy/Leetcode | /Python/0716_MaxStack/MaxStack.py | 1,327 | 4.09375 | 4 | class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.stackMax = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
if not self.stackMax or self.stackMax[-1] <= x:... |
544e3de907f65094f0a055633046d3e974afa171 | mtmmy/Leetcode | /Python/0482_LicenseKeyFormatting/licenseKeyFormatting.py | 1,323 | 3.6875 | 4 | import unittest
class Solution:
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
S = S.replace("-", "").upper()
rem = len(S) % K
return "-".join([S[:rem]] + [S[i:i+K] for i in range(rem, len(S), K)]).str... |
60bb9cb8ebe071f65f531dd18debe941b51532bf | mtmmy/Leetcode | /Python/0683_KEmptySlots/kEmptySlots.py | 1,591 | 3.5625 | 4 | import unittest
class Solution(object):
def kEmptySlots(self, flowers, k):
"""
:type flowers: List[int]
:type k: int
:rtype: int
"""
# result, left, right, n = 20001, 0, k + 1, len(flowers)
# days = [0] * n
# for i in range(n):
#... |
7420bd985c73f537922441476ed61b9bcaccb668 | mtmmy/Leetcode | /Python/0153_FindMinimuminRotatedSortedArray/findMin.py | 944 | 4 | 4 | import unittest
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = 0, len(nums) - 1
if nums[left] > nums[right]:
while left != right - 1:
mid = (left + right) // 2
... |
1dc2ec1b376662d3d96389de1c7d0ce136a3df35 | mtmmy/Leetcode | /Python/0843_GuessTheWord/findSecretWord.py | 1,816 | 3.609375 | 4 | import unittest
class Master:
def __init__(self, secretWord):
self.secretWord = secretWord
def guess(self, word):
"""
:type word: str
:rtype int
"""
if word == self.secretWord:
return 6
else:
return sum(c1 == c2 for c1, c2 in zip(... |
f53d7fbdfc35414a09506739f28234839859e806 | jplineb/OOP_Refresher | /Lessons/OOP_lesson3.py | 594 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 17:48:08 2019
@author: jline
"""
class Car:
## defining a class variable
wheels = 4
def __init__(self):
self.mil = 10 # Instance variable
self.com = "BMW" # Instance variable
c1 = Car()
c2 = Car()
c1... |
0e2ccea00baf8be2324ae4b38a3366ed30969705 | javiipzo/Ejercicios-del-tema-3 | /ejercicio1.py | 595 | 3.546875 | 4 | class Animal:
def __init__(self, age, name):
self.age = age # public attribute
self.name = name # public attribute
def saluda(self, saludo='Hola', receptor = 'nuevo amigo'):
print(saludo + " " + receptor)
@staticmethod
def add(a, b):
if isinstance(a, int) and isinstance(... |
84beba21cfcac0fc8a99b945fdc72ab1a5f578e4 | luxroot/baekjoon | /old/2609/main.py | 180 | 3.765625 | 4 | def gcd(a,b):
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
return a * b / gcd(a, b)
(a,b) = map(int,raw_input().split())
print gcd(a,b)
print lcm(a,b) |
4fc1e7a055c830baa4ea154de82a4568a60b3bdf | alicevillar/python-lab-challenges | /conditionals/conditionals_exercise1.py | 1,058 | 4.46875 | 4 |
#######################################################################################################
# Conditionals - Lab Exercise 1
#
# Use the variable x as you write this program. x will represent a positive integer.
# Write a program that determines if x is between 0 and 25 or ... |
807516283f0b9c85fdf4912375af203a8dd50e22 | Shilpaumarji/FST-M1 | /Python/Activities/Activity1.py | 214 | 4.03125 | 4 | username = input("Enter your name: ")
Age = int(input("Enter your age: "))
print("your name is: " + username)
year = str( (2021-Age) + 100)
print(username + " will be 100 years old in the year " + year)
|
08c92a58eaaeed99f8211b1965f9a2e605008147 | WaffleKing631/Curso_Python | /adivina_un_numero.py | 305 | 3.84375 | 4 | number_to_guess = 5
a = int(input("dime un numero?"))
b = int(input("dame otro numero?"))
c = int(input("solo uno mas"))
if a == number_to_guess:
print("acertaste")
if b == number_to_guess:
print("acertaste")
if c == number_to_guess:
print("acertaste")
else:
print("no has acertado :(")
|
2d02d9e158ab16e20c7705bcb3e6785e22ec33ac | WaffleKing631/Curso_Python | /encontrar_numero.py | 737 | 3.71875 | 4 | n_usuario = []
n_del_usuario = ""
while len(n_usuario) < 10:
while not n_del_usuario.isdigit():
n_del_usuario = input("Dime un numero: ")
n_usuario.append(int(n_del_usuario))
n_del_usuario = ""
print("numero añadido")
print("la lista es {}".format(n_usuario))
n_grande = n_usuario[0]
for nume... |
bb9270be02394d04551d1c05e582eb781c27a3b9 | madelinelyons/CrackingTheCodingInterview | /interviewChapter7blackJack.py | 941 | 3.546875 | 4 | class Card:
def __init__(self, num, suit):
self.num = num
self.suit = suit
available = True
def getNum(self):
return self.num
def getSuit(self):
return self.suit
class DeckOfCards:
def __init__(self):
self.min = 2
self.max = 14
self.deck... |
731a4ae9b656ffeba8417e4c166e0be86fe28c2c | Dhinacse/codekata | /guvi_strings_190.py | 143 | 3.671875 | 4 | n=input()
y=input()
l="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if(sorted(l)==sorted(n+y)):
print("complementary")
else:
print("non-complementary")
|
ddb15108ec263e7096efde366bd5a2bb3fb2e7e6 | IanGSalmon/hackerrank_python_challenges | /python_challenges/string_validator.py | 1,026 | 4 | 4 | '''Task
You are given a string .
Your task is to find out if the string contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.
Input Format
A single line containing a string .
Output Format
In the first line, print True if has any alphanumeric characters. Otherwise... |
56870e9f3f322e09042d9e10312ed054fa033fa2 | rghosh96/projecteuler | /evenfib.py | 527 | 4.15625 | 4 |
#Define set of numbers to perform calculations on
userRange = input("Hello, how many numbers would you like to enter? ")
numbers = [0] * int(userRange)
#print(numbers)
numbers[0] = 0
numbers[1] = 1
x = numbers[0]
y = numbers[1]
i = 0
range = int(userRange)
#perform fibonacci, & use only even values; add sums
sum ... |
311fb982387df43a1c79a90d48a477cb58ad3856 | silviajlee/MC102 | /lab10.py | 1,553 | 3.796875 | 4 | #"Roteiro do Lab. 10: https://www.ic.unicamp.br/~mc102/mc102-1s2020/labs/roteiro-lab10.html"
import copy
#entrada
padrao = []
quadros = 0
while True:
leitura =list(input(""))
if(leitura[0].isnumeric()):
quadros = int("".join(leitura))
break
else:
padrao.append(leitura)
... |
f87bafd4dbf5b69b9eda0f1baa5a87543b881998 | biniama/python-tutorial | /lesson4_list_tuple_dictionary/dictionary.py | 953 | 4.375 | 4 | def main():
# dictionary has a key and a value and use colon (:) in between
# this is a very powerful and useful data type
dictionary = {"Book": "is something to read"}
print(dictionary)
biniam_data = {
"name": "Biniam",
"age": 32,
"profession": "Senior Software Engineer",
... |
3c21bd12834e39d8fd1c53bb5d9885c2cc75a360 | biniama/python-tutorial | /lesson6_empty_checks_and_logical_operators/logical_operators.py | 490 | 4.1875 | 4 | def main():
students = ["Kidu", "Hareg"]
name = input("What is your name? ")
if name not in students:
print("You are not a student")
else:
print("You are a student")
# if name in students:
# print("You are a student")
# else:
# print("You are not a student")
... |
bac2a9c57de523788893acc83ddfb37a2e10ce0d | biniama/python-tutorial | /lesson2_comment_and_conditional_statements/conditional_if_example.py | 1,186 | 4.34375 | 4 | def main():
# Conditional Statements( if)
# Example:
# if kidu picks up her phone, then talk to her
# otherwise( else ) send her text message
# Can be written in Python as:
# if username is ‘kiduhareg’ and password is 123456, then go to home screen.
# else show error message
# Conditio... |
48cff82b645be0f551882888338d76f180fda1ce | aiperi2021/pythonProject | /day_7/home.py | 187 | 3.703125 | 4 | # num = [1, 2, 3, 4]
# for i in num:
# if i%2==0:
# print(i*2)
# else:
# print(i*3)
# box = 0
# num = [1, 2, 3, 4]
# for i in num:
# box+=i
# print(box)
|
f8c60b72937991f86a2bb8ae0ceaace784dea55f | aiperi2021/pythonProject | /day_7_test/test.py | 849 | 3.984375 | 4 | #1 create program which will ask input from user,
# ex: "please enter your name " it will accept the inserted name and display
#2 create variable name(string),age(number), isCold(boolean) and print
#3a create list of cars, loop and print
#3b create list of cars print last car
#3c create list of cars and count how... |
62ac86c00c6afcbb16dcc58a1a12bc426070001a | aiperi2021/pythonProject | /day_4/if_statement.py | 860 | 4.5 | 4 | # Using true vs false
is_Tuesday = True
is_Friday = True
is_Monday = False
is_Evening = True
is_Morning = False
if is_Monday:
print("I have python class")
else:
print("I dont have python class")
# try multiple condition
if is_Friday or is_Monday:
print("I have python class")
else:
print("I dont have p... |
f6c60e2110d21c44f230ec710f3b74631b772195 | aiperi2021/pythonProject | /day_7/dictionar.py | 298 | 4.3125 | 4 | # Mapping type
## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
#create dict
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
for key in dict:
print(key, '->', dict[key]) |
75c79eabc067d4703398e1a8870c1b6e9034bffb | yasaj/boston_data | /boston_data.py | 2,287 | 3.703125 | 4 |
# coding: utf-8
# In[334]:
# First let's import all the packages that wer will need in order to analyze and visualize our data
import seaborn as sns
from sklearn.datasets import load_boston
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
boston_dataset = load_boston()
# In[341]:
# We w... |
390a08b879439751866c6caa458fee0235df3387 | cpe202fall2018/lab0-asayani1 | /planets.py | 309 | 3.796875 | 4 | def weight_on_planets():
# write your code here
earth = int (input("What do you weigh on earth? "))
#print (earth)
#print("\n")
print ("\nOn Mars you would weigh", earth*0.38, "pounds.")
print ("On Jupiter you would weigh", earth*2.34, "pounds.")
if __name__ == '__main__':
weight_on_planets()
|
0949dfc3c4efa0badea19992482ee2d616315f59 | kafelka/phonebook_project | /phonebook_personal_engine.py | 2,450 | 3.59375 | 4 | import sqlite3
import json
from pprint import pprint
def get_db(db_name):
try:
if db_name != "phonebook_database.db":
raise OSError('Wrong database name!')
#connects to db
conn = sqlite3.connect(db_name)
#link to db with cursor
c = conn.cursor()
print('... |
d42487928b8129a69ee49145646347e4230f8e40 | dzeinali/11411-QA-Project | /asking/simpleBinary.py | 7,023 | 3.578125 | 4 | import warnings
warnings.filterwarnings("ignore")
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import wordnet as wn
from nltk.tag import pos_tag
import string
# after tokenize the input is a list of strings
# each string is a complete sentence
''' create a list of all "to be" verb... |
0e223753f3974b262b4c45ab87e886a6f3a3731c | Xwartu/E02a-Control-Structures | /main10.py | 3,178 | 4.375 | 4 | #!/usr/bin/env python3
import sys, random
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
print('Greetings!') # A customary hello to the user, prints in terminal
colors = ['red','orange','yellow','green','blue','violet','purple'] # Listing all the possible colors ... |
274a5c9b306e62950c8e70aeb7f237ab08521966 | mergitto/word-similarity-python | /replace.py | 869 | 3.5 | 4 | # -*- coding: utf-8 -*-
def change_word(word):
word = word.replace('it', 'ict')
word = word.replace("ウェブ", "web")
word = word.replace("gd", "グループディスカッション")
word = word.replace("pg", "プログラマー")
word = word.replace("openes", "エントリーシート")
word = word.replace("es", "エントリーシート")
word = word.replace... |
a6a89acec433c34ff3c0905890dd7ac2304eceb7 | Vaspe/Coursera_Python_3_Programming_Michigan | /Python_Classes_and_Inheritance_Mod4/Ch20_classes_Ass.py | 996 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 00:25:14 2020
@author: Vasilis
"""
#%% Ass 1
class Bike:
def __init__ (self,color,price):
self.color = color
self.price = price
testOne = Bike('blue',89.99)
testTwo = Bike('purple', 25.0)
print(testOne.color)
#%% Ass2
class Appl... |
9809e48a7efbe7447455e8bd136b609c55ddb53c | Vaspe/Coursera_Python_3_Programming_Michigan | /Python_Basics_Mod1/listsAndStrings.py | 6,561 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 29 18:20:46 2020
@author: Vasilis
"""
#%% Definitions
"""
string: A single variable which is a concatenation of single strings (nubers,letters,
symbols, etc,,,). Empty string is also a single character. They are marked with quotes
Example: 'I am a string... |
4c58f3e5799dd7de38c26d14cdaf2ca9ebd8dd5c | Vaspe/Coursera_Python_3_Programming_Michigan | /Python_Classes_and_Inheritance_Mod4/Ch18_Test_Cases.py | 3,893 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 00:03:34 2020
@author: Vasilis
Important resouces not covered in the course abut modules unittest and doctest:
https://docs.python.org/3/library/unittest.html
https://docs.python.org/3/library/doctest.html#module-doctest
Asser statement:
https://docs.pyth... |
00e3304a1b6216c18d5cd8fc9ea5c266ed72149e | Vaspe/Coursera_Python_3_Programming_Michigan | /Python_Project_pillow_tesseract_and_opencv_Mod5/Week2_Tesseract/ipywidgets_stuff.py | 2,172 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 19:49:51 2020
@author: Vasilis
"""
# In this brief lecture I want to introduce you to one of the more advanced features of the
# Jupyter notebook development environment called widgets. Sometimes you want
# to interact with a function you have created and call it mul... |
cf9fcbcad23d70ed863af3f74cbfac22543b5671 | Vaspe/Coursera_Python_3_Programming_Michigan | /Python_Basics_Mod1/Mutability_ch9.py | 4,943 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 2 22:32:44 2020
@author: Vasilis
"""
#%% Theory
# List are mutable we can add, remove or reassign elements
# Strings and tuples are immutable we can only reassign or create a new variable to change them
#%% Basics
# replacing elements
alist = ['a', 'b', 'c', 'd', 'e',... |
0229eae841f5fec0563ad643a508650a3b1b235c | nadiiia/cs-python | /extracting data with regex.py | 863 | 4.15625 | 4 | #Finding Numbers in a Haystack
#In this assignment you will read through and parse a file with text and numbers.
#You will extract all the numbers in the file and compute the sum of the numbers.
#Data Format
#The file contains much of the text from the introduction of the textbook except that random numbers are inser... |
7b0da6770e7e68abc8b52de20229e4b8ff77ba76 | mrcabellom/django-api-disney | /app/utils.py | 306 | 3.71875 | 4 | from datetime import datetime
def parse_date(string_date):
try:
d = datetime.strptime(string_date, "%Y-%m-%d %H")
except ValueError:
d = datetime.strptime(string_date, "%Y-%m-%d")
return d
def date_to_string(date):
d = datetime.strftime(date, "%Y-%m-%d %H")
return d |
255fd794666d6dc504c261877489e3b7ee872bbe | saharul/csa_ver3 | /carinfo_db.py | 4,096 | 3.515625 | 4 | import pandas as pd
class CarInfoDb:
def __init__(
self, filename="/home/saharul/Projects/csa_ver3/data/carinfo_master.csv"
):
self.dbfilename = filename
def GetModelId(self, model):
if type(model) != str:
raise TypeError("Car Model must be in str")
if len(mo... |
45e7a9010b5dd5c64c2806a33cac78e7892519bc | pascal19821003/python | /study/tutorial/if.py | 105 | 4.03125 | 4 | x=1
if x<1:
print("greater than 1")
elif x==1:
print("equal to 1")
else:
print("less than 1") |
a1cf305f838642ef9d1c17a626952e89e65753c9 | pascal19821003/python | /study/tutorial/runoob/1.py | 1,237 | 4.0625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# https://www.runoob.com/python/python-variable-types.html
counter=100 # 赋值整型变量
miles = 1000.0 # 浮点型
name = "John" # 字符串
print(counter)
print (miles)
print (name)
print("----------------------------")
a = b = c = 1
print(a)
print(b)
print(c)
print("------------------------... |
c2636f45f0515cf761426c0aea37ba3eaadfda09 | jasonDBA/pythonApp | /Read_Write_A_Text_File/Read_Write_A_Text_File.py | 1,598 | 3.640625 | 4 | # Read / Write files in Python
# Project: Read / Write 'Let it be' lylics
# Name: Jason(Jabin) Choi
# Date: June 8, 2020
# Reference: https://docs.python.org/3/tutorial/inputoutput.html
import os # import os module
script_dir = os.getcwd()
odd_path = "oddlines.txt"
even_path = "evenlines.txt"
output_... |
4e8ad87dcc310d0b2dc8ec15dadb325cdae597f6 | dmi3s/stepik-512-py | /Hierarchy.py | 1,098 | 3.890625 | 4 | import string
class Hierarchy(dict):
def is_derived_from(self, derived: string, base: string) -> bool:
if derived not in self:
return False
if derived == base:
return True
for p in self[derived]:
if p == base or self.is_derived_from(p, base):
... |
85268e65ca2eefeec04a1501f96479be569f23bd | fshi7418/hack-the-north-2018 | /digital_recognition.py | 3,794 | 3.65625 | 4 | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
#the following is a RandomForest training program for a model
training_data = pd.read_csv("train.csv")
# Any results you write to the current directory are saved as output.
from sklearn.metrics import *
... |
c5bef145b8b46fee27bd38b53f39f93985a5588a | aanyag/15112-Clue | /clueAI.py | 3,700 | 3.703125 | 4 | from cmu_112_graphics import *
import math, random
class MyApp(App):
def appStarted(self):
self.doorsList = [(3,6),(4,9),(5,17),(6,11),(6,12),(8,6),(9,17),(10,3),
(12,1),(12,16),(15,5),(17,9),(17,14),(18,19),(19,4),(19,8),(19,15)]
#I used this website (https://www.raywe... |
ec44cec6454308cf50228aba28e85d23687d3ded | erisantiagodev/SimplePythonCarInsuranceApp | /PythonApplication1/PythonApplication1/PythonApplication1.py | 1,177 | 3.984375 | 4 | import os
import sys, time
def TicketsCalculation():
print("How many tickets do you have?")
num_tickets = int(input())
if num_tickets < 4:
print("We are able to proceed")
else:
print("We are unable to insure customers with more than 3 tickets")
print("Thank you for your time")
... |
554b6a60f0ce12acadbc4ed27d349fb4c37f04b1 | Soist/waste_sorter | /Activity2/Milestone1.py | 1,823 | 3.65625 | 4 |
import cv2
import numpy as np
uppLeft = None
lowLeft = None
uppRight = None
def mouseResponse(event, x, y, flags, param):
"""This function is a callback that happens when the mouse is used.
event describes which mouse event triggered the callback, (x, y) is
the location in the window where the event happ... |
779f35f7c879f19b76f34ac1c613a9a9293eb790 | muskan121/code-example | /sample09.py | 117 | 3.96875 | 4 | def string_length(str1):
count=0
for char in str1:
count = count+1
return count
print(string_length("muskaan"))
|
08122e08dcda056d55f018213db1082b01492827 | DarkDivision4/CrackCaesar | /crackcaesar.py | 402 | 3.90625 | 4 | KEY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ciphertext = input('Enter Cipher Text? ')
def decrypt(x, ciphertext):
result = ''
for l in ciphertext:
try:
index = KEY.index(l)
i = (index - x) % 26
result += KEY[i]
except ValueError:
... |
c0eea93b3e10fd8afd3abddc0869da07ad7a47d5 | Yaz015/EjerciciosPython | /Guia2/E6.py | 640 | 4.03125 | 4 | #Escribir un programa que seleccione una operación de cuatro operaciones numéricas disponibles,
# una vez seleccionada la operación, introducir dos números y ejecutar la operación.
elegir_operacion = int(input("""Seleccionar la operación que desea realizar:
1 - Suma
2 - Resta
3 - Producto
4 - División
... |
5a012ca3c16c00425e65c1c2414a70f6f7254e81 | Yaz015/EjerciciosPython | /Guia1/Ejercicio4.py | 164 | 3.84375 | 4 | #Ejercicio 4: Crear un programa que pregunte al usuario su nombre y devuelva "¡Hola {nombre}!"
nombre = input("Cual es su nombre?: ")
print("Hola "+ nombre +"!") |
b86aed3a1e2423a694aeed07db31085f8632993f | Yaz015/EjerciciosPython | /Guia1/Ejercicio8.py | 316 | 3.59375 | 4 | # Ejercicio 8: Crear un programa que almacene en una lista las siguientes materias: Historia, Matemática, Lengua y Geografía.
# Luego devolver por pantalla la última materia almacenada.
lista_materias = ['Historia' ,'Matemática', 'Lengua', 'Geometria']
ultimaMateria = lista_materias[-1]
print(ultimaMateria) |
38144f2e286a1ef7b1c997c0cad7a55e2174f7ba | astroteo/OptimizationExperiments | /genetic_boxes.py | 4,988 | 3.65625 | 4 | #!/usr/bin/python2.7
# -*-coding:Utf-8 -*
import numpy as np
import random
#step-1: create a fitness function
def fitness (password, test_word):
if (len(test_word) != len(password)):
print "taille incompatible"
return
else:
score = 0
i = 0
while (i < len(password)):
if ( test_word[i] == password[i] ):
... |
0e236cdd26114b7f59f5b0b713931790a54145fd | arnoldfini/namra | /recommendations_algorithm/input_related/cs50.py | 1,158 | 3.8125 | 4 | import re
import sys
def get_string(prompt) -> object:
"""
Read a line of text from standard input and return it as a string,
sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n)
as line endings. If user inputs only a line ending, returns "", not None.
Returns None upon error or n... |
59bb55684bffde3abd337b0617af2117a9e4abb4 | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/FindAllAnagramsinaString.py | 2,464 | 4.1875 | 4 | # 438. Find All Anagrams in a String
# Easy
# 1221
# 90
# Favorite
# Share
# Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
# Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
# The order of output... |
3b45f252180ac6e85fdf1e94f783542378efd2de | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/CountUnivalueSubtrees.py | 1,443 | 3.578125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countUnivalSubtrees(self, root: TreeNode) -> int:
self.count = 0
def dfs(root):
if root == None:
... |
041f21360e8762ff26a339ef28e8891df72e5951 | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/TrappingRainWater.py | 2,064 | 3.859375 | 4 | # Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for ... |
fa550f5026cc16f1dc02ef204fc352e79d027f57 | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/StringToInteger.py | 1,972 | 3.796875 | 4 | # mplement atoi which converts a string to an integer.
#
# The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and inte... |
17dfc714163d95c66f05278ffc62b2b69ec0b967 | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/FindtheDuplicateNumber.py | 1,020 | 3.53125 | 4 | # # import collection
# class Solution:
# def findDuplicate(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# a = collections.Counter(nums)
# return a.most_common(1)[0][0]
# class Solution:
# def findDuplicate(self, nums: List[int]) -> int:
# ... |
5e2f86e03c300b8c89217e1402e66901514951c6 | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/LongestSubstringwithAtMostTwoDistinctCharacters.py | 2,760 | 4.09375 | 4 | import sys
# Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
# Example 1:
# Input: "eceba"
# Output: 3
# Explanation: t is "ece" which its length is 3.
# Example 2:
# Input: "ccaabbb"
# Output: 5
# Explanation: t is "aabbb" which its length is 5.
# ... |
fbc9f13538fa5ff7d4ed03965ee844c23d2cd6e4 | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/MiddleoftheLinkedList.py | 477 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
pointer1 = head
pointer2 = head
while (pointer2 != None and pointer2.next != None):
poi... |
9b552a95d0405e484c6b53ab2ce6d97d96f83daa | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/AddDigits.py | 293 | 3.6875 | 4 | class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
sum = 0
for ch in str(num):
sum = sum + int(ch)
if sum<10:
return sum
else:
return self.addDigits(sum)
|
d784762141d91432fde3d91b904d9d2faa909dec | HelenaZanini/python_design_patterns | /strategy_pattern/strategy.py | 396 | 3.75 | 4 | from abc import ABC, abstractmethod
class ImpostosAbstrato(ABC):
@abstractmethod
def calcula(self):
pass
class ICMS(ImpostosAbstrato):
def calcula(self, valor):
return valor * 0.11
class ISS(ImpostosAbstrato):
def calcula(self, valor):
return valor * 0.05
class PIS(Imp... |
154ed2e640f90b554e3e3750371211592e1ae30e | xheniscoba/XRating | /client/result/result.py | 1,653 | 3.671875 | 4 | class Result:
"""
A class used to represent a rated task.
Attributes
----------
checkbox_results : list
list of the rated attributes using Yes/No chekboxes
slider_results : list
list of the rated attributes using a slider with values in [0,100]
Methods
-------
... |
0cd4fbd232f8b0d85ff333b2111e0a70826aec41 | dhydrated/pgconn | /pgconn/menu_builder.py | 522 | 3.515625 | 4 | class MenuBuilder:
"""Menu builder"""
menu=""
selection=None
def __init__(self, logger, items):
self.logger = logger
self.logger.name = self.__class__.__name__
self.items = items
def display(self):
index = 1
self.menu = "Please select a connection:\n"
for item in self.items:
self.menu += str(index... |
24a6d25c1621d6beda9926c9e11d510c7f7f6f1f | JobStoker/ProgrammingCourseHU | /2-6.InputAndOutput.py | 303 | 3.609375 | 4 | uurloon = input('Uurloon: ')
werkuren = input('Aantal werkuren: ')
int(uurloon)
int(werkuren)
salaris = int(werkuren)*int(uurloon)
print('Je verdient: ' + str(uurloon) + ' per uur')
print('Je hebt: ' + str(werkuren) + ' uren gewerkt')
print(str(werkuren) + ' uur levert ' + str(salaris) + ' Euro op') |
537fbef2767aed8a86d85cba69ff0ca8d1f8fcb6 | JobStoker/ProgrammingCourseHU | /3-5.ForIfNumbers.py | 85 | 3.84375 | 4 | numbers = [3, 6, 4, 1, 7, -2]
for i in numbers:
if i % 2 == 0:
print(i)
|
c3e814f8455d25a6b3d6279167f5a84578debf74 | veenaGangi/serviceportal | /mapreduce/wordcount.py | 1,260 | 3.859375 | 4 | #!/usr/local/bin/python3.8
from mapreduce import MapReduce
class WordCount(MapReduce):
def mapper(self, _, line):
for word in line.split(" "):
yield (word.strip(),1)
def combiner(self, key, values):
yield key, sum(values)
def reducer(self, key, values):
yield key, su... |
94953f4e3009292aa5af210633ef280b0bc02725 | abishekbalaji/hundred_days_of_code_python | /day_25/main.py | 1,390 | 3.828125 | 4 | # import csv
#
# with open(file="weather_data.csv") as data_file:
# data = csv.reader(data_file)
# temperatures = []
# for row in list(data)[1:]:
# temperatures.append(int(row[1]))
# print(temperatures)
import pandas
# data = pandas.read_csv('weather_data.csv')
# print(data["temp"])
# temp_lis... |
01046b00459e9344c53d1d3f4872e7cea3355d1e | abishekbalaji/hundred_days_of_code_python | /day-26-1/main.py | 1,541 | 3.84375 | 4 | nums = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
squared_nums = [num ** 2 for num in nums]
print(squared_nums)
# Filter even nums
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
even_nums = [num for num in numbers if num % 2 == 0]
print(even_nums)
# Common nums
with open('file1.txt') as file1:
list1 = file1.read().split('... |
f32d4eafb08ee037e0e9637638db9d1b5c43b693 | abishekbalaji/hundred_days_of_code_python | /CoffeeMachine1/main.py | 2,196 | 3.9375 | 4 | import menu
items = menu.MENU
resources = menu.resources
money = 0
def report():
print(f"Water: {resources['water']}\nMilk: {resources['milk']}\nCoffee: {resources['coffee']}\nMoney: {money}")
def is_sufficient(req):
return req['water'] <= resources['water'] and req['milk'] <= resources['milk'] and req['co... |
b99d753d1130578e2305ddca338afb294f978715 | abishekbalaji/hundred_days_of_code_python | /five_percent.py | 137 | 3.921875 | 4 | import math
def five_percent(num):
return math.ceil(num + (num * 0.05))
while True:
print(five_percent(int(input("num: "))))
|
444d702ca4a6f39db57afab2acecfddf50e1a677 | MenacingManatee/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 202 | 3.890625 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
new_dict = {}
keys = a_dictionary.keys()
for key in keys:
new_dict.update({key: a_dictionary.get(key) * 2})
return (new_dict)
|
795cbf40f98ad3a775af177e11913ce831752854 | MenacingManatee/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 504 | 4.21875 | 4 | #!/usr/bin/python3
'''Prints a string, adding two newlines after each of the following:
'.', '?', and ':'
Text must be a string'''
def text_indentation(text):
'''Usage: text_indentation(text)'''
if not isinstance(text, str):
raise TypeError('text must be a string')
flag = 0
for char in text:
... |
1ee074079729475b25368a84a39006e5306aec28 | MenacingManatee/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 571 | 4.375 | 4 | #!/usr/bin/python3
'''Adds two integers
If floats are sent, casts to int before adding'''
def add_integer(a, b=98):
'''Usage: add_integer(a, b=98)'''
if (a == float("inf") or (not isinstance(a, int) and not
isinstance(a, float)) or a != a):
raise TypeError('a must be a... |
0979d91394847fbe8ff9edd49d6bb1e2d0fc451e | MenacingManatee/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 319 | 3.921875 | 4 | #!/usr/bin/python3
def islower(a):
a = ord(a)
if a > 96:
return(a - (ord("a") - ord("A")))
else:
return(a)
def uppercase(s1):
s2 = list(s1)
for i in range(len(s2)):
check = islower(s2[i])
s2[i] = chr(check)
print("{:s}".format(s2[i]), end="")
print("")
|
d5d557f24d2e74375e95cf22f7df5d2ed5587e8c | MenacingManatee/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 321 | 4.3125 | 4 | #!/usr/bin/python3
'''Defines a function that appends a string to a text file (UTF8)
and returns the number of characters written:'''
def append_write(filename="", text=""):
'''Usage: append_write(filename="", text="")'''
with open(filename, "a") as f:
f.write(text)
f.close()
return len(text)... |
d91f8e862b939ab0131fab2bf97c96681fba005a | MenacingManatee/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 595 | 4.1875 | 4 | #!/usr/bin/python3
'''Defines a function that inserts a line of text to a file,
after each line containing a specific string'''
def append_after(filename="", search_string="", new_string=""):
'''Usage: append_after(filename="", search_string="", new_string="")'''
with open(filename, "r") as f:
res = ... |
faefe53c66424e822ce06109fc4d095f013e64c0 | MenacingManatee/holbertonschool-higher_level_programming | /0x06-python-classes/102-square.py | 1,442 | 4.40625 | 4 | #!/usr/bin/python3
'''Square class'''
class Square:
'''Defines a square class with logical operators available based on area,
as well as size and area'''
__size = 0
def area(self):
'''area getter'''
return (self.__size ** 2)
def __init__(self, size=0):
'''Initializes size'''... |
55ea45a451bca133710791cb21e86bb40f5a85d3 | MenacingManatee/holbertonschool-higher_level_programming | /0x06-python-classes/testfiles/6-main.py | 544 | 3.5 | 4 | #!/usr/bin/python3
Square = __import__('6-square').Square
my_square_1 = Square(3)
my_square_1.my_print()
print("--")
my_square_2 = Square(3, (1, 1))
my_square_2.my_print()
print("--")
my_square_3 = Square(3, (3, 0))
my_square_3.my_print()
print("--")
try:
my_square_4 = Square(0, (0))
my_square_4.my_print(... |
5d5fc3a5e07ea8c85394024194ebbb62b4a49a56 | higher68/Introduction_to_Algorithms_and_Data_Structures | /ALDS1_7_A.py | 3,691 | 4.03125 | 4 | # ouput:parent, depth, type, 子の節点番号をそれぞれのノードに対してアウトプット
# pythonはnullじゃなくてNonce
class Node:
'''
leftは子ノード
rightは同depthのノード
'''
def __init__(self):
self.parent = None
self.left = None
self.right = None
# def getDepth(u):
# '''
# depthを入力した番号のノードに対して求める
# '''
# ... |
774a96446d5fe9f8d4539871c36ab489d1531262 | akhileshkaushal/annotation-refinery | /utils.py | 4,259 | 3.640625 | 4 | import os
import tempfile
import shutil
import requests
import urllib
from urlparse import urlsplit
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
def check_create_folder(folder_name):
"""
Small utility function to check if a folder already exists, and
create... |
8c7829926b918d3cfce2b4eba919b84c0d4b4da3 | MilesTide/Tree | /BinaryTree.py | 1,691 | 4 | 4 | #二叉树类
class BinaryTree(object):
# 初始化,传入根节点的值
def __init__(self, root_value):
self.root = root_value
self.leftchild = None
self.rightchild = None
# 插入左子树
def insert_left(self, left_value):
if self.leftchild == None :
self.leftchild = BinaryTree(left_value)
... |
0e53f01af5ec7831f99804d3973a11052cf98426 | shea7073/More_Algorithm_Practice | /bubble_sort.py | 356 | 3.984375 | 4 | # Implement bubble sort
def bubble(arr):
for j in range(len(arr)):
for i in range(len(arr)-1):
first = arr[i]
second = arr[i+1]
if first > second:
temp = arr[i+1]
arr[i+1] = arr[i]
arr[i] = temp
print(arr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.