blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0dedcfce8f2367f6016617e07ad19ff4d74ee39e | wang-adam/MonteCarloSimulationStock | /simulator.py | 3,015 | 3.5 | 4 | # Monte Carlo simulation based on https://www.investopedia.com/terms/m/montecarlosimulation.asp
import csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import statistics as stat
from scipy.stats import norm
import math
# number of days to predict
numDays = 50
# number of monte... |
9661b306d908114d111dc509536ac225ddba9f18 | JasonLin1230/leetCode | /Algorithms/101~200/106.py | 758 | 3.65625 | 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
# 60ms 18.3M
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
ino_dict = {... |
261bb6fe44d30b1354e584979a19dc935c2d621c | aetooc/Practice-Questions-Python | /Pf Exercise/Q5.py | 170 | 3.890625 | 4 | def ftn(limit):
sum=0
for i in range(1,limit+1):
if i%3==0 or i%5==0:
sum+=i
print(i)
print("Total sum is =",sum)
ftn(20)
|
919a73a176fc5263e8759e24448371f3c893deb8 | aetooc/Practice-Questions-Python | /Programming Exercise/Q10.py | 230 | 3.65625 | 4 | def s_maxL(lst):
lst.sort() # Sorting List
length=len(lst)-2 # Length-2 because start by 0 index
return lst[length] # Returning second max value
a=[22, 5, 7, 35, 1, 21, 15]
print(s_maxL(a)) |
dcc0597d7402de5668da683e0cfddabd6f8130bc | Giova262/Algoritmos-I--Reversi | /Reversi2.1.py | 9,914 | 3.53125 | 4 | #Configuracion inicial
matriz= []
colorJugador='B'
colorPc='N'
nombre=' '
resultado=0
pasoturno=0
sinmovidas=0
libres=0
blancas=0
negras=0
#Funciones
def crear_matriz(matriz):
for i in range(10):
matriz.append( [' ']*10 )
def llenar_matriz(matriz):
for i in range(1,9):
matriz[i]... |
2fd78f9c7fd9713792a299fb68728b7d6a9263cb | joecatarata/CodeDump | /Kattis/Aaah!/aaah.py | 1,514 | 3.859375 | 4 | # Aaah!
# Jon Marius shouted too much at the recent Justin Bieber concert, and now needs to go to the doctor because of his sore throat. The doctor’s instructions are to say “aaah”. Unfortunately, the doctors sometimes need Jon Marius to say “aaah” for a while, which Jon Marius has never been good at. Each doctor requ... |
a9a24913a8d4de7786a4da5b3979b620b9833516 | joecatarata/CodeDump | /UVA/Volume 1/102.py | 2,206 | 3.5 | 4 |
def moveBottles(bins):
# largestB = 0
# largestG = 0
# largestC = 0
# currBinIndex = 0
# largestBIndex = 0
# largestGIndex = 0
# largestCIndex = 0
# for ctr in range(0,10):
# print(ctr)
# if ctr <= 2:
# currBinIndex = 0
# elif ctr > 2 and ctr <= 5:
... |
e74a87341cdd4633220bdac9bce452c7929db2e2 | hokkyss/AssymmetricCrypto | /utils/RSA.py | 2,643 | 3.703125 | 4 | # RSA Algorithm
import random
from textwrap import wrap
from typing import List
from .utils import PrimeGenerator, pow_mod, inverse_modulo
def text_to_block(message: str, n: int) -> List[int]:
digits: int = len(str(n))
messages: List[int]
try:
messages = list(map(int, wrap(message, digits)))
... |
b0f8f86cdcc179d22f305f70b40cfe3988480601 | AlexandruGG/project-euler | /25.py | 667 | 4.15625 | 4 | # The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
# The 12th term, F12, is the first term to contain three digits.
# What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
from typing import Generator
def fibonacci(a: int = 0, b:... |
38a17fa62ec65edc663c0589e1777a7cfdfe2e47 | AlexandruGG/project-euler | /7.py | 385 | 3.953125 | 4 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10001st prime number?
from sympy import isprime
def get_nth_prime(n: int) -> int:
i = prime_count = 0
while prime_count < n:
i += 1
if isprime(i):
prime_count += 1
... |
4e88c1d5ffc8edf39ab8959491b387a768bbe673 | matthew-carpenter/nplib | /strongai/machine_learning/01b_linear_regression.py | 2,107 | 3.734375 | 4 | from numpy import *
def get_gradient_descent(points, starting_b, starting_m, learning_rate, iterations):
b = starting_b
m = starting_m
for i in range(iterations):
b, m = step_gradient(b, m, array(points), learning_rate)
return [b, m]
def get_linear_regression_error(b, m, points):
total_e... |
1e2b1eaf680ac25574d2f8a1b35fda2a83adf4a7 | BioGeek/euler | /problem044.py | 1,422 | 3.8125 | 4 | # Pentagonal numbers are generated by the formula, P_n=n(3n1)/2. The first ten
# pentagonal numbers are:
#
# 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
#
# It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
# 70 22 = 48, is not pentagonal.
#
# Find the pair of pentagonal numbers, P_j and P_... |
c0136df637394c76f7e6cd424255ff9cc5fc3f96 | BioGeek/euler | /problem043.py | 1,562 | 3.703125 | 4 | # The number, 1406357289, is a 0 to 9 pandigital number because it is made up of
# each of the digits 0 to 9 in some order, but it also has a rather interesting
# sub-string divisibility property.
#
# Let d_1 be the 1st digit, d_2 be the 2nd digit, and so on. In this way, we
# note the following:
#
# d_2d_3d_4=406 i... |
8ea15c9a0c34701b1526be0ec2f7912f6293583e | BioGeek/euler | /problem230.py | 1,744 | 3.984375 | 4 | # -*- coding: utf-8 -*-
# For any two strings of digits, A and B, we define F_A,B to be the sequence
# (A,B,AB,BAB,ABBAB,...) in which each term is the concatenation of the previous
# two.
#
# Further, we define D_A,B(n) to be the n^th digit in the first term of F_A,B
# that contains at least n digits.
#
# Example:
... |
9290c9ebc58312c844b289862681dde5e3036cc1 | BioGeek/euler | /problem018.py | 2,410 | 3.90625 | 4 | # By starting at the top of the triangle below and moving to adjacent numbers on
# the row below, the maximum total from top to bottom is 23.
#
# 3
# 7 4
# 2 4 6
# 8 5 9 3
#
# That is, 3 + 7 + 4 + 9 = 23.
#
# Fin... |
0fb32e14b68fa9bdaa1bceda75646eca662b7d6d | BioGeek/euler | /problem034.py | 606 | 3.890625 | 4 | # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
#
# Find the sum of all numbers which are equal to the sum of the factorial of
# their digits.
#
# Note: as 1! = 1 and 2! = 2 are not sums they are not included.
fac = lambda n: n<=0 or reduce(lambda a,b: a*b, xrange(1,n+1))
def sum_factorial_of_digi... |
c7c9dbb7f4ffedf713be0f01bceac662f82b5f21 | alf42pac/python1 | /4.py | 285 | 3.921875 | 4 | num = input('Введите целое положительное число: ')
i = 0
max_num = int(num[0])
while( i < len(num)):
if(int(num[i]) > max_num):
max_num = int(num[i])
i = i + 1
print('Самая большая цифра в числе: ', max_num)
|
316891e13fe0e056df713ed32882e0b9d973d4e1 | alf42pac/python1 | /lesson2_4.py | 127 | 3.625 | 4 | #lesson2_4
_str = input('Enter the numbers with space - ').split()
for i, n in enumerate(_str, 1):
print(f'{i} {n[:10]}') |
75a253f3efb4c91c7a1b239f93b2c1aa5dfec1b3 | StZiza/coding-practices | /Preactice01.py | 1,414 | 3.625 | 4 | import numpy as np
from time import time
#############################################
# #
# Pencil Beam #
# #
#############################################
#I have a box size of 100 from -50 to 50.... |
a6833f60e1569288122b02d538745f8c24ea5d64 | fuyuanhao/PyGeoSpatialStudy | /SkitLearn/Reg_LinearModel.py | 3,190 | 3.75 | 4 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import os
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
#一元线性回归模型
#Linear Regression Example
#读取本地EXCEL或者CSV文件进行回归
def LinearModel(fil... |
3f102436fd1359fb0a594b601c65c37a9f909963 | daviskeene/MLPractice | /MLPractice/fedpredict.py | 579 | 3.828125 | 4 | #A program to predict the winner of the Wimbledon Finals
import random
#Set the count of wins for both
f = 0
c = 0
#Array containing both players
players = ["Cilic","Federer"]
#Count
x = 0
#Runs through 101 random simulations
while(x<101):
prediction = random.choice(players)
if prediction == "Federer":
... |
9c75908505fa83e03375189f1519df5ef8c9869f | micromag/texting-with-micropython | /demo.py | 4,480 | 3.984375 | 4 | # this imports the micro:bit-specific functions such as buttons, display, pins etc
from microbit import *
# brings in the micro:bit Bluetooth functions
import radio
# we use two tunes plus a bleep
import music
# Initialise all the global variables
# this variable is used to hold a single character at a t... |
024583a50f779c9bd58e1143864f24fe6bc28cc7 | AndrewVCoding/neuronEngine | /main.py | 946 | 3.5 | 4 | import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import random
import network
plt.style.use('ggplot')
network = network.Network()
# Create input data
data = []
x = np.linspace(0, np.pi * 2, 256)
for i in range(0, 1000):
sinx = np.sin(0.1 * i + x)
data.append(s... |
cda296416b068deab8cf6670e3bac0f86112318d | Official21A/PyCookNum | /9.NumPy/num_py.py | 1,562 | 3.984375 | 4 | # Problem 9
# When working with large numbers or vectors, mathmatical operations can take
# alot of time and space, and you might not get a correct answer.
# By using python library "numpy" we can save alot of time and space.
# Python lists
x = [1,2,3,4]
y = [5,6,7,8]
x * 2 # [1,2,3,4,1,2,3,4] not what we wanted
x + ... |
57458882a89d3d2e4aca535d1b27ef343b0b394b | Lowton/grokking-algorithms | /scripts/Chapter 3/factorial.py | 217 | 3.921875 | 4 | def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
print(f'2! = {factorial(2)}')
print(f'5! = {factorial(5)}')
print(f'0! = {factorial(0)}')
print(f'10! = {factorial(10)}')
|
8465ce2372f6744412705e07bd68a667b72c20d0 | Lowton/grokking-algorithms | /scripts/Chapter 4/array_sum.py | 231 | 3.625 | 4 | from random import randrange as rand
def sum(arr):
if len(arr) == 1:
return arr[0]
else:
return arr.pop(0) + sum(arr)
arr = [rand(10) for i in range(rand(10))]
print(f'For array {arr} sum is {sum(arr)}')
|
59cde930fc9d4eaab3601eac9af6fd027822b26c | kallyrhodes/LIS4930 | /Module #5.1.py | 158 | 3.75 | 4 | def insert_sting_middle(str, word):
length=len(str)//2
s=str[:length] + word + str[length:]
return s
print(insert_sting_middle('[[]]', 'Python'))
|
9cd3475f7ded74dbfcd625756f498228d38f998d | rathiinitesh/assignment | /assignment.py | 594 | 4.3125 | 4 | """
This is if the array is of length greater than 2 because otherwise there will not be an upper and lower bound
since its not mentioned whether its just a positive or negative integer array and even after that there will be
some concerns. So, I will be returning the array as it is.
Also, in case there is no element ... |
7e3c37e7dc858115bd12c3d7d81b360678e3e66a | uglyduck/github-upload | /new 100.py | 1,678 | 3.765625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import random
def function_move(position):
pos = position;
n=random.randint(1,6)
move=int(n)
moved = np.array([0,0,0])
if move == 1:
pos_current=pos+np.array([0,1,0])
#print ("moved UP, Current Position ",pos_current)
if move == 2:
pos_current=pos+np.ar... |
25d1201e916012d5cb75ed9a635ffbb426d26ba5 | Lennart99/ASM-interpreter | /interpreter/nodes.py | 2,479 | 3.5 | 4 | from enum import Enum
class Node:
class Section(Enum):
TEXT = 0
BSS = 1
DATA = 2
# No __str__ implemented because Enum implements it itself
def __init__(self, section: Section, line: int):
self.section: Node.Section = section
self.line: int = line
def __st... |
a34fd9280ca6c6185bb939d3406beb5494f67c53 | Aggelosborlokas/PYTHON-PROJECTS | /ergasia4.py | 2,129 | 3.71875 | 4 | def times(x):
x = str(x) + "*"
return x
def minus(x):
x = str(x) + "-"
return x
def plus(x):
x = str(x) + "+"
return x
def chooseoperation(y, calc, number):
if calc == "*":
return number * y
elif calc == "-":
return y - number
elif calc == "+":
return nu... |
87314b479673cfd3de736f8307f315c8c00e6821 | mjggibson4/Practical1 | /framework.py | 9,405 | 4.4375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Script which defines the properties and behaviours of the wolves and sheep
agents within the population model.
This script sets up a generic agent class. This defines how the agents move
within the model. Leave one blank line. The rest of this docstring shoul... |
2191f3d7ef7d976d5c669772572b4d9b6938b520 | Cool-Codey/Calculator-by-Codey-using-Python | /main.py | 408 | 4.21875 | 4 | a=int(input("Enter the first number:\n"))
op=input("Enter the operation you want to perform(+,-,*,/):\n")
b=int(input("Enter the second number:\n"))
if op=="+":
print(f"{a} + {b} = {a+b}")
elif op == "-":
print(f"{a} - {b} = {a-b}")
elif op =="*":
print(f"{a}*{b} = {a*b}")
elif op =="/":
... |
7eb195477311c83ed73d570643afae38a5a29557 | xubojoy/python-study | /day11/温度转换.py | 361 | 3.921875 | 4 | #Author:xubojoy
fahrenheit = 0
while fahrenheit <= 250:
celsius = (fahrenheit - 32) / 1.8
print('%5d %7.2f' % (fahrenheit,celsius)) #等价于print('{:5d} {:7.2f}'.format(fahrenheit, celsius)) #%5d 或者 {:5d} 默认保留5个位置的整数 %7.2f或者{:7.2f} 默认占7个单位的保留两位小数的浮点型
fahrenheit = fahrenheit + 25
|
c60af54a46cfffa1177892c6a0c9d7f8456f2758 | xubojoy/python-study | /pyimage/Animal.py | 437 | 3.5625 | 4 |
class Animal(object):
def run(self):
print('Animal is running.....')
class Dog(Animal):
def run(self):
print('Dog is running......')
dog = Dog()
dog.run()
def run_twice(animal):
animal.run()
animal.run()
run_twice(Animal())
run_twice(Dog())
print(type('abc') == str)
import t... |
4c793a19553a65eac16f32eb27efc0319a39f08b | xubojoy/python-study | /python/s14/guess.py | 459 | 3.828125 | 4 | #Author:xubojoy
num = 50
count = 0
while count < 3:
guess_num = int(input('age:'))
if guess_num == num:
print('you got it !')
break
elif guess_num > num:
print('猜大了!')
else:
print('猜小了!')
count = count + 1
if count == 3:
countine_confirm = input('do you w... |
e329e3f6b740b3c8852821c98a3714124fb70e57 | xubojoy/python-study | /python/learn_22.py | 973 | 3.765625 | 4 | Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> def factorial(n):
if n == 1:
return 1
else:
return n *factorial(n-1)
>>> def factorial(n):
if n == 1:
return 1
else:
return... |
403da953b9facd97b4cc3b07b01fc8c213d60eff | xubojoy/python-study | /python/s21/day6/学校.py | 2,083 | 3.84375 | 4 | #Author:xubojoy
class School(object):
def __init__(self,name,addr):
self.name = name
self.addr = addr
self.students = []
self.staffs = []
def erroll(self,stu_obj):
print('%s学员注册成功'% stu_obj.name)
self.students.append(stu_obj)
def hire(self,staff_obj):
... |
e6dc40306c4d85e3529d6f2683b77413edc93309 | xubojoy/python-study | /python/s14/copys.py | 269 | 3.53125 | 4 | #Author:xubojoy
import copy
names = ['lilei','hanmei',['lll','rrrr']]
#深拷贝
names2 = copy.deepcopy(names)
#浅拷贝2中方式 只拷贝一层
#1
#names2 = copy.copy(names)
#2
#names2 = names[:]
names[1] = 'HANMEI'
names[2][0] = 'KKKKK'
print(names)
print(names2) |
7c0b8c30e11af90c2c2016e8bd92ec43565481f0 | open-eio/mock_upython_server | /mock_machine.py | 566 | 3.578125 | 4 | DIRECTION_IN = 0
class Pin(object):
IN = DIRECTION_IN
def __init__(self, i, direction = DIRECTION_IN):
self._i = i
self._direction = direction
self._value = False
def __str__(self):
return str(self._i)
def value(self):
return self._value
def __setattr__(self... |
c1c6e42ed3f57db1fa2b743f4f5505c3fb97279a | dghuang/Euler_Problems | /Euler Problem 7.py | 303 | 3.78125 | 4 | #find the 10000th prime number
prime_list = [2]
number_of_primes = 0
current_number = 3
while number_of_primes <= 10000:
y = 0
for x in prime_list:
if current_number % x == 0:
break
else:
prime_list.append(current_number)
number_of_primes += 1
current_number += 2
print prime_list[10000] |
e536dce9983df7abb56b2710deb2314907209a6a | dghuang/Euler_Problems | /Euler Problem 40.py | 427 | 3.671875 | 4 | #an irrational decimal is created by concatenating every consecutive number from 1 onwards
#ie. 0.123456789101112, etc.
#if dn is the nth digit, find d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000
dec = ""
counter = 1
while len(dec) < 1000000:
dec = dec + str(counter)
counter += 1
prod = int(dec[0]) * ... |
3bf30e7084e8485ddf2ce0fc2408d0038d5a2d12 | dghuang/Euler_Problems | /Euler Problem 14.py | 522 | 3.859375 | 4 | #collatz sequence: given a starting number, if it is even, divide by 2, if odd, 3n + 1
#if all collatz sequences end at 1 find the largest chain of numbers under a million
longest_chain = 0
for number in range (1, 1000000):
chain_length = 0
term_value = number
while term_value != 1:
if term_value % 2 == 0 and ter... |
1d8a9996dd7b61e8c4a967ebab67fe0d9af0fc98 | tcoenraad/rolit | /rolit/leaderboard.py | 1,513 | 3.703125 | 4 | class Leaderboard(object):
def __init__(self):
self.scores = []
def add_score(self, name, date, score):
self.scores.append(self.Score(name, date, score))
def scores_per_player(self):
if len(self.scores) == 0:
raise NoHighScoresError("No high scores available")
... |
9328a6259741e5c8ae964241725a0920f05959a7 | chulanovskyi/hackerrank | /30_code/25_prime_complexity.py | 302 | 4.09375 | 4 | from math import sqrt
T = int(input())
n = [int(input()) for i in range(T)]
for num in n:
if not num % 2 and num > 2 or num == 1:
print('Not prime')
continue
if all(num % i for i in range(3, int(sqrt(num)) + 1, 2)):
print('Prime')
else:
print('Not prime')
|
e7b7fca8645c0b6788bdb9eda5e80bc0ecf57ebe | AndreRdz7/MachineLearning | /KNN/otherknn.py | 2,039 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
K Nearest Neighbours (no dataset)
@author: David André Rodríguez Méndez (AndreRdz7)
"""
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
import warnings
from math import sqrt
from collections import Counter
import random
... |
a239c82146fa8b48128c13a0cac02682f08fae6c | TommyN99/Hello-word | /Session8p1.py | 128 | 3.734375 | 4 | def main():
x = 2
y = 3
def mystery(x,y):
result=(x+y)/(y-x)
return result
print(mystery(2,3))
main()
|
51b071bacaf885b601388a1b1199c401afd1ea88 | TommyN99/Hello-word | /Session8p4.py | 190 | 3.765625 | 4 | def main():
page = int(input("Enter number of pages:"))
if page % 2 == 0:
print("")
else:
print("%60s%d" % (" ", page))
main()
|
08bcd9572ea2e5029adaf90b2d576daabb495793 | boscotron/Rele-4 | /test.py | 1,161 | 3.703125 | 4 | #obteniendo la biblioteca principal de GPIO
import RPi.GPIO as GPIO
#obtener la biblioteca de tiempo
import time
# configurando un modo actual
GPIO.setmode(GPIO.BCM)
#eliminando los warings
GPIO.setwarnings(False)
#creando una lista (matriz) con el numero de GPIO que usamos
pins = [18,17,15,14]
#establec... |
616be9e2b98bebbc4600e6ce300c017f05e67d87 | danial1021/python-study | /py_file/class/class1.py | 970 | 4 | 4 | class Quadrangle:
width = 0
height = 0
color = "black"
#사각형 넓이
def get_area(self):
return self.width * self.height
#사각형 width, height 설정
def set_area(self, data1, data2):
self.width = data1
self.height = data2
square = Quadrangle()
square.set_area(5, 5) ... |
ba2a6ac65ee4fc574d97b9d50ecb50fb3a2387ab | arthurdysart/LeetCode | /0609_find_duplicate_file_in_system/python_source.py | 2,164 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Find Duplicate File in System
https://leetcode.com/problems/find-duplicate-file-in-system
Created on Tue Nov 27 22:11:24 2018
@author: Arthur Dysart
"""
# REQUIRED MODULES
from collections import defaultdict
import sys
# FUNCTION DEFINITIONS
class Solution:
... |
3b4e9b2c326c5af7e7021de7d27af5a7d0f64da2 | arthurdysart/LeetCode | /0784_letter_case_permutation/python_source.py | 2,501 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Letter Case Permutation
https://leetcode.com/problems/letter-case-permutation
Created on Fri Nov 30 22:20:04 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
from collections import deque
import sys
## MODULE DEFINITIONS
class Solution:
"""
Breadt... |
c47745b6e41aa1333fa71a2dcc9029519c332fe7 | arthurdysart/LeetCode | /0771_jewels_and_stones/python_source.py | 1,700 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Jewels and Stones
https://leetcode.com/problems/jewels-and-stones
Created on Thu Nov 22 10:59:49 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
import sys
## MODULE DEFINITIONS
class Solution:
"""
Iterative search of dynamic window over string.
... |
32b1544503f3e0135a45c71be54e62351e7a252a | arthurdysart/LeetCode | /0565_array_nesting/python_source.py | 5,831 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Array Nesting
https://leetcode.com/problems/array-nesting
Created on Sun Dec 2 15:42:26 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
import sys
## MODULE DEFINITIONS
class Solution:
"""
Iteration over all elements and nesting cycles.
Ti... |
667d159440f043f5346a6ee126b7a0007bbd03a3 | arthurdysart/LeetCode | /0951_flip_equivalent_binary_trees/python_source.py | 6,312 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Flip Equivalent Binary Trees
https://leetcode.com/problems/flip-equivalent-binary-trees/
Created on Sun Dec 2 19:46:25 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
from python_util import TreeNode
import sys
## MODULE DEFINITIONS
class Solution:
"... |
64434fbe764f20ed5610b6db11948b5b454c5568 | arthurdysart/LeetCode | /0954_array_doubled_pairs/python_source.py | 3,396 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Array of Doubled Pairs
https://leetcode.com/problems/array-of-doubled-pairs
Created on Sat Dec 8 23:56:50 2018
@author: Arthur Dysart
"""
# REQUIRED MODULES
from collections import defaultdict
import sys
# FUNCTION DEFINITIONS
class Solution:
"""
It... |
433e1110824f14068678a7f050050a3a3c1d4b41 | arthurdysart/LeetCode | /0941_valid_mountain_array/python_source.py | 1,980 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Valid Mountain Array
https://leetcode.com/problems/valid-mountain-array
Created on Sun Nov 18 17:24:12 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
import sys
## MODULE DEFINITIONS
class Solution:
"""
Traverse all elements of array.
Time... |
05be49c9e24df0de8bf979349fc1fc5e36b17743 | arthurdysart/LeetCode | /0867_transpose_matrix/python_source.py | 3,120 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Transpose Matrix
https://leetcode.com/problems/transpose-matrix
Created on Fri Nov 23 11:13:48 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
import sys
## MODULE DEFINITIONS
class Solution:
"""
Iteration over all elements of 2D array.
Tim... |
dff3ca9a1108fbc2db2bf97c5f8b3ac8ec1ac5d8 | arthurdysart/LeetCode | /0026_remove_duplicates_sorted_array/python_source.py | 1,201 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Remove duplicates from sorted array
https://leetcode.com/problems/remove-duplicates-from-sorted-array
Two pointers (forwarding) solution
Created on Fri Nov 2 21:57:17 2018
@author: Arthur Dysart
"""
# REQUIRED MODULES
import sys
# FUNCTION DEFINITIONS
class Solution:
def ... |
4132c22dce0f7f35bd8dbee0b16054df539295d1 | arthurdysart/LeetCode | /0200_number_islands/python_source.py | 2,551 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Number of Islands
https://leetcode.com/problems/number-of-islands
Recursive depth-first-search solution
Created on Sat Nov 10 16:29:52 2018
@author: Arthur Dysart
"""
# REQUIRED MODULES
import sys
# FUNCTION DEFINITIONS
class Solution:
"""
Time complexity: O(r * c)
... |
b6b2ad4835fe7a6c69267c549568df8c44cccb38 | arthurdysart/LeetCode | /0890_find_and_replace_pattern/python_source.py | 2,751 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Find and Replace Pattern
https://leetcode.com/problems/find-and-replace-pattern
Created on Fri Nov 23 00:18:48 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
from collections import defaultdict
import sys
## MODULE DEFINITIONS
class Solution:
"""
... |
1c7b3b4f10618f0de22c6ad711ca29a85db2350f | phprandom/python | /ex7.py | 529 | 3.75 | 4 | print "Mary had a little lamb."
print "Its fleece was white as %s." % 'snow'
print "And everywhere that Mary went."
print "." * 30 # what'd that do?
end1 = "C"
end2 = "h"
end3 = "a"
end4 = "i"
end5 = "n"
end6 = "s"
end7 = "m"
end8 = "o"
end9 = "k"
end10 = "e"
end11 = "e"
end12 = "r"
# watch that comma at the end. t... |
2d374ed74387c0a255c41bd2613cc06bb3626a27 | PickertJoe/algorithms-data_structures | /Chapter4_Recursion/sierpinski_triangle.py | 1,440 | 4.09375 | 4 | # A recursive program to create a Sierpinski Triangle using the Turtle graphics package
# Base code sourced from Miller and Ranum's Problem Solving with Algorithms & Data Structures Using Python
from turtle import *
def drawTriangle(points, color, myTurtle):
myTurtle.fillcolor(color)
myTurtle.up()
myTurt... |
12e9adbdaf017e2c0f6d13ffe50f3bdbf62558f8 | PickertJoe/algorithms-data_structures | /Chapter3_Basic_Data_Structures/queue_class.py | 722 | 3.9375 | 4 | # A representation of a Queue data structure as modeled in the text
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def siz... |
44bbf820dfbd4da11fc55c5ff3e5432c44d50e7b | PickertJoe/algorithms-data_structures | /Chapter3_Basic_Data_Structures/print_queue_simulation.py | 1,202 | 3.734375 | 4 | # A program to simulate average waiting time for a computer lab printer- Miller and Ranum
from pythonds.basic import Queue
import random
from printer_class import Printer
from task_class import Task
def main():
"""Function to serve as main menu and driver"""
def simulation(numSeconds, pagesPerMinute):
"""P... |
b9f6639d95a198717d06383472fdf5fcbd2b4a72 | wisdom2018/letterCombination | /letterCombination.py | 800 | 3.75 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/1/25 6:01 PM
# @Author: wisdom
# @File:letterCombination.py
def letterCombination(digits: str) -> list:
KEY = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n... |
8d9319f1974778f8f47a3d4340007dd6e141c362 | hinriksnaer/DeepLearning | /code/train_convnet_pytorch.py | 5,570 | 3.9375 | 4 | """
This module implements training and evaluation of a Convolutional Neural Network in PyTorch.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import os
from convnet_py... |
a8fe4aa3fe2c51fc4aea159223dfc48a8058cc28 | alixtc/pythonProject | /main.py | 269 | 3.84375 | 4 | import re
a = 'Rilke'
b = 'martin'
def are_you_playing_banjo(name):
if name[0] == "R" or name[0] == "r":
name = name + " plays banjo"
else:
name = name + " does not play banjo"
return name
are_you_playing_banjo(a)
are_you_playing_banjo(b) |
dfa9a719ea6c205c96270971839c96ab24567d6a | t6nesu00/python-mini-projects | /characterInput.py | 345 | 3.984375 | 4 | from datetime import date
user_name = input("What is your good name?: ")
user_age = int(input("What is your age?: "))
gap_to_be_hundred = 100 - user_age
# date.today().year gives current year
hundred_in = date.today().year + gap_to_be_hundred
print("Hello", user_name, "you will be 100 years old in", hundred_in)
# c... |
cd13d9bce305cdfcfab787492179309ac039c4aa | HierarchThurs/Net-Study_Code | /poem_code.py | 2,035 | 3.609375 | 4 | # coding=utf-8
# python2版本
"""
最后一行有密文路径,使用前请修改相关内容,
poem.txt里只存放poem,cipher.txt里存放密文,两文件里不存放其他无关字符
"""
import itertools
def load_file(filename):
with open(filename, 'r') as fp:
lines = fp.readlines()
words = []
for line in lines:
for word in line.split():
# 过滤特殊字符 .
wo... |
6ebccfb0b82912bd0630ecce3ff45f586d93b512 | HierarchThurs/Net-Study_Code | /PythonLearn/Learn_1.py | 6,724 | 3.703125 | 4 | # -*- coding : UTF-8 -*-
# @Time : 20:04
# @Author : Hierarch
# @File : Learn_1.py
# @Software : PyCharm
# print('hello world')
# num_1 = 10
# print(type(num_1))
# num_2 = 4
# print(type(num_2))
# num_3 = num_1 / num_2
# print(type(num_3))
#
# num_comp = complex(5, 2)
# print(num_comp)
#
# info = '''
# 12... |
25816a31206834756253e5512224e3e09d3455e6 | cyxorenv/Test | /Working_with_numbers.py | 431 | 4.03125 | 4 | # Some functions that work with numbers.
# =------------------------------------=
import math # <-- Calling a math Module for advanced math operations.
# Rounding a number.
print(round(2.9))
# Return the Absolute value of a number.
print(abs(-2.9))
# Find the ceiling of a number
print(math.ceil(2.2))
# Return x ra... |
50113a8edd2297564831576eba8f0fe70a990e48 | Duibh/kernel-maze | /grid.py | 5,282 | 3.796875 | 4 | from random import randint
from collections import defaultdict, deque
from heapq import heappush, heappop
import operator
def build_maze(m, n, swag):
grid = []
for i in range(m):
row = []
for j in range(n):
row.append("wall")
grid.append(row)
start_i = randint(0, m-2)
... |
97f1623243f1b6e07fe389f5d3acc0b1b5f41585 | fexxsuku/sukumar | /no of spacial characters.py | 106 | 3.71875 | 4 | n=input()
sum=0
for x in n:
if(x.isdigit() or x.isalpha()!=True or x==" "):
sum+=1
print(sum)
|
60792406313b6e20521fd09c63798df14dadf63b | rcuhljr/MyEuler | /prob2.py | 652 | 3.640625 | 4 | memo = {0:1, 1:2}
def fib(x):
if not x in memo:
memo[x] = fib(x-1)+fib(x-2)
return memo[x]
def solve():
def f(x):
if x%2 == 0:
return x
else:
return 0
counter = 0
result = 0
while fib(counter) < 4000000:
result += f(fib(counter)... |
b2ea24c4469b90eb711ec3525a81815154b08da2 | rcuhljr/MyEuler | /myprimes.py | 3,072 | 3.5625 | 4 | import cPickle as pickle
import math
class Primes:
def __init__(self):
try:
self.primes = pickle.load( open( "primes.p", "rb"))
except IOError:
self.primes = [2, 3]
try:
self.divisors = pickle.loa... |
4daf076125d1a91690db7b58a4c9f39d9ecdcef1 | sunshinee24/leetcode | /problem_10.py | 1,112 | 3.5 | 4 | class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
#import pdb;pdb.set_trace()
#s = list(s)
#p = list(p)
#print('s: '+str(s)+ ' p:' +str(p)+'\n' )
if 0 == len(p):
return l... |
080835b1b877d222a5dda97e9d77fe7ce75fb677 | kvssea/Python-Challenges | /digits.py | 379 | 4.0625 | 4 | '''● Create a program, digits.py, that has a function
that takes a number and prints the number of digits in the number.
It should work for numbers with decimals, too.
'''
#digits.py
def digits(number):
number = str(number)
digits = 0
for num in number:
if num in map(str, list(range(9)... |
7cf2541f4a39695c0e7426867ec544335c6d45eb | niharparikh/EmoryCS | /CS325/multiagent/multiAgents.py | 14,857 | 3.53125 | 4 | # THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING A TUTOR OR CODE WRITTEN BY OTHER STUDENTS - Nihar Parikh
# multiAgents.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2)... |
cf1b2f8be0f876d989f23278a035f9960822e3a9 | poppinfresh82/miniputt2 | /mouse_events.py | 571 | 3.546875 | 4 | class MouseEvents:
def __init__(self, screen):
self.screen = screen
def mouseDown(self, game, mousePosition):
if game.gameMode == 'splash':
if mousePosition[0] in range(100,200) and mousePosition[1] in range(150,250):
print('you clicked in the 50x50 box')
#def m... |
7dd8dabbb6c3f4e4cf39b5a3f40509d17e7c20c3 | tan-eddie/google-code-jam-2020 | /qualification/indicium_revisited/indicium.py | 4,585 | 3.609375 | 4 | """
Solved this after reading analyses after the round was over. Based on Errichto's analysis.
https://youtu.be/VayKvCg4vvQ
"""
def find_triplet(n, k):
for a in range(1, n+1):
for b in range(1, n+1):
for c in range(1, n+1):
if ((n-2)*a + b + c == k and
... |
41e988580e7485c0864e4422aad17bf96a5cd8f1 | kristjanr/harjutusi | /variant1/yl4.py | 187 | 3.609375 | 4 | def debt(apples, price, cash):
cost = 0
try:
for i in range(1, apples + 1):
cost += i * price
except TypeError:
return None
return cost - cash
|
f71a270f22be7ef7c76e92db05e4447000958a1c | a200411044/Python_Crash_Course | /motercycles.py | 639 | 3.78125 | 4 | car = ['BMW', 'Audi', 'Nissan', 'Toyota']
print(car)
#car[0] = 'Lexus'
#print(car)
#car = []
#car.append('BMW')
#car.append('Audi')
#car.append('Nissan')
#car.append('Toyota')
#print(car)
#del car[0]
#print(car)
#car.insert(0, 'BMW')
#print(car)
#popped_car = car.pop()
#print(car)
#print(popped_car)
#last_owned =... |
178137cc0325eff2056261ccab3d0804c909ab60 | a200411044/Python_Crash_Course | /bicycles.py | 869 | 3.703125 | 4 | bicycles = ['trek', 'cannondale', 'redline', 'specialized']
#print(bicycles)
#print(bicycles[0])
#print(bicycles[0].title())
#print(bicycles[1])
#print(bicycles[3])
#print(bicycles[-1])
message = "My first bicycle was a " + bicycles[0].title() + "."
#print(message)
#Test
#3-1:
names = ['tom', 'tim', 'steve', 'jack']... |
24b82b4de75cb762ce4b13e761e6359d1aa07425 | amankumar38/Python-Basics | /add.py | 163 | 4.09375 | 4 | import math
x=int(input("Enter the 1st number: "))
y=int(input("Enter the 2nd number: "))
z=x+y
w=math.pow(z,3)
u=math.sqrt(z+9)
print(z)
print(w)
print(u) |
e3536c439996cd8881f81a34a1d3b053b2310a53 | SparshBansal/Dive-into-Python | /datatypes.py | 3,641 | 4.4375 | 4 | # ==================== LIST DATA CONTAINER =========================
a_list = [2,'three' , 4.0]
# print a List
print a_list
# Slicing a List - a_list[a : b] -- a inclusive and b exclusive
print a_list[0:2]
# ******* Add single items to the List **************
a_list.append('five')
print a_list
# insert at a given ... |
5cbced40774d55c4c780272e3bd3224d08696adb | zenbert5/data_analytics | /crunchie_munchies - pyplot & pandas/crunchie_munchies.py | 1,942 | 3.625 | 4 | """
CrunchieMunchies Project
Python with matplotlib, pandas & numpy
Shawn Chen
Jan 2, 2018
"""
from matplotlib import pyplot as plt
import numpy as np
# .2 - load data into numpy array
calorie_stats = np.genfromtxt('cereal.csv', delimiter=',')
sample_set_size = len(calorie_stats)
# .3 - find the ... |
6d95239cf2771ab02a6699bdfa79d43f6d361b43 | zenbert5/data_analytics | /stats_scipy/references_scipy.py | 5,058 | 3.90625 | 4 |
"""randomize data set with selection for probability test"""
import numpy as np
population = np.random.normal(loc=65, scale=3.5, size=300)
population_mean = np.mean(population)
print "Population Mean: {}".format(population_mean)
sample_1 = np.random.choice(population, size=30, replace=False)
sample_2 = np.random.ch... |
bf1f3b1c874a08b4df706bcab4a34a2c7e519946 | vh42720/ISLR | /chapter4/12.py | 527 | 3.90625 | 4 | # Applied - Question 12
import seaborn as sns
import matplotlib.pyplot as plt
def power(x=2):
print(x**3)
def power2(x, a):
print(x**a)
num_dict = {10: 3, 8: 17, 131: 3}
for x, a in num_dict.items():
power2(x,a)
def power3(x, a):
return x**a
x = range(0,11)
y = [power3(i,2) for i in x]
sns.scatterplot(x=... |
28e4851a7f8fc7e6aaa848090778820e06da8e8a | abbyschantz/cs35 | /hw4/titanic.py | 7,962 | 3.640625 | 4 | #
# Abby, Eliana, and Liz
# titanic.py
# SEE GITHUB
# https://github.com/abbyschantz/cs35/tree/master/hw4
#
import numpy as np
from sklearn import datasets
from sklearn import cross_validation
import pandas as pd
# For Pandas's read_csv, use header=0 when you know row 0 is a header row
# df here is a "d... |
5a0214dea07caba1c10c5e274482c78a9a0228e8 | abbyschantz/cs35 | /hw7/hw7pr3.py | 5,224 | 3.671875 | 4 | # ## Problem 3: green-screening!
#
# Names: Liz Harder, Eliana Keinan, Abby Schantz
#
# This question asks you to write one function that takes in two images:
# + orig_image (the green-screened image)
# + new_bg_image (the new background image)
#
# It also takes in a 2-tuple (corner = (0,0)) to indicate where to... |
22a44a9751012e51208d7d84ee8cf62e5c206f98 | abbyschantz/cs35 | /hw2/cs35_week2_starter_code.py | 15,071 | 3.984375 | 4 | # Liz Harder, Eliana Keinan, and Abby Schantz
# starting examples for cs35, week2 "Web as Input"
#
import requests
import string
import json
"""
Examples you might want to run during class:
Web scraping, the basic command (Thanks, Prof. Medero!)
#
# basic use of requests:
#
url = "https://www.cs.hmc.edu/~dodds/demo... |
827050d4c6e2c6dfeaed3836dc6ae4d2f7ecfdbd | galanteria01/XML-Translater | /main.py | 2,132 | 3.546875 | 4 | import xml.etree.ElementTree as ET
from googletrans import Translator
from Languages import *
from time import *
translator = Translator()
# Make a list of optional languages
nameOfLanguages = [french, spanish, arabic, english, hindi, portuguese, russian, japanese,
german, korean]
tree = ET.pa... |
d4a660c0fafd591dba37480f3c733f8022903bcb | andresebr/remote-compiler | /client.py | 4,060 | 3.859375 | 4 | #!/usr/bin/python
#Author: Andres E. Barreto
from socket import *
#Function definitions----------------------------------------------
def writeFile(filename, path, filecontent):
f = open(path + filename, "w")
f.write(filecontent)
f.close()
return
#----------------------------------------------------------------... |
4fe75d53c46f04d477ba3335a7523b9d679f8dfd | PizzaShift/TwitterPMI | /DataCollection/driver.py | 968 | 3.515625 | 4 | __author__ = 'asb'
import main, collections, itertools
PMITerm = 'apple'
listOfBGWords = main.GetSortedRelevantTweets(PMITerm)
lister = [] #this code block calcs tuplesIT variable
for words in listOfBGWords:
lister.append(words)
counted = collections.Counter(lister)
sortedCounter = counted.most_common()
tuplesI... |
a0f6d8005f2288119e7c85688688db9e71bb0bdb | the-inevitable/algorithms-in-python | /dynamic-programming/longest_common_subsequence.py | 941 | 3.546875 | 4 | """
Longest common subsequence algorithm.
Works on sequences of any lengths.
O(n**2)
"""
def lcs(s1, s2):
if not len(s1) or not len(s2):
return 0
max_len = max((len(s1), len(s2)))
grid = [[0] * max_len for _ in range(max_len)]
for i, ch1 in enumerate(s1):
for j, ch2 in enumerate(s2):... |
706d5ad3a1d020263131eb6b53dd31205de66da9 | quyenxhuynh/DSA-Practice | /sorts/test.py | 160 | 3.59375 | 4 | import sorting, random
lst = []
for i in range(100):
lst.append(random.randint(1,100))
bubble = sorting.bubbleSort(lst)
sorted(lst)
assert(bubble == lst) |
88e38c5ea7c1417871c3ac2c815d1bcb4a1c98db | akahenry/movie-user-rating-analysis | /readFiles.py | 2,984 | 3.703125 | 4 | import csv
from trie import *
from hash import *
def transpose(matrix):
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
def readCSV(filename):
file = open(filename, 'r', encoding='utf-8')
csvreader = csv.reader(file)
return_list = list(list(csvreader))
# Tira o header
retur... |
82e886640492f9a565bf9e9707fe7f27523fc7c6 | tommwq/demo | /ByLanguage/python/port-checker.py | 2,238 | 3.828125 | 4 | #! /usr/bin/python
'''
˿ɨ
port-scanner
for python 2.x
see usage()
port-scanner host port
port-scanner host_file
'''
'''
todo:
1. use multi-thread to scan port
'''
import sys
import socket
import time
# port stats: OPEN CLOSED NOT_SCANNED SCANNING
port_list = {}
def check_port(host, port, timeout... |
735b75cdcd1a4ec532826935c03a1b5dc0ff0272 | tommwq/demo | /ByLanguage/python/PersonalAccount/version3/personal_account.py | 1,311 | 4.0625 | 4 |
class Item(object):
def __init__(self, is_debit, label, amount):
self.is_debit = is_debit
self.label = label
self.amount = amount
class Account(object):
def __init__(self):
self.items = []
self.expense = 0.0
self.income = 0.0
self.balance = 0.0
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.