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 |
|---|---|---|---|---|---|---|
06aca33161814988db31606378dc99117dfc80e6 | lemakefyalew/holbertonschool-interview | /0x16-rotate_2d_matrix/0-rotate_2d_matrix.py | 541 | 3.9375 | 4 | #!/usr/bin/python3
"""
Given an n x n 2D matrix, rotate it 90 degrees clockwise.
"""
def rotate_2d_matrix(matrix):
"""
Rotates matrix 90 degress
"""
row = len(matrix)
column = row - 1
for i in range(0, int(row / 2)):
for j in range(i, column - i):
temp = matrix[i][j]
... |
9dca594fa4824bc94880e2aa250bd46180d89d65 | syz247179876/Flask-Sports | /extensions/crypto.py | 2,475 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/12/4 下午5:12
# @Author : 司云中
# @File : crypto.py
# @Software: Pycharm
import base64
import hashlib
import hmac
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
使用伪随机函数进行加密
Return the hash of password using pbkdf2.
"""
if digest is None:
... |
322bdb0b3381a696bc3b088f015f2e3c1b5e2665 | himeshnag/Ds-Algo-Hacktoberfest | /Python/ArrayRotation.py | 569 | 4.28125 | 4 |
from Arrays import Array
def rotation(rotateBy, myArray):
for i in range(0, rotateBy):
rotateOne(myArray)
return myArray
def rotateOne(myArray):
for i in range(len(myArray) - 1):
myArray[i], myArray[i + 1] = myArray[i + 1], myArray[i]
if __name__ == '__main__':
myArray = Array(10)
... |
163730bb0979010c933814f0005f6c00ce61c0a9 | himeshnag/Ds-Algo-Hacktoberfest | /Python/loops/primeno.py | 427 | 4 | 4 | n=int(input("Enter the lower range:"))
m=int(input("Enter the upper range:"))
for num in range(n,m+1):
if(num>1):
for i in range(2,num):
if(num%i==0):
break
else:
print(num)
celsius = int(input("Enter temp."))
fahrenheit = (celsius *... |
84190ee6244ab767a917e02330b86eeb9963ac24 | peterpathros/mqttdockersample | /samples/timeprint.py | 323 | 3.625 | 4 | from datetime import datetime
import time
import calendar
x=1
while True:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time : ",current_time)
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print("UnixTime : ",unixtime)
print("***********")
time.sleep(1)
x+... |
3d33eb6cadd1028c81b2190b91fb3cdde5763a7c | sewald00/Pick-Three-Generator | /pick_three.py | 951 | 4.28125 | 4 | """Random pick three number generator
Seth Ewald
Feb. 16 2018"""
import tkinter as tk
from tkinter import ttk
from random import randint
#Define the main program function to run
def main():
#Define function to change label text on button click
def onClick():
a = randint(0, 9)
... |
d42a11bf8758464b5fd854ab5cef46f863035c66 | anueshenxing/DeepLearningTutorial | /Mathematical-Modeling-2014/Project/myTest/test_dict_360.py | 711 | 3.515625 | 4 | #coding:utf-8
path = "C:\\Users\\Syndrome\\Desktop\\语料数据\\360W_字典\\dict_360.txt".decode('utf8').encode('cp936')
f = open(path,"r")
line = f.readline()
i = 0
while line:
line = line.rstrip('\n') #去除字符\n
m = line.split('\t') #字符串分割,以\t
print len(m[0])/3
for item in m:
print item ... |
ef34fa1bfc636c42cf43b46848c6c13286f6ba6e | YYY3000/PySparkTest | /leetcode.py | 3,247 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
@staticmethod
def two_sum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num = {}
... |
4a0f3dc372011dfc762a72b22b26188c5c9c7c93 | ruebyi/atem-remote | /test.py | 427 | 3.890625 | 4 | #!/usr/bin/env python3
import tkinter as tk
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300)
canvas1.pack()
def hello ():
label1 = tk.Label(root, text= 'Hello World!', fg='green', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 200, window=label1)
button1 = tk.Button(text='Click... |
233f3bdaefe7d745b03eb01384a7966b2fc8b14e | CMU-IDS-2020/a3-yet-another-streamlit | /multivariate_LR.py | 3,908 | 4.0625 | 4 | # A simple linear regression model.
# we write one instead of using sklearn, to get the time-series loss and weights,
# for time-series visualization and interaction of the training process.
import numpy as np
class LinearRegression:
def __init__(self, lam):
"""
Class constructor.
... |
33cfa76f8d5b5a5d3309e07a7194cf7bec645686 | KennethStreet/Data_Structures | /Module_2/Assignment_2/max_stack_da.py | 4,544 | 4.1875 | 4 | # Course: CS261 - Data Structures
# Student Name: Kenneth Street
# Assignment: Project 2 - Your Very Own Dynamic Array
# Description: Max Stack data structure and it's methods
from dynamic_array import *
class StackException(Exception):
"""
Custom exception to be used by Stack class
DO NOT CHANGE THIS ME... |
7c338d275fa134652a697c557d6ac523a84671fe | metamemelord/Algorithms | /impl-two-number-sum.py | 1,415 | 3.828125 | 4 | """
Given an array, find a pair of numbers from the array that add to a specific sum
Optimal Complexity:
Time: O(n)
Space: O(n)
or
Time: O(nlog(n))
Space: O(1)
"""
class TwoNumberSum(object):
def nSqrTimeOneSpace(self, array, expectedSum):
for i in range(len(array)):
for ... |
7d3279e79e140c6feffd735171703b00a5310377 | katcosgrove/data-structures-and-algorithms | /challenges/binary-search/binary_search.py | 321 | 4.21875 | 4 |
def BinarySearch(arr, val):
"""
Arguments: A list and value to search for
Output: The index of the matched value, or -1 if no match
"""
if len(arr) == 0:
return -1
counter = 0
for item in arr:
counter += 1
if item == val:
return counter - 1
return -1... |
47c0044f75bda61909c95611c4a4ca729ef5d0b4 | katcosgrove/data-structures-and-algorithms | /data_structures/linked-list/ll_merge.py | 641 | 4.0625 | 4 | def merge_lists(list_one, list_two):
"""Merge two lists."""
if list_one._size > list_two._size:
current, current_two = list_one.head._next, list_two.head
while current_two is not None:
list_one.insert_before(current.val, current_two.val)
current, current_two = current._... |
3cbb921b6d67b3811de9e9e117d3013dd03bb5bc | renefueger/cryptex | /path_util.py | 980 | 4.4375 | 4 | def simplify_path(path: str, from_separator='/', to_separator='/') -> str:
"""Returns the result of removing leading/trailing whitespace and
consecutive separators from each segment of the given path."""
path_parts = path.split(from_separator)
stripped_parts = map(lambda x: x.strip(), path_parts)
va... |
59ce6520d4755bc2a6458e76d06224896e088cac | vicuartas230/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 203 | 3.84375 | 4 | #!/usr/bin/python3
""" This program defines a class MyList """
class MyList(list):
""" This class inherits from class list """
def print_sorted(self):
s = sorted(self)
print(s)
|
0e9ec1c8a17363cb711c5db67ee0743135048f58 | vicuartas230/holbertonschool-higher_level_programming | /0x03-python-data_structures/9-max_integer.py | 230 | 3.671875 | 4 | #!/usr/bin/python3
def max_integer(my_list=[]):
if len(my_list) == 0:
return None
else:
max_i = my_list[0]
for i in my_list:
if i > max_i:
max_i = i
return max_i
|
da73cd924c0b1e5b33b8a47a882815fb8c232b3a | nramiscal/spiral | /spiral.py | 1,598 | 4.25 | 4 | '''
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5], <-- matrix[0]
[6, 7, 8, 9, 10], <-- matrix[1]
[11, 12, 13, 14, 15], <-- matrix[2]
[16, 17, 18, 19, 20]] <-- matrix[3]
You should print out the f... |
f40c6a62fd9e67635940bb4c62a23ad06e091b25 | simonwardjones/python_cookbook | /python_recipes/absolute_min_of_list.py | 673 | 3.984375 | 4 | """
Section:
list
Author:
Simon Ward-Jones
Description:
How to find the absolute min value in list
Tags:
list, min, abs
"""
numbers = [-23, 534, -134, 36, -294]
# method one using comprehension (note this works as by default min
# uses first element of each tuple then returns that tuple, we then
# s... |
47a41db9200dcbdb6fb452f64bd752eebefd0169 | simonwardjones/python_cookbook | /python_recipes/save_metadata.py | 2,213 | 3.546875 | 4 | """
Section:
Reading and Writing
Author:
Carlos Aguilar
Description:
Add metadata information to files, so they can be easily summarised, ie: latest version, contents, ways of generating
or ways of using it.
Tags:
write, metadata, json
"""
import os
import json
import datetime as dt
def save_m... |
f6cb7a8c8cecae6cb03bf0e7ab0eee162d7286c9 | simonwardjones/python_cookbook | /python_recipes/filter_dataframe.py | 1,481 | 4.03125 | 4 | """
Section:
Pandas
Author:
Simon Ward-Jones
Description:
Dataframe filtering by values
Tags:
pandas , filter, values
"""
import pandas as pd
import numpy as np
import random
from datetime import datetime
from dateutil.relativedelta import relativedelta
# First we create example dataframe
r = rando... |
0dcb58cda22d8dbe89d2c4ee293e804163862463 | LeiGan0215/Interview | /Data Structures and Algorithms/Sword refers to offer/Python/1.py | 753 | 3.734375 | 4 | # -*- coding:utf-8 -*-
class Solution:
# array άб
def Find(self, target, array):
# write code here
m,n=len(array),len(array[0])
i=0
j=n-1
while (i<m and j>=0):
if target==array[i][j]:
return True
elif target<array[i][j]:
... |
8fbd7072886f1c8ee8b1286be1aa6d00a8564e9a | gentlemil/python_exercises | /slowniki.py | 641 | 3.59375 | 4 | # element mapujacy/haszujacy/ funckja skrotu -> wikipedia
# do slownikow nie wsadzimy elementow mutowalnych
# dictionary
# dict()
# lista jako klucz nie,
slownik = {
'klucz': [2,4,5],
(1,2,3): 'wartosc2',
'd': 'wartosc3',
(0,4): 'X',
True: 'tak',
'tal': False,
#(1,3, [2,4,5]): '234,'
... |
42391e5e5ae8b679d30b32019e4ee0132b35e823 | abhiformular/python-class | /PythonTest/q5.py | 113 | 3.921875 | 4 | y = int(input("choose a number "))
for x in range(1,11,1):
table = x * y
print(f"{y}*{x}={table}")
|
421b5bd732d7b6d2ecf70f0f9644fec9ef49491e | pierrebiver/spotify-puzzle | /zipf_song/zipf_song_test.py | 350 | 3.546875 | 4 | import unittest
from zipf_song.zipf_song import zipf_song
inputOne = [(30, "one"), (30, "two"), (15, "three"), (25, "four")]
class MyTestCase(unittest.TestCase):
def test_zipf_song(self):
expected = [(25, "four"), (30, "two")]
self.assertEqual(zipf_song(2, inputOne), expected)
if __name__ == '_... |
7a794010f5597e2eedb24bc19b3ca29d7a6a793b | yirand/python-assignments | /assign0/bridge.py | 1,269 | 4.09375 | 4 | #!/usr/bin/env python3
"""Module-level comments"""
def main():
with open("answers.txt") as f:
for line in f:
print("KEEPER: Stop! Who would cross the Bridge of Death must answer me these questions three, 'ere the other side he see.")
name = input("KEEPER: What is your name? ").strip(... |
2047056b45017b5284555de99a086a164252e82c | Mattdinio/Code-at-GU-2019 | /Assignment 1.py | 1,303 | 4.1875 | 4 | # Question 1
def divisibleByThree ():
for i in range(1,101):
if i % 3 == 0:
print (i)
# Question 2
def shakespeare ():
quote = ""
# Question 3
def numberThing():
for i in range (1,11):
if i % 3 == 0:
print (i**3)
elif i % 2 == 0:
print (i**2)
... |
d3e3e81daa7f1709ea1e22957f931079117eabf6 | larryk91/rock-paper-scissors-game | /game.py | 1,627 | 3.625 | 4 | # game.py
import random
import os
from dotenv import load_dotenv
load_dotenv() # invokes / uses the function we got from the third-party package. this one happens to read env vars from the ".env" file. see the "python-dotenv" package docs for more info
USER_NAME = os.getenv("USER_NAME", default="Player One")
print("R... |
c033830b88d31645021c669316fc745049a7e88b | Youssefares/Sorts | /AVL/BST.py | 2,242 | 3.796875 | 4 | from AVL.BSTNode import *
class BST:
""" Naive implementation of a Height Augmented Binary Search Tree """
def __init__(self):
self.root = None
self.stack = None
def insert(self, key):
# if root, just root = node with parent: None
if self.root == None:
self.roo... |
f798770dc538aca5e2f6da4b91419be999454e1d | Youssefares/Sorts | /Quicksort/Quicksort.py | 733 | 3.953125 | 4 | from Quicksort import KnuthShuffle
def quicksort(arr):
KnuthShuffle.knuth_shuffle(arr)
run_quicksort(arr, 0, len(arr) - 1)
def run_quicksort(arr, left, right):
if left >= right:
return
split = partn(arr, left, right)
run_quicksort(arr, left, split - 1)
run_quicksort(arr, split + 1, r... |
6c2c87b8921daddfc9a88abab237a3189e86833f | jowisaidman/SimulacionTp1 | /Ejercicio2.py | 1,596 | 3.71875 | 4 | import matplotlib.pyplot as plt
import random
def GCL_con_rango(n,Xo,incremento, modulo, multiplicador):
"""Recibe como parametro cinco enteros, numero de iteraciones n, semilla Xo,
, incremnto, modulo y multiplicador.
Los numeros random generados estan entre 0 y 1.
Imprime el valor de cada iteracion"... |
c0e3115d48f9134c8c2fe623e4c65660c1b0480a | shannonh90/D06 | /D06ex02.py | 352 | 3.765625 | 4 | #To write ten numbers to a file, do this in the interpreter:
import random
numbers = random.sample(range(100), 10)
print(numbers)
ten_numbers = open('ten_numbers.txt', 'w')
ten_numbers.write(str(numbers)
ten_numbers.close()
ten_numbers()
# if want to do it the other way:
# with open("ten_numbers.txt", "w") as f:
# ... |
b92034d839ff24abe092ef5fc9b40abe3486ee85 | braidwords/PythonBasics | /Smallest_number in the list.py | 120 | 4.03125 | 4 | numbers = [23, 20, 2, 45, 67, 87]
small = numbers[0]
for x in numbers:
if x < small:
small = x
print(small)
|
042c0ba559ec10d7fd62c0b07717d627e55ae8c8 | braidwords/PythonBasics | /Self and init.py | 494 | 3.640625 | 4 | class StudentData:
def __init__(self, name, marks, marks1):
self.name = name
self.marks = marks
self.marks1 = marks1
def marks_cal(self):
result = (self.marks + self.marks1)
return result
print("Enter the name")
name = str(input())
print("Enter your marks for Maths: ")... |
04e6251f38a87afe8d52bcc270898de75aa45b44 | Lyondealpha-hub/Python-Programs | /FizzBuzz.py | 325 | 4.15625 | 4 | #A program that changes multiple of 3 to fizz, multiple of 5 to buzz and multiple of
#both 3 and 5 to fizzbuzz
print("A program for a FIZZBUZZ ")
for i in range(1,101):
if i%3==0:
print( i, "\t","Fizz")
if i%5 == 0:
print(i, "\t","Buzz")
if i%3==0 and i%5==0:
print(i, "\t","FizzBu... |
944011219a388bb9434c8e68ab11da48992558d3 | marydeka/advent_of_code_2019 | /7/permutations.py | 505 | 3.546875 | 4 | import copy
my_list = [0,1,2,3,4]
permutations = [[]]
for i in my_list:
new_permutations = []
# new_list = [i]
# permutations.append(new_list)
for perm in permutations:
for j in my_list:
if j in perm:
continue
else:
new_perm = copy.deepc... |
683f1d4704ad051b6388bf875b05be7d91b5bdaf | oGemeye/MyFirstChess | /pieceController.py | 3,379 | 4.09375 | 4 | """
controls pieces in an 8x8 board
top left coord is (x, y) = (0, 0) internally, A1 externally, found at board[y][x]
top right coord is (x, y) = (0, 7) internally, A8 externally
bottom left coord is (x, y) = (7, 0) internally, H1 externally
bottom right coord is (x, y) = (7, 7) internally, H8 externally
"""
from piec... |
e5ad45d008d355650dca1009d91d1666226b1f4f | JNorrie12/PriceSearcher | /searcher.py | 686 | 3.53125 | 4 | #!/usr/bin/python
import time
from price import SearchCsv, SearchJson
def main():
x = raw_input("Welcome to my search! Would you like to run the Json or Csv example?")
if x.lower() == "csv" :
s = SearchCsv( "products.csv", "f" ,"5860865")
t1 = time.time()
s.fullSearch()
t2 = time.time()
print "Full so... |
406a7794a274ef819acdbe4e8dc0b7ed7248f8bc | pgharat/InsightChallenge | /src/average_degree.py | 7,696 | 3.640625 | 4 | #! /usr/bin/env python
"""
Program Name : average_degree.py
Date : 04/02/2016
Desc : This program reads tweeter input flat file, parses for timestamp and hastags.
From the hashtags, it creates a graph of hashtags and calculates average degree
of vertex. It maintains a... |
e86b04da6740d863c6d84e4cd52f1e211e15a694 | tayloryeow/Codemon2.0 | /Renderer.py | 1,436 | 3.59375 | 4 | '''
Class that renders the board into graphical format.
It is the controller that build the view from the models that is the Board class
Board contains references to that needs to be represented in it, so only board
'''
'''
Class that renders the board into graphical format.
It is the controller that build the view ... |
5a34d3c9e5d8b57cfd86511a93c9c85c5d6653c8 | cs-fullstack-2019-spring/python-review3-cw-gkg901 | /review3.py | 1,432 | 3.96875 | 4 | def main():
# ex1()
ex2()
# ex3()
# Given a number n, return True if n is in the range 1..10, inclusive.
# Unless outside_mode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.
# Print the result returned from your function.
def ex1():
print("")
def... |
748e0e841763a241125c6beaf82c874e971774d4 | lokisapocalypse/project-euler | /problem-010.py | 468 | 3.890625 | 4 | # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
# This is not the most elegant solution, but I'm new to python and its late and I'm tired
numbers = range(2, 2000000)
for x in range(3, 2000000):
isPrime = True
for prime in primes:
if x % pri... |
07499ffed61c1dce95ff7521911ce3284e86f9bd | MrCrazyCat/FlManager | /sqlDB.py | 622 | 3.953125 | 4 | import sqlite3
db = sqlite3.connect('Account.db')
cur = db.cursor()
# Создаем таблицу
cur.execute("""CREATE TABLE IF NOT EXISTS Account (
ID INTEGER PRIMARY KEY,
EMAIL TEXT,
PASS TEXT
)""")
db.commit()
email = "join.ronin3412@gmail.com"
password = "Prokuror@228"
cur.execute(f"SELECT ... |
5e4f83be7e9f128a11e3c7d96fb5b89618fc7f08 | subZiro/adventofcode_2020 | /code/day_5.py | 1,984 | 3.921875 | 4 | # -*- coding: utf-8 -*-
from math import ceil, floor
# --- Day 5: Binary Boarding --- #
# --- Part One --- #
"""
ROW For example, consider just the first seven characters of FBFBBFFRLR:
Start by considering the whole range, rows 0 through 127.
F means to take the lower half, keeping rows 0 through 63.
B means to... |
b4c93996e1bb5773bfbe76ef275e62cfdbfadb49 | subZiro/adventofcode_2020 | /code/day_7.py | 3,269 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# --- Day 7: Handy Haversacks --- #
# --- Part One --- #
"""
In the above rules, the following options would be available to you:
A bright white bag, which can hold your shiny gold bag directly.
A muted yellow bag, which can hold your shiny gold bag directly, plus some other bags.
... |
ab5fa0ddceaa6297b8dc1e658461e8ae38b3641a | Crone1/Ant-Agent-Based-Model-Simulation | /ant_classes.py | 6,241 | 3.859375 | 4 |
# ===================
# | IMPORT PACKAGES |
# ===================
# packages for incrementing the ants
from random import random, randint, choices
# ====================
# | CUSTOM EXCEPTION |
# ====================
class AllAntsDead(Exception):
pass
# ===================
# | TRAIL CLASS |
# ==============... |
e265130d5d01b05cba7fd6d8acf5670e6dfacaba | timg1234/beta | /listbox.py | 716 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter as tk
window = tk.Tk()
window.title('My Window')
window.geometry('500x300')
var1 = tk.StringVar()
l = tk.Label(window, bg='green', fg='yellow',font=('Arial', 12), width=10, textvariable=var1)
l.pack()
def print_selection():
value = lb.get(lb.cur... |
bccf4604075283a37d3d33095be8428d57069089 | fatiando/harmonica | /examples/forward/prisms_topo_gravity.py | 3,451 | 3.5625 | 4 | # Copyright (c) 2018 The Harmonica Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Gravitational effect of topography
==================================
One possible app... |
c28794bff1212dd85c8076c2364abdfd3950d959 | Minjire/MachineLearningAlgorithms | /IBM_Recommender_Systems_Content-Based.py | 5,093 | 3.78125 | 4 | # %%
import pandas as pd
import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
# %% Loading
# Dataset Link
# https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/moviedataset.zip
movies_df = pd.read_csv('ml-latest/movies.csv')
ratings_df = pd.rea... |
adf804c78c165f98bff660077784aeca3bbc1932 | BryantCR/FunctionsBasicII | /index.py | 2,717 | 4.3125 | 4 | #1 Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countDown(num):
result = []
for i in range(num, -1, -1):
result.... |
e48269b77233beddd1ed6b393801e662afbcc66b | dhilankp/GameDesign2021 | /Python2021/Challenge3.py | 7,118 | 4.3125 | 4 | #Dhilan Patel
#Create a list of at least 5 elements (or ask the user to give the Values)
#Create a menu similar to what we did for the Strings MEthods
#in each selection you will allow the user to:
#1 insert elements either appending or inserting
#2 delete an element either by value or by index
#3 find if something in... |
1ef6cc0dd575247f5b227eca08802a0f623744f1 | dhilankp/GameDesign2021 | /Python2021/VarAndStrings.py | 902 | 4.15625 | 4 | #Dhilan Patel
# We are learning how to work with Srtings
# While loop
# Different type of var
num1=19
num2=3.5
num3=0x2342FABADCDACFACEEDFA
#How to know what type of data is a variable
print(type(num1))
print(type(num2))
print(type(num3))
phrase='Hello there!'
print(type(phrase))
#String functions
num=len(phrase)
p... |
1cd2c40012eb3693c8609f82a68145c0c3c008c0 | zmwas/python_bucket_list | /tests/test_bucket_list_methods.py | 950 | 3.859375 | 4 | """This module contains tests for bucket list methods
"""
import unittest
from bucket_app.buckets import BucketList
class TestBucket(unittest.TestCase):
"""TestCase class for BucketList.
"""
def setUp(self):
self.my_bucket = BucketList("My resolutions", "In Progress")
def test_create_buck... |
1e1b9d565f7b24052fb946b3cd76a80689b80628 | zmwas/python_bucket_list | /bucket_app/buckets.py | 1,546 | 3.9375 | 4 | """Module for Bucket object and its methods
"""
class BucketList(list):
"""Class for the buckets
Args
name (str): Name of the bucket list
completion_status(str): How far one has gotten in the bucket list
Attributes
name (str): Name of the bucket list
completion_status(st... |
40abfe0c9bba9d05c17cf06b3e64a1546b27df67 | Casper-Smet/ABD | /2/2_9.py | 2,436 | 3.671875 | 4 | import random
import itertools
class DirtyCarpetEnv():
def __init__(self, n_tiles: int) -> None:
self.n_tiles = n_tiles
self.reset()
def step(self, action):
"Makes one step in the (episodic) environment."
if action == "Suck":
self.suck_total += 1
if sel... |
c866c92036fbd6d45abb7efc3beca71b065abda9 | DNA-16/LetsUpgrade-Python | /Day3Assign.py | 679 | 4.21875 | 4 | #Assignment1:Sum of N numbers using while
sum=0
N=eval(input("Enter the number "))
flag=0
n=0
while n!=N+1:
if(type(N)==float):
flag=1
break
sum=sum+n
n+=1
if(flag==1):
print(N,"is not a natural number")
else:
print("Sum of first",N,"natural number is ",sum)
... |
e602247091c15d87c702fdbad7bbee44df0b3fe9 | xuemy/ziyuan | /pinziyuan/utils.py | 495 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
from datetime import datetime
#
#@param g 数据库连接对象
#@param 表名
#
#
#
def select(g,*wargs,**kwargs):
pass
def time_format(time_str):
#将时间字符串转换为时间邮戳
time_tuple = time.strptime(time_str,'%Y/%m/%d %H:%M:%S')
#按照指定的格式格式化时间邮戳
return time.strftime... |
babcd92a74decde5d35882ac3ead0b4464985078 | milen-yordanov/advent-of-code | /2018/9/1.py | 1,722 | 3.53125 | 4 | # See: https://adventofcode.com/2018/day/9#part1
import re
import pprint
input_file_name = 'input.txt'
with open(input_file_name) as f:
content = f.readlines()
def parse_marbel_game_description(coordinate_str):
toks = coordinate_str.split(' ')
return (int(toks[0]), (int(toks[6])))
marble_games = [parse... |
c985aebb313c2cb5602fe2c9baf081f158caebff | zipper555/MobilityModels | /Random waypoint/random_waypoint.py | 1,957 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(-1, 1), ax.set_xticks([])
ax.set_ylim(-1, 1), ax.set_yticks([])
# Set initial coordinates
x0 = 0
y0 = 0
# Set cu... |
9f3ee1ff0d09ed86cba419188fb9e2fde2a2a34c | guangmingsi/test | /函数递归.py | 105 | 3.859375 | 4 | def recursion(num):
if num>1:
return num*recursion(num-1)
else:
return num
i=recursion(4)
print(i)
|
4b196a26887fdb30028d5e3fc3b83671af4b5458 | devin177/Sorting-Visualization | /value.py | 609 | 3.84375 | 4 | """Definition of bubble class which will be used
to contain the data of the lists"""
import pygame
class Value:
"""Definition of bubble class"""
def __init__(self, value):
self.value = value
def draw(self, display, left_corner, width):
""""Draw function for the bubbles"""
pygame.dr... |
bc91c3f4f474b25c685f619d629ac8c608247f45 | jmcelroy5/CodeSprint | /digits.py | 589 | 3.84375 | 4 | """
You are given an integer N.
Find the digits in this number that exactly divide N and display their count.
For N = 24, there are 2 digits - 2 & 4. Both these digits exactly divide 24. So our answer is 2.
"""
import sys
lines = sys.stdin.readlines()
for line in lines:
n_str = line.strip()
n = int(line)
... |
4230fa26d1a2df7954fc2845c2a75f4a627706b5 | dukedaffy/sudoku-solver | /sudoku.py | 1,848 | 3.765625 | 4 | board= [ [4,0,5,0,0,0,7,0,1],
[6,8,0,0,7,0,0,9,0],
[1,9,0,0,0,4,5,0,0],
[8,2,0,1,0,0,0,4,0],
[0,0,4,6,0,2,9,0,0],
[0,5,0,0,0,3,0,2,8],
[0,0,9,3,0,0,0,7,4],
[0,4,0,0,5,0,0,3,6],
[7,0,3,0,1,8,0,0,0]]
def solve(sudoku):
find = find_empty(sudoku)
... |
594cd76e835384d665f0a8390f82265616e34359 | stackpearson/cs-project-time-and-space-complexity | /csSortedTwosum.py | 667 | 4.1875 | 4 | # Given a sorted array (in ascending order) of integers and a target, write a function that finds the two integers that add up to the target.
# Examples:
# csSortedTwoSum([3,8,12,16], 11) -> [0,1]
# csSortedTwoSum([3,4,5], 8) -> [0,2]
# csSortedTwoSum([0,1], 1) -> [0,1]
# Notes:
# Each input will have exactly one so... |
9c2dcf4ea826961f1e545a490bed3ed6cdbcb0a4 | nem0301/AI | /4/search.py | 1,699 | 3.84375 | 4 | # ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your function should return the string
# 'fail'... |
df221dadd3d035e85e77cd66f41d56f36ad1fbfb | harrysha1029/prover | /src/logic.py | 1,758 | 3.578125 | 4 | class Formula:
"""Goal == Formula"""
def __repr__(self) -> str:
del self
raise NotImplementedError
def __eq__(self, other) -> bool:
return str(self) == str(other)
class Var(Formula):
def __init__(self, str):
self.str = str
def __repr__(self):
return self.... |
42b74c409ce3620fa9ca9157b314b78e1dccb50c | hamzalimouri/HackerRank-Python-Problem-Solving | /Problem Solving (Basic)/Sherlock and Squares.py | 378 | 3.734375 | 4 | import math
def squares(a, b):
temp = math.ceil(math.sqrt(a))
res = 0
while temp ** 2 <= b:
res += 1
temp += 1
return res
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
ab = input().split()
a = int(ab[0])
b = int(ab[1])
... |
0bae75108be5ae265b5aec5a3230a1f8e3beda10 | hamzalimouri/HackerRank-Python-Problem-Solving | /Problem Solving (Basic)/Alternating Characters.py | 307 | 3.953125 | 4 | def alternatingCharacters(s):
res = 0
for i in range(1, len(s)):
if s[i - 1] == s[i]:
res += 1
return res
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
s = input()
result = alternatingCharacters(s)
print(str(result))
|
7a6c5e5644929a80eba80f20b51c551a7a831a2a | hamzalimouri/HackerRank-Python-Problem-Solving | /Problem Solving (Basic)/StrongPassword.py | 783 | 3.796875 | 4 | NUMBERS = "0123456789"
LOWER_CASE = "abcdefghijklmnopqrstuvwxyz"
UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def minimumNumber(n, password):
# Return the minimum number of characters to make the password strong
d = {'n': 0, 'l': 0, 'u': 0, 's': 0}
for i in password:
if i in NUMBERS:
d['n... |
40abdcf56113d8be616d4c9081a2e9f564fcdf63 | hamzalimouri/HackerRank-Python-Problem-Solving | /Problem Solving (Basic)/gameOfStones.py | 244 | 3.578125 | 4 | def gameOfStones(n):
return 'First' if n % 7 >= 2 else 'Second'
if __name__ == '__main__':
t = int(input().strip())
for t_itr in range(t):
n = int(input().strip())
result = gameOfStones(n)
print(result)
|
f6ac5580d98a9784bd231c3d1046f377a2112c04 | hamzalimouri/HackerRank-Python-Problem-Solving | /Problem Solving (Basic)/Chocolate Feast.py | 418 | 3.890625 | 4 | def chocolateFeast(n, c, m):
w = n // c
res = w
while w >= m:
temp = (w // m)
res += temp
w = w % m + temp
return res
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
ncm = input().split()
n = int(ncm[0])
c = int(ncm[1])
... |
32650bd6a53ba4dd9a1ce7c8c6716f303b67e180 | hamzalimouri/HackerRank-Python-Problem-Solving | /Problem Solving (Basic)/maximizingXor.py | 318 | 3.65625 | 4 | def maximizingXor(l, r):
res = 0
for i in range(l, r + 1):
for j in range(l, r + 1):
if i ^ j > res:
res = i ^ j
return res
if __name__ == '__main__':
l = int(input().strip())
r = int(input().strip())
result = maximizingXor(l, r)
print(str(result))
|
4360e2b0d089974a4f3c713f729539bfae5a584e | helito01/brioa_port | /brioa_port/util/args.py | 325 | 3.78125 | 4 |
def parse_period_arg(arg: str) -> int:
"""
Makes sure that a period argument is a valid postive integer.
"""
try:
period = int(arg)
except ValueError:
raise ValueError("Period must be an integer")
if period < 0:
raise ValueError("Period cannot be negative")
return pe... |
359d0ea194c5daaced2c22ff2ac46fdfaab48a92 | rubivenkatesan/rubi21 | /guvi39.py | 94 | 3.5625 | 4 | #rubi
n=int(input())
k=1
while k<n:
k=k*2
if k==n:
print("yes")
else:
print("no")
|
8e6f72c29b1df04b02cb9c3b2ae63891e1d18ffd | rubivenkatesan/rubi21 | /88.py | 130 | 3.5 | 4 | #rubi
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
n,m=map(int,input().split())
p=gcd(n,m)
lcm=n*m//p
print(lcm)
|
e959091eac529699b0748c3c255077cf8f50777f | rubivenkatesan/rubi21 | /33.py | 110 | 3.671875 | 4 | #rubi
string=input()
count=0
for i in range(0,len(string)):
if string[i]==" ":
count=count+1
print(count)
|
263e35c47464a3fee4967b212ac0b7ba6a2c286e | maheshbabuvanamala/Python | /LinkedList.py | 839 | 4.15625 | 4 | class Node:
""" Node in Linked List """
def __init__(self,value):
self.data=value
self.next=None
def set_data(self,data):
self.data=data
def get_data(self):
return self.data
def set_next(self,next):
self.next=next
def get_next(self):
return self.ne... |
43a17d2e920f11556f3e15f962eb5abb3718f3e4 | kong1510/workshop2 | /variable/global_2.py | 141 | 3.640625 | 4 | x = "awesome"
def myfunc():
x = "fantastic"
print("[-] Pythin is " + x)
#Output: [-] Python is fantastic
#Ouuput: Python is awesome |
21d46ad34544112c300244cecac46c24882894e5 | 3107Omar/data-analysis | /intersection_data.py | 1,183 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 17:10:51 2020
@author: ahmedomar
"""
import pandas as pd
pd.set_option('display.max_rows', None) ## by default dataframe results are truncated so this option display all data
pd.set_option('display.max_columns', None) ## same but for columns
df1 ... |
4952a6ac5f3d8f91bd165603355c75eb68450fcf | muthoni12/ppython_listsandforloops | /dictionary.py | 614 | 4.125 | 4 | #student = {
# "name" : "pal",
# "age" : 19,
# "gender" : "F"
#}
#
#student["name"] = "val"
#print(student["name"])
'''
combined list with dictionary to have all that same data but for more than one item.
'''
users = [
{
"name" : "hal",
"age" : 19,
"gender" : "F"
},
{
"name" : "ma... |
4a57bc0efa10ece9b6815578fcc1e0e7ee66e2cc | tttlinh08t3/FurnitureStore | /furnitures/admin.py | 25,428 | 3.59375 | 4 | '''
CREATING A NEW DATABASE
-----------------------
Read explanation here: https://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts/
In the terminal navigate to the project folder just above the miltontours package
Type 'python' to enter the python interpreter. You should see '>>>'
In python interpreter type the f... |
80b0a6fe206fb6084cd149631248c49bd86aed70 | AHL96/Checkers-AI | /board.py | 9,994 | 3.828125 | 4 | from random import randint
class Board(object):
'''
this class will hold all the data and functionality of the checker board
Instead of white and black, i will use x's and o's for the game pieces and
spaces, ' ', to represent and empty spot on the board
When pieces get kinged they will turn into... |
2d55c87814c8a9ee66e0ed3a47c12c739b02d6e3 | BuildingDecarb/URAP_2020 | /LoadHourlyProfileData/AJ_Day_Year_Class.py | 3,135 | 3.5 | 4 | #Amy Jiang's code with Shuba's edits
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from LoadProfiles_Inputs import *
monthbeg = [1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] #first day of month
monthend = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] #last day... |
ec7ef62e32d0cbcb34c0f1c7b8c5ba699026c869 | alecbarber/parsimony-unlambda | /tm/tm/machine.py | 4,470 | 3.609375 | 4 | from .state import State
import sys
class Machine:
def __init__(self, alphabet, states):
self.alphabet = alphabet
self.states = states
def printMachine(self, output = sys.stdout):
output.write(self.alphabet + '\n')
for state in self.states:
state.printState(outp... |
ea0c284f1acaf85a17de68b8f91c1c9179dc6aae | Jimmy-INL/causal-analysis-on-air-pollution | /data_acquisition/weather/subset_sensors.py | 4,599 | 3.671875 | 4 | """
This script maps the sensors from a specific location given its coordinates constraint by a maximum radius defined by the user to their
closest weather stations, it saves the final results to the relative path: ../../data/intermediate/berlin_enrichable_sensors.csv
"""
__author__ = 'Ricardo Salazar'
from g... |
e6f903562157eec946758927bce73b274df2ea09 | augustjanse/project-euler | /Project Euler/src/p009.py | 467 | 3.734375 | 4 | # a^2 + b^2 = c^2
# a + b + c = 1000
# 0 < a < b < c < 1000
c = 334
c_list = []
while c <= 1000:
c_list.append(c)
c += 1
b = 334
b_list = []
while b <= 1000:
b_list.append(b)
b += 1
a = 1
a_list = []
while a <= 333:
a_list.append(a)
a += 1
def loop():
for c in c_list: # O(n^3)
for b in b_list:
for a in ... |
c3e4e9f463ebb501e3cd5153b3730afa55c3c6b1 | TeoCalvo/esp-bdds | /1semestre/lin-ds/andre/aula02/base_tri.py | 211 | 3.796875 | 4 | def area_tri(base, altura):
return base * altura / 2.
base = float( input("Entre com a base do triangulo: ") )
altura = float( input("Entre com a altura do triangulo: ") )
print( area_tri( base, altura) )
|
a5366432eeadf8c2c2e022206a86bb80ab820258 | QUAFFquaff/EECS221_Assignment1 | /e.py | 1,549 | 3.546875 | 4 | # Simple demo of the TCS34725 color sensor.
# Will detect the color from the sensor and print it out every second.
import time
import board
import busio
import adafruit_tcs34725
import RPi.GPIO as GPIO
# Initialize I2C bus and sensor.
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_tcs34725.TCS34725(i2c)
GPIO.s... |
12f482950563599c33857c3264b4ce5c56e6a64d | xwinxu/foobar | /p1/cake.py | 2,679 | 4.1875 | 4 | """
The cake is not a lie!
======================
Commander Lambda has had an incredibly successful week: she completed the first test run of her LAMBCHOP doomsday device, she captured six key members of the Bunny Rebellion, and she beat her personal high score in Tetris. To celebrate, she's ordered cake for everyone -... |
d75f8d1721d875e4381ca2ec95163ac364362fab | MinghaoDu1994/Asteroseismology | /io/make_dir.py | 842 | 3.859375 | 4 | #!/usr/bin/env/ python
# coding: utf-8
import os
import shutil
__all__ = ["mkdir"]
def mkdir(path: str, if_delete=False):
folder = os.path.exists(path)
if not folder: #判断是否存在文件夹如果不存在则创建为文件夹
os.makedirs(path) #makedirs 创建文件时如果路径不存在会创建这个路径
print("--- new folder... ... |
886e2b44d6bdaac9a5ef0ad6c363e0d6a5d623b9 | Dissturbia/Phyton- | /index.py | 664 | 4.0625 | 4 |
#Declarar 5 variables (nombre, apellido, edad, altura, peso)
#con tus datos personales (o los que tu quieras).
#Luego, con la función print devuelve todos los datos por pantalla con el siguiente formato:
#>>> print "Texto: ", variable
#Donde "Texto: " cambiará por el valor que queremos mostrar
# (en caso de que se... |
39645cbea1e45457840179ba93709fa02890327b | Harsh-0606/python-projects | /digital python clock .py | 1,088 | 3.96875 | 4 | #importing libraries
from tkinter import Label, Tk
import time
#creating the window, naming it and setting the size
app_window = Tk()
app_window.title("Digital Clock")
app_window.geometry("450x150")
app_window.minsize(300,90)
app_window.resizable(1,1)
#definig the properties of label
text_font= ("Times New Roma... |
47d983b56b8db5afe7802a4ee8c87e39bb4030cd | jorgedelavg04/Algorithms-Analysis- | /Algorithms.py | 5,255 | 3.703125 | 4 | import matplotlib.pyplot as plt
import numpy as np
import time
import random
import sys
sys.setrecursionlimit(1500)
__Nombre__ = "Jorge C De la Vega C"
### Algoritmos ###
# Insertion Sort(Ciclico)
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
... |
1c0189f64205fe22df2f1a1fe1db9264c37e99e2 | milySW/DataScience | /ML projects/food_classifier_with_CNN/functions/food_classifier_plotting_functions.py | 4,495 | 3.515625 | 4 | import matplotlib.pyplot as plt
import matplotlib.image as img
from PIL import Image
import numpy as np
import itertools
def plot_accuracy_loss(history):
"""
Function plotting:
:accuracy and validation accuracy on firs plot
:loss and validation loss on second plot
"""
fig = plt.figure(figsize=... |
cc6c2f04fe552a6253622ebc1b66a3ca307183c0 | milySW/DataScience | /ML projects/face_detector/face_detector/data_validation/check_images.py | 1,598 | 3.5625 | 4 | import os
from PIL import Image
def my_root_listdir(root_dir):
"""
Method counting photos and creatig list of subfolders with images.
:param str root_dir - images main directory name.
:return list of subfolders with images.
"""
root_listdir = [
images_dir
for images_dir in... |
4d91b5800f27122802fe8925b6b2cb851285c767 | bopes/ml-study | /sklearn/2-statistical-learning/2-supervised-learning/1_nearest_neighbors.py | 1,959 | 3.953125 | 4 | import numpy as np
from sklearn import datasets
iris = datasets.load_iris()
iris_X = iris.data # Raw data
iris_y = iris.target # Known classifications for training
# Split data randomly (seed is used to ensure consistency with tutorial)
np.random.seed(0)
indices = np.random.permutation(len(iris_X))
# Training sets
i... |
e2e65f0ea7ca91a71f0e3518c1e668ea8cebf37e | bopes/ml-study | /sklearn/2-statistical-learning/1-statistical-inference/1_datasets.py | 748 | 3.703125 | 4 | # Datasets
from sklearn import datasets
# Iris data is already prepped for sklearn - it is a 2d array
iris = datasets.load_iris()
data = iris.data
print(data.shape) # (150, 4) - 150 examples with 4 features each
# Digits data is not ready for sklearn - it is a 3d array and needs to be reduced to 2d
digits = datasets.l... |
ac7af28c0ed6ff0af79901f717def13a2b41b150 | bopes/ml-study | /sklearn/2-statistical-learning/5-putting-it-together/1-pipelining.py | 1,096 | 3.546875 | 4 | # Pipelining
# Pipe lining lets you create combined estimators
from sklearn import linear_model, decomposition, datasets
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
# Create estimators
logistic = linear_model.LogisticRegression()
pca = decomposition.PCA()
# Create pipeline
pi... |
c49dd699ab8c20e84e819834d0e99bda61bfbbf6 | xdedss/wxDemo | /breakpoint.py | 773 | 3.515625 | 4 | # -*- coding: utf-8 -*-
def breakpoint(bpname, args):
print('>enter breakpoint ' + str(bpname))
while True:
try:
input_exp = input('>>')
if input_exp == 'break':
print('>exit breakpoint ' + str(bpname))
break
eval_res = eval(input_exp)... |
c6697b21ba37c3b107d8a7e1be3ead49319c2841 | pinkrabbit412/tweepy | /examples/API_v2/get_liking_users.py | 531 | 3.609375 | 4 | import tweepy
bearer_token = ""
client = tweepy.Client(bearer_token)
# Get Tweet's Liking Users
# This endpoint/method allows you to get information about a Tweet’s liking
# users
tweet_id = 1460323737035677698
# By default, only the ID, name, and username fields of each user will be
# returned
# Additional fiel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.