blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a8bb46279130d89fc0485b7fe7770d078a9a39f5 | mia2628/Python | /Basic/If.py | 978 | 3.5 | 4 | class Person:
def __init__(self, name, grad, score, port, vol):
self.name = name
self.grad = grad
self.score = score
self.port = port
self.vol = vol
def say_hello(self):
print("안녕하세요 저는 " + self.name + " 입니다.")
def check_graduate(self):
if self.score > "130":
if se... |
edbb00c443365e1f6a05d6e7ab9b39c21c26460e | duilee/workspace | /Algorithms/sorting/fraud_activiy.py | 1,423 | 3.53125 | 4 | """
# works, but takes too long
# Complete the activityNotifications function below.
def activityNotifications(expenditure, d):
count = 0
for i in range(0, len(expenditure)-d):
trails = expenditure[i:i+d]
trails.sort()
if d % 2 == 1:
median = trails[int((len(trails)-1)/2)]
... |
b52973f45f4a89b9b6615be3cfff283c40ce9fe6 | boredbird/Python_Exercise_Code | /runoob/isPrime.py | 265 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 23 14:13:12 2016
@author: zhangchunhui
"""
###IS Prime Number?
from math import sqrt
from sys import stdout
def isPrime(n):
for i in range(2,int(sqrt(n))):
if n % i ==0:
return 0
return 1 |
a58016003122b3280dfff37c2828946bac347a7d | jmurray305/Udemy_Beginner_to_Intermediate | /Exercise2.py | 475 | 4.0625 | 4 | '''1. Write a program in python which finds a letter in a string?
Example: String = "Example String", letter = "S" returns True.
2. Write a program in python to reverse a string using slicing method?
Example: String = "helloworld", Returns reversed string = "dlrowolleh" '''
def search(inputstring, letter):
... |
9341f9fc1d0a447c6a60bf52b608e2a5a74cccc9 | wh-acmer/minixalpha-acm | /LeetCode/Python/merge_intervals.py | 1,203 | 3.84375 | 4 | #!/usr/bin/env python
#coding: utf-8
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __repr__(self):
return repr((self.start, self.end))
class Solution:
# @param intervals, a list of Interval
# @return a list of Inter... |
1a251ff60dded59995dd898affa076d9330a4f73 | chenpengcode/Leetcode | /str/844_backspaceCompare.py | 1,358 | 3.65625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
def handle(s: str):
res = list()
for ch in s:
if ch != '#':
res.append(ch)
elif res:
res.pop()
return "".join(res)
return h... |
4c8c6fe3e3ff9b5b347ec118ffbebe9542e64896 | BurnFaithful/KW | /Programming_Practice/Python/Base/Bigdata_day1029/FACTORIAL.py | 299 | 3.984375 | 4 | # factorial
def fac(n):
if n == 1:
return 1
else:
return n * fac(n - 1)
def fac_for(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
if __name__ == "__main__":
print(f"fac(5) : {fac(5)}")
print(f"fac_for(5) : {fac_for(5)}") |
aa87e86775e1bfdfe64bafbcdc0ad0c83b1b29dd | daniel-reich/ubiquitous-fiesta | /nC7iHBbN8FEPy2EJ2_6.py | 218 | 3.671875 | 4 |
from math import pi
class Circle:
def __init__(self, radius=0):
self.radius = radius
def getArea(self):
return pi * self.radius**2
def getPerimeter(self):
return 2 * pi * self.radius
|
af931f55c1bca1905a079438344c78abc5630a6a | ivankmk/18_price_format | /format_price.py | 591 | 3.5 | 4 | import sys
def format_price(price):
try:
price = round(float(price), 2)
except (ValueError, TypeError):
return None
if price.is_integer():
return '{0:,}'.format(round(float(price))).replace(',', ' ')
else:
return '{0:,}'.format(float(price)).replace(',', ' ')
if __nam... |
f5a2d9db0384d4976b91c355b297fb9daaca1f5e | robbieford/PHYS400 | /chapter5.py | 1,381 | 3.671875 | 4 | #5.2
def is_triangle(x,y,z):
if x > y + z or y > x + z or z > x + y:
return 'No'
return 'Yes'
def is_triangle_dialogue():
prompt1 = 'Please enter the length of the first stick:'
prompt2 = 'Please enter the length of the second stick:'
prompt3 = 'Please enter the length of the third stick:'
len1 = int(raw_inpu... |
eeb29fe72a8155d6d7596e60ffb7251ef1ccf951 | amantaya/Image-Processing-Python | /image-processing/08-edge-detection/LaplacianEdge.py | 1,117 | 4.125 | 4 | '''
* Python script to demonstrate Laplacian edge detection.
*
* usage: python LaplacianEdge.py <filename> <kernel-size> <threshold>
'''
import cv2
import numpy as np
import sys
# read command-line arguments
filename = sys.argv[1]
k = int(sys.argv[2])
t = int(sys.argv[3])
# load and display original image
img = cv... |
d7e052d1a3317b73002a6a640980d77b3ba9f97c | Austin-Bell/PCC-Exercises | /Chapter_8/car.py | 371 | 4.03125 | 4 | """Write a function that sroes information about a car in a dictionary."""
def make_car(manufacturer,model, **add_info):
car_profile = {}
car_profile['manufacturer'] = manufacturer
car_profile['model'] = model
for key, value in add_info.items():
car_profile[key] = value
return car_profile
car = make_car('Hond... |
eef1620b834c2c8098f94e76a59c700ac04f8d1b | jms7446/hackerrank | /leetcode/pai/chapter7/q09_p03_3sum.py | 3,183 | 3.515625 | 4 | from typing import List
from itertools import combinations
from collections import Counter
class SolutionNaive:
"""
1956ms, 18.9MB (14%, 5%)
"""
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = set()
nums.sort()
counter = Counter(nums)
for a, b in combin... |
8776efbda802d8af88bda7818ed742edae835b2d | JianghaoPi/LeetCode | /501-600/592.py | 3,501 | 3.59375 | 4 | """
思路:
本题也属于比较基础,没有什么骚操作,干就完事了.
我用了两种方法,最开始面向对象,构造了分数类,实现了add方法和toString方法,然后用栈逆序存储表达式,不停计算化简,
但是很遗憾,这种方法只能打败30%的python对手,看来建新建对象开销还是太大了,但是我还是比较喜欢这种完备的方法
后来就很简单,直接上手处理,思路一样,估计还是越简单越光荣吧,这种没有任何亮点的方法打败了100%的对手
总结起来说,刷题这种东西和实际工程应用还是有很大不一样
"""
class Solution(object):
def fractionAddition1(self, expression):
""... |
ebf677c433a29be7f7dc78605a2480618c75e246 | timmyshen/LearnPython | /euler-mike/1.py | 137 | 3.90625 | 4 | #!/usr/bin/env python3
# MZ
# 233168
sum = 0
for x in range(1, 1000):
if x % 3 == 0 or x % 5 == 0:
sum = sum + x
print(sum)
|
435bdefb61b3bbb7afe53ecae423892b2e70c2fe | ardenzhan/hawaiianbbq | /hacker-rank/tutorials/cracking-coding/queue.py | 950 | 4.09375 | 4 | class Queue:
class Node:
def __init__(self, data = None):
self.data = data
self.next = None
def __init__(self):
self.head = None # remove from head
self.tail = None # add to tail
def isEmpty(self):
return self.head is None
def peek(self):
if self.head is None: return None... |
3df3b11353daf9a8e36fc17da8cbe5437ab3e002 | ErikGartner/love-letter | /loveletter/agents/agent.py | 4,200 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Abstract Agent for a Love Letter AI
"""
import random
from loveletter.card import Card
from loveletter.player import PlayerAction, PlayerActionTools
class Agent():
"""Abstract Class for agent to play Love Letter."""
def move(self, game):
"""Return a Player Action based o... |
c5001da9f5f226a7111b8cd72b8a060d5b7494d6 | aayush2601/Assignment | /1.py | 145 | 3.5625 | 4 | text = list()
filename = 'text.txt'
with open (filename) as fin:
for line in fin:
text.append(line.strip())
print(text)
|
476085626a03d21c736328088bd40b00582ae757 | DunwoodyME/meng2110 | /08_strings/strings_class.py | 442 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
strings_class.py
In-class string exercises
Daniel Thomas
September 29, 2017
"""
def erase_letter(word, letter):
''' Prints word without the given letter '''
edited_word = ''
for w in word:
if w == letter:
edited_word += ' '
else:
... |
e39af30d8d6d99122890ad7e70246c67d36ad43e | elenabarreto/Funciones | /a_imprimanaturales.py | 203 | 3.859375 | 4 | def numnatural(k):
i=1
print "Numeros naturales de 1 hasta ",k
while i<=k:
print "Numero Natural",i
i=i+1
#k=input("Ingrese el valor hasta el cual desea ver los numeros naturales: ")
#numnatural(k) |
1813347a036ebfbfeb0e71d004bd1e3f2aec7cc7 | sskodje/CodeClassifier | /CodeClassifier/training-set/python/spellcheck.python | 388 | 3.515625 | 4 | #!/usr/bin/python
# $Id: spellcheck.python,v 1.2 2005-02-19 17:05:39 bfulgham Exp $
# http://shootout.alioth.debian.org/
#
# From Tupteq, based on original code by Fred Bremmer
import sys
def main():
dict = set(line[:-1] for line in file("Usr.Dict.Words") if line != '\n')
for line in sys.stdin:
word ... |
0010a9ad4ebd557cf5b53f659788e0330bf8c391 | erossiter/PythonCourse2016 | /Day3/Labs/ordinalLab.py | 486 | 3.5 | 4 | def ordinalFunc(x):
if not isinstance(x, int):
return "Input must be integer"
x_string = str(x)
last_digit = x_string[-1]
last_2_digits = x_string[-2:]
last_digit = int(last_digit)
last_2_digits = int(last_2_digits)
if last_2_digits in range(11,16):
return "%sth" % x
else:
if last_digit == 1:
ret... |
5a6b6fe4867bf0d8e11bb0d62ebcc62ca8634213 | orlyrevalo/Personal.Project.1 | /Project1.20.py | 350 | 4.25 | 4 | def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
base_num = int(input("What is the base number? "))
pow_num = int(input("What is its power? "))
print(str(base_num) + " raised to " + str(pow_num) + " is " + str(raise_to... |
ade9b4ebd573160ff95b6ae0750079bf4cf863e0 | alexlimofficial/machine-learning | /linear-classification/perceptron-ideal-function.py | 1,676 | 4.0625 | 4 | """
Starts by creating a target function and own data set. Evaluates
target function on each data input to classify output as +1 or -1.
Author: Alex Lim
"""
# Import packages
import numpy as np
import matplotlib.pyplot as plt
# Create own target function f
m = 0.5 # slope
b = 1 ... |
3f6e2504d0c05930ecbbe85a5d12b69a4d1c3b1f | Panda3D-public-projects-archive/pandacamp | /Handouts 2012/src/3-2 Driving/02-drivingwithfriction.py | 1,751 | 3.859375 | 4 | # 01-racecar.py
#
# In virtual worlds there are different ways to recreate movement seen in the real world.
# In this file we try to recreate the movement of a car using
# Read the code along with the comments and try to understand how the behavior of a real car is being recreated.
#
# Run the file and drive the car ar... |
fa639733768f818dda890f7df195e7b842e397dd | innovatorved/BasicPython | /list/enumetrate() -.py | 331 | 3.96875 | 4 | #enumerate() -
#Returns an enumerate object with elements and the index values provided by the user
friends_name = ['Sudhanshu' , 'Suraj' , 'Abhishek Yadav' , 'Ajay Sharma' , 'Anchal' , 'Amit']
enumerate_fri = enumerate(friends_name)
print(type(enumerate_fri))
print(enumerate_fri)
print(list(enumerate_fri))
print(typ... |
eb091aa00c1eec63eee443635f8ecc4970e82ab3 | mindful-ai/15032021PYLVC | /day_02/livedemo/swapelements.py | 503 | 4.34375 | 4 | def swap(col, x, y):
if(type(col) is list):
temp = col[x]
#print("temp : ", temp)
col[x] = col[y]
#print("col[x]: ", col[x])
col[y] = temp
#print("col[y]: ", col[y])
#print ("swap : ",col)
return col
else:
return -1
L = [... |
639a87f3726c4b593406c1a154480bfc12b2560c | youngminju-phd/BigDataEconometrics_Projects | /Python/1_Computational_Complexity.py | 2,901 | 3.71875 | 4 | import numpy as np
from timeit import default_timer as timer
from sklearn.linear_model import LinearRegression
# A.1. Inner product of two vectors:
def inner_prod(v1, v2):
'inner production of two vectors.'
result = 0
for i in range(len(v1)):
result += v1[i] * v2[i]
return result
# defining v... |
e037de83b28d8c9acc4f077cb1e9aa303a8bae64 | smitasasindran/END | /Session8/python_programs.py | 8,867 | 4 | 4 | # write a Python program to check if year is a leap year or not
year = 2000
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format... |
10864ca24ad14776ce2cb895eeb32f767f86f45e | Ramaiml/Ram_Projects | /objects/election.py | 1,973 | 3.578125 | 4 | import random
from constants import MESSAGES
from objects.message import Message
class Election:
"""Defines an election in a universe.
:param universe: Universe in which the election is happening
:param candidates: Candidates competing in the election
:type universe: Universe
:type candidates: li... |
a00c6a1e788ceb22dc3078809ff46f9b61d27e9b | rosswelltiongco/King_Pong | /signal_test.py | 832 | 4.03125 | 4 |
#!/usr/bin/env python from time import sleep
# Allows us to call the sleep function to slow down our loop
import RPi.GPIO as GPIO
import time
# Allows us to call our GPIO pins and names it just
GPIO.setmode(GPIO.BOARD)
# Set's GPIO pins to BCM GPIO numbering
INPUT_PIN = 36
# Sets our input pin, in this example I'm c... |
4138ea7f8e652c40909185138be8c524662a92e9 | Nagendracse1/Competitive-Programming | /graph/Ratndeep/alien dictionary.py | 1,166 | 3.515625 | 4 | from collections import defaultdict
'''
dict : array of strings denoting the words in alien langauge
N : Size of the dictionary
K : Number of characters
'''
string = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
final_string=""
def topsortutil(stack,graph,cur_... |
e2a30608e7ab127b063a4de72591ce2163cbb921 | rerapony/software-design-2021 | /cli/src/shell.py | 1,472 | 3.5 | 4 | import sys
class Shell:
"""Class Shell, which implements logic of using
Parser and CommandFactory for processing bash command"""
def __init__(self, factory, parser, input_flow=sys.stdin, output_flow=sys.stdout):
self.factory = factory
self.parser = parser
self.input_flow = input_f... |
47eeb84e583db7b930bda649baf2c202f0efbcdc | JNewberry/Selection | /development 1.py | 1,015 | 4.125 | 4 | #John Newberry
#06/10/2014
#selection development 1
monthnumber = int(input("Please enter a month number: "))
if monthnumber == 1:
print("The month you entered is January.")
if monthnumber == 2:
print("The month you entered is Febuary.")
if monthnumber == 3:
print("The month you entered is March.")... |
0a7b7f4aa54f833a75d1428db65ae463bc9a0faf | DmitryMedovschikov/Python_for_beginners.PNIPU | /Python для начинающих 6/Задание 2/Python для начинающих 6 (Задание 2).py | 4,355 | 3.84375 | 4 | # Python для начинающих 6
# Задание №2
# Реализовать поиск по полям, типа: рост больше 120, имя Наташа
from pprint import pprint #подключение модуля
class Person: #создание к... |
102495892c64fa35a74b58e68749c14a236b5d81 | Supermac30/CTF-Stuff | /Mystery Twister/Autokey_Cipher/Autokey Cracking.py | 440 | 4.15625 | 4 | """
This script decodes the ciphertext when knowing part of the plaintext with the AutoKey Cipher
"""
ciphertext = input("input ciphertext ")
part = input("input part of plaintext ")
for i in range(len(ciphertext) - len(part)):
word = ""
for j in range(len(part)):
word += chr((ord(cipher... |
8e5c9f9a55afffb2e9addaa6570682dcfef0f138 | ziyuan-shen/leetcode_algorithm_python_solution | /hard/ex295.py | 648 | 3.546875 | 4 | import bisect
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
def addNum(self, num: int) -> None:
idx = bisect.bisect(self.data, num)
self.data.insert(idx, num)
def findMedian(self) -> float:
lengt... |
5c2d16823c088ed99a264199217df74cca5582c6 | xuyingnan90/pythonpractice | /day10/zidian.py | 1,993 | 3.53125 | 4 | '''
字典(类似js中的对象)
info={
"k1":"v1",
"k2":"v2"
}
value可以是任意值
列表不可以作为key 但元组可以
字典不可以做KEY
布尔值可以作为KEY,但key里不能有1或0
python3.6中 字典有序 之前版本字典无序
***比较常用的方法:keys() values() items() get() update()
'''
info = {
"k1": 18,
2: True,
1: 333,
True: 12,
"k3": [
11, [], (), 22, 33, {
"kk1": ... |
d598a8899f692db28fb84a46f023394dd01b78bc | RAMNATH007/Python-learning-process | /python concepts/file handling/unzipping.py | 219 | 3.828125 | 4 | from zipfile import *
f=ZipFile("files.zip","r",ZIP_STORED)
names=f.nameslist()
for name in names:
print(name)
print("The content of this file is:")
f1=open(name,'r')
print(f1.read())
print() |
2f1ac720cdc51ed70d299a71c70b46c75201e81f | DmitryVlaznev/leetcode | /79-word-search.py | 3,258 | 3.921875 | 4 | # 79. Word Search
# Given a 2D board and a word, find if the word exists in the grid.
# The word can be constructed from letters of sequentially adjacent
# cell, where "adjacent" cells are those horizontally or vertically
# neighboring. The same letter cell may not be used more than once.
# Example:
# board =
# [
#... |
a84877397189ec4fb196ba56841ef7ac7cfe9870 | GGjin/algorithm_python | /easy/83.删除排序链表中的重复元素.py | 889 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding::utf-8 -*-
# Author :GG
# 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
#
# 示例 1:
#
# 输入: 1->1->2
# 输出: 1->2
#
#
# 示例 2:
#
# 输入: 1->1->2->3->3
# 输出: 1->2->3
# Related Topics 链表
# 👍 368 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked l... |
566f1dc6fced38848219f804a2a08e6a3010a379 | 27Saidou/cours_python | /EleveHamdallaye.py | 468 | 4.0625 | 4 | def main():
#recolter la premier note
note1=int(input("Entrer la premier note de l'eleve"))
#recolter la deuxieme note
note2=int(input("Entrer la deuxieme note de l'eleve'"))
#recolter la troisieme note de l'eleve'
note3=int(input("Entrer la troisieme note de l'eleve"))
#calculer la moyenne ... |
fd540d9e25941f8a02a22b422597b9a5a5f8f28f | anushkrishnav/deepFibreTracking | /src/dataset/exceptions.py | 1,991 | 3.578125 | 4 | class WrongDatasetTypePassedError(Exception):
"""Error thrown if `ConcatenatedDataset` retrieves wrong datasets.
This means that the datasets you passed aren't exclusively IterableDatasets
Attributes
----------
caller: ConcatenatedDataset
The ConcatenatedDataset raising the error.
data... |
629c57381910185dd9a8a872e2c991cbdcd5b30a | K-K-P/Ferie-Challenge | /Dzień 7_Password generator.py | 1,239 | 4.15625 | 4 | """#PASSWORD #GENERATOR
Napisz program do generowania losowych haseł o zadanej przez użytkownika długości. Hasło musi spełniać zadane warunki
np. co najmniej jedna liczba, co najmniej po jednej dużej i małej literze. Warto skorzystać z modułów string i secrets.
Propozycja rozszerzenia: Po wygenerowaniu hasła skopiu... |
d583ab56ad8bedb702223f55f75c48873df737b6 | EdersonLuiz/Lista_Estudo_Dirigido01 | /Exercicio5.py | 277 | 3.78125 | 4 | vmercadoria = float (input("Digite o valor da mercadoria: "))
pdesconto = float (input("Digite o percentual de desconto: "))
print("Você ganhou R$", (vmercadoria * pdesconto / 100),"de desconto.")
print ("Valor a pagar: R$", vmercadoria - (vmercadoria * pdesconto / 100)) |
048f5c1bb140e7d93c5f1fca2f2ba3432b6ea04c | AdrianVides56/holbertonschool-higher_level_programming | /0x06-python-classes/2-square.py | 464 | 4.09375 | 4 | #!/usr/bin/python3
"""Creting a class"""
class Square:
"""Class that defines a square"""
def __init__(self, size=0):
self.__size = size
"""Initializing size as private attribute"""
if type(size) is not int:
raise TypeError("size must be an integer")
"""Check if si... |
7dca02a8ab7bca3bf7719611f21b866fd24fa93e | omarun/BaselineRemoval | /build/lib/BaselineRemoval.py | 4,579 | 3.625 | 4 | import numpy as np
from sklearn.linear_model import LinearRegression
import warnings
warnings.filterwarnings('ignore')
class BaselineRemoval():
'''input_array: A pandas dataframe column provided in input as dataframe['input_df_column']. It can also be a Python list object
degree: Polynomial degree
''' ... |
b5ff6ff3107fec9ae728ac5a09ccfb13a1f695ba | bbster/PythonBigdata | /workspace/16-inherit/exam2.py | 826 | 4 | 4 | class CalcParent1:
def __init__(self):
self.aa = 5
self.bb = 7
def plus(self, x, y):
return x+y
def minus(self, x, y):
return x-y
class CalcParent2:
def __init__(self):
self.aa2 = 50
self.bb2 = 70
def plus2(self, x, y):
re... |
2c398e46ce605f8b5a9b29ba9ec9c5b2f43952fa | jaumecolomhernandez/adventofcode2019 | /day1/day1_1.py | 129 | 3.640625 | 4 | #!/usr/bin/env python3
input_file = open("input", "r")
fuel = 0
for line in input_file:
fuel += int(line)//3-2
print(fuel) |
48885a9e15cc4fc0450bd29bf2939e9fe97c15b2 | morrisjh/TweetProcessor | /TweetProcessor.py | 838 | 4.15625 | 4 | ##A simple python program which can be used to process twitter data prior to analysis. It will return the text of all the tweets and write them to a new file.
filename = 'tweet.txt'
try:
with open(filename) as file_object:
text = file_object.read() #Opens and reads the file "tweet.txt".
except FileNotFoun... |
4f9692a44bdca3489c7d5a7d169e0bb79aae8cce | Glomyer/estcmp060 | /atividade 002: Aquecimento Python/triangulo.py | 561 | 4.0625 | 4 | import turtle
def desenharTriangulo(x, y):
tortuga.pencolor("red")
tortuga.penup()
# para fazer o desenho no ponto (x, y) clicado pelo mouse
tortuga.goto(x, y)
tortuga.pendown()
for i in range(3):
tortuga.backward(100)
tortuga.right(120)
tortuga.backward(100)
wn = tu... |
7c2fa7fef2e7ba96f52081c7969f7660650cbc67 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4254/codes/1637_2703.py | 100 | 3.6875 | 4 | idade = int(input("Digite a idade: "))
if(idade>=18):
print("eleitor")
else:
print("nao_eleitor") |
e983adab169ddb3b94f415c244b63b59f79ca072 | duvallj/alpha-zero-general | /othello/tourney_files/Othello_Core.py | 3,191 | 4.09375 | 4 | """
Base class for Othello Core
Must be subclassed by student Othello solutions
"""
#
EMPTY, BLACK, WHITE, OUTER = '.', '@', 'o', '?'
PIECES = (EMPTY, BLACK, WHITE, OUTER)
PLAYERS = {BLACK: 'Black', WHITE: 'White'}
# To refer to neighbor squares we can add a direction to a square.
UP, DOWN, LEFT, RIGHT = -10, 10, -1... |
15f07634fe51d6de4c61518be542934711343139 | HoweChen/PythonNote-CYH | /Python Algorithm/selection_sort.py | 645 | 3.953125 | 4 | import create_random_number_list
random_number_list = create_random_number_list.main()
def selection_sort(random_number_list):
min_number = random_number_list[0]
result = []
while len(random_number_list) != 0:
min_number_index = 0
for i in range(len(random_number_list)):
if ra... |
bf0cb2d065e7c5ccf46598bb2dd835472dcba650 | Max-p-otential/picoCTF2019 | /Compare.py | 2,240 | 3.53125 | 4 | import sys
class Compare:
def __init__(self,file1,file2,mode):
try:
self.listA=list(open(file1,mode).read())
except FileNotFoundError:
print ("File A doesn't exist! Maybe it is spelled wrong?")
exit()
except:
print ("Something went wrong! Mayb... |
1175ddb5c680338b6c4d0cf7cf0146f890cdcc9c | jukim20/Python_Practice | /Day24/algo04.py | 572 | 3.5625 | 4 | # 팩토리얼(factorial) 구하기(1) : 1 ~ n까지의 곱을 구하기
def fact(n):
num = 1
for i in range(1, n+1):
num *= i
return num
print(fact(10))
# 팩토리얼 구하기(2) : 재귀호출 이용
def fact2(n):
if n <= 1: # 종료조건
return 1
return n * fact2(n-1) #더작은 입력값
print(fact2(10))
# n * (n-1) * (n-1-1) * (n-1-1-1) * ....... |
bcb8a524a3a17c6bfceefdb252ad55e607c735a2 | Ouyang-maxzx/robust-stochastic-portfolio-optimization | /code/method/Markowitz.py | 1,004 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 2 12:00:23 2019
@author: wangtianyu6162
"""
import numpy as np
def Markowitz(train_return_mean,train_return_covar,test_return):
sigma_inv = np.linalg.inv(train_return_covar)
relative_weight = sigma_inv.dot(train_return_mean)
abs_weight = np.arra... |
04c4718ed562869bef1ea34876260e117c8c7653 | theassyrian/Competitive_Programming | /AdHoc/ValueOfPi.py | 643 | 4 | 4 | '''
DCP #14
This problem was asked by Google.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x2 + y2 = r2.
Approach: Monte Carlo Algorithm
'''
import random
def approximate_pi(iterations=10000):
total=0
inside=0
for i in... |
cf066f50c081d17a3197890d0ea6635f0d7d0f4a | mohamedgamal500/python | /Basics/largest_numberin_list.py | 526 | 4.125 | 4 | #numbers = [1, 2, 3, 45, 67, 88, 99, 77, 67, 890]
input_string = input("Enter a list element separated by space ")
numbers = input_string.split()
print(numbers)
def find_max(numbers):
#ref = 0 #
ref = int(numbers[0])
for num in numbers:
x = int(num)
print(x)
print('type(x)')
... |
2ac474069c7ecda0dbc93b106333d0c601d7d187 | cikent/Python-Projects | /LPTHW/ex26-TakeATest-ErrorChecking.py | 3,980 | 4.40625 | 4 | # import Argv module from System's Library
from sys import argv
# unpack Argv into its separate parameters
script, filename = argv
# open the File object and create a instance for manipulation
txt = open(filename)
# Ask the User for their Age and save the input returned
print("How old are you?", end=' ')
age = input... |
e7a9d187ec31fcbf04e0681df242be3e645b8f71 | fuadsuleyman/hackerrank-py | /integerNumbersTask9.py | 659 | 3.71875 | 4 | # Dördrəqəmli tam ədəd verilib.
# Bu ədədin yazılışında ardıcıl gələn 3 və 7 rəqəmlərinin olub-olmadığını müəyyənləşdirin.
num = input("Enter 4 digits number: ")
arrNumsStr = []
# create string digits array
for digit in num:
if digit != '-':
arrNumsStr.append(digit)
print(arrNumsStr)
temp = []
threeNumI... |
f58b2e2144868e7a148c5b9c58544aad06538380 | samgd/procsim | /procsim/feedable.py | 457 | 4.09375 | 4 | import abc
class Feedable(abc.ABC):
"""A Feedable instance can be fed."""
@abc.abstractmethod
def feed(self, food):
"""Feed food to the Feedable.
Args:
food: Food to be fed.
"""
pass
@abc.abstractmethod
def full(self):
"""Return True if the Feed... |
d5cfbae3d2f021633326bd675c512a16b9bd77f7 | baumeise/amselpy | /amselpy/skills.py | 2,133 | 3.640625 | 4 | import time
import random
class Skills():
def __init__(self, speed):
self.speed = speed
# Define movement functions.for
def forward(self, speed=0):
if not speed: speed = self.speed
endpoint = "/forward?speed=%s" % speed
response = self.get(endpoint)
return response.status_code
def backwa... |
77963a9c1cc39ac64a0232dfa5b555236d7d2921 | huangyt39/algorithm | /94.py | 974 | 3.71875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxPathSum(self, root):
# write your code here
if not ... |
ef551428f7a799a040e07e4b049b28c36434fd5c | ASV1870asv1977/client_server_applications | /lesson_1/lesson1_task2.py | 758 | 3.5625 | 4 | """
Задача № 2. Каждое из слов «class», «function», «method» записать в байтовом типе без преобразования
в последовательность кодов (не используя методы encode и decode) и определить тип, содержимое и длину соответствующих
переменных.
"""
# -------------------------------------------------------------------------------... |
cfad1aa0cc76f65d28a1dff3c6cf2b22aa116475 | mpettersson/PythonReview | /questions/list_and_recursion/knapsack_bounded_fractional.py | 5,338 | 4.1875 | 4 | """
THE BOUNDED FRACTIONAL (OR CONTINUOUS) KNAPSACK PROBLEM
Given a set of items that each have a value, a weight, and a number of units, determine the set of fractional items
to select as to maximize the total value, constrained by the given knapsack's capacity.
Example:
items = (("ma... |
12abf8a4986d575b2846bcec1bd4b3c5ceb7bb30 | ChenYenDu/LeetCode_Challenge | /Problems/01_Easy/0009_Palindrome_Number.py | 745 | 3.75 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
if (x < 0 or (x % 10 == 0 and x != 0)):
return False
revertedNumber = 0
while x > revertedNumber:
# add remainder of x divided 10 to revertedNumber*10
revertedNumber = revertedNumber * 10 + (x % 10)
... |
b3f385ebc1e96ee6f89d31f3cf2c81c730928e67 | PabloViana12580/corto_derivate_cost | /funciones.py | 512 | 3.515625 | 4 | def gradient_descent(x, y, theta_0,alpha,cost_derivate,treshold=0.001,max_iters=10000):
theta, last_cost, i = theta_0
while i < max_iters and abs(cost(x,y,theta) - last_cost) > treshold:
last_cost = cost(x,y,theta)
theta -= alpha * cost_derivate(x,y,theta)
i++
def linear_cost(theta,X,y):
m, n = X.shape
h = n... |
176af85eda6189de18067e8df4cf63c52a7abaf4 | Bbulatovv/week-1 | /разность времен.py | 282 | 3.609375 | 4 | hour1 = int(input())
min1 = int(input())
sec1 = int(input())
hour2 = int(input())
min2 = int(input())
sec2 = int(input())
hourTotal = (hour2 - hour1) * 3600
minTotal = (min2 - min1) * 60
secTotal = (sec2 - sec1)
solution = hourTotal + minTotal + secTotal
print(solution)
|
fadfdb74b8e4e1dcd9bc0585530934dfb3034a36 | Ahead180-103/ubuntu | /python/shell.py/if_01.py | 358 | 3.796875 | 4 | #!/usr/bin/python3
'''
任意输入一个数
1、判断这个数是否大于100
2、判断这个数是否小于0
3、判断这个数是否在20~50之间
'''
s=input("请输入任意一个数: ")
n=int(s)
if n<0:
print("这个数小于0")
elif n>100:
print("这个数大于100")
elif 20<n<50:
print("这个数在20~50之间")
else:
print ("其他")
|
6894b1d125cabc83fab39e7ff91b918652d31535 | Jeongm1n/DKU_Class | /오픈소스활용SW/Problem_Final/Problem7.py | 846 | 4.09375 | 4 | """
Problem #7
"""
class Letter:
def __init__(self, letterfrom, letterto):
self.letterfrom = letterfrom
self.letterto = letterto
self.text = ""
def addLine(self, line):
self.text += line + "\n"
def get_text(self):
print("----------------------------... |
89a47e76752af2b8069f5b4ee38c39dd48b9cd78 | estela-ramirez/PythonCourses | /Lab 3 Q 3.py | 989 | 4.09375 | 4 | '''
ICS 31 Lab 3 Question 3
Driver: UCI_ID:18108714 Name:Estela Ramirez Ramirez
Navigator: UCI_ID:69329009 Name:Karina Regalo
'''
def main():
i = get_info()
continue_or_not(i)
def get_info():
string_list = []
letter = input("What letter do you want to count the number of occurences of: ")
string = i... |
b01c399ca898f23b7be7a1dde4abb1a31301644e | iamhectorotero/iamhectorotero.github.io | /snippets/python-mro/diamond_example.py | 517 | 3.53125 | 4 | class Car:
def driven_for(self):
print("Driven for personal purposes.")
class PrivateCar(Car):
pass
class Taxi(Car):
def driven_for(self, color):
print(f"Driven for business purposes. They are normally {color}.")
class RentalCar(PrivateCar, Taxi):
def rental_car_driven_for(self):
... |
f34e9d077c4398de989f63df4a4fbc70dd3ca673 | TannerReese/xmath | /graph.py | 9,039 | 3.78125 | 4 | class Graph:
"""
Class to represent a graph as a collection of vertices and edges
Generics:
I -- type to index and identify different vertices
V -- value stored in each vertex
Attributes:
vertices (dict of (I, V)) -- identifies the value of each vertex using the vertex id
inedg... |
922d874a4183b037d39233916d0afce972ac97ad | doyoonkim3312/PythonPractice | /Exercise/Hex Spiral/hex_spiral.py | 761 | 4.0625 | 4 | ################################################################################
# Author: Doyoon Kim (kim3312@purdue.edu / doyoon3312@kakao.com
# Date: Mar 13, 2021
# Description This program draws hexagonal spiral with length increment of 6
# pixels
####################################################################... |
1b67cc7f90ff8fbd8155f07529eccef5534d9083 | drbailey/GroupShare | /Learning-Python/ex11.py | 497 | 3.828125 | 4 | print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
# Additional practice
print "Who is your favorite author?",
author = raw_input()
print "What is you... |
8d4dd752f37cc90ff22c31fb32be7edc24d4a631 | umunusb1/PythonMaterial | /python3/17_Data_science_modules/04_nltk/nltk_module/d_nltk_ex.py | 544 | 3.890625 | 4 | #!/usr/bin/python
"""
Purpose: NLTK
Stemming vs Lemmatization
- While stemming can create words that do not actually
exist, Python lemmatization will only ever result in
words that do. lemmas are actual words.
"""
import nltk
from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatizer
ps = P... |
9c33ca8b0583759203c8698a22b98749916ef100 | krisleeann/IntroPython | /authorship.py | 1,040 | 3.828125 | 4 | import sys
def read_and_format():
# Usage logic was buggy, commented it out for testing purposes
# if len(sys.argv != 2):
# sys.exit("USAGE: python3 authorship.py your_file.txt")
with open(sys.argv[1], "r") as file:
line = file.readline()
while line != "":
word_li... |
390882bf7c689cecefb560f483cd7d7285ee7ae6 | 5h3rr1ll/LearnPythonTheHardWay | /ex42.py | 1,828 | 4.34375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Dog is a ClassInstanz of Animals. Dog Instanz has a name.
class Dog(Animal):
def __init__(self, name):
## A varibale which contains the name
sel... |
7f95d9b93182a8f0bf38f95a4fd325b4e1bcb839 | benquick123/code-profiling | /code/batch-2/vse-naloge-brez-testov/DN13-M-153.py | 1,881 | 3.734375 | 4 | # Napiši razred Minobot. Ta sicer ne bo imel več nobene zveze z minami, imel pa bo zvezo z nalogo Minobot, ki smo jo reševali pred časom.
# Minobot se v začetku nahaja na koordinatah (0, 0) in je obrnjen na desno.
# Koordinatni sistem je takšen kot pri matematiki: koordinata y narašča navzgor.
# Razred Minobot ima n... |
807ff7a07405b608abced2b534b4e7fee0f69928 | lanboys/HelloPython | /语法基础/04.元组、函数-上/09-带有参数的函数.py | 261 | 3.9375 | 4 | # 定义了一个函数
def sum_2_nums(a, b):
# a = 10
# b = 20
result = a + b
print("%d+%d=%d" % (a, b, result))
num1 = int(input("请输入第1个数字:"))
num2 = int(input("请输入第2个数字:"))
# 调用函数
sum_2_nums(num1, num2)
|
a46eda240cf658b6adbd71538e025996960db7e2 | eduardogomezvidela/Summer-Intro | /10 Lists/Excersises/21.py | 179 | 3.734375 | 4 | #even number adder
list = [2,5,65,43,46,70,6,9,10,11,32,6] # 2+46+70+6+10+32+6 == 172
adder = 0
for num in list:
if num % 2 == 0:
adder = adder + num
print(adder)
|
1a67ba0aa0da9c2123bab9ea5ab3b99606ecc4ef | ShumaoHou/MyOJ | /mi_oj/7.py | 811 | 3.609375 | 4 | '''
第一个缺失正数
给出一个无序的数列,找出其中缺失的第一个正数,要求复杂度为 O(n)
如:[1,2,0],第一个缺失为3。 如:[3,4,-1,1],第一个缺失为2。
输入
1,2,0
输出
3
输入样例
1,2,0
3,4,-1,1
-1,-3,-5
1,2,3
-1,-10,0
输出样例
3
2
1
4
1
'''
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
def solution(line):
numList = list(map(int, line.strip().split(",")))
numList.sort()
... |
f5a7158f6d3314911c5b5e113005b4b51a2022b1 | hanrick2000/Leetcode-for-Fun | /leetcode/290_Word_Pattern.py | 1,779 | 3.5 | 4 | # @Author: Xingxing Huang
# @Data: 2017/03/24
# two map method
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
str_map = {}
pat_map = {}
str_array = str.split()
if len(str_arra... |
62b52aac4c7344d9acc3a5eda95ba175bed13e04 | mixelburg/Sockets-PinkFloyd | /clientFunctions.py | 3,747 | 4.3125 | 4 | INPUT_ERROR = "[!] Invalid input"
NUMBER_ERROR = "[!] Only numbers allowed"
def get_input(local_switch):
"""
Gets input from user and checks it
:return:
"""
data = INPUT_ERROR
while data == INPUT_ERROR:
try:
choice = int(input("Enter your choice: "))
except ValueEr... |
c2fa3a724ae4e64f24355ec542a81fc67fc6b8c5 | a313071162/letcode | /letcode_17_电话号码的字母组合.py | 2,497 | 3.75 | 4 | #!/usr/bin/env python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@File:letcode_17_电话号码的字母组合.py
@Data:2019/7/22
@param:
@return:
"""
# 递归调用
class Solution:
def __init__(self):
self.res = []
self.number = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': ... |
43f699305fd4e8b9de57a3c518e04f7b72857184 | huseynakifoglu/Hangman | /Topics/Split and join/Find words/main.py | 77 | 3.578125 | 4 | text = input()
print("_".join([x for x in text.split() if x.endswith('s')]))
|
6f5a4513f5ebb14690e006b23082e77b612f50c0 | filipi86/Studies-Python-Bases | /World_2/Exercises/ex048.py | 284 | 3.609375 | 4 | soma = 0
cont = 0
cont_impar = 0
for c in range(1, 501, 2):
if c % 3 == 0:
cont = cont + 1
soma = soma + c
cont_impar +=1
print('Existem {} valores solicitados IMPARES, porem existe apenas {} diviziveis por 3 que somados sao {}'.format(cont_impar, cont, soma)) |
31a87086458ba41e73cac8e617d15f7dc1fb456a | sanyaJolly/Python | /Projects/bankMgmtSystem.py | 4,039 | 3.765625 | 4 |
from os import system, name
import getpass
import json
f = open("data.txt",'r')
x = json.load(f)
f.close()
b=open("database.txt",'r')
money=json.load(b)
b.close()
def check(a):
if(len(a)<8):
return False
special = '[@_!#$%^&*()<>?/\|}{~:]'
numbers='0123456789'
boo = False
booll=False
... |
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__ == "__... |
e4f729e6de70edbd3c96d0fc48269c736a67fa62 | thematthaslem/minesweeper | /players.py | 8,382 | 3.546875 | 4 | import pygame as pg
class player(object):
def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, board) : # board is actually the board object (for hitting Tiles)
self.size_ratio = 0.75
self.h = 30.0
self.w = self.h * self.size_ratio
self.posx = 0
self.posy = 50
... |
84d9658f67f76477400fa7c76a11b73b515037f5 | jackbourkemckenna/PythonProject | /LICENSE.md/run.py | 1,685 | 3.59375 | 4 |
...
import csv
user = [] #my users array
dates = [] #my dates aaray
height =[] #my heigh array
width = [] #my width array
usrDates =[] #my array for users id and date sign up
setHeight = "960"
setWidth = "640"
countsWH = 0 #counter for width and heigh
totalspent = 0 #total spent
try:
with open('sa... |
28ae6f58c4479be6c721b86886cad0aab6fb3f6b | ZongLin1105/PythonTest | /test2.py | 228 | 3.59375 | 4 | a = eval(input("請輸入一正整數a:"))
b = eval(input("請輸入一正整數b:"))
c = eval(input("請輸入一正整數c:"))
d = eval(input("請輸入一正整數d:"))
print("a= %d,b= %d,c= %d, a+b= %d" % (a,b,c,a+b))
|
775e0fdde3f243cd7a1d446d12ab065a3dfd6694 | IanniMuliterno/salary-simulation-API | /salary_simulation_API/models/addapters/adaptador_imposto_interface.py | 482 | 3.59375 | 4 | from abc import ABC, abstractmethod
class Adaptador_Imposto_Interface(ABC):
"""
Baseada no Design Pattern "Adapter", essa interface padroniza comunicão entre os "Coletores de Dados" e
os "Calculadores de Imposto" com o objetivo de minimizar mudanças decorrentes de diferentes fontes de obtenções.
"""
... |
46e98005af8ff1d8696b7632134a965fb1215952 | Damian772/Project1-NumberGuessingGame | /Number Guessing Game - Damian Hernandez.py | 530 | 4.03125 | 4 | from random import randint
print("There is a random number between 1 and 100")
x=1
digit=randint(1,100)
a=int(input("Guess the random number: "))
while digit != a:
if a < digit:
print (a,"was too low! Try again.")
a=int(input("Guess the random number: "))
x=x+1
elif a > dig... |
b006223dbfcccccb917de69bce27b23d6551369b | prathi22/Assignment-3 | /matrix_mul.py | 1,002 | 4.125 | 4 | #Finding cost of matrix multiplication and parenthesization of matrices using dynamic programming
def mat_mul(p):
n=len(p)-1
m=[[None]*n for _ in range(n)]
s=[[None]*n for _ in range(n)]
for i in range(n):
m[i][i]=0
for l in range(1,n):
for i in range(n-l):
j=i+l
... |
0d9b4cdd88c30222fa72dc43f06bcfed63929169 | mrmalaitai/2020_students | /Level 3/Gio/waka_gio/Final.py | 3,909 | 3.90625 | 4 | # Created by: Giovaani
import tkinter as tk
from os import walk
# Displays the clubs for the Waka competition
def display_clubs(clubs):
display = tk.Toplevel(root)
display.title("All Club Points")
display.iconbitmap("WakaAma.ico")
#Turn dict into list
results = [[k,v] for k, v in clubs.items(... |
e86cdac2d1fd7b9fee7e76a6e7b8178068493b00 | nicolaepetridean/codility_solutions | /zinc2018.py | 988 | 3.734375 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
if len(A) < 3:
return 0
day_1_index = 0
day_2_index = 1
day_3_index = 2
possibilities = set... |
fe98a1879a07bab1172df118d3495691c3a5311b | peanut996/Leetcode | /Python/DataStructure.py | 514 | 3.703125 | 4 | # Definition for singly-linked list.
class ListNode:
"""Definition for singly-linked list.
"""
def __init__(self, x):
self.val = x
self.next = None
# Definition for binarytree.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None... |
c8af9918202ab76a3192f5f814bb81439d401258 | luismbacha/hackerrank-training | /python/07 Collections/03 Collections.namedtuple().py | 280 | 3.703125 | 4 | # https://www.hackerrank.com/challenges/py-collections-namedtuple/problem
from collections import namedtuple
n = int(input())
Student = namedtuple('Student', input().strip().split())
print("{0:.2f}".format(sum([int(Student(*input().strip().split()).MARKS) for _ in range(n)])/n)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.