blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
a6bfb8e19711bd8696cadc24ce2a0fa6eea41164 | ErmoGarcia/isa681project | /game/mus.py | 20,848 | 3.703125 | 4 | ##################################
# OBJECTS USED DURING A MUS GAME #
##################################
import secrets
from datetime import datetime
# A Spanish naipe (card)
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
if self.suit == 'o':
... |
6d936111702efce84d2317b776778db9541e07f8 | ayushikhandelwal99/summer19_python_code | /problem3.py | 203 | 3.96875 | 4 | #!/usr/bin/python3
adhoc=[1,2,3,1,4,5,66,22,2,6,0,9]
print("Numbers greater than 5")
y=[i for i in adhoc if i>5]
print(y)
print("Numbers less than or equal to 2")
x=[i for i in adhoc if i<=2]
print(x)
|
98017e757f569a6cfc147832ecc00798a9ac69c9 | jaime-araujo-ntt/CursoemVideo-YouTube | /ex039_Alistamento.py | 891 | 3.9375 | 4 | import datetime
hoje = datetime.datetime.now()
idade = input("Insira sua data de nascimento (dd/mm/aaaa): ")
idade = idade.split('/')
idade = [int(i) for i in idade]
dias_18 = 365*18
dias_nascido = ((hoje.year - idade[2])*365)+((hoje.month - idade[1])*30)+(hoje.day - idade[0])
anos_nascido = int(dias_nascido/365)
pri... |
81597435833fea947efa7243ded93f814d79899d | jaime-araujo-ntt/CursoemVideo-YouTube | /ex010.py | 155 | 3.703125 | 4 | n = float(input('Conversor de dolar!! \n>> Insira o valor desejado:'))
d = n / 3.27
print('Com R$ {:.2f} reais você tem U$ {:.2f} dólares'.format(n, d))
|
a25e5eeb27fd30c0bad43ef3c634cc8c00f27f22 | Qeswer/info_second | /exam/1-3.py | 2,101 | 3.546875 | 4 | def getWordsByString(string):
words = []; word = str(''); n = 0
for i in string:
if i != ' ' and i !=',' and i !='.' and i !='!' and i !='?' and i !=':' and i !='-' and i !='/':
word += i
if len(word) != 0 and i == ' ':
words.append(word); word = ''
elif i ... |
130bebc39dfead58b1cd48b635a0bb3ffaa21e8d | evgen55000/python | /HomeWork9.py | 2,103 | 4.03125 | 4 | # Задания 3
# Даны четыре действительных числа: x1, y1, x2, y2. Напишите функцию
# distance(x1, y1, x2, y2), вычисляющую расстояние между точкой (x1, y1) и (x2, y2).
# Считайте четыре действительных числа и выведите результат работы этой функции.
import math
def distance(x1, y1, x2, y2):
dist = math.sqrt((x2 - x1)... |
578d6677bb2af74218b11e650a9a2949e6eb93e4 | dressacl/Exercicios-WTTD- | /Andressa/Desafio-com-test/tabuada.py | 218 | 4.0625 | 4 | num = int(input("Digite o número para calcular:"))
for numero in range(1, 11):
result = numero * num
print(num, 'X', numero, '=', result)
assert num * 1 == num
assert numero * num == result
assert num > 0
|
0d7f0ca5690606e71f6d22284b956c6676f76b70 | wlllssd/leetcode | /40.combination-sum-ii.py | 1,523 | 3.515625 | 4 | #
# @lc app=leetcode id=40 lang=python3
#
# [40] Combination Sum II
#
# https://leetcode.com/problems/combination-sum-ii/description/
#
# algorithms
# Medium (40.04%)
# Total Accepted: 208.1K
# Total Submissions: 511.9K
# Testcase Example: '[10,1,2,7,6,1,5]\n8'
#
# Given a collection of candidate numbers (candidate... |
e097feee1915b54afe8d879241cb554827f1992d | lorimer1/aoc-2019 | /02.py | 672 | 3.625 | 4 | import aoc_download
from intcode_computer import IntCodeComputer
YEAR = 2019
DAY = 2
puzzle_input = aoc_download.aoc.puzzle_input_file(YEAR, DAY)
computer = IntCodeComputer(puzzle_input)
computer.memory[1] = 12
computer.memory[2] = 2
computer.run()
print("Part 1:", computer.memory[0])
def find_noun_verb(computer):
... |
f7e6225cdf68f34263c7b0d22d96b3dd5da27632 | royopa/python-2 | /ex5.py | 464 | 4.15625 | 4 | maior = None
menor = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
num=int(num)
except:
print('Invalid input')
else:
if menor is None:
menor= num
elif num < menor:
menor= num
if ma... |
b9351f573b382775a3b8c938c70b58024ed3c22d | royopa/python-2 | /ex2.py | 113 | 3.828125 | 4 | hrs=input('Enter the hour: ')
rate=input('Enter the rate: ')
pay=float(hrs)*float(rate)
print(f'Pay: {pay}')
|
aac6f3b90bbf4f8a1cc966d3fa07946f39faa0b4 | royopa/python-2 | /ex8.py | 271 | 3.921875 | 4 | fname = input("Enter file name: ")
fh = open(fname)
separado = list()
for line in fh:
nline= line.rstrip()
piece=nline.split()
for w in piece:
if w not in separado:
separado.append(w)
separado.sort()
print(separado)
|
09bfa039461965a5bd37c06b1272359a827a162c | emorycs130r/Second-Assignment | /medium_assign.py | 1,516 | 3.625 | 4 | '''
Implement the following functions based on the question. Retain the name of the functions, and parameters as is in the question.
=================
1. assign_grades(final_score) --> 30% (Returns Grade or False)
Get input for the final score, if the score is greater than 100, return False. If not, return appro... |
66111b8b79434a28b3b9ca7e6dc834630db57e6a | mybeang/workspace | /find_key.py | 513 | 3.609375 | 4 | data = {
"A": {
"a1": 1,
"a2": 2,
"a3": 3
},
"B": {
"b1": {
"b11": 4,
"b12": 5
},
"b2": {
"b21": 6,
"b22": 7
}
}
}
def find_item(obj, key):
if key in obj: return obj[key]
for k, v in obj.item... |
47d4074b203e2f96442d7d93f5bae8abe7c673f5 | cxx839113797/future | /0219/divide_3_5.py | 330 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# @Time : 2019/2/20 11:36
# @Author: xiaoxiao
# @File : divide_3_5.py
def divide():
num = int(input('请任意输入一个数:'))
if num%3==0 and num%5==0:
print('%d能同时被3和5整除'%num)
else:
print('%d不能同时被3和5整除' % num)
return divide()
divide()
|
3960750ee7a4588ddc5c7d1f04462fc4df604678 | cxx839113797/future | /class_0302/file_operate.py | 695 | 3.515625 | 4 | # -*- coding:utf-8 -*-
# @Time : 2019/3/3 14:31
# @Author: xiaoxiao
# @File : file_operate.py
import io
def file_operate(file):
file1 = open(file, "r")
f = file1.readlines()
c=[]
for i in f:
s=i.strip().split("@")
d = {}
for j in s:
l=j.split(":",1)
d[... |
ef8728c54bb2d3145a17bf838199e3e7a183cfe9 | Zahidsqldba07/ippp | /exercicios/provedor.py | 432 | 3.5 | 4 | gb = input('Informe a quantidade de GB consumida: ')
gb = int(gb)
tipo = input('Informe o tipo de plano (R-Residencial, E-Empresarial): ')
valor = 0
if tipo == 'R':
if gb <= 10:
valor = 8 * gb
else:
valor = (8 * 10) + (12 * (gb - 10))
elif tipo == 'E':
if gb <= 100:
valor ... |
c65d9519b2ba33b3d76520a625d512658a466005 | alex-ozerov/Python_starter | /006_Functions 2/task_3.py | 184 | 4 | 4 | def step(n):
if n == 1 or n == 0:
return 1
else:
return step(n - 1) + step(n - 2)
n = int(input("Введите номер ступеньки:"))
print(step(n)) |
8ac63fa967e8039741738dfc34c720ce02c2b662 | alex-ozerov/Python_starter | /005_Functions 1/task_2.py | 219 | 3.875 | 4 | def function(x):
if x < 0:
return x * 2
else:
return x * 3
def main():
for i in range(-10, 10):
i /= 2
y = function(i)
print('function(', i ,') =', y, sep=' ')
main()
|
b6c2178e51ff58a5b63110c9d0fbb555101056a7 | BoyerDamien/libasm | /test/utils.py | 244 | 3.515625 | 4 | import random
import string
def random_string(length):
string_len = random.randint(1, length)
string_params = [random.choice(string.ascii_lowercase + string.ascii_uppercase) for _ in range(string_len)]
return "".join(string_params) |
0a0777af3640d53aecd021c63eea1a04b363a1ad | pongola/Python2 | /Findnearbypoles.crl.python2.py | 21,695 | 3.75 | 4 | # -*- coding: utf-8 -*-
#
###################################################################
#
# This text-based Python script was an early iteration of what became the program "Evaluate Poles", in which the user can find prior poles on the Kaapvaal Craton that are near a user-specified pole location.
#
# First, the ... |
5d3bf3c856321aba510dd0bf9a90e03d152b7a43 | echcz/leetcode-test-using-python3 | /zigzag-conversion.py | 904 | 3.90625 | 4 | """
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串。
"""
from unittest import TestCase, main
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
cache = ["" for x in range(numRows)]
flag = True
i = 0
for c ... |
963457b801041f846f94fad6d5fd81d83476b9c8 | andres-condezo/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/12-fizzbuzz.py | 385 | 3.921875 | 4 | #!/usr/bin/python3
def fizzbuzz():
for num in range(1, 101):
if ((num % 3) == 0 and (num % 5) == 0):
print("{}".format("FizzBuzz "), end='')
elif ((num % 3) == 0):
print("{}".format("Fizz "), end='')
elif ((num % 5) == 0):
print("{}".format("Buzz "), end=... |
82a29209d6c58a741eeab167a8e6a79445e30ade | andres-condezo/holbertonschool-higher_level_programming | /0x06-python-classes/100-singly_linked_list.py | 1,856 | 4 | 4 | #!/usr/bin/python3
"""singly linked list module"""
class Node:
"""Node class"""
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
@property
def data(self):
"""get __data attribute"""
return self.__data
@data.setter
def data... |
d30b36c7b77cc90bd8f49f2c5ca2e21c1d8346d5 | Amenti90/IS211_Assignment6 | /conversions_refactored.py | 1,219 | 3.859375 | 4 | class ConversionNotPossible(Exception):
pass
def convert(fromUnit, toUnit, value):
if fromUnit==toUnit:
return value
if fromUnit=="Celsius" and toUnit=="Kelvin":
return value+273.15
if fromUnit=="Celsius" and toUnit=="Fahrenheit":
return ((value*(9.0/5.0))+32)
if fromUni... |
c2b9a2fa057e0364970e45af749ce2ca62a8697e | priyanka24798/Armstrong | /solution.py | 425 | 3.890625 | 4 | # Write a program determine whether the given number is Armstrong number or not.
# The program should return true or false
def checkArmstrong(n):
num = n
sum = 0
while(n > 0):
m = n % 10
sum = sum + m **3
n = n//10
if(sum == num):... |
0ee72e16b6298d3fb58679a08c03c035ab900cc1 | Rs-py/Arithmetic_Arranger | /arithmetic_arranger.py | 2,553 | 3.71875 | 4 | def arithmetic_arranger(problems,est = False):
#Create lists to append later
allproblems = []
results = []
firstnum = []
secondnum = []
op = []
length = []
spacer = " "
#Limit input to 5 problems
if len(problems) > 5:
return "Error: Too many problems."
for h in prob... |
9ad3a8d24dc0e674631f9d13939b0ea8be6e3c89 | oliviastats/sandbox_github | /python_coding_problems/valid_palindrome.py | 324 | 4.09375 | 4 | def check_if_valid_palindrome(string_input: str):
str_lower = string_input.lower()
str_lower_list = list(str_lower)
str_lower_list_reversed = str_lower_list[::-1]
str_lower_reversed = ''.join(str_lower_list_reversed)
if str_lower_reversed == str_lower:
return True
else:
return F... |
51b39c102b83393a8bc7feb10ff236cc8a272144 | mahzabin-hasnath/GWC2018 | /Unit1/Python/Hangman/hangman_v2.py | 1,368 | 4.0625 | 4 | '''
Sample solution of a hangman game between two players: one player chooses the word and the other player has to guess it
'''
print("Welcome to Hangman! \n")
while True:
word = input("Please enter a word for someone to guess: ")
word = word.lower()
# check if input is valid
if word.isalpha() == Fal... |
214e05faa14fb4878af21edce344955735c7b442 | luchiago/python-com-my-sql | /lista_1/qst_2.py | 186 | 4 | 4 | nota_1 = float(input("Digite a primeira nota: "))
nota_2 = float(input("Digite a segunda nota: "))
media = (nota_1 + nota_2)/2
if media >= 6:
print("Aprovado")
else:
print("Reprovado") |
aab04428f198da78c38bab6f3647da513b0742eb | JJtheNOOB/NLP | /Latent Semantic Analysis/tokenizing.py | 2,155 | 3.703125 | 4 | import nltk
from nltk.stem import WordNetLemmatizer
#Setting up lemmetizer, transform words to their original form
word_lemmetizer = WordNetLemmatizer()
#Read in all the titles and save them into a list called titles
titles = [line.rstrip() for line in open('C:/Users/lianj/Desktop/Udemy/NLP_machine_learning_... |
254bb334a6a3d31d71290d62aefdc569ea0d1007 | crichgriffin/code_snippets | /py/create_dirs.py | 413 | 3.953125 | 4 | # To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using:
import os
if not os.path.exists('my_folder'):
os.makedirs('my_folder')
# You can also use the python idiom EAFP: Easier to ask for forgiveness than permission. For example,
import os
try:
... |
d593608e9b995d374b5090196176bb2177fe6f84 | mnechip/Pyano-pyHook | /pyHook_Module.pyw | 191 | 3.546875 | 4 |
from pynput.keyboard import Key, Controller
import pyautogui
pyautogui.write('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character
|
d4c0dbee1de20b3fae2f2ae80f74d105463d4c07 | akhilkrishna57/misc | /python/cap.py | 1,727 | 4.21875 | 4 | # cap.py - Capitalize an English passage
# This example illustrates the simplest application of state machine.
# Scene: We want to make the first word capitalized of every sentence
# in a passage.
class State (object):
def setMappedChar(self, c):
self.c = c
def getMappedChar(self):
return self.c
def se... |
8277fe27d3880865067e36d3fd529d1f3438ae17 | Elena2631/labs_python | /m8_lab_2_2.py | 1,328 | 4 | 4 | def file_generation(name: str, mb: float, a: int, b: int, c: int, d: int):
from random import choice, randint
from string import ascii_letters
if a > b:
a, b = eval(input("Error, a must be less than b! Enter a and b: "))
print("K = (", a, ",", b, ")")
else:
print("K = (", a, ","... |
a88805621508fd3770aa12ccd93fbba8adb2cd14 | amirnk/studying_track | /studying.py | 5,676 | 3.609375 | 4 |
get_ipython().run_line_magic('pylab', 'inline')
from matplotlib import pyplot as plt
import datetime
import time
global t1
now = datetime.datetime.now()
time_now2 = str(now.year) + "/" + str(now.month) + "/" + str(now.day) + " " + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
print("Hel... |
f5dda96f6834a01df9271007ebc1f7a530ebb703 | Elias-SS/python | /pythonProject/media_turma.py | 233 | 3.9375 | 4 | soma = 0
quantidade = 1
while quantidade <= 8:
nota = float(input("Nota Aluno {}: ".format(quantidade)))
soma = soma + nota
quantidade = quantidade + 1
media = soma/8
print("A média da turma foi {}".format(round(media))) |
5e8aa341fdceb4aa1a105edd8e2969826d5190e0 | Padsher/PythonLittleConsoleGame | /consoleGame.py | 2,188 | 3.890625 | 4 | from game import Game
class ConsoleGame:
def __init__(self, game: Game):
self.game = game
def run(self):
print('New game started')
self.game.visualizeField()
currentPlayerNum = 0
maxPlayerNum = len(self.game.players) - 1
while True:
print('######... |
902b1a0f9e9e3ce533bddbd733e239f0d9c36bea | maq1995/JianZhi_offer_python | /Q9_相关题目_矩形覆盖.py | 970 | 3.59375 | 4 | # encoding: utf-8
"""
@project:JianZhi_offer
@author: Ma Qian
@language:Python 2.7.2
@time: 2019/8/20 下午3:21
@desc:
"""
'''
题目:我们可以用2行1列的小矩形横着或者竖着去覆盖更大的矩形。
请问用8个这样的2*1的小矩形无重叠地覆盖一个2行8列的大矩形,共有多少种方法?
解析:
我们先把2*8的覆盖方法记为f(8),用第一个2*1的小矩形覆盖大矩形的最左边时,我们有两种选择:横着放,或者竖着放。
当竖着放时,右边还剩2*7的区域,这种情形下的覆盖方法记为f(7), 当横着放时... |
8a409c468cd948083010dd5aec61645633cac730 | maq1995/JianZhi_offer_python | /Q9_斐波那契数列.py | 9,800 | 4 | 4 | # encoding: utf-8
"""
@project:JianZhi_offer
@author: Ma Qian
@language:Python 2.7.2
@time: 2019/8/20 上午10:49
@desc:
"""
'''
题目:写一个函数,输入n,求斐波那契数列的第n项。
斐波那契数列的定义如下:
| 0, n=0
f(n) = | 1, n=1
| f(n-1) + f(n-2), n>1
'''
# 我们最常见的解法如下:
def Fibonacci_dg(n):
if n <= 0:
... |
a88db226f6b581649ea8cdbfc01103884a8fad0f | maq1995/JianZhi_offer_python | /Q18_树的子结构.py | 1,644 | 3.59375 | 4 | # encoding: utf-8
"""
@project:JianZhi_offer
@author: Ma Qian
@language:Python 2.7.2
@time: 2019/8/22 下午3:17
@desc:
"""
'''
题目:输入两颗二叉树A和B,判断B是不是A的子结构
解析:
要查找树A中是否存在和树B结构一样的子树,饿哦们可以分为两步:第一步在树A中找到和B的根节点的值一样的结点R,第二步再判断
树A中以R为根节点你的子树是不是包含和树B一样的结构。
代码鲁棒性:
'''
class TreeNode:
def __init__(self, data):
... |
c4359e3d98455c4dbb8d5cab72457cc1bea86433 | JunlinWu/Baxter_Tic-Tac-Toe_Project | /BaxterTicTacToe/tictactoe_AI.py | 4,715 | 4.03125 | 4 |
#!/usr/bin/env python3
import math
from random import choice
import platform
import time
from os import system
"""
An implementation of Minimax AI Algorithm in Tic Tac Toe,
using Python.
This software is available under GPL license.
Author: Clederson Cruz
Year: 2017
License: GNU GENERAL PUBLIC LICENSE (... |
21ca29ba7a6e2a124a20291d11490a4eefabe4d3 | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex8.py | 1,364 | 4.53125 | 5 | formatter = "{} {} {} {} " # this is the equivalent of taking a data of type str and creating positions (and blueprints?) for different arguments that will later be passed in and storing it in a variable called
#formatter
print(formatter.format(1, 2, 3, 4)) #The first argument being passed in and printed is of dat... |
06efc287d6c51abc7851cbccbece718179a9e4a0 | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex16.py | 1,368 | 4.3125 | 4 | from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (>C).")
print("If you do want that, hit RETURN.") #print statement doesn't ask for input. Only to hit the return key, which is what you would normally hit after entering user input. (or qu... |
0ba974b7a198bea2c267cb0a1d87c719c6bef25e | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex15a.py | 1,171 | 4.65625 | 5 | filename = input("What's the name of the file you want to open?")
txt = open(filename) #the open command takes a parameter, in this case we passed in filename, and it can be set to our own variable. Here, our own variable stores an open text file. Note to self: (filename) and not {filename} because filename is alread... |
17b59990095fb7cbc931d1dcbfeb1e3fca5d0da5 | kretzschauer/notebooks | /meineNotebooks/maschinenlernen/PythonLibs/vectors.py | 4,204 | 4.4375 | 4 | # Copyright (c) 2017, Dr. Edmund Weitz
# simple vector library for educational purposes without any error
# checking or optimizations; not recommended for production use
# to create a new Vector object, call Vector with the components of
# the vector as arguments as in Vector(3, 4, 5)
# alternatively, use something ... |
8766d95aa13ba82a2c1dac1624cb7c95373b51b4 | Julialva/RememberScripts | /StatusCodes.py | 1,231 | 3.75 | 4 | import random
ReasonPhrase = ["OK","Created","No Content","Moved Permanently","Found","Not Modified","Bad Request",
"Unauthorized","Forbidden","Not Found","proxy authentication required","multiple resource use conflict",
"Unsupported media type","Too many requests - rate limit reached","... |
978b7f059d6d56e440b8d58b7ff51a87e895ba0f | DanCRichards/16QAM-Decoder | /mainWorks.py | 2,293 | 3.5625 | 4 | #====================================
# Made for #
# Computer Science 314 #
# Assignment 1 #
# #
# By Dan Richards #
# #
# Special Thanks: #
# C... |
fbe4eded058b07cef05561e1a9e2542f3f672f35 | Wizard-J/library | /library_worm.py | 4,215 | 3.609375 | 4 | # http测试:http://httpbin.org/
import requests
import json
session = requests.Session()
def get_class_list():
create_class_url = "http://localhost:8080/library/api/get/classificationlist"
class_list = session.get(create_class_url)
return class_list.json()
def create_class():
class_list = get_class... |
52fc8e48194b8c912624b41ee255664a1c359970 | saiphaniedara/HackerRank_Python_Practice | /Set_SymmetricDifference.py | 445 | 3.890625 | 4 | '''
Problem statement:
https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
from sys import stdin
a = int(stdin.readline())
A = set(map(int,stdin.readline().split()))
b = int(stdin.readline())
B = set(map(int,s... |
66b138cfa4abc3912cde69bf4c8d4b2af72e9849 | saiphaniedara/HackerRank_Python_Practice | /BasicDataTypes_Find_RunnerUp.py | 422 | 3.71875 | 4 | '''
Problem statement:
https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list
'''
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
arr = list(arr) #convert it to list
m = max(arr) #find top marks
while(m in arr):
#remove the top mark... |
b680c447ba93fd06633e7fe81e100d1327b0fe0c | saiphaniedara/HackerRank_Python_Practice | /DateTime_CalendarModule.py | 300 | 3.75 | 4 | '''
Problem Statement:
https://www.hackerrank.com/challenges/calendar-module
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
import calendar
from sys import stdin
m,d,y = map(int,stdin.readline().split())
print(calendar.day_name[calendar.weekday(y, m, d)].upper()) |
22b45e5ca4bca2ce49d2f1f97ef411ff4b07250e | saiphaniedara/HackerRank_Python_Practice | /BuiltIns_Zipped.py | 553 | 3.84375 | 4 | '''
Problem statement:
https://www.hackerrank.com/challenges/zipped
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
from sys import stdin
s,no_sub = map(int,stdin.readline().split())
subjects = list()
for i in range(no_sub):
subjects.append(list(map(float,stdin.readline().spli... |
0e8b9d2ccbd278f76372523370aae8eed804e571 | saiphaniedara/HackerRank_Python_Practice | /BuiltIns_Input.py | 282 | 3.53125 | 4 | '''
Problem statement:
https://www.hackerrank.com/challenges/input
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
from sys import stdin
x, k = map(int,stdin.readline().split())
expression = stdin.readline()
print(eval(expression) == k)
|
44781bff110a8dd1640e7e284eaa97051c6f8c28 | saiphaniedara/HackerRank_Python_Practice | /ItertoolsProduct.py | 403 | 3.90625 | 4 | '''
Problem statement:
https://www.hackerrank.com/challenges/itertools-product/problem
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import product
import sys
a = sys.stdin.readline().strip()
a = list(map(int,(a.split())))
b = sys.stdin.readline().strip()
b = l... |
e05e1017a145be447ce26436f232be852a8ab834 | saiphaniedara/HackerRank_Python_Practice | /Introduction_Write_a_function.py | 316 | 3.96875 | 4 | '''
Problem statement:
https://www.hackerrank.com/challenges/write-a-function/problem
'''
def is_leap(year):
leap = False
if(year%100 == 0):
if(year%400 == 0):
leap = True
elif(year%4 == 0):
leap = True
return leap
year = int(input())
print(is_leap(year)) |
cce07a2298bda8444f3d86bd336c8cb613e8e015 | Brian-Mascitello/Old | /Codeacademy/Taking a Vacation.py | 976 | 3.921875 | 4 | def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
else:
return "Data not available."
... |
219318ea934d401270c7bd59856e00bf6ca21a1d | roboforgeufu/DesafioLARC2018 | /teste.py | 604 | 3.734375 | 4 |
"""
Remove repeating letters.
"""
# pylint: disable=C0103
import re
class RepeatReplacer(object): # pylint: disable = R0903
"""
Class implementation
"""
def __init__(self):
self.repeat_regexp = re.compile(r'(\w*)(\w)\2(\w*)')
self.repl = r'\1\2\3'
def replace(self, word)... |
350270a530a218e464ffb346993323941e1b3f8d | Yash-barot25/DataStructresInPython | /Dictionaries/AdvantureGame.py | 1,318 | 3.84375 | 4 | Locations = {0: "You'r standing front of your computer learning python",
1: "You'r at your home 430 mcmurchy south ave",
2: "You'r at tuckshop of brampton towers",
3: "You'r in garden",
4: "You'r inside of shopper's drug-mart",
5: "You'r at 440 mcmur... |
af39202b24672f1f45155c6916ad00af7f6b65c9 | Requiem97/2018-Code-Sprint-Problems | /Problem_G_Almost_Prime.py | 815 | 3.734375 | 4 | from math import ceil
def is_prime(num):
n = ceil(num/2)
if num != 2 and num % 2 == 0: return False
for i in range(3, n):
if num % i == 0:
return False
return True
def get_factors(num):
factors = []
for i in range(2, num + 1):
if num % i == 0: factors.append(i)
... |
e5cc80e4c8114c5a0778806167daeeb57f41b68d | t97lee/DailyKata | /7_kyu/14 - Find the capitals.py | 336 | 3.84375 | 4 | '''
7 kyu
Write a function that takes a single string (word) as argument. The function must return an ordered list containing the indexes of all capital letters in the string.
Example
Test.assertSimilar( capitals('CodEWaRs'), [0,3,4,6] );
'''
def capitals(word):
return [cap for (cap,count) in enumerate(word) if c... |
c476b23aedcee7ef9f1ae6a484ce13f827184242 | ThatBlobEbola-chan/CompCamps2018 | /Python/gaem.py | 1,728 | 3.765625 | 4 | import random
import sys
name = input("Whomstve dost thou be of Kickstart? (Hint, your name is Tiger.): ")
health = 40
score = 0
class sodieboi:
"""Sodiebois - The Rogue Gods"""
def __init__(self, name):
self.name = name
@property
def damage(self):
return random.randint(1,5)
def ... |
5feea868a4bbfc7ba35782d57e69fa70586f3780 | arashout/OnlineEducation | /MIT6002/Unit 3/greedy_sum.py | 832 | 3.90625 | 4 | def greedySum(L, s):
""" input: s, positive integer, what the sum should add up to
L, list of unique positive integers sorted in descending order
Use the greedy approach where you find the largest multiplier for
the largest value in L then for the second largest, and so on to
... |
2009c99cfcc37246aacc63c6acf60c0a2019046f | arashout/OnlineEducation | /Nand2Tetris/projects/06/Nand2TetrisAssembler.py | 4,820 | 3.640625 | 4 | import os #
import re
def is_instruction(string):
"""Function formats string to be only instructions in assembly, otherwise returns false"""
comment = '//'
index_comment = string.find(comment)
#Return false if line is just comment
if index_comment == 0:
return False
#Return false if l... |
0ce38aa16b1f124e77c861e7f9dfe141dd584521 | rayidghani/database-utilities | /load_to_postgres.py | 951 | 3.78125 | 4 | """
Takes a path to csv or a url with a csv and loads it in to
postgres table. Assumes header row with column names.
Input: filepath or url, table name, db connection string
Output: table created in postgres database
Uses: usual things plus ohio
pip install ohio
"""
import pandas as pd
import requests
import ohi... |
0dacbf7918dff026016d5f5f272dd32661ed1261 | mate86/ToDoApp | /toDoApp.py | 4,315 | 4.125 | 4 | # ========== Functions ==========
# If the file does not exist, it creates a new file
def CreateFile():
file = open("to_do_list.txt", "a")
file.close()
# It counts the number of lines in the file and return with it
def CountFileLines():
file = open("to_do_list.txt", "r")
NumOfLines = len(file.read... |
d2f35c97b9d80435dbfbeb17032e72c28eb747cf | fsoest/netdyn | /p3.py | 4,983 | 3.75 | 4 | # Nagel-Schreckenberg-Modell
import numpy as np
import matplotlib.pyplot as plt
# %%
class Car:
"""Car class for implementation of iterations"""
def __init__(self, x_start):
self.x = []
self.x.append(x_start)
self.v = 0
self.distance_traveled = 0
def distance_to_other_car(se... |
5801328332c67f3402892bab049ad7bcc2fa4514 | Giselii/numero-maior-e-menor | /033_NumeroMaioreMenor.py | 1,218 | 4.125 | 4 | #Faça um programa que leia três números e mostre qual é o maior e qual é o menor
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número:'))
n3 = int(input('Digite outro número: '))
#print('O maior número é {}'.format(max(n1, n2, n3)))
#print('O menor número é {}'.format(min(n1, n2, n3)))
if (n1 < n2)... |
8c035e7b062f86d4c90b504d16f5f4fa29e5a3f1 | AliZet-to/Homework2 | /Task_3.py | 1,196 | 4.25 | 4 | # Data input
side_AB_len = float(input("Please input AB side length \n"))
side_BC_len = float(input("Please input BC side length \n"))
side_AC_len = float(input("Please input AC side length \n"))
# Verification for a triangle existence
if (side_AB_len + side_BC_len) > side_AC_len and (side_BC_len + side_AC_len) > side... |
51cc4743d3401af5b04c9e19b0d90be32ff3b608 | jasper0909/python | /range.py | 127 | 3.859375 | 4 | for i in range(1,6):
for i in range(1,12):
print("★"*i)
for a in range(10,0,-1):
print("★"*a)
|
d9d9b96ebb5380d242f5532e475bb0a3f7547a01 | Nixer/lesson01 | /dictionaries.py | 358 | 4.125 | 4 | my_dict = {"city": "Москва", "temperature": "20"}
print(my_dict["city"])
my_dict["temperature"] = str(int(my_dict["temperature"]) - 5)
for k, v in my_dict.items():
print(f"{k} : {v}")
if "country" in my_dict:
print(True)
else:
print(False)
print(my_dict.get("country", "Россия"))
my_dict["date"] = "27.05.... |
ebc936ef6319636609c9e121debf09da6bb91bc6 | simontudge/assortative_mating | /tests/test_pairs.py | 2,600 | 3.765625 | 4 | """
File for testing the pair class. Mostly it's functionality is quite trivial, so these
tests are quite simple.
"""
import unittest
import numpy as np
from assortative_mating import Pair, Individual
class test_pair(unittest.TestCase):
def setUp(self):
"""
Setup by creating some dummy individuals that can b... |
1c019d6be170ec64daed560c2753f5758f68fa3c | linhenry2004/Python-Projects | /Tryouts/functionAndClass.py | 620 | 4 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def sayHi(self):
print("Hello my name is %s" % self.name)
def sayAge(self):
print("I am %s years old" % self.age)
def sayBDay(self, bDay):
print("My birthday is %s" % bDay)
def sa... |
3b7681887d52c8f1985fc22576dc0672479e4e32 | CyborgVillager/Intro_Python_Oct_and_Forward_on | /Begin_anew/Variables/Variables_Expressions_Statement/Operator.py | 498 | 3.984375 | 4 |
# Can use + - * // & **
# 5 * 5
doublehe = 5 ** 2
# divide
divide0 = 25 // 2
print(doublehe)
print(" ")
print(divide0)
print("==================================")
# Expressions
input_x = int( input("Enter a number: "))
twenty_five = 25
exp0 = (input_x + twenty_five)
print_sum_total_exp0 = int(exp0)
print("You h... |
d7c81c09262124a47ffbe0497ce678494e712d4a | CyborgVillager/Intro_Python_Oct_and_Forward_on | /Begin_anew/Tuple/tuple0.py | 2,429 | 3.78125 | 4 | # External Import -> func_spacing
import func_spacing
space = " "
divider = "========"
# Internal Func
def tupspace():
print(func_spacing.space(space))
def tupdivider():
print(func_spacing.space(divider))
def combspacing():
tupdivider()
tupspace()
def minor_divide():
print("--------")
# Tu... |
923a129f314bbc2a32318f56f5a75f09522b89e2 | riabov-vladimir/ADPY13_interview | /task_2.py | 723 | 3.984375 | 4 | from task_1 import Stack
def is_balanced(text):
left = ['(', '[', '{']
right = [')', ']', '}']
stack = Stack()
for character in text:
if character in left:
stack.push(left.index(character))
# print(f'{character} added to stack')
# print('stack: ' + str(stack... |
62d2d625eb12b86f89dd4821305ba7b893770e05 | SoSorryTT/Compro2 | /lecture3/dry1.py | 386 | 3.796875 | 4 | # Make this code DRY
def num_digits(a):
a_digits = 0
while a > 0:
a = a // 10
a_digits = a_digits + 1
return a_digits
def same_length(a, b):
"""Return whether positive integers a and b have the same number of digits."""
return num_digits(a) == num_digits(b)
print(same_length(50, ... |
79bfaac8ea1d7c69aa8b15e130f323309697a71e | SoSorryTT/Compro2 | /Lab3/lab3.py | 4,051 | 4.1875 | 4 | from operator import add, mul, mod
# We can transform multiple-argument functions into a chain of single-argument, higher order functions by taking advantage of lambda expressions. Your solution to this problem should fit entirely on the return line.
def lambda_curry2(func):
"""
Returns a Curried version of a... |
63043be9d8b39e5caf053a06bd8129a27f0c4ffe | BSR-AMR-RIVM/blaOXA-48-plasmids-Microbial-Genomics | /scripts/printLine.py | 273 | 4.1875 | 4 | # quick code to print the lines that starts with >
import sys
FILE = sys.argv[1]
with open(FILE, 'r') as f:
count = 0
for line in f:
count =+ 1
if line.startswith(">"):
newLine = line.split(' ')
if len(newLine) < 3:
print(newLine)
print(count) |
e1ca310c14b0b065791ce8dbe47f5818292c610a | fdouw/aoc20 | /day20 | 7,809 | 3.625 | 4 | #!/usr/bin/python
# Floris Douw
# 2020
#
# AoC 2020 Day 20: Jurassic Jigsaw
import math
def tohash(array, reverse=False):
if reverse:
array = list(array)
array.reverse() # not nice for the caller
return int(''.join(map(str, array)), 2)
class Tile:
def __init__(self, data):
sel... |
4c61bec1d21679f772343c262dc90b60fe1707ee | bridgetree/checkio | /right_to_left.py | 123 | 3.53125 | 4 | # Join strings and replace "right" to "left"
def left_join(phrases):
return ",".join(phrases).replace("right", "left")
|
834aaf0e0daeb6a94bc737b947f605f8e5df8a4d | erikanni/physics-calc | /work-energy-power-calc.py | 1,595 | 4.09375 | 4 | import math
def solve(choice):
if choice == 1:
work = (input("enter work: "))
force = (input("enter force: "))
displacement = (input("enter displacement: "))
if work == "":
force = float(force)
displacement = float(displacement)
work = str(force ... |
dec162b66fd5edee1bc882439169d7df912ae421 | JamesNolan17/MNIST | /MNIST.py | 2,742 | 3.75 | 4 | # Part 1 - Building the CNN
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
import os
o... |
731ec34f049fe363309ebfb733fd270eb325b4bd | cabanmichal/aoc2017 | /day12/day12.py | 4,115 | 3.765625 | 4 | """
--- Day 12: Digital Plumber ---
Walking along the memory banks of the stream, you find a small village that is experiencing a little confusion:
some programs can't communicate with each other.
Programs in this village communicate using a fixed system of pipes. Messages are passed between programs using these
pipe... |
2cc57de4d474b4aa7756d41f167e6debeaf70cde | cabanmichal/aoc2017 | /day19/day19.py | 4,060 | 3.546875 | 4 | """
--- Day 19: A Series of Tubes ---
Somehow, a network packet got lost and ended up here. It's trying to follow a routing diagram (your puzzle input),
but it's confused about where to go.
Its starting point is just off the top of the diagram. Lines (drawn with |, -, and +) show the path it needs to take,
starting b... |
13bb620115e3db2985675553e070f89cd661219c | William-Chuu/CS50 | /Week 6 - Python/readability.py | 914 | 3.75 | 4 | from cs50 import get_string
def main():
sentence = get_sentence()
# all = 0 except word counter to account for last word that does not have space after it
word_counter, sent_counter, letter_counter = 1, 0, 0
# looping over every char in sentence
for char in sentence:
if char.isalpha() ==... |
b48bbe647eedb43c9e4adaa726842cfed8c38fd0 | Rythnyx/py_practice | /basics/reverseArray.py | 1,125 | 4.46875 | 4 | # The purpose of this excercise is to reverse a given list
exList = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g']
# The idea here is to simply return the list that we had but step through it backward before doing so.
# This however will create a new list, what if we want to return it without creating a new one?
... |
f2ec0eb1bab25988c27ab5af5e2529a7f7b90af9 | bayanijulian/effective-giggle | /agent.py | 7,782 | 3.609375 | 4 | import utils
import math
import numpy as np
class Agent:
def __init__(self, actions, two_sided = False):
self.two_sided = two_sided
self._actions = actions
self._train = True
self.paddle_height = 0.2
self._x_bins = utils.X_BINS
self._y_bins = utils.Y_BINS
se... |
787bb5e6c13463126b80c1144ae7a19274aab61b | ebonnecab/CS-2-Tweet-Generator | /regular-challenges/dictionary_words.py | 1,176 | 4.125 | 4 | #an algorithm that generates random sentences from words in a file
#TO DO: refactor code to use randint
import random
import sys
# number = sys.argv[:1]
number = input('Enter number of words: ') #takes user input
''' removes line breaks, and appends the words from the file to the list, takes five words from the list... |
f0a8bb4baa13523116082bda76dcb58dc774e65c | alisatsar/itstep | /Python/Lessons/class/subClass.py | 1,519 | 3.875 | 4 | class One():
def meth1 (self, a, b):
print("Line 1 - User 1")
a.meth2()
b.meth3()
class Two():
def meth2(self):
print("Line 2 - User 2")
class Tree():
def meth3(self):
print("Line 3 - User 3")
obj1 = One()
obj2 = Two()
obj3 = Tree()
obj1.meth1(obj2, obj3)
_______... |
4bc9518aa69b04463b7e1630bb8f79057582d86b | alisatsar/itstep | /Python/Lessons/notesString.py | 3,913 | 3.71875 | 4 | >>> S = ‘Spam’
>>> len(S) # Длина
4
>>> S[0] # Первый элемент в S, счет начинается с позиции 0
‘S’
>>> S[1] # Второй элемент слева
‘p’
>>> S[-1] # Последний элемент в конце S
‘m’
>>> S[-2] # Второй элемент с конца
‘a’
>>> S[-1] # Последний элемент в S
‘m’
>>> S[len(S)-1] # Отр... |
b7bd042233235ec6d6b753ae4588c96645f0759d | alisatsar/itstep | /Python/Lessons/class/reloadOperators.py | 1,053 | 4.21875 | 4 | class Newclass():
def __init__(self, base):
self.base = base
def __add__(self, a): #позволяет добавлять к объекту значение
self.base = self.base + a
def __mul__(self, b): #позволяет объетку быть умноженным
self.base = self.base * b
def __sub__ (self, c): ... |
b353a763c6b697507691d39221a9b289fb6a0dd3 | alisatsar/itstep | /Python/Lessons/class/boundAndUnbound.py | 434 | 3.921875 | 4 | __________________BOUND AND UNBOUND METHOD__________________
class Cat:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print("i am hungry")
self.hungry = False
else:
print("No, thanks!")
class Barsik(Cat):
def __init__(self... |
7fd6c03c4e267afd9c5d136e954254b7460fe3ef | alisatsar/itstep | /Python/Lessons/dictionary.py | 1,396 | 3.796875 | 4 | D = {‘food’: ‘Spam’, ‘quantity’: 4, ‘color’: ‘pink’}
D[‘food’] #Получить значение, связанное с ключом ‘food’
D[‘quantity’] += 1 #Прибавить 1 к значению ключа ‘quantity’
D = {}
D[‘name’] = ‘Bob’ #В результате присваивания создается ключ
D[‘job’] = ‘dev’
D[‘age’] = 40
print(D)
{‘age’: 40, ‘job’: ‘dev... |
b3dc81f673b84d01eadf1e4826b3369970c90540 | alisatsar/itstep | /Python/Tkinter/bind.py | 1,025 | 3.53125 | 4 | def output(event):
s = ent.get() #input значений
if s == "1":
tex.delete(1.0,END) #очистка экрана
tex.insert(END,"Обслуживание клиентов на втором этаже")
elif s == "2":
tex.delete(1.0,END)
tex.insert(END,"Пластиковые карты выдают в соседнем здании")
... |
595b329a176d2ecdb2c21801a80bc8f83e035133 | tharunpeddisetty/DecisionTreeRegression | /DecisionTree.py | 1,263 | 4.09375 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('/Users/tharunpeddisetty/Desktop/Machine Learning A-Z (Codes and Datasets)/Part 2 - Regression/Section 6 - Polynomial Regression/Python/Position_Salaries.csv')
X = dataset.iloc... |
151172bdb8289efb3e3494a7c96db79c0d07de4c | kushrami/PythonProgramms | /LoanCalculator.py | 439 | 4.125 | 4 | CostOfLoan = float(input("Please enter your cost of loan = "))
InterestRate = float(input("Please enter your loan interst rate = "))
NumberOfYears = float(input("Please enter Number of years you want a loan = "))
InterestRate = InterestRate / 100.0
MonthlyPayment = CostOfLoan * (InterestRate * (InterestRate + 1.0) * N... |
64ba4a1a3ed69d48c3e0ac5e53cc8d1422a70ac6 | kushrami/PythonProgramms | /createcsv.py | 448 | 3.703125 | 4 | #There is csv library. to do all the fun stuff import csv.
import csv
filename = "Test.csv"
accessmode = "w+"
file = open(filename, mode = accessmode)
file.write("kush,26\n")
file.write("shweta,31")
file.close()
with open (filename, mode = 'r') as mytestfile:
datafromfile = csv.reader(mytestfile)
for curre... |
3724da5589417935ec1f7bddc8c328ebecee9627 | ricardosilva1998/pythonBeginnerCourse | /cicloWhile.py | 101 | 3.796875 | 4 | numero=20
while True:
numero=numero-1
print(numero)
if(numero==2):
break
|
ad73f8f9a63a1ab696338e8b249884c2e1c78bbb | Dawyer/Code | /problems/LeetCode/LeetCode42. 接雨水.py | 2,126 | 3.5625 | 4 | # 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
#
#
#
# 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。
#
# 示例:
#
# 输入: [0,1,0,2,1,0,1,3,2,1,2,1]
# 输出: 6
# 方法一 暴力
# def trap(height) -> int:
# ans = 0
# for i in range(len(height)):
# max_left, max_right = 0, 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.