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 |
|---|---|---|---|---|---|---|
6387ea1e60a82a3acf7d2480e5e7beee6c2f6b0c | ntmk/ICS-Labs | /114-python/Python labs/AutoService.py.py | 517 | 4.0625 | 4 | services = { 'Oil change': ('$35'),
'Tire rotation': ('$19'),
'Car wash': ('$7'),
}
oil = input('Enter desired auto service: \n')
print('You entered:', oil)
print()
if oil == 'Oil change' :
print('Cost of oil change:', services ['Oil change'])
elif oil == 'Tire rotation' :
prin... |
9546adcacab926cb0557506b52d139b9202c4aa5 | ntmk/ICS-Labs | /114-python/Python labs/ShapesInheritance/square.py | 378 | 3.5 | 4 | from rectangle import Rectangle
import math
class Square(Rectangle):
def __init__(self, centre_x, centre_y, side, name ='Square'):
Rectangle.__init__(self, centre_x, centre_y, side, side, name)
def __str__(self):
return ('%s: (%d, %d), area=%.2f, s=%d' % (self.name, self.centre_x, ... |
0a8fa9847296b540bc3107bc176be844065cf658 | Sumitbansal-01/bookMyMovie | /BookMyMovie/package/Mymainmodule.py | 4,492 | 3.953125 | 4 | class Cinema:
list1=[]
while True:
print("Enter the number of rows:")
no_of_rows=input()
print("Enter the number of seats in each row:")
no_of_seat=input()
if no_of_rows.isdigit()==False or no_of_seat.isdigit()==False:
print("\nEnter the correct input in numbers\n")
else:
no_of_rows=int(no_... |
925f611103e6901a48b469f67a1c30a111403299 | jacopo308cilibrasi/python_exercise | /P3.py | 218 | 3.84375 | 4 | # Write a programm , that gives you back how many digits
# are composing the n number.
def digits(n):
if n<0:
return "negative"
elif n<10:
return 1
else:
return digits(n // 10) + 1
|
73d509b7f09ccd110cdfff3192e8d8387dc4661c | vaishnav22/python_windows | /y_fractal_tree.py | 317 | 3.6875 | 4 | import turtle as tu
bob = tu.Turtle()
bob.left(90)
bob.speed(10)
#recursion
def draw(l):
if(l<1):
return
else:
bob.forward(l)
bob.left(30)
draw(3*1/4)
bob.right(60)
draw(3*1/4)
bob.left(30)
bob.backward(l)
draw(100)
|
bbb301cd923a183029eac244e23568ee07439cd4 | amateurdullahan/TokaidoNakama | /deck.py | 5,179 | 3.59375 | 4 | #!/usr/bin/python3
"""deck objects"""
class Card():
def __init__(self, type="", point_value=0, name=""):
"""initializing the Card obj"""
self.type = type
self.point_value = point_value
self.name = name
@property
def type(self):
"""get... |
fcd242237a7c3f6004380877542e49243c1e5776 | johngarciadev/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/12-roman_to_int.py | 799 | 3.65625 | 4 | #!/usr/bin/python3
def get_value(c):
if c == 'I':
return 1
elif c == 'V':
return 5
elif c == 'X':
return 10
elif c == 'L':
return 50
elif c == 'C':
return 100
elif c == 'D':
return 500
elif c == 'M':
return 1000
def roman_to_int(roman... |
ad57cdfdaa05cd4191f9ac1be6d3f6d613c45d72 | johngarciadev/holbertonschool-higher_level_programming | /0x0A-python-inheritance/3-is_kind_of_class.py | 408 | 3.546875 | 4 | #!/usr/bin/python3
"""Function that returns True if the object
is an instance of, or if the object is an
instance of a class that inherited from,
the specified class; otherwise False."""
def is_kind_of_class(obj, a_class):
"""Function that returns True
if the object is exactly an
instance... |
ad79baa9bd795e7e28ba7df8db472be9725d86de | amitauti/HelloWorldPython | /ex02.py | 1,019 | 4.25 | 4 | # http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html
# Ask the user for a number. Depending on whether the number is even or
# odd, print out an appropriate message to the user.
import sys
def main():
askuser ()
def askuser():
#part one
str = input("Enter a number: ")
num = int(flo... |
7411be28c217372cfc6b3808e34606c5135ab16b | rjrealworld/flying-plane | /FlyingPlane.py | 4,719 | 3.515625 | 4 | import turtle
import math
import random
import pygame
#setup Screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.bgpic("space.gif")
wn.tracer(3)
#Draw border
border = turtle.Turtle()
border.color("white")
border.penup()
border.setposition(-300, -300) #Left Bottom
border.pendown()
border.pensize(3)
fo... |
2f7f8cb23eb74c9046769b6200a49147384375cd | nasirmajid29/Anthology-of-Algorithms | /Algorithms/sorting/mergeSort/mergeSort.py | 972 | 4.28125 | 4 | def mergeSort(array):
if len(array) > 1:
middle = len(array) // 2 # Finding the middle of the array
left = array[:middle] # Split array into 2
right = array[middle:]
mergeSort(left) # sorting the first half
mergeSort(right) # sorting the second half
# Copy... |
5f232071e5c18576770bd2749dd6d553e519c4d2 | nandinichhajed/Python-Projects | /Translator/Translate in new txt file.py | 704 | 3.859375 | 4 | # translate and save in a txt file
from translate import Translator
translator = Translator(to_lang='ja')
# we can change language here based on the documantation
try:
with open(r"File Path", 'r') as my_file:
text = my_file.read()
translation = translator.translate(text)
with open('test-j... |
04db2c059278b04fbea28a3f03f1a1f063d07392 | nilax97/leetcode-solutions | /solutions/Smallest Subtree with all the Deepest Nodes/solution.py | 1,100 | 3.703125 | 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 subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
self.keys = dict()
def calcdept... |
ae9ae531f2cfc0d1113f632977a7264e65875a02 | nilax97/leetcode-solutions | /solutions/Simplify Path/solution.py | 449 | 3.765625 | 4 | class Solution:
def simplifyPath(self, path: str) -> str:
ans = list()
val = path.split('/')
for x in val:
# print(x,ans)
if x == '':
continue
if x == ".":
continue
if x == "..":
if len(ans) != 0:... |
03d6221c948c1009333447558fe9d46d4f255819 | nilax97/leetcode-solutions | /solutions/Inorder Successor in BST/solution.py | 598 | 3.859375 | 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 inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode':
def inorder(node):
if(node==None):
... |
1e6f384b5abc2319523e9c2b2a084056c25fda5e | nilax97/leetcode-solutions | /solutions/N-Queens/solution.py | 1,710 | 3.8125 | 4 | class Solution:
def solveNQueens(self, n):
# Making use of a helper function to get the
# solutions in the correct output format
def create_board(state):
board = []
for row in state:
board.append("".join(row))
return board
... |
621f4dba7f501382a36b5040843d83e80426660d | nilax97/leetcode-solutions | /solutions/Find a Corresponding Node of a Binary Tree in a Clone of That Tree/solution.py | 803 | 3.578125 | 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 getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
check = list()
check.append(... |
2c6e5e857b628e6b2e802e236ff575bb79840c1c | nilax97/leetcode-solutions | /solutions/Find Largest Value in Each Tree Row/solution.py | 657 | 3.703125 | 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 largestValues(self, root: TreeNode) -> List[int]:
val = list()
def check(root,level,ans)... |
f06b7d363ba714948f8225f7d7b7592cd1988287 | nilax97/leetcode-solutions | /solutions/Add One Row to Tree/solution.py | 966 | 3.796875 | 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 addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
def addrow(root,n,v,d):
... |
99b2566ef247b94245253783ba9720f402d383d6 | nilax97/leetcode-solutions | /solutions/Validate Binary Search Tree/solution.py | 569 | 3.84375 | 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 isValidBST(self, root: TreeNode) -> bool:
def preorder(root):
if root == None:
... |
f9122c3eaf5e5bc84021a1004ce700061c19cc6e | nilax97/leetcode-solutions | /solutions/Pacific Atlantic Water Flow/solution.py | 1,836 | 3.859375 | 4 | class Solution:
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix or not matrix[0]:
return []
# Initialize variables, including sets used to keep track of visited cells
num_rows, num_cols = len(matrix), len(matrix[0])
pacific_r... |
94fc34297cdcb36e6bb7ed2cec03239ee927e1d6 | nilax97/leetcode-solutions | /solutions/Construct Binary Search Tree from Preorder Traversal/solution.py | 856 | 3.9375 | 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 bstFromPreorder(self, preorder: List[int]) -> TreeNode:
def rectree(orderlist):
if len(orderlist) == 0:
... |
157614db053e4ccddc9c5d467431983538e97a23 | nilax97/leetcode-solutions | /solutions/Second Minimum Node In a Binary Tree/solution.py | 748 | 3.796875 | 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 findSecondMinimumValue(self, root: TreeNode) -> int:
def order(root):
if root == Non... |
65141d81fa52c6249a6749b1464825ce39b0af43 | Shakil97/python-work | /function.py | 763 | 3.71875 | 4 | def my_func(param1= "default"):
"""
THIS IS DOCSTRING
"""
print("my first python function {}".formet(param1))
my_func()
###
def hello():
return "hello"
result = hello()
print(result)
####
def addNum(num1,num2):
if type(num1)==type(num2)==type(10):
return num1+num2
else:
return "sorr... |
d297ece0cbf2fbb7048195d8fc2ee76065d67435 | dougmvieira/single_hidden_layer_neural_network | /mnist_tools.py | 1,165 | 3.59375 | 4 | """
Functions for downloading the MNIST data set, loading into memory and showing
characters.
"""
import cPickle as pk
import gzip as gz
import numpy as np
from pylab import imshow, cm
from requests import get
from os.path import isfile
deeplearning_file_name = "mnist.pkl.gz"
deeplearning_url = "http://deeplearning.... |
75b0001197c683d48ab4871db876591689b81793 | bryanphua/50.020-Security-Labs | /lab 3/test.py | 107 | 3.546875 | 4 | import itertools
x = itertools.combinations('abcde', 2)
for i in x:
print(''.join(i))
print('extra')
|
310c8beb0d1e34686643c8678a6d8447905d76d2 | nicolasenciso/DES-crypto-algorithm | /DESalgorithm.py | 1,534 | 3.578125 | 4 | import os
import io
import base64
import Image
import pyDes
from array import array
#Algorithm of DES cipher, with 8 bits key, for images, presented by Nicolas RIcardo Enciso
def convertToByteArray(originalImage):
with open(originalImage, "rb") as f:
return bytearray(f.read())
def menu():
print(">>>>>... |
c2577f2e4a513f772183567759eee009eac2fa25 | gpfvic/NewWordDector | /test/read_file_by_chunk.py | 473 | 3.515625 | 4 | #coding:utf-8
'''
Created on 2015年8月14日
@author: g00297221
'''
def read_in_chunks(file_object, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
data = file_object.read(chunk_size)
if not data:
break
yiel... |
09d823731e829104ab276bc1356e5d1e6caa48c7 | sebastianljs/leetcode_challenges | /leetcode_challenges/palindrome_pairs.py | 392 | 3.703125 | 4 | class Solution(object):
def palindrome_pairs(self, words):
"""
:type words: list[str]
:rtype: list[list[int]]
"""
def _is_palindrome(self, word):
left, right = 0, len(word) - 1
while left <= right:
if word[left] != word[right]:
return ... |
fe7dc646e6803d550245c1e42b84b4e935c02343 | michaeljs-c/CS50-Artificial-Intelligence | /Week_0_Search/tictactoe/tictactoe.py | 3,103 | 3.921875 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who ha... |
2929f49be61557f3233c7c68291711c9426c4638 | huchen086/web-caesar | /caesar.py | 1,154 | 4.1875 | 4 | def alphabet_position(letter):
"""receives a letter (that is, a string with only one alphabetic character)"""
"""and returns the 0-based numerical position of that letter"""
"""within the alphabet."""
letter = letter.upper()
position = ord(letter) - 65
return position
def rotate_character(char... |
cc6e52863e787d0ae22223598bd409e29a6230af | NSGregory/GroupAlign | /lib/groups.py | 6,104 | 3.6875 | 4 | """Takes a dataReader object and uses it to assign subjects to groups as determined by the parameters of that object
Expected parameters to be supplied in the excel document from the end user:
Grouped -- TRUE / FALSE : do you have to keep the subject from a group together
Var_range -- float : if multiple fac... |
9afee39db5f15d957c60df0a1c50213b73d888aa | ciccolini/Python | /Function.py | 2,459 | 4.46875 | 4 | #to create a function
#by using def keyword
def my_function():
print("Hello from a function")
#to call a function
my_function()
#to add as many parameters as possible
def my_function(fsurname):
print(fsurname + " " + "Name")
my_function("Anthony")
my_function("Romain")
my_function("MP")
#improvement
def my_f... |
fad3cc8551cfa433361718aad74ce1feafb97a35 | ciccolini/Python | /Operator.py | 697 | 4.03125 | 4 | #to verify the type of any object
myint = 5 #entier
myfloat = 7.3 #decimal
mycomplex = 1j #complexe avec j pour la partie imaginaire
print(myint, type(myint))
print(myfloat, type(myfloat))
print(mycomplex, type(mycomplex))
#to change the type of the value
print(float(myint)) #will be 5.0
print(int(myfloat)) #will be 7... |
24f2d6b80085dbd8dde7a3dbb30e17e937911c4b | tukalian/hangman | /chap14_210424_2.py | 188 | 3.703125 | 4 | # isキーワード
class Person:
def __int__(self):
self.name = 'Bob'
bob = Person()
same_bob = bob
print(bob is same_bob)
anather_bob = Person()
print(bob is anather_bob)
|
fd46b3b91ea07d302f8224fd938725390173f00d | tim-win/botman-v3 | /botman/markov.py | 4,712 | 3.765625 | 4 | """markov.py"""
import random
N = 4
def choose_ngram(counts, function=random.random):
"""Choose next ngram based on a function.
Parameters
----------
counts : dict
Key > value pairs where keys are ngrams and values are integer counts
they have been seen as
function : callable
... |
654675daeb90fd3a24064fa8257b6ce7eb9e996c | Nevilli/unit_five | /d2_unit_five_warmups.py | 141 | 3.5 | 4 | total_sum = 0
for x in range(10001):
if x % 3 == 0:
total_sum = total_sum + x
print(total_sum)
# The answer I got was 16668333
|
c80afeb916c245689bfada0870cfb11da66abf48 | quinnpertuit/ideal-enigma | /pt_data.py | 4,640 | 3.765625 | 4 | import pandas as pd
import numpy as np
def load_file(filename, sep=';'):
""" (string) -> DataFrame
Returns a pandas DataFrame with all the contents of the file specified.
"""
data = pd.read_csv(filename, sep=sep)
# Create helper columns
data["Player Full Name"] = data["Player First Name"] +... |
040d858e3b8ecc36dfac024498e71030d8890593 | hubgit122/python | /字符串,元表和列表.py | 110 | 3.5625 | 4 | print ['s','s']=="ss"
print ['s','s']
print "ss"
print str(('s','s'))
print "ss"[0]
print ['s','s']==('s','s') |
7857f876b476280ea19cf05d84662a0a42e7e074 | AEG90/Rock-Paper-Scissors-Game | /RPS.py | 811 | 3.984375 | 4 | import random
choice = ['rock', 'paper','scissors']
n = 5
while n > 0:
n -=1
pc_choice = random.choice(choice)
p1_choice = input('Choose Rock, Paper or Scissors:\n')
print('The computer picked',pc_choice)
if pc_choice == p1_choice:
print('A tie!')
elif pc_choice == 'rock'... |
76bc73c658a9ed0f9c1437f485bb5c9a7df27ef2 | lukehowerter/LukePWM | /lukecsv.py | 3,082 | 3.5625 | 4 | import csv, fileinput, hashlib, time
def createcsv(filename='lukePWM.csv'):
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Accountname', 'Datechanged', 'mpwcheck'])
def updateentry(accountname, csvfile='lukePWM.csv'):
with open(csvfile, ne... |
e09d88413f22afee9604ef82652ba6a367214362 | idan0610/intro2cs-ex3 | /decomposition.py | 897 | 4.25 | 4 | ######################################################################
# FILE: decomposition.py
# WRITER: Idan Refaeli, idan0610, 305681132
# EXERCISE: intro2cs ex3 2014-2015
# DESCRIPTION:
# Find the number of goblets Gimli drank of each day
#######################################################################
num_... |
3b02f43987dd30da8a4ed1d4194b060b1614c06c | savadev/bdrecipes | /src/main/java/spark/fractions/prepare_input.py | 844 | 3.53125 | 4 | file_1_gb_bytes = 1000000000
file_500_mb_bytes = file_1_gb_bytes/2
file_3_gb_bytes = file_1_gb_bytes*2
def generate_file(file_size, file_name):
mb_in_file = 100
bytes_in_file = 1000*1000*mb_in_file
with open(file_name, 'w') as generated_file:
file_rounds = file_size/bytes_in_file
print('file_rounds: ' + str(fi... |
8a980f70473f02ee70ef90c247e15132101601ec | jamesnogra/PerceptronNumpy | /TestPerceptron.py | 445 | 3.5 | 4 | from PerceptronClass import Perceptron
import numpy as np
inputs = np.array([
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
])
outputs = np.array([
[0, 1],
[0, 1],
[0, 1],
[0, 1],
[1, 0],
[1, 0],
[1, 0],
[1, 0],
])
test = Perceptron(inputs, outputs, 0.1, 100)... |
56b3ba4f85438c9655fdfe45da4fc5b0c75bbd92 | TamaWilson/floyd_python | /floyd.py | 723 | 3.8125 | 4 | INF = float("inf")
#Matriz de distancias entre cada Nó. INF = Nós não possuem ligação.
grafo = [ [0, 5, INF, 10],
[INF, 0, 3, INF],
[INF, INF, 0, 1],
[INF, INF, INF, 0]
]
def floyd(grafo):
ponderados = grafo
len_matrix = len(grafo)
#Aplicação do al... |
24ab741d03a1dcf1aeb7e3324a7b376564868207 | zhangxinying1997/Seminar01 | /merge.py | 649 | 3.875 | 4 | def merge(a, b):
if isinstance(a, tuple):
ans = list(a[:])
else:
ans = a.copy()
index = 0
for i in range(0, len(b)):
while index < len(a):
if b[i] <= a[index]:
ans.insert(index + i, b[i])
break
else:
index +... |
8a46787b7f97ae24428f87352598095d054fd805 | Albas-tomi/Materi-Pytho | /TampilanNilAbjad.py | 806 | 3.65625 | 4 | '''
Menampilkan Nilai Huruf Dari Bilangan Bulat 0 - 100
'''
jwb="y"
while jwb=="y" or jwb=="Y":
n=1
while int(n) > 0 and int(n) <= 100:
print("========================")
print(" Cek Nilai ")
print("========================")
n=input("Masukkan Nilai = ")
... |
be86016236c395692e98580942e72e3324dd1558 | sabalyshen/is_leap | /is_leap.py | 278 | 3.6875 | 4 | #閏年計算
def is_leap(y):
if y % 4 != 0: # != 不等於
return False
elif y % 100 != 0:
return True
elif y % 400 != 0:
return False
elif y % 3200 != 0:
return True
y = input('請輸入西元年: ')
y = int(y)
print(is_leap(y))
|
625086292e7df6169fd0029150706ea71f67c7bc | Nermeen3/Python-Practice | /Merge Sort Recursion.py | 1,444 | 4.40625 | 4 | ### Merge sort: works by dividing the array into halves and each half into another half
### until we're left with n arrays each holds one element from the original array
### then we go back up by comparing arrays and sorrting them as we go up
### time complexity is O(nlogn)
### Auxillary space is O(n)
from random impo... |
597e0f369d8f1fc8948642515925b2b37d69aafb | christopher-henderson/501 | /assignment5/knapsack.py | 889 | 3.765625 | 4 | from time import time
def knapsack(max_size, items):
known = [None for _ in range(max_size + 1)]
known[0] = 0
def knapsack_closure(size):
known[size] = known[size] if known[size] is not None else max(
item[1] + knapsack_closure(size - item[0]) if
size - item[0] >= 0 else 0... |
761d028f12ce52d7b4893506879955c25c7037b0 | ThushanthaSanju/Algorithm-Python | /BubbleSort.py | 374 | 4.46875 | 4 | array1 = []
for v in range(8):
array1.append(int(input("Enter the number : ")))
print(array1)
def bubbleSort(array):
n=len(array)
for i in range (0,n):
for j in range(n-1,i,-1):
if array[j]<array[j-1]:
array[j],array[j-1] = array[j-1],array[j]
bubbleSort(array1)
print... |
cc35fdcb39ec8d8d70e9bbc4d325fadfecba12cb | thaynagome/teste_python_junior | /teste_1015.py | 656 | 4.15625 | 4 | #!/usr/bin/env python
# -- coding: utf-8 --
#Importa a biblioteca para a raiz quadrada
import math
#Solicitará em uma linha a inserção dos valores em uma linha
x1,y1 = input("Digite os valores de x1 e y1: ").split(" ")
# Converte os valor para flutuantes
x1 = float(x1)
y1 = float(y1)
#Solicitará em uma linha a i... |
f46ab39b3d768e73922c1d09ec115c9e92c566b8 | arriolac/Project-Euler | /problem19.py | 1,318 | 4.25 | 4 | def is_leap_year(year):
return year % 4 == 0 and ((year % 400 == 0) or (year % 100 != 0))
def num_days_for_year(year):
num_days_in_feb = (29 if is_leap_year(year) else 28)
return (4 * 30) + (31 * 7) + num_days_in_feb
def num_days_for_month(month, year):
if month == 2:
return (29 if is_leap_y... |
0bbbeed4ea65d0ecdff72a113d95fd74b55139da | arriolac/Project-Euler | /problem21.py | 515 | 3.703125 | 4 | import math
def sum_divisors(n):
total = 1
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
total += i
total += (n/i)
return total
def main():
pairs = set()
for a in range(1, 10000):
if a not in pairs:
b = sum_divisors(a)
if a !... |
7e7f91cba3896b50f784d2a7a24ed39c7cd1ab44 | ioduduk/doraemon | /min_transform/min_transform.py | 667 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def F(a, b, tmp={}):
if not a:
return len(b)
if not b:
return len(a)
if a == b:
return 0
if (a, b) in tmp:
print("(%s, %s) in tmp" % (a, b))
return tmp[(a, b)]
if a[-1] == b[-1]:
result = F(a[0:-1], b[... |
3a69b93e588b557ab32e1259ff71733042076cc8 | Inviernos/BasicGameEngine | /pyGameEngine.py | 6,818 | 3.59375 | 4 | import pyglet
import math
#Keyboard Constants
K_UP = pyglet.window.key.UP
K_DOWN = pyglet.window.key.DOWN
K_RIGHT = pyglet.window.key.RIGHT
K_LEFT = pyglet.window.key.LEFT
#Constants
UP=0
DOWN = 1
LEFT = 2
RIGHT = 3
#Boundary Action Constants
WRAP = 0
DIEOFFSCREEN = 1
UNBOUNDED = 2
#The user can... |
e8770affa4a508e485b3d895ef0515595ed133dc | TeamAutoMod/Toolbox | /toolbox/timer.py | 881 | 3.796875 | 4 | import threading
import time
from typing import Callable, Union
class Timer(threading.Thread):
"""
A basic timer that works like setInterval in JavaScript
To start a timer, run the `start()` method on the class
This subclasses from `threading.Thread`
Parameter
---------
callback : `Calla... |
d9645fb15f8e1b5e4c6519da2728ed67b66a347c | oliviaross/miniature-octo-computing-machine | /python/multiplesOf5And3.py | 855 | 3.671875 | 4 | '''
--------------------------------------------------------
PROBLEM ONE
------------
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of
these multiples is 23. Find the sum of all the multiples
of 3 or 5 below 1000.
https://projecteuler.net/problem=1
----------... |
037697a3032c968b4877116764d5af20ad1ed0c5 | Pedro-B-Alves/Reajustando-o-salario | /exe.1.py | 329 | 3.8125 | 4 | salario=float(input("Digite o salário que você tem: "))
if salario<500:
print("O novo salário é de", salario+0.15*salario, "Reais.")
elif salario>=500 and salario<1000:
print("O novo salário é de", salario+0.1*salario, "Reais.")
elif salario >1000:
print("O novo salário é de", salario+0.05*salario, "Reais."... |
2c209124259f582722a9ad9a9989470c4d97f9f9 | TwoShot22/Likelion_BoostCourse | /File_Compression/Look_And_Say.py | 676 | 3.65625 | 4 | line = int(input("Enter Number Of line : "))
char = "1"
output = ""
for i in range(line):
j = 0
while j < len(char):
# 문자열의 첫 문자부터 Count 시작
is_char_equal = char[j]
count = 1
# 현재 검사중인 숫자와 다음 숫자가 동일할 때 Count를 증가시키는 조건문
while j+1 < len(char) and is_char_equal == char[j+1]:... |
39351a74c9a0e7e20d2fd64e10982fdd2cd0611b | ospupegam/for-test | /Processing_DNA_in_file .py | 570 | 4.28125 | 4 | '''
Processing DNA in a file
The file input.txt contains a number of DNA sequences, one per line. Each sequence starts with the same 14 base pair fragment – a sequencing adapter that should have been removed.
Write a program that will
trim this adapter and write the cleaned sequences to a new file
print the length of... |
df627b90b594cd0caef201a7a25726c1cbc78797 | vanditagoyal1997/operator-precedence-grammar | /stack.py | 225 | 3.703125 | 4 | class stack():
def __init__(self):
self.st=[]
self.top=-1
def push(self,a):
self.st.append(a)
self.top+=1
def pop(self):
if self.top==-1:
return("empty")
else:
b=self.st.pop()
self.top-=1
return(b)
|
c081de53eeb0a40cfb2e23a31e3fb03e7fa743a3 | bestzye/CEZ_pohovor | /EURCZK_conversion_rate.py | 1,271 | 3.703125 | 4 | import datetime #time stamp
import time #function sleep
import pandas as pd #pandas data analysis, csv
from yahoofinancials import YahooFinancials #info from Yahoo!Finance
ticker = "EURCZK=X"
csv_name = "EURCZK_conversion_rate.csv"
yahoo_currency_rate = YahooFinancials(ticker)
def time_stamp():
'''creates a time... |
7650c8db58ef6be1c8b08967139c3148a832e7a1 | DanglaGT/code_snippets | /pandas/statistic_summary.py | 555 | 3.625 | 4 | # the describe() function shows a quick statistical
# summary of your dataframe (numeric values only)
import pandas as pd
# using a dictionary to create a pandas dataframe
# the keys are the column names and the values are the data
df = pd.DataFrame({
'gender': ['Male', 'Male', 'Female', 'Male', 'Female'],
'a... |
566e05e99024a9a86095738523f5ad0522c41da1 | DanglaGT/code_snippets | /pandas/operations_on_columns.py | 303 | 4.15625 | 4 |
import pandas as pd
# using a dictionary to create a pandas dataframe
# the keys are the column names and the values are the data
df = pd.DataFrame({
'x': [1, 3, 5],
'y': [2, 4, 6]})
print(df)
# adding column x and column y in newly created
# column z
df['z'] = df['x'] + df['y']
print(df)
|
c0cea824ff38c3659024de3f8136746c2b5d6223 | Ern-st/advent_of_code_2017 | /4/check.py | 684 | 3.9375 | 4 | #!/usr/bin/env python
f = open("input.txt")
input = f.readlines()
passwordCandidates = [line.rstrip().split(" ") for line in input]
validPasswords = len(passwordCandidates)
print "part 1: candidates " + str(validPasswords)
for password in passwordCandidates:
if len(password) != len(set(password)):
validPasswords ... |
8ad0c59c85f6c9d4d22a3744981d39f9f7033e68 | robbieswan/cse210-tc04 | /hilo/game/cards.py | 1,351 | 4.03125 | 4 | class Cards:
"""
The 'Cards' class will be the stack of cards in the deck. It will have
all 52 cards from their respective suits. This inteded to be used by
the 'Dealer' so that it has cards to choose from.
Attributes:
deck: A list of all 52 cards in a deck.
last_card: reme... |
c6dd52dc9c6f3ff0711c27cfe6acc4f4eaedffdd | jmccutchan/python_snippets | /generator.py | 1,386 | 4.1875 | 4 | #This example uses generator functions and yields a generator instead of returning a list
#use 'yield' instead of 'return' - yield a generator instead of returning a list, this consumes less memory
def index_words(text):
if text:
yield 0
for index, letter in enumerate(text):
if letter == ' ':
... |
bffcc275e781c951645a44f0e9b291d075461f1b | raufkarakas/PythonExercises | /9_randomQuoteGenerator/randomQuoteGenerator.py | 2,431 | 3.765625 | 4 | __author__ = 'rkarakas'
import random
def randomQuoteGenerator():
sentences = """A telephone, or phone, is a telecommunications device that permits two or more users to conduct a
conversation when they are too far apart to be heard directly. A telephone converts sound, typically and most
efficiently the h... |
3544c040c9604f847765b7a74041c59ff6b1cb27 | FabianoBill/Estudos-em-Python | /jogo_nim.py | 2,599 | 3.84375 | 4 | def computador_escolhe_jogada(n, m):
comp_retira = 1
while comp_retira <= m:
r = n - comp_retira
if r % (m + 1) == 0:
print(f"O computador tirou {comp_retira} peça(s).")
return comp_retira
comp_retira += 1
comp_retira = m
print(f"O computador tirou {comp_r... |
01a3983ad06be499932f3b89cf27a63d49239c6a | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d103_ficha_jogador.py | 444 | 4.34375 | 4 | # Exercício Python 103: Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente.
def ficha(j="<desconhecido>", g=0):... |
5d25b7f11594efecde8c32383658f942ce0b8f37 | FabianoBill/Estudos-em-Python | /Exercicios/Contagem-caracteres-dicionario.py | 1,370 | 4.125 | 4 | def contar_caracteres(s):
"""Função que conta os caracteres de uma string
Ex:
>>> contar_caracteres('banana')
{'b': 1, 'a': 3, 'n': 2}
:param s: string a ser contada
"""
resultado = {}
for caracter in s:
# contagem = resultado.get(caracter, 0)
# contagem += 1
#... |
3d7c3c40434bd6acb88da21eb61b8ae57ca9bedf | FabianoBill/Estudos-em-Python | /teste.py | 373 | 3.546875 | 4 | def maior(probabilidades):
# for indice in range(0, len(textos)):
# as_b = calcula_assinatura(textos[indice])
# probabilidades.append(compara_assinatura(ass_cp, as_b))
for indice, valor in enumerate(probabilidades):
if valor == max(probabilidades):
return indice + 1
probabil... |
bd190ff7638072ae4befb62e0c73c880d61bb371 | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d073_times.py | 576 | 4.21875 | 4 | # Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times.b) Os últimos 4 colocados.c) Times em ordem alfabética.d) Em que posição está o time da Chapecoense.
times = ("a", "e", "i", "o", "u... |
a4fa802993bf870d74d1b1510f8ff32f508ecd0b | FabianoBill/Estudos-em-Python | /Coursera/ex2.3.py | 246 | 3.984375 | 4 | # Receba um número inteiro na entrada e imprima Buzz se o número for divisível por 5. Caso contrário, imprima o mesmo número que foi dado na entrada.
n = int(input("Digite um número: "))
if n % 5 == 0:
print("Buzz")
else:
print(n)
|
6b15856efe6aabec9c69941a37163a8525d17d7d | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d052_num_primo.py | 307 | 3.765625 | 4 | # Exercício Python 52: Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
n = int(input("Digite um número inteiro: "))
co = 0
for c in range(1, n + 1):
if n % c == 0:
co += 1
if co == 2:
print(f"{n} é primo.")
else:
print(f"{n} não é primo.")
|
a6e091a1521b10fda7f78763f5c2cab15a5071cb | FabianoBill/Estudos-em-Python | /matematica/primos.py | 836 | 3.734375 | 4 | def maior_primo(n):
""" Recebe n >= 2 e devolve o próximo número primo > n.
Ex:
>>> maior_primo(7)
11
>>> maior_primo(25)
29
:param n: number
:return: number
"""
while n >= 2:
c = 0
p = n + 1
while 1 <= p <= n + 1:
if (n + 1) % p == 0:
... |
027b0e68c4d465c6205958003e387023c8158722 | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d55_maior_menor_5.py | 438 | 3.84375 | 4 | # Exercício Python 55: Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos.
maior = 0
menor = 0
for c in range(1, 6):
p = float(input(f"Digite o peso da {c}ª pessoa: "))
if c == 1:
maior = p
menor = p
else:
if p > maior:
... |
42fd336b56a83f68c5d05f22818c28d39b67f195 | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d095_futebol2.py | 1,561 | 4.125 | 4 | # Exercício Python 093: Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o c... |
4cc1f98c0942117be944787f90e1289d382daf3d | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d056_média_velho_mulheres20.py | 709 | 3.796875 | 4 | # Exercício Python 56: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos.
soma = 0
menos20 = 0
maisvelho = 0
nomevelho = ""
media = 0
for c in range(1, 5):
nome = inpu... |
e9c5c126fbd46a8cd039645207842bd60bbd5988 | FabianoBill/Estudos-em-Python | /Coursera/ex2.1.py | 224 | 4 | 4 | # Receba um número inteiro na entrada e imprima
# par quando o número for par ou ímpar quando o número for ímpar.
n = int(input("Digite um úmero inteiro: "))
if n % 2 == 0:
print("par")
else:
print("ímpar")
|
b5a4675e7b252d58079c48e760ebfe623a8cbecd | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d099_maior.py | 477 | 4.25 | 4 | # Exercício Python 099: Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior.
def maior(* prmt):
c = max = 0
for valor in prmt:
if c == 0:
max = valor
els... |
793bab6ce8192a35c8542dd7d9389de767185276 | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d072_por_extenso.py | 631 | 3.96875 | 4 | # Exercício Python 72: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.
l = ("Zero", "Um", "Dois", "Três", "Quatro", "Cinco", "Seis", "Sete", "Oito", "Nove", "Dez")
while Tr... |
aa88860ce4c7dfc9fbc0f7172e4a95cc5e050283 | FabianoBill/Estudos-em-Python | /Curso-em-video/115-exerciciospython/d088_megasena.py | 592 | 4.09375 | 4 | # Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA a criar palpites.O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta.
from random import randint
j = int(input("Quantos jogos você deseja sortear? "))
... |
a9dcb1d6a8040b4028960ba380f6f5deba70dd34 | elicegreen/week4-tic-tac-toe | /ticTacToe.py | 5,797 | 4.125 | 4 | ########################################################
# This function displays the game board on the screen. #
########################################################
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
... |
520f0ceb87c598168cc1b3bb8521317e626e9a0c | naveenkunareddy/cs231n.assignments | /2016winter/assignment1/cs231n/classifiers/softmax.py | 3,789 | 3.890625 | 4 | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X:... |
88d90565463656c4f4405e9862f47403a51d8ce8 | lwz7512/gleyeserver | /dboperate.py | 4,092 | 3.875 | 4 | # -*- coding: utf-8 *-*
"""
insert, modify, delete, query, VACUUM
2012/09/26
"""
import sqlite3
class SqliteQuery:
def __init__(self, dbName):
self.dbName = dbName
self.con = sqlite3.connect(dbName)
self.cur = self.con.cursor()
def __del__(self):
try:
sel... |
d8a40076448e996ed54e1d75062ad93645a344b0 | MiyainNYC/Rose | /CodeON/sort.py | 752 | 3.515625 | 4 | l = [3,4,88,1,4,5,0,3]
## divide and conquer
def qsort(array):
if len(array) < 2:
return array
head, *tail = array
less = qsort([i for i in tail if i < head])
more = qsort([i for i in tail if i >= head])
return less+[head]+more
def sort_list(l):
sorted_list = [None]*len(l)
leng = ... |
3b8f47c9b97133f8d8d8557747b8d3e9c6322e3f | MiyainNYC/Rose | /CodeON/max.py | 522 | 3.5 | 4 | l = [7,6,8,22,6,9]
def max_find(array):
if len(array) ==1:
return array[0]
head = array[0]
more = max_find([i for i in array[1:] if i > head]+[head])
return more
max_value = max_find(l)
print(max_value)
def find_min(k,array):
if len(array)<=k:
return array
head = array[0]
... |
7c686477574842100495712a0c4317739c113ce5 | patorres61/prg105-Inheritance | /officeFurniture.py | 4,308 | 4.21875 | 4 | # Phyllis Torres
# Module 13: Inheritance
# Due 12/2/2016
# The office furniture class holds general information
# about office furniture items for sale
# it will be the parent class for desks, chairs, filling cabinets, etc.
class Furniture(object):
"""
accepts category, material, length, widt... |
add8943f93429e1f5dbdc7ead0ed78ece143a3b2 | zwh18123/Peter-python | /Polygon.py | 1,214 | 3.875 | 4 | import math
import itertools
from Point_1 import Point
class Polygon(object):
def __init__(self,points):
self.vertices=points
def translate(self,a=0.0,b=0.0):
for p in self.vertices:
Point.translate(p,a,b)
def scale(self,sx=0.0,sy=0.0):
for p in self.vertices:
... |
59538b5a2fcdcdd9e83fd5421ec93fd6d10c2fa7 | Amit-007/pythonTutorials | /PythonTutotials/ControlFlow.py | 1,835 | 4.09375 | 4 |
# IF Statements
print('Control Flow Statements : IF Statements')
x = int(input("Please enter a number : "))
if x < 0:
x = 0
print("X was negatie so its changed to 0")
elif x == 0:
print("Zero")
elif x == 1:
print("One")
else:
print(x)
# For Loops
print("For Loops")
for num in range(0, 10):
... |
7f2cd9f807349b48ecce6f648c8662ae5b467adc | he-grace/Python_challenge | /PyBank_GHF.py | 1,242 | 3.703125 | 4 | import csv
#1st Answer
count = len(open("C://Users//grace//Desktop//TECMC201902DATA2//02-Homework//03-Python//Instructions//PyBank//Resources//budget_data.csv").readlines( ))
print(count)
#2nd Answer
csvpath = "C://Users//grace//Desktop//TECMC201902DATA2//02-Homework//03-Python//Instructions//PyBank//Resource... |
6619d23aad4c075f32a56267110ea0e44ac1d5df | wiratmo/Python-Projects-Protek | /Praktikum 05/Latihan 2/Lat4.py | 163 | 3.640625 | 4 | kolom = 5
baris = 5
i = 0
while (i < kolom):
j = 1
while (baris - j >= i):
print('*', end='')
j += 1
print('')
i += 1
|
9b39f51f148403285a240b6b5b696539c79aa2fd | wiratmo/Python-Projects-Protek | /Praktikum 04/Latihan4.py | 574 | 3.6875 | 4 | import math
print("Pak Amir Menempuh Waktu kota A ke C adalah ?")
print("=======================================")
waktuAwal = int(6)
waktuJeda = int(45)
jarakAB = int(125)
jarakBC = int(256)
Kecepatan1 = int(62)
Kecepatan2 = int(70)
waktuAB = (jarakAB / Kecepatan1)
waktuBC = (jarakBC / Kecepata... |
8a4c007a288f72aa76d74c805583fc2f97add128 | wiratmo/Python-Projects-Protek | /Praktikum 08/Project6.py | 697 | 3.828125 | 4 | Data = []
inpBuah = int(input("Masukan jumlah buah : "))
def sortStringByChar(Data):
angkaBuah = 0
while True :
for angkaBuah in range (0, inpBuah):
angkaBuah += 1
posisiKe = str(input("Masukan Nama Buah ke-" + str(angkaBuah) + " = "))
Data.append(posisiKe)
... |
6c75191f7c71f85a32d1a127d3eebed638dab65a | wiratmo/Python-Projects-Protek | /Praktikum 05/Latihan 2/Lat6.py | 1,069 | 3.78125 | 4 | import random
rentangAngka = random.randint(0,100)
print("---------------Game Tebak Angka Mr.Sekuyy---------------")
print("Hai.. nama saya Mr. Sekuyy, saya telah memilih sebuah bilangan bulat secara acak antara 0 s/d 100. Silakan tebak ya!!! semoga beruntung")
print("----------------------------------------------... |
cb49b35d1b196e2fbc8a95005fb7d003f9ec97b0 | wiratmo/Python-Projects-Protek | /Praktikum 11/Prog2.py | 910 | 3.734375 | 4 | from datetime import date
import datetime
from dateutil.relativedelta import relativedelta
print("Selamat datang di Program Input KodeMember, NamaMember, JudulBuku")
print("-"*80)
def tglBukuPinjaman(set7hari):
set7hari = date.today()
return set7hari+relativedelta(days = 7)
out = "";
while True:
... |
94b62ea6b6f7d47fe59132ada52234ad09146bc6 | wiratmo/Python-Projects-Protek | /Praktikum 05/Latihan 1/L3.py | 1,702 | 3.6875 | 4 | bIndo = int(input("masukan nilai Bahasa Indonesia => "))
MTK = int(input("masukan nilai Matematika => "))
IPA = int(input("masukan nilai IPA => "))
print("+++++++++++++++++++++++++++++++++++++++++++++++++")
if ((bIndo > 100) or (bIndo < 0) or (MTK > 100) or (MTK < 0) or (IPA > 100) or (IPA < 0)):
status ... |
4905470d3df5046af1d7b7d54fdb7b46d845be87 | wiratmo/Python-Projects-Protek | /Praktikum 07/pencarianFile(Latihan 1).py | 579 | 4.0625 | 4 | Namadarifile = str(input("Masukan nama file : "))
print("|================================================|")
print("| Program Pencarian File Anda |")
print("|================================================|")
def pencarianFile():
Namadarifile = str(input("Masukan nama file : "))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.