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 |
|---|---|---|---|---|---|---|
7ecf3bacc861279c81c6b011c0ac14d3889881cd | jeremykl/LeetCode | /1022. Sum of Root To Leaf Binary Numbers.py | 854 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
# Use DFS to find all of the numbers in binary and c... |
bf1001d5716ba846c6ddfe9c5992b88551a145ac | aerinkim/AndrewNG_ML_Python | /ex7/ex7_pca.py | 9,469 | 3.6875 | 4 | ## Machine Learning Online Class
# Exercise 7 | Principle Component Analysis and K-Means Clustering
#
# Instructions
# ------------
#
# This file contains code that helps you get started on the
# exercise. You will need to complete the following functions:
#
# pca.m
# projectData.m`
# recoverData.m
# ... |
d2d0f73ff6e62ebdb529d93386ea023910ecdc0d | aerinkim/AndrewNG_ML_Python | /ex5/linearRegCostFunction.py | 732 | 3.8125 | 4 | import numpy as np
def linearRegCostFunction(X, y, theta, Lambda):
"""computes the
cost of using theta as the parameter for linear regression to fit the
data points in X and y. Returns the cost in J and the gradient in grad
"""
m, _ = X.shape
# ====================== YOUR CODE HERE ======================
# Instr... |
f4fccc29a5d6062c61c5b746fb474e7301a655ad | kristiyanto/zigzagsort | /kom/phone-dial.py | 448 | 3.84375 | 4 | '''
Design all possible text combination on a phone
e.g: input = 223
out = ['aa']
'''
def phone(a):
dic = {1: [''], 0: [''], 2:['a','b', 'c'], 3:['d','e','f'],
4: ['g','h','i'], 5: ['j','k','l'], 6:['m','n','o'],
7: ['p','q','r','s'], 8:['t','u','v'], 9:['w','x','y','z']}... |
9726bfe53b37e33967056213cd2ab2ef9f70f56d | amakhyon/kmeans | /smart_kmeans.py | 5,915 | 3.5625 | 4 | import random
import math
class Cluster:
def init(self):
self.x_points = []
self.y_points = []
def set_centroid(self,x, y):
self.centroid = []
self.centroid.append(x)
self.centroid.append(y)
def get_centroid_x(self):
return self.centroid[0]
def get_centroid_y(self):
return self.centroid... |
7340f81d1ab1a2f749e15754978d9cc4ad7d756f | tscholz26/python-project | /test scripts/test checkbutton.py | 728 | 3.53125 | 4 | from tkinter import *
master = Tk()
check1 = IntVar()
check2 = IntVar()
check3 = IntVar()
cbiko = Checkbutton(master, var = check1, text = 'Ikosaeder zeichnen', command = lambda:(cbokt.deselect(), cbkep.deselect()))
cbiko.grid(row = 1, column = 0, columnspan = 1, pady = 15)
cbokt = Checkbutton(master, va... |
a380df9a2e1b59ddea7136796a61ba7d084a995d | tscholz26/python-project | /test scripts/mouse movement test.py | 1,809 | 3.609375 | 4 | from tkinter import *
master = Tk()
global clickx
global clicky
global currentx
global currenty
global releasex
global releasey
global posx
global posy
posx = 100
posy = 100
def greet():
print("Greetings!")
def ausgeben(string):
print(str(string))
def click(eventclick):
global... |
3b7416b0202ed4d0dab761c190f8fd17760d79f4 | SmithUtittawai/Problem-Solving-in-IT-Python- | /PythonAssignment5_2.py | 2,353 | 3.875 | 4 | #6306021631061 สมิทธ์ อุทิศถวาย
import random
def Show():
print("Select Option")
print("1.Sex")
print("2.Payment type")
print("3.Education")
print("4.Age group")
def Init():
for r in range(55):
data.append([0,0,0,0,0])
for r in range(5):
result.append([0,0,0,0... |
bb501e1028325e1a2c3591ad669a7e45d54d721d | vincentgc/Leetcode | /504. base 7/504.py | 630 | 3.609375 | 4 | class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
#注意等号
res = ''
if num > 0:
tmp = num
elif num == 0:
return '0'
else:
tmp = num * -1
res += '-'
i = 0
... |
d2b8eb159d4ff7687d49275b01fbed401d963b4f | vincentgc/Leetcode | /Binary Tree- Base operation/652.Find Duplicate Subtrees.py | 683 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
""... |
187269a9d58a66513d8bdda626b909f8c62ef928 | mosesokemwa/bank-code | /darts.py | 1,113 | 4.375 | 4 | OUTER_CIRCLE_RADIUS = 10
MIDDLE_CIRCLE_RADIUS = 5
INNER_CIRCLE_RADIUS = 1
CENTRE = (0, 0)
def score(x: float, y: float):
"""Returns the points earned given location (x, y) by
finding the distance to the centre defined at (0, 0).
Parameters
----------
x : float,
The cartesian x-coordinate ... |
e52d775f79831414f58c5ceeef965f1306b27293 | OsamaOracle/python | /Class/Players V1.0 .py | 1,294 | 4.3125 | 4 | '''
In the third exercise we make one final adjustment to the class by adding initialization data and a docstring. First add a docstring "Player-class: stores data on team colors and points.". After this, add an initializing method __init__ to the class, and make it prompt the user for a new player color with the messa... |
e4dc9d2ba525fc6e1a1fa293cddfffde7af4fbf9 | OsamaOracle/python | /Modules/Head_tails_Random_module.py | 89 | 3.546875 | 4 | from random import randint
if randint(0,2) == 1:
print("Heads!")
else:
print("Tails!") |
0914be891ca99ee0b3958269a9e55302644aae8d | OsamaOracle/python | /Loops/voewls.py | 347 | 3.828125 | 4 | voewls = 0
consonants = 0
ask = input("Please enter your word here?! ").strip()
for letter in ask:
if letter.lower() in "aeiou":
voewls = voewls + 1
elif letter == " ":
pass
else:
consonants = consonants + 1
print ("There are {} vowels".format(voewls))
print ("There are {} consonan... |
5e56658d01a741066a6b93a7ef4e38fa5da4f123 | salmanchik1/Project_Euler | /32.py | 576 | 3.875 | 4 | the_set = set(x for x in range(1, 10))
list_products = set()
def combination(myset, string):
"""gives all the permutations for set"""
if len(myset) == 0:
check(string)
return None
for i in myset:
combination(myset - {i}, string + str(i))
def check(string):
"""checks the string... |
6a813ed3ba244f682d80cf8beaf1675a5b68749c | salmanchik1/Project_Euler | /38.py | 622 | 3.5 | 4 | # This algorithm is written in Python 3.7
def pandigital(num_str):
if len(num_str) != len(num_str):
return False
my_set = set()
for char in num_str:
if char != '0' and int(char) <= len(num_str):
my_set.add(char)
return len(my_set) == len(num_str)
maximum = 0
for i in range(... |
5cd415d41b6e2b7bfd4b59c04e47cab0b5f92df0 | salmanchik1/Project_Euler | /26.py | 1,538 | 3.546875 | 4 | d_max = 1000 # The searching area, maximum for d
list_n = list() # the list, where we will save all the values for n
# n is changing remainder, a found out that it repeats in cycles.
# If we stumble on it second time in the loop that means we found the cycle.
str_a = '' # We will save here the sequence of all the di... |
ca8b83f1f135d08304c74227d2dd9d255219616c | denizcetiner/rosalindpractice | /INI4.py | 249 | 3.5625 | 4 | def run(user_input="""100 200"""):
params = [int(i) for i in user_input.split()]
start = params[0]
end = params[1]
sum = 0
for i in range(start, end+1):
if i % 2 == 1:
sum += i
print(sum)
return sum
|
a4190af9127aff8c5a43c1e95cbc138926c595d7 | leo-herran/Markov-Chain-Word-Generator | /markov.py | 2,344 | 3.578125 | 4 | import random, pickle, sys
#a markov chain-based text generator.
class Markov:
def __init__(self, file, wordDataFile=None):
if(wordDataFile == None):
self.chains = self.processRawData(file.read().split());
else:
self.chains = pickle.load(open(wordDataFile, 'rb'));
... |
f5fe210b66217372f07067c4af5a1d6166b24221 | muhzii/bankers-algorithm-demo | /banker.py | 3,919 | 3.625 | 4 | import random
NUM_OF_PROCESSES = 0
NUM_OF_RESOURCES_TYPES = 0
class Banker(object):
def __init__(self, avail, Max):
self.Need = Max
self.avail = avail
self.Allocation = [[0] * NUM_OF_RESOURCES_TYPES for _ in range(NUM_OF_PROCESSES)]
def request_resource(self, process, type, quantity)... |
1b33d3847230a6dc8ea92e4f673d8a2858ff14db | sigridure19/HR_Python | /2. sequence.py | 1,014 | 3.90625 | 4 | #Design an algorithm that generates
#the first n numbers in the following sequence:; 1, 2, 3, 6, 11, 20, 37, ___, ___, ___, …
# Talnaröðin byggist á að 3 tölurnar á undan eru lagðar
# saman og gildið úr því verður næsta tala í rununni
#n(x) = n(x-1)+n(x-2)+n(x-3)
n = int(input("Enter the length of the sequence: ")... |
9e836586bf103caa7123c2a12ddaaed87974d021 | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex044 # simulador de loja if elif else .py | 1,221 | 4.09375 | 4 | # simulador de loja if elif else
print(' ')
rs = float(input('Qual o valor das compras? R$ = '))
print(' ')
print('''Formas de pagamento
[ 1 ] à vista dinheiro/déboto/PIX
[ 2 ] à vista no cartão
[ 3 ] 2x no cartão
[ 4 ] 3x ou mais vezes no cartão''')
print(' ')
opção = int(input('Qual a opção? '))
if opção == 1 :
... |
bd36ffbfe9fc98c700b158e427375a1ee7bbbe4c | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex063 # Fibronacci while .py | 297 | 3.890625 | 4 | # Fibronacci while <=
n = int(input('Quantos valores quer ver dentro da sequência de Fibroonacci? '))
v1 = 0
v2 = 1
print('{}-> {}'.format(v1, v2), end='')
cont = 3
while cont <= n:
v3 = v1 + v2
print('-> {}'.format(v3))#, end='')
v1 = v2
v2 = v3
cont += 1
print('-> FIM') |
9b1e267b6e4b202d6218bafe73ad3c8be49bd317 | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex020 # cria uma sequencia aleatotiamente -=-.py | 344 | 3.78125 | 4 | # cria uma sequencia aleatotiamente -=-
import random
n1 = input('Escreva o nome. Primeiro aluno: ')
n2 = input('Escreva o nome. Segundo aluno: ')
n3 = input('Escreva o nome. Terceiro aluno: ')
n4 = input('Escreva o nome. Primeiro aluno: ')
lista = [n1, n2, n3,n4]
random.shuffle(lista)
print('A ordem de apresentação s... |
6f3533baee84ab6fb62d366982ba533440719695 | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex066 # números com flag while true break .py | 352 | 3.875 | 4 | # números com flag while true break
soma = cont = 0
while True:
num = int(input('[Pare digitando 999] Digite um número: '))
if num == 999:
break
cont += 1
soma += num
#print('Você digitou {} números e a soma entre eles foi {}.'.format(cont, soma))
print(f'Você digitou {cont} números e a som... |
9b6251e242f2ed25df6a81d9faf8b5cc94d7eb70 | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex031 # calcola um valor dependendo da distância -=- if else.py | 291 | 3.921875 | 4 | # calcola um valor dependendo da distância -=- if: else:
dist = float(input('Sua viagem é de quantos Km ? '))
print('Para sua viagem de {}Km'.format(dist))
if dist <= 200:
valor = dist * 0.50
else:
valor = dist * 0.45
print('O valor da sua passagem é de R$ {:.2f}'.format(valor)) |
5471b08a2c83d8aa77a7e8485205160371bcec88 | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex038 # selecionando o maior valor if else .py | 328 | 4 | 4 | # selecionando o maior valor if else
print(' ')
num1 = int(input(' Primeiro número inteiro: '))
num2 = int(input(' Segundo número interiro: ' ))
print(' ')
if num1 > num2:
print(' O primeiro valor é o maior!')
elif num1 == num2:
print( 'Os dois valores são iguais!')
else:
print(' O segundo valor é o maior... |
cb159d75464cd184798a3069e8779a0ec65b9472 | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex037 # bin oct hex fatiamento str if elif else .py | 594 | 4.125 | 4 | # bin oct hex fatiamento str if elif else
num = int(input(' Digite um númeto inteiro: '))
print('''Escolha a base de conversção que deseja:
[ 1 ] para Binário
[ 2 ] para Octal
[ 3 ] para Hexadecimal''')
opção = int(input(' Sua opção: '))
if opção == 1:
print(' {} convertido para Binário é {} '.format(num, bin(n... |
8b7d86e49c6e62bdf0fc60e126481a219b0af673 | jbmarcos/Python-Curso-em-video-Mundo-1-2-3- | /ex036 # financiamento de uma casa if else -=- .py | 535 | 3.921875 | 4 | # financiamento de uma casa if else -=-
print(' ')
casa = float(input(' Valor da casa: R$ '))
ganha = float(input(' Qual o valor mensal ganho pelo comprador? '))
anos = int(input(' Quantos anos de financiamento? '))
prestacao = casa / (anos * 12)
print(' ')
print(' Para pagar uma casa de {:.2f} R$'.format(casa))
prin... |
e05906c1218a1e438bef7d80970127915fe9aa44 | sunkadshreyas/Python-Apps | /weatherData.py | 2,275 | 3.6875 | 4 | import xlsxwriter
import requests,json
import time
# Opening a Excel workbook with two sheets
workbook = xlsxwriter.Workbook('example.xlsx')
worksheet1 = workbook.add_worksheet('Sheet 1')
worksheet2 = workbook.add_worksheet('Sheet 2')
# In sheet 1 writing the column headings
# First column is City and next three are ... |
87c6013053de3c1b0cdddff68e64ea6b76e5040f | lihaoranharry/INFO-W18 | /week 2/Unit 2/sq.py | 316 | 4.25 | 4 | x = int(input("Enter an integer: "))
ans = 0
while ans ** 2 <= x:
if ans **2 != x:
print(ans, "is not the square root of" ,x)
ans = ans + 1
else:
print("the square root is ", ans)
break
if ans **2 == x:
print("we found the answer")
else:
print("no answer discovered")
|
a8c3809738492d3355e150601d87826ba158ab72 | gothickaka/leetcode | /14. Longest Common Prefix.py | 437 | 3.578125 | 4 | class Solution(object):
def longestCommonPrefix(self, strs):
if len(strs)==0:
return ''
strs.sort()
i=0
while i<len(strs[0]):
if strs[0][i] == strs[len(strs)-1][i]:
i=i+1
else:
break
return strs[0][:i]
if __... |
908c1b911b9b0697766d3ee84b2ecf34a9bea6ac | gothickaka/leetcode | /88. Merge Sorted Array.py | 472 | 3.828125 | 4 | class Solution(object):
def merge(self, nums1, m, nums2, n):
if n > 0:
i = m
j = 0
while i < m+n:
if i < len(nums1):
nums1[i] = nums2[j]
else:
nums1.append(nums2[j])
i += 1
... |
93251d4d1a84f99924dee7a21b99090f3b976622 | NhernandezB/Python_practicas | /puntuacion.py | 500 | 3.890625 | 4 | '''
Escribir un programa que lea la puntuación del usuario
e indique su nivel de rendimiento,
así como la cantidad de dinero que recibirá el usuario.
'''
puntos = float(input("Introduzca los puntos obtenidos: "))
pago = 2400
if(puntos == 0.0):
print("Su nivel es inaceptable, su pago es de: ",str(pago*puntos))... |
191ff60e5dccb8e38ccb8769735cc77716e8b15c | FabianPalacios/Automatas | /View/windows.py | 7,253 | 3.53125 | 4 |
from tkinter import *
import tkinter as tk
from Control.Controller import Controller
from Control.Afnd import Afnd
from Control.Afd import Afd
from Control.MinAfd import MinAfd
from Control.Graph import Graph
import tkinter.messagebox
class Windows:
# Constructor de la ventana
def __init__(self):
... |
055abc0aa8a0fe307d3b1dda6ec697c908e61e44 | RelayAstro/Python | /ejercicio29.py | 962 | 4.5625 | 5 | #The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like "Never Odd or Even". Fill in the blanks in t... |
e7823e0ecf021d6cbb170d8d807c4ec5ad18de2e | mybestnickname/learn_python | /lesson2/string_comparison.py | 302 | 3.640625 | 4 | def string_comp(first_str, second_str):
try:
if first_str == second_str:
return 1
elif len(first_str) > len(second_str):
return 2
elif second_str == 'learn':
return 3
except TypeError:
print('string_comp(str, str)')
|
36899188f23150d7884d09598dc3c44b35c92388 | season-7/Natare-Gardens | /booking.py | 377 | 3.703125 | 4 | import csv
# Read each row and print it
# Open the file declaring each mode that I am going to use
# loop through the rows, checking first the size of the row then printing
with open('booking.csv', 'r') as f:
r = csv.reader(f, delimiter=' ')
for row in r:
if len(row) >= 4:
print(row[0] + '... |
6e0e2417c0ebb6503a255659c869ce0e0e2440a6 | dbrooks83/PythonBasics | /email count.py | 1,002 | 3.8125 | 4 | #Write a program to read through the mbox-short.txt and figure out
#who has the sent the greatest number of mail messages.
#The program looks for 'From ' lines and takes the second word of those
#lines as the person who sent the mail. The program creates a Python
#dictionary that maps the sender's mail address to a... |
5c84f84a9e1816751630c17bb1acb9b3301459a3 | dbrooks83/PythonBasics | /Grades.py | 711 | 4.5 | 4 | #Write a program to prompt for a score between 0.0 and 1.0.
#If the score is out of range, print an error. If the score is between
#0.0 and 1.0, print a grade using the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error messa... |
0c97c087bc5194bb39225c5eb34eb627b49145e2 | jwsi/Microprocessor | /simulator/classes/reservation_station.py | 5,395 | 3.53125 | 4 | import curses
from classes.constants import N
class ReservationStation:
"""
Reservation station class to store instructions pending execution.
"""
def __init__(self, reorder_buffer):
"""
Constructor for the reservation station class.
"""
self.queue = []
self.reor... |
bafe64d0c9a7ecbe27d40053eea9d2d132cb5456 | qarawlus/fi-vnf | /res/fi.py | 854 | 3.640625 | 4 | """Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class ... |
4395828aca481917ef8484005aa73be5a47ae49a | joemenna/Arithmetic-arranger-for-free-code-camp | /arithmetic_arranger.py | 2,328 | 3.5625 | 4 | import operator
def arithmetic_arranger(problems, svt = False):
#
# Step 1: Check preconditions and return proper error
# Step 2: Split strings, into number1s, number2s, operators, and results
# Step 3: Build line 1 of output <num1>
# Step 4: Build line 2 of output <op> <num2>
# Step 5: Build line 3 of outp... |
91fa15b2c4ae7d49ff66f69e13a921aed349f63e | TranshumanSoft/Repeat-a-word | /repeataword.py | 205 | 4.1875 | 4 | word = str(input("What word do you want to repeat?"))
times = int(input(f"How many times do you want to repeat '{word}'?"))
counter = 0
while counter < times:
counter = counter + 1
print(word) |
03892ef026daa6231c113260bfa5ad5147fe18a6 | fullere/craps | /craps.py | 3,995 | 4.03125 | 4 | # Elizabeth Fuller
# 10/21/19
# game of craps
import random
def roll_dice():
# creates dice roll number
roll = random.randint(2, 12)
return roll
def create():
# starts fresh game and fills in bankroll amount
bankroll = int(input("Enter bankroll amount:\n> $"))
while bankroll <= 0:
pr... |
543cc84a22cfe06cf4caf6baada5f65f38da4064 | insomnia250/K | /HousePrice/examples/eg3.py | 6,416 | 3.71875 | 4 | #coding=utf-8
'''
https://www.kaggle.com/yadavsarthak/house-prices-advanced-regression-techniques/you-got-this-feature-engineering-and-lasso/notebook
We'll look into
1. basic feature engineering and extraction
2. use the Lasso model and give our newly developed data a test run!
3. Some (minor) visualizations
'''... |
a790b4992c5c6b57d5655bb3ef4b4e2527a750d6 | romanguerrero/tetris | /tetris.py | 12,677 | 3.5 | 4 | # file: tetris.py
# auth: Roman Guerrero
# date: 20/08/10
# desc: Simple Tetris game implemented in Python
# ref: Citation - Tech with Tim Tetris pygame tutorial
# link: https://techwithtim.net/tutorials/game-development-with-python/tetris-pygame/tutorial-1/
import pygame
import random
# Global variables
s_width = ... |
0cf71a15c7380832da5db42a6e74b0414006921f | thewrongjames/chessapi | /chessapi/utilities.py | 439 | 3.984375 | 4 | from .discrete_vector import DiscreteVector
def iterable_to_discrete_vector(value):
"""
If this recieves an iterable, it will return a DiscreteVector with x =
iterable[0], y = iterable[1]. But, if it recieves anything else, it will
just return that.
"""
try:
return DiscreteVector(*valu... |
f180fb0e98f0b58bed1c1d8f1de0ee967cb6a19b | thewrongjames/chessapi | /chessapi/game/is_in_checkmate.py | 426 | 3.828125 | 4 | from ..constants import COLOURS
def is_in_checkmate(self, colour):
if not colour in COLOURS:
raise ValueError('colour must be in colours {}'.format(COLOURS))
# Because moves that leave a player in check are not in their current moves
# lists, a player is in checkmate if there are in check, and th... |
928e0e7bf064b0f82f6eebcf0d20c0f51ed5cd74 | trgy2145/-Assignment-009-3 | /assignment/armstrong_num.py | 534 | 3.796875 | 4 | num = input("Enter a number: ")
if "." in num or "," in num:
print("float blr sayı giremezsiniz..")
elif num.startswith("-"):
print("sıfırdan küçük bir değer girdiniz.")
elif not num.isdigit():
print("karakter dizisi giremezsiniz..")
else:
power = len(num)
sum = 0
temp = int(num)
while temp > 0:
... |
8c855c41046f03888b12b957cfb66ac866144ca7 | fandres70/Python1 | /functiondefaults.py | 575 | 4.34375 | 4 | # Learning how Python deals with default values of
# function parameters
def f(a, L=[]):
'''This function appends new values to the list'''
L.append(a)
return L
# not specifying a list input
print(f(1))
print(f(2))
print(f(3))
# specifying a list input
print(f(1, []))
print(f(2, []))
prin... |
39b12a36d1c809b5b64250ac4543c95d26f5912b | fandres70/Python1 | /factorial.py | 426 | 4.34375 | 4 | #!/usr/bin/env python
# Returns the factorial of the argument "number"
def factorial(number):
if number <= 1: #base case
return 1
else:
return number*factorial(number-1)
# product = 1
# for i in range(number):
# product = product * (i+1)
# return product
user_input = int(raw_... |
b0fd0d7d490e08d90bc5bab0336613c375d800c4 | fandres70/Python1 | /oddeven.py | 200 | 4.28125 | 4 | x = int(input('Enter an integer: '))
if x < 0:
x = 0
print('Negative changed to zero.')
elif x == 0:
print('Zero.')
elif x % 2 == 1:
print('Odd.')
else:
print('Even.')
|
0361514e2daabc0bc8ca3646237ae302c488f080 | yitshen/clrs_python_implementation | /sort/randomized_select.py | 1,166 | 3.859375 | 4 | '''
randamized select: get the ith smallest number
use randomized_partition and partition from quick sort
'''
import random
def randomized_partition(inputList,left, right):
tempPivot = random.randint(left, right)
inputList[right], inputList[tempPivot] = inputList[tempPivot], inputList[right]
return partiti... |
291e3a23b45876c985e97437d65c412dc37e4bc0 | yitshen/clrs_python_implementation | /sort/insertion_sort.py | 357 | 3.90625 | 4 | def insertion_sort(input, ascending = True):
for iii in range(1, len(input)):
key = input[iii]
while iii > 0 and key < input[iii-1]:
input[iii-1], input[iii] = input[iii], input[iii-1]
iii -= 1
if ascending:
return input
else:
return input[::-1]
test ... |
f1b64cca82f43a4b1733b88ed0c9f17262b13c20 | Jinglever/python_algo | /binary_search_tree.py | 4,946 | 3.890625 | 4 | """
实现二叉查找树即相关算法
"""
from typing import Optional
class Node(object):
"""
二叉树节点
存储的值是整数
"""
def __init__(self, data: int=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __repr__(self):
return repr(self.data)
class BinaryS... |
b24ffc58a8f6a8eeaafc2ef55d19a43cefa66c44 | ywpark/Python3 | /STEP9/ExLast.py | 2,161 | 3.984375 | 4 | # Python이 추구하는 철학 ( The Zen of Python )
#import this
# Python Enhancement Proposals (PEP) : 파이선을 개선하기 위한 제안
# Function Arguments
# *args = 기본 파라미터 외에 다른 파라미터를 tuple로 return
# def function(named_arg, *args):
# print(named_arg)
# print(args)
#
# function(1,2,3,4,5)
# Default Value
# def function(x,y,food='spa... |
c846c8871aec1ca26bee49a839c1cb8aeae50b7e | ywpark/Python3 | /STEP7/ExOop.py | 4,651 | 4.59375 | 5 |
# #Classes
# # __init__ 메소드는 중요하다. this is called when an instance of the class is created, using the class name as a function
# # self.attribute (__init__ method) : set the initial value of an instance's attributes
# class Cat:
# def __init__(self, color, legs):
# self.color = color
# self.legs = ... |
a4034f4c5a30994a6b8568eb369a8a4df8610c46 | Saskia-vB/eng-57-pyodbc | /error_file.py | 1,338 | 4.5 | 4 | # Reading a text file
# f = open ('text_file.txt', 'r')
#
# print(f.name)
#
# f.close()
# to use a text within a block of code without worrying about closing it:
# read and print out contents of txt file
# with open('text_file.txt', 'r') as f:
# f_contents = f.read()
# print(f_contents)
# reading a txt file ... |
6c5e707b2bd9ec32c5be34ef687fd51a20adeacf | FYCompsci/games | /slotmachine.py | 6,636 | 3.6875 | 4 | # -*- coding: utf-8 -*-
#Text-Based Slot Machine
#By Zack Nathan
from random import choice
from time import sleep
import sys
#Every spin of the slot machine runs this function once
def spin():
global wins, losses
#Pick a random character for each of the 9 boxes
for i in range(9):
boxes[i] = choi... |
b158bea68bd6ad4aa2ee7bf0452e863c1d877e6e | airallergy/zotutil | /zotutil/tools.py | 773 | 3.734375 | 4 | from pathlib import Path
def remove_empty_directories(root_directory):
ignore_files = (".DS_Store", "desktop.ini", "Thumbs.db")
root_directory = Path(root_directory)
directories = tuple(item for item in root_directory.iterdir() if item.is_dir())
for directory in directories:
if set(item.name f... |
0fafaab6ffd894f1593b93d0d770ec72619debd6 | yungzim/python | /exercise9E.py | 337 | 4.09375 | 4 | import random
lucky_number = random.randint(1,9)
guess_count = 0
while guess_count < 3:
guess = int(input("Guess the lucky number 1 - 9: "))
guess_count += 1
if guess == lucky_number:
print("Boom!!, That is correct!")
break
else:
print(f"you ran out of chances, the lucky number is {luc... |
2db0a57dfa06168256f20e50cff23cccb3e97139 | Arshak24/Arshak-python | /bot.py | 1,337 | 3.546875 | 4 | import random
import time
import math
print('Barev es Qeropn em unes xndirner ches karoxanum lucel es ktam qez xorhurd, @ntri nshvacneric vor xndirne qon@')
time.sleep(0.5)
print('1) mtacum es anhajoxakes? ')
time.sleep(0.5)
print('2) Krvel es @nkeruhut het? ')
time.sleep(0.5)
print('3)Unes tshnaminer? ')
time.sleep(0... |
6999261014e4ac4bd9633ea6003dd30ed3cc455c | Arshak24/Arshak-python | /lesson8 (2).py | 1,739 | 3.84375 | 4 | '''Write a Python program to calculate a dog's age in human years. Note: For the first two years, a dog year is equal to 10.5 human years. After that, each dog year equals 4 human years.'''
# dog = int(input('Tur inc shan tariq@ '))
# if dog < 0:
# print('error')
# elif dog >= 0 and dog <= 2:
# human = dog * 5.25
#... |
082b2cb9dc56b20901654981a785293c4cf1cae0 | kurtrm/gas_usage_calculator | /trip_features.py | 2,024 | 3.734375 | 4 | """
Module containing functions to calculate routes via the Google Maps
API, and return the total number of miles on the route.
"""
import os
import googlemaps
import requests
from bs4 import BeautifulSoup
def get_maps_data(start_point: str, end_point: str, api_key: str=None) -> str:
"""
"""
... |
5f62cb78547b5a4152223c2a9c55789768d87b21 | bhumphris/Chapter-Practice-Tuples | /Chapter Practice Tuples.py | 2,234 | 4.46875 | 4 | # 12.1
# Create a tuple filled with 5 numbers assign it to the variable n
n = (3,5,15,6,12)
# the ( ) are optional
# Create a tuple named tup using the tuple function
tup = tuple()
# Create a tuple named first and pass it your first name
first = tuple("Ben")
# print the first letter of the first tup... |
30b38b69420ef8013deac4cf446bb890e55b2096 | sharkySharks/notes | /Python/PythonForDevs/Labs-Worked/Day3/lab26.py | 2,160 | 4.09375 | 4 | """
This class implements the __del__ method to decrement the
account counter when an account is deleted
"""
class BankAccount(object): # Top tier class (super class)
acct_cntr = 0 # class variable
def __init__(self): # This method runs during instantiation
self.balance = 0 # instance varia... |
1c701e4977d3da20f8d3a80f690121321b09e250 | knobay/jempython | /quiz_program/library/question.py | 1,349 | 3.859375 | 4 | """ A question has an ID, some question text, some options, and a correct answer """
import random
class Question(object):
'Returns a question object if supplied all the \
required attributes as parameters: id (integer), questions text, \
list of options and an answer index (integer referring to the corre... |
b4f4dbbefa4d5775c0231803674af13466b3f7be | knobay/jempython | /advanced_week1/worksheet5a.py | 407 | 4.03125 | 4 | def get_items():
"gets a number of items into a list from user input"
items = []
for i in range(5):
items.append(input("what is in your pocket?"))
return items
def main():
items = get_items()
print(items)
print('The item at position 3')
print(items[3])
del(items[0])
prin... |
03ef1ea5a2c991e7a597f40b06aac37890dde380 | knobay/jempython | /exercise08/h01.py | 593 | 4.1875 | 4 | """Uniit 8 H01, week2"""
# Gets an input from the user works
# out if it is an Armstrong number
def armstrong_check():
"Works out if the user has entered an Armstrong number"
userinput = input("Enter a 3 digit number")
evaluation = int(userinput[0])**3 + int(userinput[1])**3 + int(userinput[2])**3
i... |
688fa627915adf73bf41bc04d0636d41fb0d349d | knobay/jempython | /exercise08/e03.py | 581 | 4.125 | 4 |
"""Uniit 8 E03, week2"""
# Gets an input from the user works
# out if it contains a voul
PI = [3.14, 2]
def voul_or_not():
"Works out if the user has entered a voul or consonant"
userinput = input("Enter a letter")
if (userinput == 'a' or userinput == 'e'
or userinput == 'i' or userinput == ... |
93b353c031fd6005c0503337580a371c48fc1029 | knobay/jempython | /exercise06/m05.py | 1,084 | 3.640625 | 4 | # Import all libraries
import math
#
dayInSeconds = 24*60*60
hourInSeconds = 60*60
print("\n--------------------------------------------------------------")
print("------------------------ M05 -------------------------")
x = True
while x:
kmStr = input("Please enter a distance in Kilometres:- ")
if kmSt... |
2d766aea3921242f98860cc272bbfda43fb38efe | knobay/jempython | /exercise08/e02.py | 720 | 4.28125 | 4 | import math
#
print("\n--------------------------------------------------------------")
print("------------------------ E02 -------------------------")
x = True
while x:
numStr = input("Please enter a whole number:- ")
if numStr.isdigit():
num = int(numStr)
break
elif numStr.replace(... |
1ac377c630aef77a3d3f5f4cf4106ea8ea380b76 | knobay/jempython | /advanced_week1/zipfunction.py | 147 | 3.5 | 4 | firstnames = ['kim', 'jane', 'eric']
lastnames = ['nobay', 'harrington', 'bristow']
fullnames = zip(firstnames, lastnames)
print(list(fullnames)) |
e2f74a50015ff54481fcd9bc9680053b1bea1700 | AlexGottschall/program-arcade-games | /Lab 01 - Calculator/lab_01_part_b.py | 246 | 3.8125 | 4 | #
print("Area of a trapezoid")
bottom = int(input('Enter the bottom of the trapezoid: '))
bottlen = int(input('Enter the length of the bottom of the base: '))
toplen = int(input('Enter the length of the top base: '))
print(str(.5 * (l + tl) * t)) |
224b5e89e34fd67a481f08faebea9b88e663360d | ZorkinMaxim/Extra_HomeWork | /DZ_Palindrome.py | 487 | 4.15625 | 4 | # Detect Palindrome
# Запросить ввод числа. Определить является ли введенное число полиндромом или нет.
number = int(input('Enter a number'))
reversed_number = 0
tmp_original = number
while tmp_original > 0:
reversed_number = (reversed_number * 10) + tmp_original % 10
tmp_original = tmp_original //... |
2aeef72e6c60c1e0848e7e65768158b662ce21b8 | ZorkinMaxim/Extra_HomeWork | /Pagination.py | 1,427 | 3.765625 | 4 | class Pagination():
def __init__(self, items=[], page_size=10):
self.items = items
self.page_size = page_size
self.total_pages = 1 if not self.items else (len(self.items) // self.page_size) + 1
self.current_page = 1
def get_visible_items(self):
start = (self.curr... |
0fc96fca44c941fee8e8f8c857fc061f09a11c1d | ZorkinMaxim/Extra_HomeWork | /list_comprehension.py | 587 | 3.609375 | 4 | numbers = [n for n in range(1, 11)]
print(numbers)
numbers1 = [n*n for n in range(1, 11)]
print(numbers1)
numbers2 = [n*n for n in range(1, 11) if n % 2 != 0]
print(numbers2)
len_in_centimeters = [12, 10, 54, 124, 64]
len_in_inches = [(round(cm / 2.54, 2)) for cm in len_in_centimeters]
print(len_in_inches... |
44549590e162718f1847d602d0e3969e5d1b6645 | mayukhg/pythonDataScience | /Code/test.py | 192 | 3.6875 | 4 | list1 = [0,2,3,4,5,6,7,8]
list1[1:3]=[9,10,11]
#print(list1)
a= "Man"
#print(type(a))
set1 = {7, 2 , 13}
#print(set1)
mydict={1:2,2:4,3:6, 'test':2, 'check':'final'}
print(mydict['check'])
|
7fa78e9dc2c4fa3f13512321f4fb42869576630d | sgrees/PyWeb-06 | /simple-mvc/wsgi.py | 2,591 | 3.5625 | 4 | """
Widget Storage: a Simple MVC Application With Persistence
Each widget shall be addressed as follows:
http://localhost:8080/example/
http://localhost:8080/blarg/
http://localhost:8080/4/
or any other alphanumeric "root" "directory". There
exists a widget at each possible widget address,
irrespective of... |
f55c5faea4edc14ed453f87cad75843d19a884f8 | AstroLRene/AstroBlackBox | /bigData/test/globalAndNonlocal.py | 986 | 3.578125 | 4 | gcount = 1
def global_test():
global gcount
gcount += 1
print(gcount)
# global_test()
# print(gcount)
def scope_test():
def do_local():
spam = "local spam" # 此函数定义了另外的一个spam字符串变量,并且生命周期只在此函数内。此处的spam和外层的spam是两个变量,如果写出spam = spam + “local spam” 会报错
def do_nonlocal():
nonlocal spam ... |
378e0b3f129230aae31b144ab00fe46aa123b537 | Habits11/Python-Programs | /name_order.py | 953 | 4.15625 | 4 | # name_order.py
# A program to reorder a person's name
# Author: Tyler McCreary
def main():
name = input("Input the name to be reordered: ")
spaces = name.find(" ")
if spaces <= 0:
print("invalid name")
else:
first = name[:spaces]
name = name[spaces + 1:]
spaces = name.f... |
1a9cbb01c102907f1abc0e2dbd4ca263a0340df2 | gabrielifaria/Banco_Python | /Banco_FINAL/codigos/alteracao_dados.py | 1,967 | 3.921875 | 4 | from verificacao import verificar_senha
from leitura_e_escrita import *
from cadastrar import *
from tratamentos import limpar_tela
def mudar_dados(nome_pasta,nome_arquivo, dado):
senha = input('Para realizar mudanças digite sua senha: ')
if verificar_senha(nome_pasta, senha) is True:
escreve... |
ca79982fdf3136f2b41153ba0c500eef058d949d | gabrielifaria/Banco_Python | /Banco_FINAL/codigos/menu_operacoes_bancarias.py | 1,470 | 3.59375 | 4 | from operacoes_bancarias import *
from tratamentos import limpar_tela, positivo
def operacoes_bancarias(numero_conta):
menu = 0
while True:
limpar_tela()
print('****OPERAÇÕES BANCARIAS!****')
print('1 - Deposito')
print('2 - Saque')
print('3 - Transferencia')
... |
7aec4787cf86b566517d4d542881d4589db2747b | XinArkh/PAT_Codes | /BasicLevel_Python(disabled)/pat_basic_1014-x.py | 794 | 3.640625 | 4 | Week = {'A': 'MON', 'B': 'TUE', 'C': 'WED', 'D': 'THU', 'E': 'FRI', 'F': 'SAT', 'G': 'SUN'}
L1 = input()
L2 = input()
L3 = input()
L4 = input()
length12 = min(len(L1), len(L2))
ans = ''
flag = False # flag means whether it is the second pair
for i in range(length12):
if not flag and L1[i] == L2[i] and 'A' <= L1... |
4b0b793ac6cdfbbee4e51c18209a36b0f719dc78 | XinArkh/PAT_Codes | /BasicLevel_Python(disabled)/pat_basic_1009.py | 133 | 3.640625 | 4 | wordList = input().split()
wordList = wordList[::-1]
ans = ''
for w in wordList:
ans += w + ' '
ans = ans[:len(ans)-1]
print(ans) |
4be0db806d1d5c32ec0cd72121bf8cc9d7244de2 | jlh040/Python-data-structures-exercise | /25_sum_pairs/sum_pairs.py | 1,221 | 4.1875 | 4 | def sum_pairs(nums, goal):
"""Return tuple of first pair of nums that sum to goal.
For example:
>>> sum_pairs([1, 2, 2, 10], 4)
(2, 2)
(4, 2) sum to 6, and come before (5, 1):
>>> sum_pairs([4, 2, 10, 5, 1], 6) # (4, 2)
(4, 2)
(4, 3) sum to 7, and finish before (5, 2... |
bdd4e00e31390d070ed7fd61ebce0c031c652cbc | yashpatel4900/Sorting-Algorithms | /Selection Sort.py | 216 | 3.71875 | 4 | array = [12, 11, 13, 5, 6, 7]
for i in range(0, len(array)-1):
j = i+1
while(j < len(array)):
if array[i] >= array[j]:
array[j], array[i] = array[i], array[j]
j += 1
print(array) |
9f4f1ac07f0063357611bbf1b9a425d68da3ac86 | earchanjo/Radiotracador | /sensor1/sensor.py | 4,037 | 3.5625 | 4 | ## Simulador de dados.
## Reproduz situações reais nos dutos
import random
import math
''' O programa sensor é um meio que temos de simular os dados provenientes dos sensores de radiacao, ao qual nao temos recurso.
Ele utiliza um simples esquema de geração de valores de posicao e radiacao em funcao da coordenada de d... |
589a9d90e1fe9dd0787c76c8ab746475408e921a | jcborras/PolePositionENGR133FinalProject | /polePositionRunner.py | 1,923 | 3.765625 | 4 |
'''
===============================================================================
ENGR 133 Fa 2020
Assignment Information
Assignment: Final Project
Author: Alec Pannunzio, afpannun@purdue.edu
Team ID: LC4-5
===============================================================================
'''
f... |
eae7d7750b39d3ac6f3235a298400efde113c53a | jcborras/PolePositionENGR133FinalProject | /edgeDetection/MyTrix.py | 13,684 | 3.625 | 4 |
'''
===============================================================================
ENGR 133 Fa 2020
Assignment Information
Assignment: Python Project 1
Author: Alec Pannunzio, afpannun@purdue.edu
Team ID: LC4-5
Contributors: Jonathan, jdufresn@purdue.edu
Sam, graha205@purdu... |
ecc4d8468168080d5a37e5383c397413acc880cf | topless/anagram | /solver.py | 1,978 | 3.78125 | 4 | #!/usr/bin/env python3
# coding: utf-8
import json
md5_answer = "4624d200580677270a54ccff86b9610e"
PHRASE = ''.join(sorted("poultryoutwitsants"))
# Experimenting with some structures to figure out how to approach multi word
# anagram solving.
# One thing would be to sort each word and try to do stuff with it but it... |
6abb106146471374115d6b51360f0806b5b25a6c | krastykovyaz/python_hse | /Сократите дробь.py | 269 | 3.71875 | 4 | def gcd(a, b):
if a == 0 and b != 0:
return b
elif a != 0 and b == 0:
return a
else:
return gcd(b, a % b)
def ReduceFraction(n, m):
k = gcd(n, m)
return (n // k, m // k)
print(*ReduceFraction(int(input()), int(input())))
|
e6178c5543c39e459d026229418650b030ef5e1a | krastykovyaz/python_hse | /Цвет клеток шахматной доски.py | 144 | 3.671875 | 4 | f1 = int(input())
f2 = int(input())
s1 = int(input())
s2 = int(input())
if (f1 + f2 + s1 + s2) % 2 == 0:
print('YES')
else:
print('NO')
|
f6ca57358f923e5dbcb8613373d0c7579babc421 | krastykovyaz/python_hse | /Отрицательная степень.py | 349 | 3.859375 | 4 | def power(a, n):
if n == 0:
return 1
elif n > 0:
i = 1
x = a
while i < n:
i += 1
a *= x
return a
else:
i = 1
x = a
while i < (-n):
i += 1
a *= x
z = 1 / a
return z
print(power(fl... |
75c0c736763da20c3c1a3a6a42d2acdebb56052e | krastykovyaz/python_hse | /Номер числа Фибоначчи.py | 229 | 3.546875 | 4 | a = int(input())
if a == 0:
print(0)
else:
f0 = 0
f1 = 1
i = 1
while f1 <= a:
if f1 == a:
print(i)
break
f0, f1 = f1, f1 + f0
i += 1
else:
print(-1)
|
09087851fb6e400b4085f5109772861296fdd1ff | krastykovyaz/python_hse | /Периметр треугольника.py | 426 | 4 | 4 | def distance(x1, y1, x2, y2, x3, y3):
a = x1 - x2
b = y1 - y2
c = (a ** 2 + b ** 2) ** 0.5
i = x2 - x3
f = y2 - y3
g = (i ** 2 + f ** 2) ** 0.5
k = x1 - x3
z = y1 - y3
m = (k ** 2 + z ** 2) ** 0.5
p = m + c + g
return p
x1 = float(input())
y1 = float(input())
x2 = float(inp... |
4298121c3733274c345529e9562fd03dc26f48cb | jagfirerwalker/HackerRank | /plus_minus.py | 751 | 3.671875 | 4 | import sys
n = int(input("Enter 1 Number: ").strip())
arr = [int(arr_temp) for arr_temp in input("Enter as many space seperated number as previously declared (pos or neg): ").strip().split(' ')]
positive = 0
negative = 0
zero = 0
for i in range(n):
positive += (1 if arr[i] > 0 else 0)
negative += (1... |
f59f67268a48d8976dab4a8cf8bff464aad70f4d | gokayozcoban/counting-in-str | /str içerisindeki karakterleri saymak (a kaç tane)metni kullanıcıdan alır.py | 595 | 4 | 4 | # Stirng içerisindeki karakterleri saymak:
# Mesela a harfinden kaç tane var?
metin = input("Metni girin: ")
harf = input("Sorgulanmak istenilen harf hangisi: ")
sayı = 0
for i in metin:
if harf == i:
sayı += 1
print(sayı)
input()
##Önce metni yaz.
##kullanıcıdan input() ile sorgulanmak istenil... |
71a2ea694a3da163c4bb96734ddef4eb8d8c5406 | KiranVKV/pythonworkshop | /arithimetic operations.py | 261 | 4 | 4 | x = int(input("enter:"))
y = int(input("enter:"))
print("Addition value is:",x+y)
print("Subtrsction value is:",x-y)
print("Multiplicatio value is:",x*y)
print("divison value is:", x/y)
print("exponent value is:", x**y)
print("Floor division value is:", x//y)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.