blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7adc7d3e922cd17a5043083cfc140f351bc28208 | Great-designer/BUAA-OJ-Project | /python/1205 刘同学家的电费.py | 251 | 3.53125 | 4 | n = int(input())
res = float(0)
if n <= 150:
res = float(n * 0.4463)
else:
if n <= 400:
res = float(150 * 0.4463 + (n - 150) * 0.4663)
else:
res = float(150 * 0.4463 + 250 * 0.4663 + (n - 400) * 0.5663)
print("%.3f" % res)
|
120e5399891ed4383322627f9c3c2086cc94cd67 | LeandroRezendeCoutinho/fibonacci | /fib.py | 213 | 3.8125 | 4 | import time
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
start = time.clock()
print fibonacci(42)
end = time.clock()
print "%.2gs" % (end-start) |
53ab7c733da044c1903ac7810fd9cf69a44ac9ac | Llixin/LeetCode | /findKthLargest.py | 1,041 | 3.5625 | 4 | class Solution:
def partition(self, nums, l, r):
rand = randint(l, r)
nums[l], nums[rand], nums[r] = nums[rand], nums[r], nums[l]
i, j = l, r
tmp = nums[i]
while i < j:
while i < j and nums[j] >= tmp:
j -= 1
nums[i] = nums[j]
... |
bb6c77e281f74f42dc5efd36d037966ab43fd426 | roshan13ghimire/Competitive_Programming | /HackerEarth/Bricks_Game.py | 223 | 3.6875 | 4 | #Bricks_Game
n = int(input())
i = 1
while(True):
if n <= i:
print("Patlu")
break
n-= i
if n <= i * 2:
print("Motu")
break
n-= i*2
i+= 1
|
b2b57bff8dd27f0cc4cab50f374e9342800366a4 | imoea/pygame | /Pong/main.py | 11,406 | 3.546875 | 4 | #!/usr/bin/env python
""" a PONG clone by Joshua Wong """
from argparse import ArgumentParser
from init import *
from pygame.locals import *
import pygame
import random
import sys
import time
class Ball(pygame.Rect):
""" ball object """
def __init__(self, round_num):
""" initialise sta... |
1bd21746e4f5aaee277063dbf707eb6743b92ef8 | CesarVeras/algoritmos_senai | /problema41.py | 989 | 3.953125 | 4 | from utils import meses
def main():
tamanho = 12
menorMes = 0
maiorMes = 0
menorTemperatura = 0.0
maiorTemperatura = 0.0
temperaturas = []
for i in range(tamanho):
temperaturas.append(
float(input("Informe a temperatura média de {}: ".format(meses[i])))
)
... |
a674e76a65c2ee3e4efc5362693853ed260f61c8 | achalagarwal/Chai | /chai/src/Utils/sku_utils.py | 8,749 | 3.5 | 4 | from fuzzywuzzy import fuzz
from sys import maxsize
def is_valid_word(word):
if len(word) < 3:
return False
for char in word:
if str(char).isdigit():
return False
return not is_invalid_word(word)
def clean_words(words):
cleaned_words = list(filter(lambda x: not is_inval... |
01671af3940cfed5423bd75c546e6e57e0b8ad5e | noahc66260/ProjectEuler | /problem3.py | 688 | 3.65625 | 4 | import array
def isPrime(n):
for i in xrange(2,n-1):
if n % i == 0:
return False
return True
#max = 1
#i = 1
num = 600851475143
#num = 13195
#rtnum = int((num)**(.5))
#while i <= rtnum and i <= num:
# if isPrime(i) and num % i == 0:
# max = i
# num = num / i
# else:
# i += 1
primes = array.a... |
646273e26145bd854f0d86bfe800032b89f658ff | vangorade/Atcoder_training | /atcoder_training/Easy/B_Trained_.py | 351 | 3.765625 | 4 |
#init, butt1 is light up, stop when button2 is light up
# basically if 2nd light is get skipped then return -1
n = int(input())
arr = [int(input()) - 1 for _ in range(n)]
light = 0
couter = 0
while(light != 1):
light = arr[light]
counter += 1
if(counter > n): # we skipped second
print(-1)
... |
7c4280fe88050dd2a6bea9c6545bdccac703ebc8 | Sedoid/GCE-platform-project | /test.py | 223 | 3.6875 | 4 | import re
txt = "The rain in Spain and after the following, there is (7) another The Spain What wrong (8) what abou the rest (9)"
x = re.search(r"(Spain and).*?\(", txt)
print(x)
# if type(x) == 'None':
print(x.group(0))
|
f13742cd563194b4b25e608a7c97b58b9e1dacf4 | iishchenko/PythonCoursesExercises | /31.py | 207 | 4.09375 | 4 | for i in range(2, -3, -1): #Counts down from 2 to -2: 2, 1, 0, -1, -2
try:
print(2 / i) #Prints 2 divided by the current value of i
except ZeroDivisionError:
print("We can't divide by 0!")
|
b6fef0f3731988a88b08da830235bd2e9bada3f3 | nbremond/agilkia | /agilkia/utils.py | 4,463 | 3.953125 | 4 | # -*- coding:utf8
from typing import Optional
import random
class MinList:
def __init__(self, size):
"""Create a list of minimals values and the indexes associated with thoses values
:para size: the number of values to keep
"""
assert size > 0
self.values = []
self... |
0d46caf6946194614bf1656f855dd9b829f5a7fb | aniketshelke123/hello-world.io | /bineary_search.py | 393 | 3.546875 | 4 | def binary_rec(lst, l, r, key):
# while l <= r:
mid = (l + r) // 2
print("mid is: ", mid)
print(lst[mid])
if key == lst[mid]:
return mid
elif key < lst[mid]:
r = mid - 1
else:
l = mid + 1
binary_rec(lst, l, r, key)... |
dd132b73f3e24a1400a773bfd6a20b8f8fb60641 | psrawat23/Python-assignments-1 | /Assignment_1.py | 7,327 | 3.75 | 4 | #Sort the list based on the top level domain (edu, com, org, in) using custom sorting
import re
url = ['www.annauniv.edu', 'www.google.com', 'www.ndtv.com', 'www.website.org','www.bis.org.in', 'www.rbi.org.in']
y=lambda x: list(reversed(x.split('.')))
print(sorted(url,key=y))
#2. Given a list of strings, return ... |
48511443e0e54c8de1ed3cf7df0dad86742a2e6f | chengchuanqiang/pythonTest | /test/test1.py | 3,747 | 3.984375 | 4 | print("Hello Python!")
if True:
print("True")
else:
print("False")
str1 = 'ccq'
print(str1)
print(str1[0:-1])
counter = 100
miles = 100.0
name = "ccq"
print(counter)
print(miles)
print(name)
a, b, c, d = 20, 5.5, True, 4 + 3j
print(type(a), type(b), type(c), type(d))
def aaa():
"""这是一个字符串"""
pass... |
619d4353327b168920f929fd3743722abeaf4ffb | LeoEatle/python_leetcode_practice | /LeetCode/TreeNode/112 Path Sum.py | 816 | 4.09375 | 4 | #coding: utf-8
import TreeNode
class Solution(object):
def getSum(self, node, curSum):
if node is None:
return
curSum = curSum + node.val
if self.targetSum == curSum and not node.left and not node.right:#To ensure that this path if from root to leaf
self.ifExist = Tr... |
6cd807826ee9bdef495a13f3fce6389049c48980 | mkuti/mysql_test | /mongo_project.py | 4,288 | 3.59375 | 4 | import os
import pymongo
from os import path
if path.exists("env.py"): # import file where username and password of MongoDB is saved
import env
MONGO_URL = os.environ.get("MONGO_URL") # variable with secret MONGO_URL
DBS_NAME = "myOwnDB" # variable with name of DB
COLLECTION_NAME = "myOwnMDB" # variable with ... |
6103787dab49a1f3cf0d55e952ebaef86fdbc936 | abbasjam/abbas_repo | /python/arr.py | 125 | 4.15625 | 4 | i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,n):
print(i)
|
f6fc84bada7267a3bc4875d63000fb697f3eac8c | savva-kotov/python-intro-practise | /3-1-9.py | 208 | 4.09375 | 4 | '''
Прочитайте строку и сделайте из неё список.
Sample Input:
8 11
Sample Output:
['8', ' ', '1', '1']
'''
a = input()
res = []
for i in a:
res.append(i)
print(res)
|
b5a58794b39fcf5456c40dd8ad9c7e9689b8bb70 | lizhsen/Django | /bubble_sort.py | 382 | 4.0625 | 4 | # -*- coding: utf-8 -*-
lists = [49, 38, 65, 97, 76, 13, 27, 49]
def bubble_sort(lists):
count = len(lists)
for i in range(count):
for j in range(i+1, count):
if lists[i] > lists[j]:
lists[i], lists[j] = lists[j], lists[i]
print str(lists)+"%\n"
pri... |
a5fecbaa1459f14cf75f37a3442be97fc625837b | tdworowy/PythonPlayground | /Playground/Exercises/exer42_list_median.py | 532 | 4.03125 | 4 | from typing import List
def find_median_sorted_arrays(nums1: List[int], nums2: List[int]) -> float:
nums = nums1 + nums2
nums.sort()
center = len(nums) // 2
if len(nums) % 2 != 0:
return nums[center]
else:
return (nums[center - 1] + nums[center]) / 2
if __name__ == "__main__":
... |
bc6fad0a8bf33302a58ea9d97f37a5e1b1a8b61d | zhenh65671/Math_Quiz_v2 | /ques_generrantion_v2.py | 378 | 3.640625 | 4 | import random
NUM_QUES = 5
lo_num = 1
hi_num = 8
operator = "*"
display_text = "x"
# generate question
num_1 = random.randint(lo_num, hi_num)
num_2 = random.randint(lo_num, hi_num)
question = "{} {} {}".format(num_1, operator, num_2)
display_question = "{} {} {} = ".format(num_1, display_text, num_2)
answer = eval(... |
d0fc97167133ba4b042bcd93e366e0617ae97527 | Mark-Seaman/UNC-CS350-2017 | /Exercises/Results/jone2032/unit_test.py | 2,437 | 3.78125 | 4 | # unit_test.py
from os.path import exists
from files import read_csv, read_file, write_csv, write_file
def test_user(user):
try:
test_name(user)
try:
test_email(user)
print(user.name() + " was successully checked!")
except AssertionError:
print("User: " ... |
4ae6340524c73b97d71e88d54e78f1457a542612 | eunice-ogboye/my-app | /main/index.py | 1,292 | 3.71875 | 4 | print("to calculate the prices of some goods")
qm1 = input("Enter the qmtn100 quantity: ")
m1 = 970 * float(qm1)
qm2 = input("Enter the qmtn200 quantity: ")
m2 = 1940 * float(qm2)
qm4 = input("Enter the qmtn400 quantity: ")
m4 = 3880 * float(qm4)
qm5 = input("Enter the qmtn500 quantity: ")
m5 = 4850 * float(qm5)
qm10 ... |
705678ccb57dfbd12b17f46ac41920681908c750 | lpython2006e/python-samples | /Unit 07 Lists and Functions/02 Battleship/Dont Sinc my Battleship/6-Printing Pretty.py | 168 | 3.734375 | 4 | board = []
for loop in range(0, 5):
treta = ["O"] * 5
board.append(treta)
def print_board(board):
for row in board:
print(" ".join(row))
board
|
02b40b4508320093a37ac72f950aa0152442b6dc | leandroph/Python-CursoEmVideo | /ExerciciosPython/Exercicio_009.py | 594 | 4.28125 | 4 | '''Faça um programa que leia um número Inteiro
qualquer e mostre na tela a sua tabuada.'''
print("##### TABUADA #####")
num = int(input("Digite um número: "))
print(" 1 x {} = {}".format(num, num * 1))
print(" 2 x {} = {}".format(num, num * 2))
print(" 3 x {} = {}".format(num, num * 3))
print(" 4 x {} = {}".format(nu... |
e2e2f85e14f6b6dd5068eca91250c9a1590961df | CTXz/Python-Sandbox | /GroceryStore.py | 4,853 | 4.125 | 4 | # Note, this could all be done allot nicer (ex. trough OOP, functions, arrays etc.),
# however, as this is meant to teach conditionals, it's been written to use them as much as possible (which is quite noticable).
# Also, if you're already going ahead by judging this code, you shouldn't be here in first place. This co... |
f58785c392fb0a8dabf850aebaa5a37a8997fc9f | SiddharthaPagadala/python | /strings/alphabet_rangoli_hackerRank.py | 854 | 3.84375 | 4 | #You are given an integer, . Your task is to print an alphabet rangoli of size . (Rangoli is a form of Indian folk art based on creation of patterns.)
#
#Sample Input
#
#5
#Sample Output
#
#--------e--------
#------e-d-e------
#----e-d-c-d-e----
#--e-d-c-b-c-d-e--
#e-d-c-b-a-b-c-d-e
#--e-d-c-b-c-d-e--
#----e-d-c-d-e---... |
3c4c29df93ee42251939b4caecba955c1f4d241e | internetmusic/WebScraperAllMusic | /Code/WebScraperForAllMusic.py | 2,035 | 3.765625 | 4 | '''
Created on 4 ago. 2019
@author: ingov
'''
from bs4 import BeautifulSoup
from Code import Utils
def parserForInformation(page_source):
"""
@param page_source: This is a string that contains the HTML we are going to scrap to print
the information about the discography of an artist/band
This fun... |
368d5037e7bd9944cc3d6954c4c3293f2ac43f37 | joshua-malemba/Web-Scraper | /scraper.py | 2,253 | 3.609375 | 4 | import requests
from tkinter import *
import smtplib
from bs4 import BeautifulSoup
import sqlite3
import os
# helps parse the HTML data and retrieve/pull out specific data.
master = Tk()
def scrape():
# define base price ----> check if price changed
headers = {'User Agent':'Mozilla/5.0 (Windows NT 10.0; Win64... |
def5fd22f538974461bd07ce85395b68db72b730 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4016/codes/1708_3034.py | 65 | 3.875 | 4 | X=float(input("valor de entrada:"))
if(x<= -3) or
print(round()) |
a09df6022e24324a508aaf0348653e80edbc7a29 | qtdwzAdam/leet_code | /py/back/work_572.py | 1,436 | 3.9375 | 4 | # coding=utf-8
"""
Given two non-empty binary trees s and t, check whether tree t has exactly the
same structure and node values with a subtree of s. A subtree of s is a tree
consists of a node in s and all of this node's descendants. The tree s could
also be considered as a subtree of itself.
"""
from pprint import p... |
cd973ea450bba205fdae00f4e8375c82192c0a3e | kentronnes/datacamp | /Tidy Data in Python Mini-Course/Using_Melt_to_Tidy_Data.py | 1,908 | 4.3125 | 4 | # Using Melt to Tidy Data
# In df2, the years 1980, 1981, 1982, and 1983 mark the years when
# BMI is observed. Thus, they represent three different observations
# and should be seperated in three rows. A great tool to achieve this
# is the melt function in the pandas package. Its basic syntax is
# pd.melt(df, id_... |
53bc9b2a6e10504a80dc086ae8f60cfd1508fca6 | yxtay/how-to-think-like-a-computer-scientist | /Recursion/recursive_tree_random.py | 735 | 3.96875 | 4 | import turtle
import random
def tree(branchLen,t):
width = t.width()
t.width(branchLen // 10)
if branchLen < 15:
t.color('green')
if branchLen > 5:
t.forward(branchLen)
right = random.randrange(15,46)
t.right(right)
tree(branchLen-random.randrange(10,21),t)
... |
a7b167190108f3e5c937327caafb88238ba189ba | evaristrust/Courses-Learning | /DSFIRST/NUMPYLEARN/array_process.py | 1,596 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randn
points = np.arange(-5,5,0.01)
dx, dy = np.meshgrid(points,points)
print(dx)
print(dy)
z = (np.sin(dx) + np.sin(dy))
print(plt.imshow(z)) #ploting our stf
print(plt.colorbar())
print(plt.title('MY FIRST PLOT'))
#List comprehension
A = np... |
17a49f6fa477f83a879fb51d06e1c82df267ed6b | zhanghui9700/pykit | /property/getattr.py | 1,237 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding=utf8 -*-
class Foo():
def __init__(self,name):
self.name = name
def __getattr__(self,attrName):
'''
拦截“未定义”属性访问
'''
#print type(attrName) #<type 'str'>
print '__getattr__:%s' % attrName
if attrName == 'age':
... |
88dd98db81e03e1bd78e1a5770adabe775240cd2 | naohisas/KVS | /Example/SupportPython/Array/array.py | 113 | 3.515625 | 4 | def main( array, value ):
for i in range( array.size ):
array[i] = array[i] + value
return array
|
4eff71ae417492452bc8cc142f705802dcca9653 | andymc1/ipc20161 | /lista1/ipc_lista1.06.py | 274 | 3.71875 | 4 | #ipc_lista1.6
#Professor: Jucimar Junior
#Any Mendes Carvalho -
#
#
#
#
#Faça um programa que peça o raio de um círculo, calcule e mostre sua área
raio = 0
area = 0
raio = input("Entre com o valor do raio: ")
area = 3.14 * raio*raio
print "Valor da área do círculo: %d m²" %area
|
9af384f71486de776669fd8ec0286cb696c11260 | ulyssey28/python-challenge | /PyPoll/main.py | 3,397 | 3.625 | 4 | #import necessary packages
import os
import csv
from collections import OrderedDict
#set relative path to csv file
csvpath = os.path.join('election_data.csv')
#use with statement to open the file
with open(csvpath, newline='') as filehandle:
#use csv.reader to read the contents of the file
election_csv = csv.r... |
124d94e96d806825cf9a9f5d37735284d9cbda77 | thewordisbird/pythonds | /Recursion/recursive_tree.py | 513 | 3.859375 | 4 | import turtle
def tree(width, branch_len, t):
if branch_len > 5:
t.width(width)
t.forward(branch_len)
t.right(20)
tree(width - 2, branch_len - 15, t)
t.left(40)
tree(width - 2, branch_len - 15, t)
t.right(20)
t.backward(branch_len)
if __name__ == "__... |
fa1500021bcaadf1d892614f5a6a198b85d5a76c | angelah1994/holbertonschool-higher_level_programming-1 | /0x04-python-more_data_structures/12-roman_to_int.py | 552 | 3.71875 | 4 | #!/usr/bin/python3
def roman_to_int(roman_string):
if roman_string is None:
return 0
if type(roman_string) is not str:
return 0
romans = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
number = len(roman_string)
value_int = romans[roman_string[number-1]]
for i i... |
fcbb620f8a7546d837ff383e8c95e54a1bf6e1b1 | SamPereirabr/Livro_Nilo_Ney | /Ex3.15_dias_de_vida.py | 401 | 3.828125 | 4 | print("Vamos calcular a quantidade de dias que você já perdeu devido ao cigarro. ")
qtde_cigarros = int(input("Digite a quantidade de cigarros que você fuma por dia: "))
anos = int(input("Por quantos anos, você já fuma? "))
dias = (qtde_cigarros * 10 * anos * 365) / 1440
print(f"Você já perdeu {dias:1.0f} dias de vi... |
12d45155bff13b0189dc3a832b4bce3a52617957 | RomanPutsilouski/M-PT1-37-21 | /Lessons/lesson 04-05/random_sort.py | 578 | 3.75 | 4 | import random
def is_sorted(l):
for i in range(len(l)-1):
if l[i]>l[i+1]:
return False
return True
# if l == sorted(l):
# return True
# return False
def swap(l, x, y):
l[x], l[y] = l[y], l[x]
def get_rand_index(x):
return random.randint(0,x-1)
l = [3,1,... |
560da0598080db91b044cd022e7a505180b66ee0 | CLgithub/pythonLearn | /day6/04-函数.py | 1,029 | 4.0625 | 4 | #coding=utf-8
'''
函数
函数的定义:
def funcName():
funBody
'''
#定义一个无参数无返回值的函数func1()
def func1():
print("执行...")
print("函数体...")
#定义一个有参数无返回值的函数faddFunc()
def addFunc(i,j):
print("%d+%d=%d"%(i,j,i+j))
#定义一个有参数有返回值的函数faddFunc2()
def addFunc2(i,j):
sum1=i+j
return sum1
#定义一个有参数有多个返回值的函数fun4()
de... |
94adf106ad5a39bcc004cf482c20fb5c09046e72 | sraywall/GitTutorial | /quiz.py | 1,646 | 3.828125 | 4 | #!/usr/bin/python3
import argparse
from os import system
import random
# :set noexpandtab
def ask(q,a):
response = input(q)
if response == a:
print("correct")
else:
print("incorrect,",a)
input()
system("clear")
def main():
parser = argparse.ArgumentParser()
parser.add_argume... |
31a626d0d3ea2f2592c9efa3bd7c76afeaeee271 | dxdelvin/python-100-days-project | /Tip_calculator.py | 566 | 4.125 | 4 | print("Welcome to Tip and Spilt your Bill Calculator!\n")
bill = input("What was your Total Bill???\n")
bill_as_int = int(bill)
print("What amount of tip you want to provide")
tip = input("5%,10%,15%,20%\n")
tip_as_int = int(tip)
Final_bill = bill_as_int + ((tip_as_int/100)*bill_as_int)
people = input("How many ... |
92c165a9df224045feab20eec8e2a35e76f1a52f | BeatrizBertan/FRESH-BLOOD-RPG-in-Python-3.7.2 | /FRESH BLOOD RPG.py | 20,015 | 3.671875 | 4 | # FRESH BLOOD
# Ana Paula Castro 31927017
# Beatriz Cesário Bertan 31955312
# Marcela de Oliveira Sousa 31958443
# Turma 1H - 2019
import time
import random
nome = str(input("Insira seu nome para começarmos:"))
print ("Tudo pronto! \n")
time.sleep(1)
print ("Iniciando o jogo... \n")
time.sleep(1)
print ("-----------... |
04d6a932b13df866c5f29fbfa6786eae5f08e22f | EKnapik/QR_Factorization | /factorizeTest.py | 2,116 | 3.765625 | 4 | """
Author: Eric Knapik
Advanced Linear Algebra
QR Factorization in Python
"""
from numpy.linalg import inv
import numpy as np
import math
import os
"""
QR factorization implemented from:
https://en.wikipedia.org/wiki/QR_decomposition
http://www.math.ucla.edu/~yanovsky/Teaching/Math151B/handouts/GramSchmidt.pdf
"""... |
ffc50169770d023e482521507523fd50717c29f1 | ricardoBpinheiro/PythonExercises | /Desafios/desafio047.py | 192 | 3.65625 | 4 | # mostra os numeros pares entre 1 e 50
print('-=' *20)
print('Os valores pares de 1 a 50 são:')
for i in range(1, 51):
if i % 2 == 0:
print('{} é par'.format(i))
print('-=' *20) |
d67d8f63ae329cf1dd31096aabe46fb71317c779 | mmcloughlin/problems | /elements/python/16/3/permutations.py | 660 | 4.25 | 4 | def _print_permutations_final_fixed(x, n):
"""
Print all permutations of the array x, keeping some of the final positions
fixed. The parameter n means how many of the initial positions of x may
be changed. For example if len(x)=5 and n=3 this means the last 2
positions of x must be left alone.
... |
2319f002edc1238155b359d1c9b124a8b3b2ed7a | Aarhus-Psychiatry-Research/timeseriesflattener | /src/timeseriesflattener/testing/synth_data_generator/utils.py | 932 | 3.6875 | 4 | """Utilites for generating synthetic data."""
from typing import Optional
import numpy as np
import pandas as pd
def replace_vals_with_na(
df: pd.DataFrame,
na_prob: float,
na_ignore_cols: Optional[list[str]] = None,
) -> pd.DataFrame:
"""Replace values with NAs.
Args:
df (pd.DataFrame)... |
7e684759b27cb78ee7f144ff6e685e53ace88414 | SongJeongHun/algorithm | /2020/a.py | 183 | 3.578125 | 4 | data = []
for _ in range(int(input())):
age,name = input().split()
data.append([age,name])
data = sorted(data,key = lambda x: x[0])
for i,j in data:
print(i,j,end = '\n')
|
861a0848dc7d04626e565be0aa1a60549cdd05c9 | santorin1/act3_Lunar-Marquez---Maulion-Mendenilla | /act3_marquez_lunar.py | 607 | 3.75 | 4 | price=0
print( "Online Computer Parts Store \n")
print ("****************** \n")
#Products
print ("1.Keyboard Price : 900 Pesos")
print ("2.Mouse Price : 400 Pesos")
print ("3.Monitor Price : 12000 Pesos")
print ("4.Camera Price : 500 Pesos")
print ("5.Headset Price : 1000 Pesos")
choice=int(input("Ent... |
402d764cabc0c9205a68183a154a1dc1da97d0b5 | hrishitelang/100-days-of-python | /Day 7/Final Project/Final.py | 1,069 | 4.0625 | 4 | import random
from hangman_art import *
from hangman_words import *
print(logo)
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
lives = 6
#Testing code
#print(f'Pssst, the solution is {chosen_word}.')
display = []
for _ in range(word_length):
display += "_"
while True:
g... |
058a187824448658e2654e44276265f243f3549a | fkurusu7/learning_python | /ds&a/7.minimum_size_array_sum.py | 1,033 | 3.875 | 4 | """
Given an array of n positive integers and a postive integer s, find the minimal length of a contiguous subarray
which the sum is greater or equal than s.
If there isn't one return 0.
s = 7, nums = [2, 3, 1, 2, 4, 3]
r = 2, the subarray [4, 3] has the minimal length under the problem constrain.
"""
# USE TWO POINTE... |
0d01b11385d09ae5948c4f9774703d7df051bfaf | ASENNIU/MachineLearning | /Cousera-ML-MyExercises/Logistic Regression/functions.py | 1,161 | 3.515625 | 4 | import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def cost(theta,X,y):
first = np.multiply(y,np.log(0.00001+sigmoid(X @ theta)))
second = np.multiply((1 - y), np.log(0.00001+1 - sigmoid(X @ theta)))
return -np.sum(first + second) / X.shape[0]
def gradient_descent(theta,X,y):
"""
... |
5696a5df76b30fda90d3528e8f0a3e7606011cda | claoidek/Project_Euler | /022_names_scores.py | 679 | 3.765625 | 4 | # Adds up the score of all names in the file external_files/022_names.txt
# First the list is sorted alphabetically
# Then an alphabetical value is determined for each name by summing the position
# of each of its letters in the alphabet
# This value is then multiplied by the name's its position in the alphabetical
# ... |
52c1de1561de59440ab4c8523bbf303d7470d5d6 | rayt579/leetcode | /premium/google/sorting_and_searching/diagonal_traverse.py | 1,358 | 3.640625 | 4 | class Solution:
def findDiagonalOrder(self, matrix: 'List[List[int]]') -> 'List[int]':
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
m, n = len(matrix), len(matrix[0])
i, j, d = 0, 0, 1
diagonal_order = []
while i != m - 1 or j != n - 1:
if i... |
b7f927a0439e3d6fc780e7fec066ac5c31c208af | AviSoori1x/Python_Intro | /ex25.py | 2,046 | 4.46875 | 4 | #This is a list of functions
#This function breaks words at the space. It takes in one argument
def break_words(stuff):
"""This function will break up words for us."""
#This splits a string into segments at the spaces
words = stuff.split(' ')
#Returns the string variables
return words
#This functio... |
ef1da597e8f068f31d9450f182a2a55c69e8116b | KavyaBPadmesh/hackerrank_python | /Data Structures/Linkedlist/Insert_nodein_specificposition_linkedlist.py | 1,062 | 3.984375 | 4 | """
Insert Node at a specific position in a linked list
head input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
""... |
346063676b83b21e93f995d5527bb73f1ed6d46b | DyogoBendo/URI-Python | /iniciante/2808.py | 870 | 4.03125 | 4 | if __name__ == "__main__":
# Posições do cavalo:
"""
- Um para cima:
- dois para direita
- dois para esquerda
- Um para baixo:
- dois para direita
- dois para esquerda
- Dois para cima:
- um para direita
- um para esquerda
- Dois para baixo:
... |
26d5b26fc415ddd2c8db5f908c3ff2973a318bba | Abirami33/NumPy-100 | /np_arange_linspace.py | 319 | 3.671875 | 4 | import numpy as np
#from 1 to 10 skip 2 and print
b3=np.arange(1, 10, 2)
print(b3)
#NOTE: Arange is Similar to linspace, but uses a step size (instead of the number of samples).
#prints 7 values between 1 and 10
b4=np.linspace(1, 10, 7)
print(b4)
#OUTPUT:
'''
[1 3 5 7 9]
[ 1. 2.5 4. 5.5 7. 8.5 10. ]
'''
|
fe7d162db3b220260cdc637e049041b6eab9f662 | Monkeysteingames/python-syntax | /words.py | 382 | 4.5 | 4 | words = ["hello", "hey", "goodbye", "yo", "yes"]
def print_upper_words(words, must_start_with={"h", "y"}):
"""prints all caps versions of words in list that begin
only with the letters we pass in with the must_start_with argument
"""
for word in words:
for char in must_start_with:
... |
e133e698512c1c12acc4e214536c4751bdbfae58 | kdockman96/CS0008-f2016 | /ch4-ex/ch4-ex7.py | 474 | 4.21875 | 4 | # Ask the user for the number of days
days = int(input('Enter the number of days: '))
# Print the table headings
print('Day\t\tSalary')
print('-------------')
# Initialize an accumulator variable
total = 0.01
# Print the days and the salary for each day
for days in range(1, days+1):
salary = 2**(days-1) * 0.01
... |
2e86d0ce23a28bcb8aa36006acf3384cf9ac20c9 | Patryk-Kumor/University | /Python/Zbiory innych zadań/Collatz.py | 781 | 3.734375 | 4 | from statistics import median
def F(n):
if n % 2 == 0:
return n / 2
else:
return 3 * n + 1
def energia(x):
i=0
while True:
#print(F(x))
x=F(x)
i+=1
if x==1:
#print('Koniec. Energia to:',i)
break
return i
def srednia(L):
suma = 0
for element... |
b8cfb5e7847955921a7827590945557a121f64d9 | sandeepdas31/python | /ola.py | 2,078 | 4.1875 | 4 | class micro:
def micro1(self,km):
self.km=km
print("Thanks for selecting micro cabs")
print("The max speed that a Micro cab go is 150 km per hour")
print("The fair for per kilometer is rupees 12")
self.km=12*self.km
print("The total fair is: ",self.km)
class... |
c95263d87ca2bd4c88209d82a82d0928f670a6d5 | raju0698/Python-codes---1 | /List_of_Positive_nums.py | 263 | 3.875 | 4 | input_string = input("Enter a list elements separated by space ")
print("\n")
userList = input_string.split()
print("user list is ", userList)
i = 0
for num in userList:
# checking condition
if num >= 0:
print(num, end=" ")
i += 1 |
5e6f9b290494bc1ccc7bc420f558a8e2e975169a | celestachay/chay-family | /c2/python/class_project/rubbish/time_test.py | 202 | 3.90625 | 4 | import time
def countdown(number):
number = int(number)
total_time = 60
for i in range(int(number)-1):
time.sleep(1)
print(number)
number -= 1
countdown(input('number: '))
|
172772b035807184f9d3adb64a26043dada49744 | joaohfgarcia/python | /uniesp_p1/lista02q01.py | 159 | 3.96875 | 4 | print ('Cálcular Par ou Ímpar')
n1 = int (input('Digite um numero: '))
if n1%2 == 0:
print ('O número é par')
else:
print ('O número é impar')
|
25785c99718e4f26dbb5b63a583b522d46697ebd | Agent1000/pythoner-ML2AI | /หาเลข มากสุด น้อยสุด.py | 682 | 4.25 | 4 | x=int(input("กรอกเลขครั้งที่ 1 > "))
y=int(input("กรอกเลขครั้งที่ 2 > "))
z=int(input("กรอกเลขครั้งที่ 3 > "))
if z>y and z>x :print(z,"มากที่สุด")
elif x>y and x>z:print(x,"มากที่สุด")
elif y>x and y>z :print(y,"มากที่สุด")
if z<y and z<x : print(z,"น้อยที่สุด") #if เช็คใหม่ หาเลขน้อยสุด
elif x<y and x<z:print(x,"... |
6640b0466c8371635ba348c1d4815a814ef8464e | TDalton52/CS-Projects | /Networking TCP-UDP-Client-Server/TCP_Server.py | 2,792 | 3.609375 | 4 | import socket
import sys
def is_number(string):
try:
int(string)
return True
except ValueError:
return False
def main():
print('server is up and running!')
localhost = '127.0.0.1'
server_port = 55555
server_socket = socket.socket(socket.AF_INET, socket.SOC... |
9d9e4e5d00809280c21baff6f3e6c008311f61e0 | nickmwangemi/CodeVillage | /Day5-Python/exercise1.py | 263 | 3.921875 | 4 | # further exercise using dictionaries
swahili = dict()
swahili['hello'] = 'Jambo'
swahili['blue'] = 'samawati'
print(swahili['hello'])
print("The swahili word for hello is {}".format(swahili['hello']))
print("{hello}, shati langu ni {blue}".format(**swahili))
|
62ba9dfcc73d0244fe8a64a3642359a6f94b114b | Carissaromero7/IS_Python | /ProblemSet1/factor.py | 732 | 4.28125 | 4 | # A range between 0 and 100. Remember that python is 0 indexed.
for x in range (0, 101):
# This loop determines whether each x is a multiple of 5 7 or 13.
# % finds the remainder after division of one number by another.
if x%5 ==0 and x%7 == 0 and x%13 == 0:
print(str(x) + " is a multiple of 5 and 7 and 13!") ... |
e4c3e795ee44a1c3b2695c5a89d662af55fb72c2 | acrual/repotron | /Funciones2/rectangulos.py | 521 | 4 | 4 | #pedir base y altura y dibujar rectángulo
base = int(input("Dame la base: "))
altura = int(input("Dame la altura: "))
while base <= 0 or altura <= 0:
base = int(input("Error. Dame la base: "))
altura = int(input("Dame la altura: "))
print("Rectángulo normal : ")
for i in range(1, altura + 1):
for j in ran... |
4b402063e6b6ea48feab7574522e82a696faa8c6 | cindylin75/pwd_login | /pwd_login.py | 320 | 4.0625 | 4 | password = 'a123456'
i = 3
while True:
i = i - 1
pwd = input('Please insert the password:')
if pwd == password:
print('Log in success!')
break
else:
print('The password is wrong.')
if i > 0:
print('You have', i ,'chance')
else:
print('You have no chance! Please email your protector')
break
|
df59123f4cd18bb0b8fd5494526abf0e31b7133e | Xenomorphims/Tkinter-gui | /tkinter/GetInputDialog.py | 1,440 | 3.84375 | 4 | """
Window of a dialog that returns a value
Author: Bryan Oakley (Stackoverflow)
"""
import tkinter as tk
class CustomDialog(tk.Toplevel):
def __init__(self, parent, prompt):
tk.Toplevel.__init__(self, parent)
self.var = tk.StringVar()
self.label = tk.Label(self, text=prompt)
sel... |
1123983962e54c3d6f0270414fa10c67e93213ec | Nitindrdarker/road-to-datascience | /concept/gradient_descent.py | 753 | 3.96875 | 4 | import numpy as np
def gradient_descent(x, y):
#start with some value of m_curr and b_curr
m_curr = b_curr = 0
iterations = 500 #number of baby steps
n = len(x)
learningrate = 0.01
for i in range(iterations):
y_predicted = m_curr * x + b_curr #as y = m*x + b
cost =(1/n) * sum((y... |
e4b3cc2627e9f57409bd5634eb805a6807f95efc | giraffe-tree/play-tf | /util_guide/play_numpy/try_numpy_array_range.py | 282 | 3.9375 | 4 | import numpy as np
x = np.arange(3,15).reshape(3,4)
# print(x,x.size)
# print(x[1][1])
# print(x[1,1])
# print(x[[0,1,1],[0,0,1]])
# 迭代行
for row in x :
print(row)
# 迭代列
for col in x.T:
print(col)
# 转成一行
print(x.flatten())
for item in x.flat:
print(item)
|
6e01bef1e7a7ae57a7d6531276dd68f27018d594 | wangbo-android/python | /Python编程从入门到实践/chapter9/chapter95.py | 537 | 3.578125 | 4 | class Car:
def __init__(self, name, info, price):
self.name = name
self.info = info
self.price = price
def get_description(self):
print(self.name + self.info + str(self.price))
def read_info(self, name):
self.name = name
print(self.name)
class ElectricMoto... |
75b54081025a400c110ce0eeeb95659873b19e7c | yaduvanshinitishkumar/Machine-Learning | /Machine_Learning/Part 2 - Regression/Section 5 - Multiple Linear Regression/multiple_linear_regression.py | 6,465 | 3.953125 | 4 | # Multiple Linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
# Encoding categorical data
from sklearn.preprocessing import La... |
e6916678349ac8b979e64eddcca094a87f5deffd | yashchitre03/Fetch-Rewards | /similarity/utils.py | 4,115 | 3.78125 | 4 | class ReadOnly:
"""
Marks the class attributes as read-only (i.e. client cannot update the values).
"""
def __set_name__(self, owner, name):
self.public_name = name
self.private_name = f'_{name}'
def __get__(self, instance, owner):
return getattr(instance, self.private_name... |
7e0751b7e742b0961a608cefc6f1ff2de86eb6a9 | Fr1tzler/leetcode | /06xx/617.py | 535 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def mergeTrees(self, t1, t2):
if t1 == None and t2 == None:
return None
e... |
c00d6dedb93d4707b965eee851660569b5f330d7 | StrayKoi/Hangman | /hangman.py | 11,183 | 4.0625 | 4 | # Play Hangman
import os
import random
import pickle
import sys
def start():
os.system('cls')
print('''
+---+
O |
/|\ |
/ \ |
===
H _ N G M _ N
''')
print('Would you like to play Hangman?\n')
def ask():
choice = ''
while choice.lower() != 'n':
choice... |
e836096f549797f2628044d3ba6cabf4b63c89ad | ho-kyle/python_portfolio | /106.py | 654 | 3.765625 | 4 | def removeOutlier(a, remove):
a.sort()
for i in range(remove):
a.pop()
for i in range(remove):
a.pop(0)
return a
def main():
list = []
value = ''
value = input('Please enter a value(blank line to quit): ')
while value != '':
value = eval(value)
... |
75d707ebd03a2a55993645ce87dac366ec7cc0d9 | 874656645/HelloWorld | /Python/Learning/函数装饰器.py | 180 | 3.578125 | 4 | def f1(x):
return x * 2
def new_fn(f):
def fn(x):
print('call', f.__name__ + '()')
return f(x)
return fn
print(f1(2))
# f1 = new_fn(f1)
# print(f1(2)) |
a4e087f30d38492b38863903ade352c2fe24abfe | henryoliver/cracking-coding-interview-solutions | /Linked Lists/intersection.py | 5,843 | 4.125 | 4 | def intersect(linkedListOne={}, linkedListTwo={}):
'''
Solution 1 - Tail check and parallel comparison
Complexity Analysis
O(n) time | O(1) space
Determine if the two linked lists intersects
dict: linkedListOne
dict: linkedListTwo
return: Intersected node
'''
# Gracefully hand... |
3cf74f1c44c449d68d8b6ffe620c770f7e754416 | WaiYan-1302/Git-Python | /Functions/ErrorExceptions.py | 1,622 | 4.03125 | 4 | #keyboardInterrupt
# break
# print("Oops! That was no valid number. Try again...")
# print(x)
# x = int(input("Please enter a number: "))
# except ValueError:
# try:
# while True:
# -------------------------------------------------------------------------
#OSError , ValueErro
# import sys
# # try:
# # ... |
220b14e949e638eea0e28c42c370835e7a7fa43f | alexandraback/datacollection | /solutions_2700486_1/Python/sgm/R1B-B.py | 837 | 3.640625 | 4 |
memo = {}
def C(n, r):
if n == 1 or r == 0 or r == n:
return 1
if (n, r) in memo:
return memo[(n, r)]
c = C(n - 1, r - 1) + C(n - 1, r)
memo[(n, r)] = c
return c
def calc(N, X, Y):
slide = X + Y
level = slide / 2
inner = level * (slide - 1)
if inner... |
ad91f6fcae98256d341a3dc2f9d038101dfb530c | bas-vonk/spamfilter | /volumes/python/code/datapreprocessing.py | 1,256 | 3.53125 | 4 | import re
import logging
def extract_email_features(email):
"""
Extract features from an email and return them in a dictionary. These
features can be extended, and are ultimately used to train ML models.
"""
features = {}
# Extract both the body and the metadata
# ASSUMPTION: metadata an... |
262cc601c181bbeb947c23080cc38107cdc772cd | hnytun/syntax-highlighter-and-diff | /my_diff.py | 3,516 | 3.546875 | 4 | import sys
def getListOfLines(filename):
"""function that takes a filename and returns the contents in lines of text in a list"""
return open(filename,"r").read().split("\n")
def getDiff(original,modified,output):
"""function that takes original file, modified file and an outputfile and
writes the dif... |
d7a044aba80475027308d64aebe5eec8ab7bd252 | DamnScallion/test | /FACE/Face_Recognition_PYQT5/test_get_face_descriptor.py | 880 | 3.546875 | 4 | # 测试
# 输出单张照片的128D特征face_descriptor
import cv2
import dlib
from skimage import io
# detector to find the faces
detector = dlib.get_frontal_face_detector()
# shape predictor to find the face landmarks
predictor = dlib.shape_predictor("shape_predictor_5_face_landmarks.dat")
# face recognition model, the object maps hum... |
9391c4256350a7465ac5382cd41866756a1fcd3a | shah014/assignment2 | /function/6.py | 228 | 3.953125 | 4 | a = int(input("Enter the start_of_range: "))
b = int(input("Enter the end_of_range: "))
n = int(input("Enter the number: "))
if n in range(a, b):
print(f"{n} is in range {a,b}")
else:
print(f"{n} is out of range {a,b}")
|
e9194f0824c6e7748c10873b72d77c9007d6c372 | thebest527/Python | /Ch05/5-5.py | 850 | 3.828125 | 4 | """
날짜 : 2020/06/24
이름 : 박수령
내용 : 내장함수 p231
"""
# abs() : 절대값
r1 = abs(-5)
r2 = abs(5)
print('r1 :', r1)
print('r2 :', r2)
# all() : 리스트에서 0이 포함됐는지 검사하는 함수
r3 = all([1, 2, 3, 4, 5])
r4 = all([1, 2, 3, 4, 0])
print('r3 :', r3)
print('r4 :', r4)
# any() : 리스트에 하나라도 True값이 있으면 전체 True, 모두 False이면 전체 False
r5... |
3d5a885ac53cf23dbdadc8c47cead9699344f486 | rutujadesai308/positivenumbers | /positiveint.py | 188 | 3.640625 | 4 | list1=[12,-7,5,64,-14]
for i in list1:
if (i<0):
continue
print(i)
print("----------------")
list2=[12,14,-95,3]
for j in list2:
if(j<0):
continue
print(j)
|
94f4d7d9c0ead4236a55f8d44ac7d241ab51f2d9 | RohitKochhar/advent-of-code | /2020/day1/part2.py | 1,607 | 3.703125 | 4 | # For test purposes
import time
start_time = time.time()
i_DesiredValue = 2020
def ArrayToHash(a_Sorted):
# Find how many 100 intervals we need based on our desired number, and add 1
i_Intervals = (i_DesiredValue // 100) + 1
print(i_Intervals)
a_Matrix = []
# Create a hash table with an index... |
8a02ad05d283e811e1f2e2fb258095c6a7318f04 | Nurzatnur/rabota2 | /sets_dict/problem22.py | 99 | 3.640625 | 4 | q = set()
for h in range(11):
g = int(input("vvedite chislo: "))
q.add(g)
print(tuple(q))
print() |
d5b33873f1f05a47698c462961fa12aa3d827034 | mshsarker/PPP | /The Basics/001.py | 255 | 4 | 4 | ## My solutions to the 150 Challenges by Nichola Lacey
## Get this wonderful book
# 001 Ask for the user’s first name and display the output message
# Hello [First Name]
First_Name = input("Hey Dude! What is your first Name? ")
print("Hello" , First_Name)
|
38e4f0ed3fb1f61e6c677b7a368dc58852d279b2 | AnshikaVerma-123/class-109 | /height-weight.py | 673 | 3.515625 | 4 | import pandas as pd
import statistics
import csv
df = pd.read_csv("height-weight.csv")
height_list = df["Height(Inches)"].to_list()
weight_list = df["Weight(Pounds)"].to_list()
#Mean for height and Weight
height_mean = statistics.mean(height_list)
weight_mean = statistics.mean(weight_list)
print (height_mean)
... |
95ea1f179b972ab824b52c7c3954f0abfec4a0f4 | jtomasevic/graphs_in_python | /graphs/node.py | 551 | 3.9375 | 4 | """ node in graph """
class Node(object):
""" node in graph """
adjacency_set = None
def __init__(self, vertex_id):
""" constructor """
self.vertex_id = vertex_id
self.adjacency_set = set()
def add_edge(self, vertex):
""" add edge """
if self.vertex_id == vertex... |
01ea4645d8eb90665b4742c22ea090b2e1f77ee7 | irvingperez11/python | /Python_T2/Projects/Pig Latin Translator.py | 403 | 3.875 | 4 | """def piglatin():
word = raw_input("Enter a word: ")
new = word[:1] + word[:0] + 'ay'
print word"""
"""z = str(raw_input("Enter a phrase or word: ")).split()
def pig(z):
x = z[1:] + z[0] + 'ay'
print x
pig(z)"""
def main():
words = str(input("Input Sentence:")).split()
for word in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.