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 |
|---|---|---|---|---|---|---|
ececf84cecb60878a30edeca512123ce6c5aa5d1 | s16003/PythonTutorial | /janken/play.py | 2,021 | 3.875 | 4 | HANDS = ('グー', 'チョキ', 'パー')
def select_hand():
"""
コンピュータの手をランダムに決める
:return: HANDSの中のいずれか。
"""
import random
return random.choice(HANDS)
def judgement(player, computer):
"""
じゃんけんの勝敗を判定する。
:param player: HANDSの中のどれか
:param computer: HANDSの中のどれか
:return: プレイヤーが勝ちの場合は1,あいこ... |
92dc8e04eff81c4473800ea900bd8ade076cca4e | akshat12000/Python-Run-And-Learn-Series | /Codes/205) regex.py | 5,086 | 4.4375 | 4 | # A regular exepression is a special text string for describing a search pattern
import re
String='Akshat is 20 and Lekhansh is 16'
# 1) findall() --> to find all the patters of similar types in the given string
names=re.findall(r"[A-Z][a-z]*",String) # for alphabets ( here [A-Z][a-z]* means selecting pattern which ... |
5761ee14b524939698d5a1751d6212148dcc509d | anubhab-code/HackerRank | /Python/Introduction/Python If-Else.py | 147 | 3.625 | 4 | N = int(input().strip())
n= N
w = 'Weird'
nw = 'Not Weird'
if ((n % 2 == 1) or (n % 2 == 0 and (n>=6 and n<=20))):
print(w)
else:
print(nw) |
fc55c50207ef42b6b45f28bf6e426be88317baca | Eok99/python_workout | /20201127/8-1.py | 939 | 3.515625 | 4 | #표준 입출력
print("파이썬" , "자바", sep="vs")
#sep사이에 들어 가는 값을 넣을 수 있음.
print("파이썬" , "자바", sep=" , ", end = "?")
# end 마지막에
# # import sys
# print("python", "java", file=sys.stdout)
# print("python", "java", file=sys.stderr)
# # 표준 에러로 처리되는거?? 먼말인지모름.
# scores = {"수학":0, "영어":50, "코딩":100}
# for subject, score in scores.i... |
b167cdd607b70ec421d902a503b43c6d7d6055bd | ongaaron96/kattis-solutions | /python3/1_9-akcija.py | 259 | 3.71875 | 4 | num_books = int(input())
prices = []
for _ in range(num_books):
prices.append(int(input()))
prices.sort(reverse=True)
total_price = 0
for index, price in enumerate(prices):
if (index + 1) % 3 == 0:
continue
total_price += price
print(total_price)
|
fd54bd44c782fe23a0592467590c57a5c02d1651 | phucduongBKDN/100exercies | /100 exercise/no10.py | 433 | 3.84375 | 4 | # Number Complement
def split(word):
return [char for char in word]
num = int(input("Enter num: "))
def numberComplement(num):
num= format(num,'b')
# print(type(num))
list = split(num)
list2 = []
print(list)
for i in list:
i = int(i)
i ^= 1
i = str(i)
list2.a... |
7774ca31be3c26d986106687d4350479b772d9b8 | pedrodiogo219/graduation | /sd/anel_threads/anel-simplificado.py | 2,022 | 3.75 | 4 | #!/usr/bin/python
import threading
import time
class myThread (threading.Thread):
def __init__ (self, id):
threading.Thread.__init__(self)
self.id = id
self.awake = False
self.finished = False
self.text = ''
self.next = None
def setNext(self, next):
sel... |
c5c7057fc9039dcb2b16d37d321b66557c75ad9c | tan-eddie/google-code-jam-2020 | /round_1a/pattern_matching/pattern_matching.py | 1,939 | 3.609375 | 4 | def head_match(a, b):
i = 0
j = 0
while i < len(a) and j < len(b):
if a[i] != b[j]:
return False
else:
i += 1
j += 1
return True
def tail_match(a, b):
i = len(a) - 1
j = len(b) - 1
while i >= 0 and j >= 0:
if a[i] != b[j]:
... |
5e4353718e8a538482c8bbd0f5e360fc81f71399 | ekeilty17/Project_Euler | /P089.py | 3,661 | 3.96875 | 4 | # Basic Rules of Roman Numerals
# 1) Numerals must be written in descending order
# 2) M, C, and X must not be equalled or exceeded by smaller demoninations
# 3) D, L, and V can only appear once
# But then we want subtractive combinations, so we add these rules
# 4) Only one I, X, C can be used as the leading ... |
2d381445f2c99d0f766e6b89003035809f5d4a93 | Parth731/Python-Tutorial | /pythontut/46_Self_and_Constructor.py | 617 | 3.96875 | 4 |
class Employee:
no_of_leaves = 8
def __init__(self,name,salary,role):
self.name = name
self.salary = salary
self.role = role
def printdetails(self):
# print(self)
return f"The Name is {self.name}. Salary is {self.salary} and role is " \
f"{self.role}... |
1ca1e31c9635559a29a96e11b0c680099ae9b88d | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/sieve/b45fd325255346eab82f5767f079a6bd.py | 204 | 3.65625 | 4 | #!/usr/bin/env python3
def sieve(limit):
a = [i*j for i in range(2, limit + 1)
for j in range(2, limit + 1) if i*j <= limit]
b = set(range(2, limit + 1))
return list(b ^ set(a))
|
3bad3eb204fe6bcaf9d8beb8ec291c296486cbc4 | angelvv/HackerRankSolution | /Algorithms/Warmup/06.PlusMinus.py | 566 | 3.8125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# from decimal import *
# Complete the plusMinus function below.
def plusMinus(arr):
# getcontext().prec = 6
length = len(arr)
print("%.6f" % (sum(n>0 for n in arr)/length))
print("%.6f" % (sum(n<0 for n in arr)/length))
... |
1899af5f154956047fd5f2a59a58a02f8de04596 | Hamza-ai-student/hamza | /Untitled27.py | 7,529 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # ..........................ASSIGMENT AI BATCH 3.....27/11/19...................................
# In[137]:
dir(name)
# ## CAPITALIZE()
# In[1]:
name = "My NamE is HaMZa i AM a sTuDent of PiAic iSlaMAbaD,baTch 3 OF aRtiFiciAl inTtelligenCE"
print(name.capitalize()) ... |
24dbc8f8a9b1f0ecfa7452369fbff2a91e65435e | ElHa07/Python | /Curso Python/Aula02/Exercicios/Exercicios03.py | 339 | 4.1875 | 4 | # Exercício Python #003 - Média Aritmética
# Exercício: Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média.
n1 = float(input('Digite sua primeira Nota: '))
n2 = float(input('Digite sua segunda Nota: '))
media = (n1+n2)/2
print('A media entre {} e {} é igual a {:.1f}! '.format(n... |
761be92352f40de279b1672f33cd8ed69433deed | castertr0y357/RecipeBook | /RecipeBook/Testing/parsing_test.py | 2,091 | 4.03125 | 4 | from fractions import Fraction
if Fraction(1/2) > 0:
print(True)
ingredient_1 = "1 1/2 cups flour"
ingredient_2 = "1/4 cups of sugar"
ingredient_3 = "3 tablespoons of salt"
ingredients = [ingredient_1, ingredient_2, ingredient_3]
for ingredient in ingredients:
if "/" in ingredient:
split_point = ingre... |
731c5f3653e422859009daf4d4de94f297ef0069 | idobleicher/pythonexamples | /examples/functional-programming/partial_example.py | 534 | 4.4375 | 4 | # You can create partial functions in python by using the partial function from the functools library.
#
# Partial functions allow one to derive a function with x parameters to a function with
# fewer parameters and fixed values set for the more limited function.
from functools import partial
def multiply(x,y):
... |
e0dfa26cebd90d0db0ed68c13817da89797342f9 | matt6frey/python-math-attack | /ma.py | 4,284 | 3.671875 | 4 | #
# Math Attack 1.0
#
# A simple math game that helps people practice basic
# addition, subtraction, multiplication and division.
#
# Developed on September 24th, 2017 by Matt Frey
import random
def compare(int1,int2,operator,ans_type): #Tests which int is larger and what type of information to return.
i... |
eaca002be0673b0e09c2359feada7b7cb0ce88d8 | xtreia/pythonBrasilExercicios | /02_EstruturasDecisao/20_media_tres_notas.py | 363 | 3.84375 | 4 | nota1 = float(raw_input('Informe a primeira nota: '))
nota2 = float(raw_input('Informe a segunda nota: '))
nota3 = float(raw_input('Informe a terceira nota: '))
media = (nota1 + nota2 + nota3) / 3.0
print 'Media do aluno: {}'.format(media)
if (media == 10):
print 'Aprovado com Distincao'
elif (media >= 7):
pr... |
97175b3a50259474c273bbb8644c16658ae92cc4 | pilosus/stepik-algorithms | /04_sorting/mergegen.py | 682 | 3.546875 | 4 | #!/usr/local/bin/python3
import sys
from random import randint, choice
def usage():
print("usage: inpgen N outfile")
print("N - number of elements in the list")
print("outfile - file name to write into")
def generate(N, out):
if (N >= int(10e5)):
N = int(10e5) - 1
f = open(out, 'w+')
... |
de7a366e05873258fb3961a2fe034db6fa00fdd3 | ag220502/Python | /Programs/ForLoops/PrintOddNo1ToN.py | 106 | 4.09375 | 4 | #Print Odd No from 1 to N
n = int(input("Enter Value Of N : "))
for i in range(1,n+1,2):
print(i," ")
|
c36a63f232c9092705529a5ebc4365197b63ead4 | Louis-YuZhao/MAS_visceral_ANT | /EigenfaceKNN/Func_k_nearest_neighbor_sklearning.py | 2,934 | 4.28125 | 4 | import numpy as np
from sklearn.neighbors import NearestNeighbors
# version 3
# 2017-06-04
# author louis
# (2) using sklearn
#%%
class KNearestNeighbor(object):
""" a kNN classifier """
def __init__(self, algorithm='auto', metric='minkowski', p=2):
self.algorithm = algorithm
self.metric = metric
... |
9c230476a54c42604a051e54fe1d6f8db96aa976 | idaeung/programmers | /Lev1/평균 구하기.py | 390 | 3.6875 | 4 | """
문제 설명
정수를 담고 있는 배열 arr의 평균값을 return하는 함수, solution을 완성해보세요.
제한사항
arr은 길이 1 이상, 100 이하인 배열입니다.
arr의 원소는 -10,000 이상 10,000 이하인 정수입니다.
입출력 예
arr return
[1,2,3,4] 2.5
[5,5] 5
"""
def solution(arr):
return sum(arr) / len(arr)
print(solution([1, 2, 3, 4]))
|
2191eed012b9251bc1a37d86e4fdd7a4aa3df4f7 | tomxelliott/PythonCode | /src/keras_NN/model.py | 1,564 | 3.96875 | 4 | from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy
# fix random seed for reproducibility
numpy.random.seed(7)
# load 2003data.csv dataset
dataset = numpy.loadtxt("2005data.csv", delimiter=",")
# split into input (X) and output (Y) variables
# First 36 are input variables
# 37th... |
e1444e6b474bc0599663b5e3e3cf7cb0131f6b24 | ajitabhkalta/Python-Training | /logging/dosa.py | 979 | 3.828125 | 4 | import logging
logging.basicConfig(level=logging.CRITICAL)
class Dosa():
def __init__(self, name, price):
self.name = name
self.price = price
logging.debug("Dosa object created: {} (INR-{})".format(self.name, self.price))
#print("Dosa object created: {} (INR-{})".format(self.name, ... |
a67d58195b1bbf553421b55f084ab627eeeb4438 | hsiangyi0614/X-Village-2018-Exercise | /Lesson03-Python-Basic-two/exercise2.py | 344 | 3.90625 | 4 | #Exercise2: swap
#method1
def f(a,b):
print("origin : ",a,b)
c=a
a=b
b=c
print("new :",a,b)
a=int(input("input a number : "))
b=int(input("input a number : "))
f(a,b)
#method2
def w(a,b):
print("origin : ",a,b)
a,b=b,a
print("new :",a,b)
a=int(input("input a number : "))
b=int(input("inp... |
5f9ffc3aa3a58fe5b053dc77942b096a699cfe6d | refanr/2020 | /6/4.py | 154 | 3.921875 | 4 | a_str = input("Input a float: ")
a_str = round(float(a_str), 2)
a_str = str(a_str)
if a_str[-1] == '0':
a_str = a_str + '0'
print(a_str.rjust(12)) |
c5d576fedbc1679380da337d9306e7a0530bc8f6 | 18cyoung/SoftwareDev2 | /Tasks/ListSum.py | 453 | 3.96875 | 4 | #MAIN BODY CODE
list = []
UI = "\n"
numberFlag = True
while (UI != ""):
UI = input("Enter a value for the list: ")
if (UI != ""):
try:
UI = float(UI)
except ValueError:
numberFlag = False
list.append(UI)
print("The current values are: ")
print(list... |
49dfd07ad950d90c524c5162ec7b8ee91419f6be | xintiansong/tensorflow_test | /MLP.py | 2,629 | 3.5625 | 4 | #MLP:共三层,隐藏层1000神经元,Accuracy: 0.9638
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets('MNIST_data/', one_hot = True)
#建立layer函数
def layer(output_dim, input_dim, inputs, activation = None):
... |
b362953b359377b86d28cdbb0fe8f55a3f6b705f | LordAzazzello/Work2020 | /OOPLAB/2_semestr/Pyt1/Pyt1.13/Pyt1.13.py | 711 | 3.78125 | 4 | #13
#Напишите собственную версию генератора enumerate под названием extra_enumerate. В переменной cum хранится накопленная сумма на момент текущей
#итерации, в переменной frac – доля накопленной суммы от общей суммы на момент текущей итерации.
def extra_enumerate(list):
cum = 0
frac = 0
sum_elem = 0
for... |
e4d0544924e6e67aa032382efd7348b12fe1a599 | rtgfd157/docker-Stock-Analysis-Project | /App/stock_analysis_project/others/y2.py | 550 | 3.625 | 4 | import time
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
A = [1,2,3,4,5,6,7]
B = A[:le... |
975a77b7e20f09532b63ba915715b94afed01a40 | RicardoMart922/estudo_Python | /Exercicios/Exercicio061.py | 1,751 | 4.40625 | 4 | # Crie um programa que leia dois valores e mostre um menu na tela:
# [ 1 ] Somar
# [ 2 ] Multiplicar
# [ 3 ] Maior
# [ 4 ] Novos Números
# [ 5 ] Sair do Programa
# Seu programa deverá realizar a operação solicitada em cada caso.
from time import sleep
numero1 = float(input('Informe um número: '))
numero2 = float(input(... |
0a836403af4260c00d73a744ac1855ea374c60a4 | loganrouleau/blokus | /src/validator.py | 2,128 | 3.5 | 4 | is_starting_block_for_player = {0: True, 1: True}
def placement_is_valid(state, proposed_coordinates, player):
all_immediate_neighbours = []
for coord in proposed_coordinates:
if not __square_is_within_gameboard(state, coord) or not __square_has_player(state, coord, None):
return False
... |
32d3ccd2db16235420be7edd3a877891eefeedf2 | therishimitra/GitHub-Crawler | /GitHub crawler improvements/GitHub v3.py | 6,398 | 3.78125 | 4 | """
HOW TO RUN:
To run execute the function: main().
This is done by execiting the script of "GitHub v3.py"
IMPORTANT:
Before running ensure GitHub_numpy_database.csv and numpy2.csv do not already exist.
"""
import requests
import csv
from bs4 import BeautifulSoup
from urllib import request
# Desc: App... |
0aff32ac90d94365602addbbddc061bfc14c6411 | rubetyy/Algo-study | /hyunsix/0910_괄호변환.py | 1,085 | 3.640625 | 4 | def check(p):
is_open = 0
u = ""
v = ""
for i in range(len(p)):
if p[i] == '(':
is_open += 1
else:
is_open -= 1
if i > 0 and is_open == 0:
u = p[0:i + 1]
v = p[i + 1:]
break
is_open = 0
for i in range(len(u)):
... |
a76fb1035d3598c32e3c22315f833e20fe18f315 | Dkpalea/midi-wfc | /wfc_2019f-master/wfc/wfc_tiles.py | 2,545 | 3.5 | 4 | """Breaks an image into consituant tiles."""
import numpy as np
from .wfc_utilities import hash_downto
def image_to_tiles(img, tile_size):
"""
Takes an images, divides it into tiles, return an array of tiles.
"""
padding_argument = [(0,0),(0,0),(0,0)]
for input_dim in [0, 1]:
padding_argume... |
98cfe1d60dab4da99dfa6c4dc3893632dab2af6c | 7ossam81/Scripts-for-CSV-results | /delete_rows_with_null.py | 361 | 3.609375 | 4 | # this script remove any row that has a "#NULL!"
import csv
with open('quiebras-spain-2005-clean.csv', 'r') as inp, open('first_edit6.csv', 'w',newline='\n') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
#if "#NULL!" not in row:
if not any('#NULL!' in x for x in row)... |
e37d310cc412685239ed740b6b85beaecf3f1f27 | Gabriel-Tomaz/aprendendo-python | /desafios/desafio020.py | 367 | 3.890625 | 4 | # =========Desafio 20==========
# Embaralhando nomes
import random
name1 = str(input("Infome o primeiro aluno: "))
name2 = str(input("Infome o segundo aluno: "))
name3 = str(input("Infome o terceiro aluno: "))
name4 = str(input("Infome o quarto aluno: "))
names = [name1,name2,name3,name4]
sort = random.shuffle(name... |
d72d29fd232e94c4e86db5ca498862d7390eb28f | CcWang/data_science | /Machine_Learning_in_Python/week1/example_one.py | 823 | 3.640625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
fruits = pd.read_table('fruit_data_with_colors.txt')
# print fruits.head()
lookup_fruit_name = dict(zip(fruits.fruit_label.unique(), fruits.fruit_name.unique()))
# print lookup_fruit_name
# cr... |
ce0314dc7c07e3d1806ad97bb7ae3fa8567c42cb | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_116/821.py | 2,899 | 3.546875 | 4 | def x_win(elements):
for i in range(4):
win = True
for j in range(4):
if (elements[j][i] == 'X' or elements[j][i] == 'T') is False:
win = False
break
if win is True:
return True
for i in range(4):
win = True
... |
e7cf5641a3e65dbfc5e7cdafdc566c34e469f3ef | betty29/code-1 | /recipes/Python/387776_Grouping_objects_indisjoint/recipe-387776.py | 1,757 | 4.0625 | 4 | class Grouper(object):
"""This class provides a lightweight way to group arbitrary objects
together into disjoint sets when a full-blown graph data structure
would be overkill.
Objects can be joined using .join(), tested for connectedness
using .joined(), and all disjoint sets can be retreived using
.get().
The ob... |
8ce5dffa72a57632da14eb80b06372fe7ccc199a | sandeepkapase/examples | /prep_question_sources/python/parameter_pass_by_ref.py | 717 | 3.734375 | 4 | #!/usr/bin/python
# [[file:../../../prep/python/Questions.org::python parameter_pass_by_ref example.][python parameter_pass_by_ref example.]]
from copy import deepcopy
class testclass:
def __init__(self):
print("testclass initialized")
self.var1 = 1
self.var2 = 2
def __repr__(self):
... |
63379144f05e1d38063d7cfed59da0b677e6e5fb | Laksh8/competitive-programming | /Codechef/sumofdigits.py | 184 | 3.8125 | 4 | # Sum of Digits :==
def su(a):
temp = 0
while a>0:
temp1 = a%10
temp = temp+temp1
a //=10
print(temp)
for i in range(3):
su(int(input()))
|
afd768a24326fdf1fd995da5c4896fd5fcfb0780 | mikesuhan/ErrorCodeTallier | /tally_codes.py | 6,792 | 3.890625 | 4 | import os
import re
import docx2txt
class Tallier:
"""Generates two csv files for the raw and normalized frequencies of substrings in a .docx file's text.
Files should be named in a consistent pattern identifying the treatment and subject, because this will
determine how the output is organi... |
299cdaea3d84a8bd6e32607d86446bfd7df2d3cc | PD12pd/Taschenrechner | /rechner.py | 1,100 | 4.03125 | 4 | # Taschenrechner
while True:
num1 = input("Gib die erste Zahl ein: ")
num11 = input("gib deine erste Zahl nach dem Komma ein: ")
oper = input("Welche Rechenoperation soll durchgefuehrt werden? (+,-,/.,*): ")
num2 = input("Gib die zweite Zahl ein: ")
num21 = input("Gib deine zweite Zahl nach dem Komma ein: ")
... |
5debf0cc3c309005bc5f1be269d8100895b51d99 | zhongyehong/docklet | /src/master/lockmgr.py | 890 | 3.765625 | 4 | #!/usr/bin/python3
'''
This module is the manager of threadings locks.
A LockMgr manages multiple threadings locks.
'''
import threading
class LockMgr:
def __init__(self):
# self.locks will store multiple locks by their names.
self.locks = {}
# the lock of self.locks, is to ensure that ... |
9de37ce84dbfa7b82833bf7d89bfbc99402aab16 | eroicaleo/LearningPython | /interview/leet/1283_Find_the_Smallest_Divisor_Given_a_Threshold.py | 619 | 3.59375 | 4 | #!/usr/bin/env python3
from math import ceil
class Solution:
def smallestDivisor(self, nums, threshold):
lo, hi = ceil(sum(nums)/threshold), max(nums)
while lo < hi:
mi = (lo+hi)//2
t = sum([ceil(n/mi) for n in nums])
if t > threshold:
lo = mi+1
... |
095b62c14d55d663d683e6be16f9dad7970debb1 | Maheboob1/Removing-duplicates-from-a-list | /chech_number_within_range.py | 148 | 3.65625 | 4 | def test_range(n):
if n in range(1,9):
print(n,"is within the range")
else:
print(n,"is not in range")
test_range(10) |
8ee4f4571f1880a092599794d5bafb6c228b426e | udhayprakash/PythonMaterial | /python3/09_Iterators_generators_coroutines/02_iterators/b_zip_map_filter.py | 1,385 | 4.3125 | 4 | #!/usr/bin/python3
"""
Purpose: Iterating zip(), map(), filter() result objects
- lazy loading object (or) on-demand loading object
- Iterators are disposable objects
- one time use only
"""
# iterables
alpha = {"a", "e", "i", "o", "u"}
nums = ("1", "2", "3", "4")
pairs = zip(alpha, nums) # zip objec... |
f7ef49e9cb84bce3ae2fcbd9a401902bffb89108 | adamkoy/Learning_Python | /Python_Learning/Python_fundementals/14_OOP_Animal_Kingdom.py | 3,002 | 4.5 | 4 | # What is inside class is called members
# one is a local variable -
# function inside a class is called methods. functions are outside a class
#
# def speak2(self): # This however, is not inside the class . It is in the file hence is now called a function/ D
# # functions are not used in OOP/classes... |
8f39b70bdc5fb4642183661c44e47be601f3a7c7 | gabriellaec/desoft-analise-exercicios | /backup/user_256/ch39_2020_04_23_14_16_27_780278.py | 297 | 3.9375 | 4 | numero = int(input("Digite um numero: "))
sequencia = numero
lista = sequencia
while numero < 1000:
if sequencia %2 ==0:
sequencia = sequencia/2
lista+= sequencia
elif sequencia %2 !=0:
sequencia = 3*sequencia +1
lista+= sequencia
return lista
|
4dd49b67cba8d0943a7a9102f53e806de5e84b67 | RedSunDave/recursivity-and-contingency | /recursive_functions.py | 884 | 4.21875 | 4 | import time
import random
def factorial_recursive(n):
if n == 1:
return 1
else:
return n * factorial_recursive(n-1)
def infinite_walk_recurse(n):
print(n)
time.sleep(2)
return n + recurse(n + random.randint(-5,5))
def fibonacci_recursive(n):
print("Calculating F", "(",... |
f4fc6fa9cd836ad87112917473037b25165b0bae | mkzia/eas503 | /old/fall2021/week5/dict_syntax.py | 1,815 | 4.46875 | 4 | # Dictionaries
# student
# - name
# - email
# - id
# - major
# Most people use this
my_dict = {
'name': 'john',
'email': 'john@email.com',
'id': 1234,
'major': 'Engineering'
}
# Can also do this
my_dict = dict(
name='john',
email='john@email.com',
id=1234,
major='Engin... |
bc36f62269be93c5d43ce1f93360b2c47bd50352 | bobobyu/leecode- | /leecode/剑指 Offer 16. 数值的整数次方.py | 642 | 3.65625 | 4 | class Solution:
def myPow(self, x: float, n: int) -> float:
def descending_power(x, n) -> float:
if n == 0:
return 1
if n == 1:
return x
if n == -1:
return 1/x
if n & 1:
y = descending_power(x, (n... |
b22c2361d50a85e1daee62d3263e6a44afe492ea | DineshKumaranOfficial/Python_Reference | /Decorators/Power_of_Functions.py | 353 | 3.828125 | 4 | # This one is a higher order function since it accepts another function
def hi(func):
func()
# This is a higher order function since it returns another function
def hello():
def dummy():
print('this is hello dummy')
return dummy
def sample():
print("I'm just a sample")
... |
5fdf526131ad0456fe24d7ee5566c6d0eccd61cd | rosrez/python-lang | /06-iteration/for-enumerate.pl | 262 | 4.15625 | 4 | #!/usr/bin/env python
list = [2, 4, 6, 8, 10];
print "Iteration using enumerate to get index"
for i,n in enumerate(list): # enumerate(s), where s is a sequence, returns a tuple (index, item)
print "squares[%d] = %d**2 = %d" % (i, n, 2**n)
|
61cd4b197f6ebce64dc7eabd8027727eddf8be23 | sand8080/solar | /solar/solar/orchestration/traversal.py | 990 | 3.578125 | 4 | """
task should be visited only when predecessors are visited,
visited node could be only in SUCCESS or ERROR
task can be scheduled for execution if it is not yet visited, and state
not in SKIPPED, INPROGRESS
PENDING - task that is scheduled to be executed
ERROR - visited node, but failed, can be failed by timeout
S... |
e29c8194afaab88b9dc0f253cdc9a1f35a2a8cef | wukunzan/algorithm004-05 | /Week 1/id_040/LeetCode_70_040.py | 1,187 | 3.84375 | 4 | #假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
#
# 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
#
# 注意:给定 n 是一个正整数。
#
# 示例 1:
#
# 输入: 2
#输出: 2
#解释: 有两种方法可以爬到楼顶。
#1. 1 阶 + 1 阶
#2. 2 阶
#
# 示例 2:
#
# 输入: 3
#输出: 3
#解释: 有三种方法可以爬到楼顶。
#1. 1 阶 + 1 阶 + 1 阶
#2. 1 阶 + 2 阶
#3. 2 阶 + 1 阶
#
# Related Topics 动态规划
#leetcode submit region begin(Prohibit modi... |
528a775c0295ad9bb93f4e47979ffa420622c9e5 | TejaswitaW/Advanced_Python_Concept | /Multithreading.py | 376 | 3.515625 | 4 | #Creating thread using any class
from threading import*
import time
print(current_thread().getName())
def disp():
print("I am display function executed by thread")
print(current_thread().getName())
##t=Thread(target=disp)#thread is created
t=Thread(target=disp).start() #this is also valid
##t.start()#thread is ... |
d6c36ab1d0411ba9f7020f6671c8090464b507d1 | thebigshaikh/Machine-Learning | /LinearRegressionMultiVariable.py | 1,187 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def import_data(filename):
data = np.loadtxt(filename, delimiter=',')
x = data[:, :2]
y = data[:, 2]
m = len(y)
return data, x, y.reshape((len(y), 1)), m
def plot_data(xx1, xx2, yy):
plt.scatter(xx1, xx2, yy)
plt.show()
d, X, Y, M = im... |
32a239b35f1b2bb72f4ebd72f70dd2195280305e | yawsonsamuel320/Ames-House-Prices-Prediction | /datacleaning.py | 614 | 4.0625 | 4 | import pandas as pd
def print_hello(n=2):
'''Prints hello'''
return "hello"
def missing_percentage(df):
'''missing_percentage(dataframe)
Return the number and percentage of missing values
Parameters
----------
dataframe:
Returns
-------
out: a Series
A Series showing the... |
3deeefc6ad581fb024755c56abcc6f57b02f45d9 | jdht1992/PythonScript | /class/class17.py | 528 | 3.96875 | 4 | class Person:
# the self parameter is a reference to the class itself, and is used to access variable that belongs to the class
def __init__(mysillyobjects, name, age):
mysillyobjects.name = name
mysillyobjects.age = age
#it does not have to be named self, you can all it wherever you like, but i... |
5643e320326d1d99fb062e4ce7e0d34227886349 | andrewtbanks/EIE-Transport-Models | /EIE_transport_models/reaction_sim.py | 16,838 | 3.625 | 4 | ####################################################################
## reaction_sim.py
## Author: Andy Banks 2019 - University of Kansas Dept. of Geology
#####################################################################
# Code to simulate reactive transport using trajectories generated by advection_dispersion... |
75dba783f33832dfffebb47272c9f25f338d407a | jackyen2000/workstation | /Rabbits and Recurrence Relations/rabbits3.py | 674 | 3.65625 | 4 |
def fibrabbit(n, k):
fib_table = []
for i in range(n):
if i < 2:
fib_table.append(1)
else:
fib_table.append(fib_table[-1] + fib_table[-2]*k)
return fib_table
#sample data 5 3
with open('rosalind_fib.txt', 'r') as f:
n, k = f.readline().split()
print (f... |
985c7f1f0d702579b6ea4d8c61e5ce3172b4670a | freliZh/rf-unbalance-data | /decisiontree.py | 4,625 | 3.53125 | 4 | #encoding:utf8
from __future__ import division
import random
import numpy as np
import time
from scipy.stats import mode
from utilities import information_gain, entropy
from pandas import Series, DataFrame
class DecisionTreeClassifier(object):
""" A decision tree classifier.
A decision tree is a structure in ... |
b3db546bf1a5ee86354a46450eb4e92988b747f3 | Kaali09/sunbird-analytics | /platform-scripts/python/main/vidyavaani/utils/find_files.py | 649 | 3.65625 | 4 | # Author: Aditya Arora, adityaarora@ekstepplus.org
import os
#This function traverses a directory finding all files with a particular substring
#Returns a list of files found
def findFiles(directory,substrings):
ls=[]
if (type(directory) == unicode or type(directory) == str) and type(substrings) == list:
# assert ... |
48d3584d6bc1cd0a0a2c147f58dde64fd4a1deae | pianomanzero/python_scripts | /python2scripts/baks/argv.py.bak | 571 | 3.984375 | 4 | #!/usr/bin/env python
from sys import argv
script, var1, var2, var3 = argv
print "The name of the script is: ", script
print "The first var you passed is: ", var1
print "The second var you passed is: ", var2
print "The third var you passed is: ", var3
print "\n"
print "Now we're going to work with raw_input\n"
pro... |
a6f0a34046b16fade163bc933d8aa03f2c8ef8bf | TestTech0920/cs1520 | /week02/py/functions.py | 183 | 3.609375 | 4 |
def sum(a, b):
return a + b
print(sum(4, 5))
print(sum('this is ', 'a sentence'))
def product(a, b, c=1):
return a * b * c
print(product(4, 5))
print(product(2, 3, 4))
|
0bef1ea39c18887ebad445cad60c244bbe0ebe89 | javierobledo/UTFSM-IWI131 | /2018/S2/Clases/Clase02102018/hora.py | 207 | 3.65625 | 4 | hora = raw_input("Ingrese la hora en formato hh:mm:ss :")
h = int(hora[0]+hora[1])
m = int(hora[3]+hora[4])
s = int(hora[6]+hora[7])
segundos = 3600*h + 60*m + s
print "Los cantidad de segundos es", segundos |
2e099a8fc1dbf7794e6980c3838a08c567ec527d | MikeLing/GatesMusicPet | /music_pet/utils.py | 663 | 3.5625 | 4 | # -*- coding: utf-8 -*-
from codecs import decode
def trim_quote(text):
if len(text) > 2 and text[0] == '"' and text[-1] == '"':
text = text[1:-1]
return text
def to_unicode(text, encoding="utf8"):
if type(text) == unicode:
return text
elif type(text) == str:
return decode(t... |
b33d8bb3f27149f60317c71c4638da0027b4dd97 | gabriel-bri/cursopython | /CursoemVideo/ex024.py | 145 | 3.84375 | 4 | cidade = str(input('Digite o nome de sua cidade: ')).strip()
verifica = 'SANTO' in cidade[0:5].upper()
print('Tem SANTO? {}' .format(verifica)) |
421ff2d8eb46e94793c3e227a2b520bd5ea9b548 | harrisonBirkner/PythonSP20 | /Project2/Project2/Project2.py | 9,751 | 4.28125 | 4 | #This program displays a menu with 4 options: SIGN IN, CREATE NEW USER, RESET PASSWORD, AND EXIT PROGRAM. SIGN IN prompts the user to enter a login id and password that is checked against login data in the file.
#CREATE NEW USER prompts the user to enter a new login id and password that is added to the file. RESET PASS... |
5fbf66fce05ea2fe5cc044e62657e34ea1a410a6 | Sharkuu/PitE-Olaf-Schab | /unittest/zadanie.py | 3,396 | 3.6875 | 4 | #!/usr/bin/env python3.4
from math import acos
from math import sin
from math import pi
import sys
#Klasa odpowiedzialna za wczytywanie danych:
# - zakres poszukiwan liczby pierwszej
# - wysokosc trojkata pascala
class InputReader:
def __init__(self):
self.primal = None
self.triangle = None
def Initiate(self):
... |
31c25e9c3839e13cac5d4f4e2b5a30608f08354e | UWSEDS/homework-4-documentation-and-style-gtalpey | /test_dataframe.py | 2,786 | 4 | 4 | '''
This module contains functions that check a DataFrame for various
attributes.
'''
import csv_to_df
# use csv_to_df to create dataframe using Pronto data
DF = csv_to_df.create_dataframe(
'https://data.seattle.gov/api/views/tw7j-dfaw/'
'rows.csv?accessType=DOWNLOAD')
def test_create_dataframe():
'''test... |
ed589d642ba58b58d86816cc9af1f010b8ac589d | ashrafya/secret_ciphers | /Ch1_A.py | 3,023 | 3.53125 | 4 | import pyperclip
alphabets = {'A':0,'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7, 'I':8, 'J':9, 'K':10, 'L':11, 'M':12, 'N':13, 'O':14, 'P':15, 'Q':16, 'R': 17, 'S':18, 'T':19, 'U':20, \
'V':21, 'W':22, 'X':23 , 'Y':24, 'Z':25}
opp = {0:'A',1:'B',2:'C', 3:'D', 4:'E', 5:'F', 6:'G', 7:'H', 8:'I', 9:'... |
c604c320707c1a2ab3b92c9c96548be6eb53a23f | MananKavi/lab-practical | /src/practicals/set4/fourthProg.py | 627 | 4 | 4 | def binary_search(searchList, item):
if len(searchList) == 0:
return False
else:
mid = len(searchList) // 2
if searchList[mid] == item:
return True
else:
if item < searchList[mid]:
return binary_search(searchList[:mid], item)
el... |
4cd2b9d91d0e4c5cfa803965cc51a315fa10576c | hmok567/Triangle567 | /TestTriangle.py | 1,280 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from Triangle import classifyTriangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html ha... |
d43d5166029f5ae1a6f25f6f3d4c78c8aebb4a1a | ca3tech/rectangles | /test_rectangles.py | 1,020 | 3.734375 | 4 | import unittest
import rectangles as r
class test_rectangles(unittest.TestCase):
def test_num_rectangles_square(self):
self.assertEqual(r.num_rectangles([(0,0), (1,0), (0,1), (1,1)]), 1)
def test_num_rectangles_diamond(self):
self.assertEqual(r.num_rectangles([(0,1), (1,0), (2,1), (1,2)]), 1)... |
ebd7913e0d97b47724ff9efa8716dc08ff49f96c | DSJL-ML/Find-Shortest-Path | /shortest_path_Dijkstras_Algorithm.py | 3,808 | 3.9375 | 4 | # define Vertice, Edge, Graph class
class Vertice(object):
def __init__(self, value):
self.value = value
self.edges = []
class Edge(object):
def __init__(self, value, vertice1, vertice2):
self.value = value
self.vertice1 = vertice1
self.vertice2 = vertice2
class Graph(o... |
0c92e96eb7a0c6d2d878e592694496ff5990b788 | Delitas/Python-Data-Structure | /convert_to_decimal(Non Use int func).py | 571 | 3.765625 | 4 | """
Data : 2020-12-18
dev : Python 3.8
Auth : Delitas
"""
print('Ver 1.1')
print('Convert to Decimal(Non int() function)')
print('Author : Delitas')
print('='*20)
numbers = int(input('Input number : '))
base = int(input("Input number's base (1<base<11) : "))
base_temp = 1
covert_num = 0
while(1):
... |
c0bb471a82e9a093ae286bcacdfc54cba4f8858d | DarknessRdg/mat-computacional | /metodos_abertos/newton.py | 798 | 3.5 | 4 | from funcoes_professor import letra_a, derivada_letra_a
from utils import preview
def newton(inicial, funcao, derivada, tolerancia):
x0 = inicial
x1 = x0
f_x0 = 1
it = 0
primeira = True
while primeira or abs(f_x0) > tolerancia or f_x0 != 0:
primeira = False
it += 1
f... |
43da1ecb3492b209c3c5f9af39cbf541858546d7 | niemitee/mooc-ohjelmointi-21 | /osa04-08b_lista_kahdesti/src/lista_kahdesti.py | 232 | 3.71875 | 4 | # Kirjoita ratkaisu tähän
lista = []
while True:
luku = int(input('Anna luku: '))
if luku == 0:
break
lista.append(luku)
print('Lista:', lista)
print('Järjestettynä:', sorted(lista))
print('Moi!')
|
e22580f93daca2aad2a80304c3383916663f2e52 | kencroker/card_game | /card_system/deck.py | 1,275 | 3.75 | 4 | import random
from card_system import hand
class Deck:
def __init__(self, input_cards: list):
assert type(input_cards) == list
self.cards = input_cards
def get_cards(self):
return self.cards
def shuffle(self):
random.shuffle(self.cards)
def remaining_cards(self):
... |
9239edef612b5592b24b2a7aa78704c9ee1ef240 | leonardokiyota/Python-Training | /Exercises Python Brasil/01 - Estrutura Sequencial/07.py | 327 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro
desta área para o usuário.
"""
lado = float(input("Digite o lado do quadrado: "))
print("O quadrado de lado {} possui uma área de {} e o seu dobre é {}"
.format(lado, lado * lado, lado * lado * 2 ))... |
936420384282c92b67b9e5da13aa21742bb642d0 | AmitUpadhyaya/Python_Task | /task3.py | 1,760 | 4.09375 | 4 | #1. Create a list of the 10 elements of four different types of Data Type like int, string, complex and float
x=[2,3,4,5,"amit","riyaz","consultadd",2.34,2.56, 1+6j]
print(type(x[-1]))
#2 Create a list of size 5 and execute the slicing structure
x1=x[:5]
x2=x[2:]
x3=x[3:6]
print(x1, x2,x3)
#3 Write a program to get ... |
b555c37529b6e4bd1276c7d0bda51da7d36d4dd7 | xiangyang0906/python_lianxi | /zuoye7/元组的可变参数01.py | 199 | 4.28125 | 4 | # 元组的可变参数 *args 其中args可以随意命名,但一般都已args命名
def tuple1(*args):
print(args)
for i in args:
print(i, end=" ")
tuple1(1, 3, 5, 6, 7, 8)
|
c591ee8241a5b5f35f7f49c987eb53b47b5de1b4 | Artinto/Python_and_AI_Study | /Week01/Main_HW/Find the Runner-Up Score/Find the Runner-Up Score_BJH.py | 703 | 3.578125 | 4 | if __name__ == '__main__':
n=input()
arr = list(map(int, input().split()))
temp =0
while 1:
if len(arr) == int(n): #int(n) 안하면 n의 형태를 모르기에 else로 넘어간다.
for i in arr:
if temp <i:
temp = i
arr.remove(temp)
... |
79ce59dfcb0bbf5b2a5199e263f27abf44052c27 | wednesday5028/ProblemSolving | /binary_search/chap_7_3.py | 419 | 3.515625 | 4 | def make_rice(array, start, end, M):
result = []
for i in range(start, end, 1):
for rice in array:
if rice - i <= 0:
continue
else:
result.append(rice - i)
if sum(result) != M:
result.clear()
else:
return i
... |
15d23823f1f720dae0f7fe6843dd035221acf1b5 | gitter-badger/Printing-Pattern-Programs | /Python Pattern Programs/Numeric Patterns/Pattern 3.py | 92 | 3.53125 | 4 | for x in range(5, 0, -1):
for y in range(5, 0, -1):
print(x, end="")
print() |
7dab764f27de6776f4032375861697670031469e | aniket435/pythonprog | /vowelcount.py | 265 | 3.96875 | 4 | a=raw_input('enter the string')
vowels = 0
for i in a:
if ( i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U'):
vowels = vowels + 1
print("Number of vowels are:")
print(vowels)
|
dcbfd21d93e474503c053a18371b96451763bff2 | renyalvarado/automate_the_boring_stuff_exercises | /src/chapter06/03_print_table.py | 760 | 4.03125 | 4 | #! /usr/bin/env python3
# Table Printer
table_data = [["apples", "oranges", "cherries", "banana"],
["Alice", "Bob", "Carol", "David"],
["dogs", "cats", "moose", "goose"]]
max_columns = max([len(x) for x in table_data])
max_sizes = [max([0 if i > (len(x) - 1) else len(x[i]) for x in table_d... |
0af2a913a50fb5d101ce3a54d83f3a2e5b82364e | slagmale/webcrawler | /parsinglibrary/xpath/xpathexamp4.py | 2,056 | 3.640625 | 4 | from lxml import etree
# XPath 提供了很多节点轴选择方法,英文叫做 XPath Axes,包括获取子元素、兄弟元素、父元素、祖先元素等等
text = '''
<div>
<ul>
<li class="item-0"><a href="link1.html"><span>first item</span></a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">t... |
b27afe96af284705abbc67c70bbc6168dca870ca | saintsim/adventofcode-2018 | /src/day1/part2.py | 426 | 4.125 | 4 | #!/usr/bin/env python3
def repeating_frequency(lines):
totals_found = set()
total = 0
while True:
for x in lines:
total += int(x)
if total in totals_found:
return total
totals_found.add(total)
if __name__ == '__main__':
with open('input', '... |
49604ed874da46ae572a6ac1da1db21fc98eabf0 | tomothumb/sandbox | /python/fundamental/dict.py | 1,639 | 3.671875 | 4 | print("######")
d = {'x': 10, 'y': 20}
print(d)
print(type(d))
d['x'] = 100
print(d['x'])
print(d)
d['x'] = 'XXXX'
print(d)
d['z'] = 999
print(d)
d[1] = 11111
print(d)
print("######")
dd = dict(xx=10, yy=20)
print(dd)
ddd = dict([('xxx', 10), ('yyy', 20)])
print(ddd)
print("######")
# Dictionaly Method
# print(help... |
ecd1cfb6aeef50f2f88920a3121ba3597bc41045 | feiyu4581/Leetcode | /leetcode 101-150/leetcode102.py | 843 | 3.890625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
def inord... |
bf5cc68ac1ca29faab1288174c67d3fdad86a910 | YongJunLim/python | /practical1/t1.py | 161 | 4.0625 | 4 | fahrenheit = float(input("Enter temperature in fahrenheit: "))
celsius = (5/9) * (fahrenheit - 32)
print("The temperature in celsius is {0:.2f}".format(celsius)) |
634a23e3c41f7bbc69bff1d798b1bc04c9534fb4 | pite2020win/mon-14-40-task3-PawelKepka | /task.py | 2,690 | 4.09375 | 4 | # Class diary
#
# Create program for handling lesson scores.
# Use python to handle student (highscool) class scores, and attendance.
# Make it possible to:
# - Get students total average score (average across classes)
# - get students average score in class
# - hold students name and surname
# - Count total attendance... |
88605e178a175b83bf0e16c336dfb2270f85b4ea | levleonhardt/guias_Programacion1 | /prog1/guia4/ej8_4.py | 588 | 3.578125 | 4 | #Contar la cantidad de letras (no incluir los separadores)
s = "Quiero comer manzanas, solamente manzanas."
s = s.replace(",", "")
s = s.replace(".", "")
lista_s = s.split()
cantidad_letras = 0
cantidad_letras_lista = []
for i in range(len(lista_s)):
cantidad_letras = len(lista_s[i])
cantidad_letras_lista.ap... |
93f723541a2551f172e3c42e9ea4bf97808af521 | kgbking/cs61a_fa11 | /hw6.py | 7,865 | 4.25 | 4 | """Homework 6: Object-oriented programming"""
"""1) Create a class called VendingMachine that represents a vending machine
for some product. A VendingMachine object doesn't actually return anything but
strings describing its interactions. See the doctest for examples.
In Nanjing, there are even vending mac... |
c6dbd3fe8ad4436bc6fc53562c27fc18828ea6b4 | aidsfintech/Algorithm-and-Query | /Algorithm/python/algorithmjobs/L11/L11_04valparenthesis_plus.py | 4,483 | 3.71875 | 4 | from collections import deque
import sys
'''
다음에 할때는 기호에서 숫자 변환에 있어서
dict따로 선언해두면 좀더 세련될듯
->do it now
좀더 패턴을 세부분석하면 불필요한 flag=False를 줄일수 있을듯
+중간에 2개의 연속 ()() 또는 []() 등등은 커버되지만,
3개 이상의 경우 현재 if구조로는 불가능하다는 걸 깨닫,
while이 필요.
->여기서부턴 새로운 파일에
'''
def aggregate_subsum(stack,top_stack):
tmp_list=list()
# print(stack... |
a320a25277dccc0d225079f17fd17613f7c3767e | srimaniteja19/python_projects | /tip_calculator/main.py | 467 | 4.1875 | 4 | print("Welcome to the tip calculator")
total_bill = float(input("What was the total bill? $"))
number_of_people = float(input("How many people to split the bill? "))
percentage = float(input("What percentage tip would you like to give? 10, 12, or 15? "))
bill_generated = total_bill/number_of_people
bill_generated_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.