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 |
|---|---|---|---|---|---|---|
bbe36136f25f9272139ee9691ff53d8dcd1a5030 | Shantanu0330/Random-number-generator | /ran_num_gen.py | 613 | 3.90625 | 4 | import random
winning_number = random.randint(1,100)
guess = 1
guess_number=int(input("Guess any no. between 1 to 100:"))
game_over = False
while not game_over:
if guess_number == winning_number:
print(f"YOU WIN, and You guess this no. in {guess} times")
game_over = True
else:
if gu... |
533c3f47b87608a5e60251630f015cfaf4ef3c14 | chenmoshushi/nram | /model/interpreter/datatype.py | 534 | 3.609375 | 4 | import numpy as np
class DataType(object):
'''
Input and output datatype
may be discrete(a number between 0 to M-1) or fuzzy (distribution over 0 to M-1)
'''
def __init__(self, v):
raise NotImplementedError
class Discrete(DataType):
def __init__(self, v: int):
if not isinst... |
6adb914dbdce0373fe4994bdf411bb559b1b9e53 | julienhuang/BMI_calcultion | /BMI.py | 529 | 4.03125 | 4 | #計算BMI
height = int(input('請輸入您的身高(公分) = '))
height_m = (height) / 100
weight = int(input('請輸入您的體重(公斤) = '))
bmi = float(weight / (height_m * height_m))
if bmi < 18.5:
print('您的體重過輕')
elif bmi >= 18.5 and bmi < 24:
print('您的體重正常!')
elif bmi >= 24 and bmi < 27:
print('您的體重過胖!')
elif bmi >= 27 and bmi < 30:
print('您的... |
4c3b05ff636d4f75967b46c34b5149e01ad71936 | talwai/rapcountr | /rapcountr/query_server.py | 2,105 | 3.546875 | 4 | """Script to read user queries and output ranked words matching that query.
Usage: python query_server.py [filename containing (name, score) pairs]"""
import sys
from bisect import insort
from construct import *
if len(sys.argv) is not 2:
sys.exit("Wrong Argument Length. Usage: python query_server.py [filenam... |
74978a31936ba005d40bdc677befe089ed7b8d60 | talwai/rapcountr | /src/construct.py | 874 | 3.78125 | 4 | """Module for constructing serializable JSON Trie structure.
Function construct_json(filename) reads in file 'filename'
and builds Trie from word-score pairs. This Trie is then
encoded using jsonpickle extension library."""
import jsonpickle #Before running, pip install jsonpickle
import trie
def construct_j... |
4f2085c90f63b8b6bbe54ca41668ac9eef7c5ead | felixvalin/CosmicStrings | /Code/norm_array_Eloise.py | 5,498 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 26 15:37:43 2017
@author: felix
"""
"""
In order to use this on a 2-D square, we use the functions as follow:
(Example with n = 9)
>>> twins2d(quadrant_assignment(9))
array([[ 1., 3., 5., 7., 9., 7., 5., 3., 1.],
[ 3., 3., 5., 7., 9., 7., 5., 3., 3... |
8eb45e27698a72da7d960db870b05b3379f67e0c | MrAurochs/ForWork | /ForGit/Python/UgandaAdventure.py | 3,731 | 3.90625 | 4 | import time
def End_Game():
import sys; sys.exit()
Money = 50000
print ("""
You are in a compound in Uganda. It's made of concrete, brick with iron doors.
There is trash littered randomly on the ground mixed with the mud.
Half-naked children play around casually as their mothers cook or wash clothes.
A ... |
53d9c618ee4ec455ef40048b314c4c578c521849 | tipss/c2016 | /python2016/json_imports.py | 416 | 3.75 | 4 | # Convert json file to dictionary by readin a file
import json
file = open('./friends_json.txt', 'r')
file_contents = json.load(file) #reads file and turns into dictionary
file.close()
print(file_contents['friends'][0])
print(file_contents['friends'][1])
#Convert a dictionary into json file
cars = [{'name':'altima','... |
ca1194d13b1362e8e0f92a6d90b306d8fe9aff51 | tipss/c2016 | /python2016/fibonacci.py | 281 | 3.9375 | 4 |
'''
non recursive
'''
def fib1(n):
if n <= 1:
return (n)
a = 0
b = 1
for i in range(n-1):
a, b = b, a + b
return b
def fib(n):
if n <=1:
return n
return fib(n-1) + fib(n-2)
for i in range(10):
print(fib(i), " ", fib1(i))
|
2db369fc5574fc6302e78a0170d02cb3143d3023 | darkwhale/seed_optimize | /dynamic_step.py | 2,327 | 3.515625 | 4 | from math import sqrt
from utils import merge_seed
from queue import Queue
class DynamicStep(object):
"""动态步长算法"""
def __init__(self,
seed,
spare_capacity,
max_step=10,
compact_step=20):
"""
:param seed: 种子
:param ... |
b66036793436fa8ddf922ad528128768c984bbf5 | mlberkeley/selfdriving-sp20 | /hw/control/control_loop.py | 1,844 | 3.71875 | 4 | import numpy as np
from abc import ABC, abstractmethod
'''
Abstract ControlLoop Class
Handles updating the current waypoint as the controller traverses a trajectory.
Input:
waypoints: list of numpy arrays, each with [x,y]
dt: time between each iteration of the control loop
threshold: distance that is "clos... |
886ccff861f06f5b81869362aec6da9a99dde570 | FedeFiores95/Pildoras-Informaticas | /practica bucles 4.py | 653 | 3.96875 | 4 | import math
edad=int(input("Introduce tu edad: "))
while edad<=0 or edad>100:
print("Has introducido una edad incorrecta. Vuelve a intentarlo")
edad=int(input("Introduce tu edad: "))
print(f"Tu edad es {edad}")
print("¨Programa de cálculo de raíz cuadrada")
numero=int(input("Introduce un numero: "))
intentos=0
... |
17989812c780b9b9a5ab52a1d9a1221d648a1502 | FedeFiores95/Pildoras-Informaticas | /practica condicionales 2.py | 259 | 3.75 | 4 | # IF = Si condicional
# Else = Si no es verdad
print("Verificación de acceso")
edad_usuario=int(input("Introduzca su edad: "))
if edad_usuario<18:
print("No puedes entrar")
elif edad_usuario>100:
print("Edad incorrecta")
else:
print("Puedes Pasar")
|
7924285794d1dff49eb5c534a72902188a3419d1 | FedeFiores95/Pildoras-Informaticas | /cadenas.py | 122 | 3.78125 | 4 | edad=input("Edad: ")
while (edad.isdigit()==False):
print("Por favor, introduce un numero: ")
edad=input("Edad: ") |
293a48032294678c7a0f8ad83e07adc907d59188 | Obiora-Imah/Pocket-Library | /backend_bookstore.py | 1,692 | 3.71875 | 4 | import sqlite3
class BackendBookStore:
def conn(self):
return sqlite3.connect("book_store.db")
def __init__(self):
self._conn = sqlite3.connect("book_store.db")
self.cur = self._conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TE... |
89ef1d172bb2140b128f1715486c0e56d3aeb56e | samhaak/haakMIS407 | /test2.py | 449 | 3.859375 | 4 | class Person:
def ___inti___(self, **kwargs):
self.vars = kwargs
def get_vars(self, k):
return self.vars.get(k, none)
def set_vars(self, k, v):
self.vars[k] = v
def func1(self):
print("My name is " + self.vars[k])
class Student(Person):
"""
...tuple
...lists... |
a221f1dd62fc93c85c1329c670fe4d330df35caa | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Hard_Problem004.py | 1,069 | 4.125 | 4 | import logging
'''This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the ... |
79dacd2b79eb76486bfcb0ad860b01eced6ff016 | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Hard_Problem012.py | 1,032 | 4.53125 | 5 | '''This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, ... |
8fade422847b05791bba294fe852c885c73c0395 | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Easy_Problem077.py | 1,409 | 3.921875 | 4 | ''' This problem was asked by Snapchat.
Given a list of possibly overlapping intervals, return a new list of intervals where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should return [(1, 3), (4, 10), (2... |
516d6140b5146293b8e86c804c35998117281aec | imthefrizzlefry/PythonPractice | /HackerRank/test_countingValleys.py | 803 | 3.515625 | 4 | import unittest
import countingValleys
class countingValleysTests(unittest.TestCase):
def test_exampleInput(self):
inputSteps = 'UDDDUDUU'
inputNumberSteps = 8
expectedValleys = 1
self.assertEqual(expectedValleys, countingValleys.countingValleys(inputNumberSteps,inputSteps))
... |
812203011f0a9aff21e71a490219f095b73894df | imthefrizzlefry/PythonPractice | /HackerRank/rotateArrayLeft.py | 227 | 3.6875 | 4 | def rotLeft(a, d):
finalArray = []
if d == len(a):
return a
for x in range(d, len(a)):
finalArray.append(a[x])
for x in range(d):
finalArray.append(a[x])
return finalArray |
558eae13e72f05babfc07c3e47749bd2f3c8bd64 | imthefrizzlefry/PythonPractice | /interviewProblems/blackjack_hand.py | 4,789 | 4.34375 | 4 | ''' asked by Avalara
implement a method for calculating a blackjack score
['ace', 'ace', 'ace', 'ace', '2', '2', '2', '2', '3', '3', '3'] => 21
['ace','ace'] => 12
5, 7, 10 => 0
ect...
write this method and test it
I forgot to include all my tests here, but I included:
1 test for each card alone as the hand
jack ja... |
ccbcca0086d81c6820d533a885d7bdef1f542094 | imthefrizzlefry/PythonPractice | /HackerRank/jumpingOnClouds.py | 268 | 3.53125 | 4 | def jumpingOnClouds(c):
numberOfJumps = 0
position = 0
while position < len(c)-1:
if position < len(c)-2 and c[position+2] == 0:
position += 2
else:
position += 1
numberOfJumps += 1
return numberOfJumps |
1ea4b04f82d87f5fa5e91ac7476adc0f7f2f771a | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Medium_Problem005.py | 755 | 3.984375 | 4 | import logging
'''This problem was asked by Jane Street.
cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.
For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
Given this implementation of cons on line 10
Implement car and cdr.
'''
def cons... |
b2a3c799a8468beb75694eb1a8f5b1651b0c136d | aiguy110/q_learning | /agent_env.py | 2,435 | 3.515625 | 4 | import numpy as np
import random
BLANK = 0
FOOD = 1
SPIKES = -1
WALL = -10
PLAYER = 10
UP = 0
DOWN = 1
RIGHT = 2
LEFT = 3
board_size = 25
def place_tiles(tile_type, prob):
global baord
global board_size
for i in range(board_size):
for j in range(board_size):
if board[i,j] != 0:
... |
58d509a70a6464f18296ef392692de534b97b175 | HussonnoisMaxence/mpsi_demineur | /Programmes/chrono.py | 922 | 3.609375 | 4 | def chronometre(n):
import time
import matplotlib.pyplot as plt
import numpy as np
temps=time.time()
while 1:
y=time.time()-temps
if int(y) == n:
plt.ylim([0,y+2])
plt.xlim([0,y+2])
plt.plot([0.0, y*0.5], [y, y],'k-',lw=2)
plt.plot([y*0... |
b075eaa1eb0118a9f0fd0e112b91f318e4a98a20 | Aifedayo/Logic | /palindrome.py | 346 | 4.375 | 4 | def palindrome(string):
'''
Python function that checks whether a word
or phrase is palindrome or not
'''
new_string = string.replace(' ','')
if new_string == new_string[::-1]:
print(f'{string} is a palindrome')
else:
print(f'{string} is not a palindrome')
palindrome(input(... |
e2f564aa0b5211f4d96f039c51fd28b5fc90b782 | ordikhan/exam-in-quora | /Yellow question.py | 160 | 3.59375 | 4 | def yellow(n):
print("W",end="")
for i in range(n):
print("o",end="")
print("w!")
a= eval(input("enter number"))
yellow(a)
|
f01b906855381b03ece102b02afaa7d8692b461a | Manish-code/Using-OpenCV | /Face Detector/video_face_detection.py | 1,114 | 3.53125 | 4 | import cv2
from random import randrange
#Load some pre-trained data on face frontals from opencv ( haar cascade algorithm)
trained_face_data = cv2.CascadeClassifier('Face Detector\haarcascade_frontalface_default.xml')
# to capture video from webcam
#webcam = cv2.VideoCapture(0)
webcam = cv2.VideoCapture(r'C:\Users\M... |
2b288e37ceb0c00528623ce6c863597d09aebfb8 | ish-suarez/afs-200 | /week5/function/function.py | 481 | 4.1875 | 4 | def step1():
user_input = []
print(f'I will be asking you for 3 numbers')
for i in range(3):
num = int(input(f'Give me a number: '))
user_input.append(num)
input_max = max(num for num in user_input)
input_min = min(num for num in user_input)
print(f'Your Numbers are: {user... |
affa4eda6861fe0c5a2e31f232d3714fa15d84e8 | ish-suarez/afs-200 | /week2/evenOrOdd/evenOrOdd.py | 1,078 | 4.28125 | 4 | # Getting input to determine if numbers are even or odd
def user_input_eve_or_odd():
number = int(input('Give me a number and I will tell you if it is even or odd? '))
check_if_even_or_odd = number % 2
if check_if_even_or_odd == 0:
print(f"{number} is Even")
else:
print(f"{number} is Od... |
c96575408a1134c7cb1ac313a1a92263ce725dd6 | duke-moose/nfl_bot | /nfl_bot/scrapy_nfl/scrapy_nfl/spiders/nfl_schedule.py | 814 | 3.515625 | 4 | import scrapy
"""
Scrapes NFL Schedule Website
run in terminal: scrapy crawl nfl_schedule -o [year]_nfl_schedule.json
xpath example: response.xpath('/html/body/table/tbody/tr/td/text()')
css response.css("html.body.table.tbody.tr.td::text")
.get: returns the entire selector
.get(): returns only data from the sele... |
42e994a4b51aacb4f80951ba26c1f74a7ffda0b1 | duke-moose/nfl_bot | /nfl_bot/fixes.py | 619 | 3.5625 | 4 | '''Fix Jacksonville, LA Rams, & LA Chargers'''
def team_fix(team):
if team in ['JAC']:
team_new = 'JAX'
elif team in ['STL', 'LAR']:
team_new = 'LA'
elif team in ['SD']:
team_new = 'LAC'
elif team in ['WSH']:
team_new = 'WAS'
else:
team_new = team
return t... |
4e26506e47f756f2b105fb58f2970ca7b82d5a7e | maayan20-meet/meet2018y1lab5 | /caught_speeding.py | 377 | 3.546875 | 4 | speed = 50
is_birthday = True
if (is_birthday = False and speed < 31) or (is_birthday = True and speed < 36):
print('no ticket')
if (is_birthday = False and speed > 31 and speed < 51) or (is_birthday = True and speed < 36 and speed < 56):
print('small ticket')
if (is_birthday = False and speed < 50) or (is_b... |
2c59065484a4eca931ae3e92ad20a9cdaf0aea0e | maayan20-meet/meet2018y1lab5 | /fun1.py | 269 | 3.765625 | 4 | def add_numbers(start, end, n):
SUM = 0
for number in range(start, end + 1):
SUM = number + SUM
return SUM
answer = add_numbers(1,100, 1)
print(answer)
test2 = add_numbers(333,777, 1)
print(test2)
test3 = add_numbers(1, 10, 2)
print(test3)
|
4f22ae3685a8024e3a70f7721495510c0ca139db | maayan20-meet/meet2018y1lab5 | /fun2.py | 1,111 | 4.28125 | 4 | import turtle
turtle.goto(0,0)
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
direction = None
def up():
global direction
print("You pressed the up key.")
direction = UP
on_move()
def down():
global direction
print("you pressed the down key")
direction = DOWN
on_move()
def left():
global di... |
f6ac9e587e971d4ed774173f0f0c93e883b2a690 | Harshit-1997/FlappyBirdAI | /Bird.py | 695 | 3.578125 | 4 | import pygame
class Bird:
def __init__(self, screen_width, screen_height, size):
self.screen_width = screen_width
self.screen_height = screen_height
self.x = 100
self.y = self.screen_height/2
self.size = size
self.velocity = 0
self.acceleration = 0.2
def... |
ab3e359ac1e494ae90d567d1a282f0d979308286 | kcerna/piskvorky | /tah_hrace.py | 927 | 3.546875 | 4 | from tah import tah
def tah_hrace (pole, pozice):
if pozice < 0:
#print('Pozice nemuze mit zapornou hodnotu! Zkus jeste ')
raise ValueError('Pozice nemuze mit zapornou hodnotu! Zkus jeste ')
return
elif pozice > 19:
#print('Je to prilis velke cislo drz se rozmezi 0 az 19! Zkus ... |
1ee69b4669c48ad85dd511ae57d7d4125cf6f645 | VimleshS/python-design-pattern | /Strategy pattern/solution_1.py | 2,021 | 4.125 | 4 | """
All the classes must in a seperate file.
Problems in this approch.
Order Class
It is not adhering to S of solid principles
There is no reason for order class to know about shipper.
Shipping Cost
Uses a default contructor.
Uses the shipper type stored in a shipper class to ca... |
7b0e1708e88595df66466c47dacfdfa2b07d591a | PolleAnker/FSM-and-AStar | /drawFunctions.py | 3,356 | 3.5625 | 4 | import pygame as pg
import Pathfinding as pf
import time
import fsm as fsm
def draw_grid(color, width, height, tilesize, screen):
# Draw the grid on the screen
for x in range(0, width, tilesize):
pg.draw.line(screen, color, (x, 0), (x, height))
for y in range(0, height, tilesize):
pg.draw.... |
6b3cff2f8615100d1f8522b29ff6d6b6e25f1f06 | NelsonZeng25/Ormuco-Test | /Q2-VersionString/test_compare.py | 8,039 | 3.734375 | 4 | import unittest
from versionString.version_compare import compare
class TestCompare(unittest.TestCase):
def test_numerical(self):
# ------- GREATER --------
version1 = "1.1.2"
version2 = "1.1.1"
self.assertEqual(compare(version1, version2), version1 + " is greater than " + version2)... |
0a822482c200895b00138304f062b37a85c4d4bf | alexanderbarati/python | /4: Lists, Tuples, and Sets.py | 3,280 | 4.53125 | 5 | '''1'''
courses =['History', 'Math', 'Physic', 'Computer']
print(courses)
print(len(courses))
print(courses[0])
print(courses[3])
print(courses[-1]) # This print always the last item of list
print(courses[0:2]) # first index is inclusive but the second one is not
print(courses[:2])
print(courses[2:])
'''[Slicing Lists ... |
4c3fc6f4a14ed944178709f0f9c07d41aa6acac2 | NicolaFerracin/ComputerScience | /Grokking Algorithms/quick_sort.py | 343 | 3.984375 | 4 | def quick_sort(list):
if len(list) < 2:
return list
pivot = list[len(list) // 2]
smaller = [i for i in list if i < pivot]
equal = [i for i in list if i == pivot]
greater = [i for i in list if i > pivot]
return quick_sort(smaller) + equal + quick_sort(greater)
print(quick_sort([5, 4, ... |
17e433ef0a0ca17e0e93017a65401df4402b5e81 | SobuleacCatalina/Introducere_Afisare_Calcule | /problema_7.py | 139 | 3.71875 | 4 | v=int(input("Introdu varsta:"))
g=2*v+8
h=5*v+80
print("Greutatea ideala este",g,"kilograme")
print("Inaltimea ideala este",h,"centimetri") |
498eec796d0f06500f48c4143a6ce1bd56a468c3 | sonivre/Coinche-2 | /Old/Code_vincent/test_class.py | 2,105 | 3.765625 | 4 | #!/var/bin python
import unittest
from card import Card
from deck import Deck
class TestCard(unittest.TestCase):
def setUp(self):
#initialise test
pass
def test_create_card(self):
""" TEST Card WHEN create card with correct value SHOULD create"""
cardtest = Card(4, ... |
9ec752bfa3fba08a2fd825deeb223f37a82b0365 | KTakatsuji/NewsCurate | /newsCurate.py | 5,969 | 3.890625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 21 11:14:20 2017
@author: Tacosushi
"""
#This is a python program that creates a new text file calle "News" or updates it (writes over anything previously in the text file)
#with the title and summary of articles from the NYTimes
#Import urllib2 to... |
2837fba45f481d7cf3c834a8fada0e391a23699e | John-d80/py_basic | /lesson_5/task_2.py | 721 | 3.890625 | 4 | """
2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк,
количества слов в каждой строке.
"""
count_words_dict = {}
# открываем файл на чтение в кодировке UTF-8
with open('2_task.txt', 'r', encoding='utf-8') as input_file:
for n, line in enumerate(input_f... |
ff6306733d264b4b2000ff02b5e799685af7c276 | John-d80/py_basic | /lesson_6/task_4.py | 3,666 | 3.515625 | 4 | """
4. Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты:
speed, color, name, is_police (булево). А также методы: go, stop, turn(direction), которые должны сообщать,
что машина поехала, остановилась, повернула (куда). Опишите несколько дочерних классов: TownCar, SportCar,
WorkCar, PoliceCar.... |
aff3d2b82a324e9747cc022b2d46389ca16a248a | John-d80/py_basic | /lesson_5/task_5.py | 855 | 4 | 4 | """
5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
"""
numbers_to_insert = [123, -485, 555.55, 28.27, 674, 18, 17, 16]
# запись в файл (перед записью преобразуем числа в str
with open('5_t... |
cc2a34dabe8c3befcb4d80cda6725309b610527f | sahilmishra0012/OpenCV-Tutorials | /3.shapeonimage.py | 984 | 3.5625 | 4 | # Program to read, write and show images
import cv2
img=cv2.imread('robin.jpg',1)
#cv2.line(img,(Start Point Tuple),(End Point Tuple),(RGB Tuple),thickness)
img=cv2.line(img,pt1=(100,100),pt2=(400,500),color=(255,0,0),thickness=5)
img=cv2.arrowedLine(img,pt1=(200,100),pt2=(600,500),color=(255,0,0),thickness=5)
img=c... |
e762a4808158522507799607901febcf9188377d | ejportega/Learn-Python-The-Hard-Way | /ex19_studydrills.py | 208 | 4.0625 | 4 | def add(num1, num2):
print("{} + {} answer is {}".format(num1, num2, num1 + num2))
# num1 = int(input("Enter first number:"))
add(int(input("Enter first number: ")), int(input("Enter second number: ")))
|
04df23aa5608329ede57bdd56345801bf9609044 | sourabbmk/mini_p | /pi_tillnvalue/pi_to_nvalue.py | 941 | 4.09375 | 4 | #pi=(Diameter of circle)/(circumference of circle)
#Chudnovsky Algorithm
import math
from decimal import *
#Define factorial using recursion
def factorial(n):
if not n:
return 1
return n*factorial(n-1)
#Define k
#k=number of decimal places.
#k iterations give k-1 decimal places. so, we use, k=... |
b4f369995b51c3f82e5ebb827f474ce95f06048a | afurkany/ITU-CE-MSc | /BLG604E (Deep Reinforcement Learning)/Homework2/dqn/replaybuffer/seg_tree.py | 3,575 | 3.828125 | 4 | """ Sum Tree implementation for the prioritized
replay buffer.
"""
import numpy as np
class SegTree():
""" Base Segment Tree Class with binary heap implementation that push
values as a Queue(FIFO).
Arguments:
- capacity: Maximum size of the tree. It also the number of leaf
nod... |
e113872468cb5d26e85da2a31fc20ccc81b4a867 | afurkany/ITU-CE-MSc | /BLG561E (Deep Learning)/Homework1/Coding Section/blg561/layer/layer.py | 9,651 | 3.71875 | 4 | import numpy as np
from abc import ABC, abstractmethod
class Layer(ABC):
'''
Abstract layer class which implements forward and backward methods
'''
def __init__(self):
self.x = None
@abstractmethod
def forward(self, x):
raise NotImplementedError('Abstract class!')
@a... |
c399864512a59fd1fb1e325a938013bdb0c98417 | johngable/EmpiricalStudyOfAlgorithms | /Python_Implementation/Heapsort.py | 3,378 | 4.21875 | 4 | import os
import time
import sys
#This code is meant to replicate the functionality of the
#books version of heapBottomUp. I had to make slight changes
#because of optimizations.
def heapBottomUp(H):
n=len(H)
i=n/2
while i>=1:
k=int(i)
v=H[int(k)-1]
heap = False
while( not... |
3947858a10bb6fe6e1f0549d39c60f70de70a696 | UmberShadow/PigLatin | /UmberShadow_Pig Latin.py | 989 | 4.5 | 4 | #CJ Malson
#March 6th, 2021
#Intro to Python Programming
#Professor Wright
#I don't understand pig latin at all. What is this??
#Program requests a word (in lowercase letters) as input and translates the word into Pig Latin.
#If the word begins with a group of consonants, move them to the end of the word and ... |
378886fbb3941130aea93aecdb5701bd6ef7b995 | Filter94/Learning_Python | /average2.py | 998 | 3.765625 | 4 | #!/usr/bin/env python3
numbers=[]
lowest=None
highest=None
sum=0
count=0
while True:
line = input("enter a number or Enter to finish: ")
if line:
try:
number = int(line)
except ValueError as err:
print(err)
continue
if lowest is None or number < lowe... |
1feda06fdbdda4904208bb4d15523fbba572823c | la-21/python-exercises | /data_structure.py | 2,872 | 3.734375 | 4 | string1 = "heLLo woRld"
print(string1.lower())
print(string1.upper())
print(string1.capitalize())
print(string1.title())
print(string1.count("l"))
print(string1.split(" "))
print("String here {} and another string here {}".format("string1", "string2"))
print("String here {1} and another string here {0}".format("str... |
08954644f022f41a8d1004ad215e79890cc2282d | KirstieJane/advent-code-2019 | /day01/day01_puz2.py | 2,516 | 4.03125 | 4 | #! /usr/bin/env python
import numpy as np
import pandas as pd
def module_fuel_req(mass):
"""Calculate the amount of fuel required for a module of a given mass
taking into account the additional fuel that is required for the required
fuel itself!
Parameters
----------
mass : float
The... |
35b2f997f576eb457ee070c761f44d83e7924010 | KirstieJane/advent-code-2019 | /day06/day06_puz2.py | 4,107 | 4.34375 | 4 | #! /usr/bin/env python
def load_orbit_data(fname):
"""Read in input file with the orbit information provided.
Parameters
----------
fname : string
File provided by advent of code competition
"""
# Create empty orbit dictionary
orbit_dict = {}
# Read in each line, and split b... |
3bbe87138d39f4c5be83c2a8556216a908710e8e | sudhakumari2/while-loop | /table .py | 325 | 4.09375 | 4 | # multiple two digit num1+num2
# num1 = int(input("enter first number"))
# num2 = int(input("enter second number"))
# add = 0
# i = 1
# while i<= num1:
# add = add+num2
# i = i+1
# print("multiplication of" , add)
# fibonchi series
# a = 0
# b = 1
# while a<=100:
# print(a)
# c = a+b
# a = b
# ... |
693aa7a983a83814395518f00d68d6345502694b | luqiang21/Hackerrank.com | /Cracking the Coding Interview/Davis'_Staricase.py | 1,891 | 4.1875 | 4 | '''
Davis' staircase, climb by 1, 2 or 3 steps when given n stairs
in a staircase
'''
import numpy as np
def staircase(n):
# this function is written based on discussion of this problem on
# the website
A = [1,2,4]
A.append(sum(A))
A.append(A[1] + A[2] + A[3])
M = np.array([[1,1,0],[1,0,1],[1,0,0]])
An = np.arr... |
6b09e1c2b441912475854c4e7cd363f7baabeba9 | dumildematos/Python | /exercices/string_length.py | 368 | 3.984375 | 4 | #Tamanho de Strings
text1 = input('Introduza o primeiro texto ')
text2 = input('Introduza o segundo texto ')
print('O tamanho ' , text1 , ':' , len(text1) , 'Carateres')
print('O tamanho ' , text2 , ':' , len(text2) , 'Carateres')
if(len(text1) != len(text2)):
print('As duas são diferentes')
elif(len(text1) == l... |
e5822481483705f34f2af0672ada9d3e81ed8af7 | jlesca/python-booleans | /values-booleans.py | 633 | 4.125 | 4 | # VALORES BOOLEANOS EN PYTHON
# En Python podemos usar operadores relacionales para comparar dos valores.
print(10 > 9) # Mostrará True
print(10 == 9) # Mostrará False
print(10 < 9) # Mostrará False
# Podemos hacer uso de un IF para comparar dos valores y ejecutar una instrucción si ese IF se cumple.
a = 10 # Creo ... |
7d80694d70ac90c01f38598420cf65f8fd2f11cb | tsmsogn/exercism | /python/isogram/isogram.py | 196 | 3.90625 | 4 | def is_isogram(string):
letters = string.lower()
for letter in letters:
if letter.isalpha():
if letters.count(letter) > 1:
return False
return True
|
2812126b43f67a5a328af66acb481d68fcdbb327 | christophgietl/funktionale-konzepte | /code/immutable_data_use_mutable_type.py | 160 | 3.515625 | 4 | a = [42, 1]
print(f"First value of a: {a[0]}. ID of a: {id(a)}.")
# Set first value of a to 23:
a[0] = 23
print(f"First value of a: {a[0]}. ID of a: {id(a)}.")
|
03e6a0661540007dab31ec6fd55022e9b4f2fd16 | eva-villarroya/learn-python | /chapter 5/compare.py | 1,000 | 4.0625 | 4 | answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
age = 19
print("Age is " + str(age))
print("Is age under 21?")
print(age < 21)
print("Is age under or equal to 21?")
print(age <= 21)
print("Is age above 21?")
print(age > 21)
print("Is age above or equal to 21?")
print(age ... |
f852ce47dad931c0a5caf3137117d38716cdf8dd | eva-villarroya/learn-python | /chapter 4/tuples.py | 464 | 3.53125 | 4 | # immutable list = tuple
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
# cannot change values, this fails
#dimensions[0] = 250
for dimension in dimensions:
print(dimension)
# can change the tuple itself:
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:... |
dbed4cc35824c8346f72c4c1c64544dd0aef7f45 | ProgrammingDaisukiClub/Problems2021 | /F-Mohumohumohuhu/Python-Lgeu-AC/main.py | 164 | 3.6875 | 4 | #!/usr/bin/env python3
import re
T = int(input())
for _ in range(T):
N = int(input())
S = input()
print("Yes" if re.fullmatch(r"(mohu)+", S) else "No")
|
03c52c8c589043a678895355ad4c0c94b6d913e5 | Emmarex/PlantGrowthAnalysis | /GMpi/configuration.py | 935 | 3.515625 | 4 | #!/usr/bin/env python3
import os
from sys import exit, argv
from GMPi_Pack import BuildConfig
print("Making configuration file: config.txt")
try:
if len(argv) == 3:
dht = argv[1]
data_pin = argv[2]
elif len(argv) == 4:
dht = argv[2]
data_pin = argv[3]
else:
print("ERROR: Unable to parse DHT and... |
2405def839f28a981333bde0203deed0522a33f4 | summerzhao/algorithms | /nlp/cfg/transformer.py | 1,244 | 3.5625 | 4 | '''
Created on Apr 8, 2013
@author: stefaniezhao
'''
import sys, json
from collections import defaultdict
threshold = 5
rare_label = "_RARE_"
def word_counts(counts, tree):
if len(tree) == 3:
# It is a binary rule. Recursively count the children.
word_counts(counts, tree[1])
word_counts(c... |
fd9274dfe52ebf21c113fa3b44a4390c516e1a9d | SantoDiMaio/esercizi-laboratorio | /eserchizio quadrato.py | 98 | 3.59375 | 4 | print("inserisci un numero a capocchia")
numero= input()
numero=int(numero)
print(numero*numero)
|
4bd415c085f450727517e81170243dac251f4643 | danilvr/python-practice | /extra_practice05/part1/doctest/doctest_example.py | 1,154 | 4.1875 | 4 | def p1(a, b, c):
"""
Установление по сторонам (a, b, c) треугольника его типа:
равносторонний, разносторонний, равнобедренный.
Примеры:
>>> p1(1, 1, 1)
'равносторонний'
>>> p1(3, 4, 5)
'разносторонний'
>>> p1(5, 5, 3)
'равнобедренный'
>>> p1(1, 0, -1)
'сторона не может б... |
b0e4c1f837fce1ad9d11111577d668573ea5c1e2 | danilvr/python-practice | /practice03/task3_2.py | 2,244 | 3.6875 | 4 | """
Задача 3.2. Реализовать конечный автомат Мили в виде класса C32. Начальным состоянием
автомата является A. Методы возвращают числовые значения. Если вызываемый метод не реализован
для некоторого состояния, необходимо вызвать исключение RuntimeError.
"""
class C32:
def __init__(self):
self.state = C32.... |
90a012df57e2bfee71fa4821dd242da4fccc724a | scikit-hep/particle | /src/particle/particle/enums.py | 4,682 | 3.734375 | 4 | # Copyright (c) 2018-2023, Eduardo Rodrigues and Henry Schreiner.
#
# Distributed under the 3-clause BSD license, see accompanying file LICENSE
# or https://github.com/scikit-hep/particle for details.
"""
Collection of enums to help characterising particle properties
Examples are charge, spin and parity.
"""
from __f... |
ceea6270d517105ae1d9b12f29348d88a7a23cdd | tima-akulich/lesson8 | /iterators.py | 743 | 3.78125 | 4 | import random
class Iterator:
def __init__(self, n):
self.index = 0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.index < self.n:
index = self.index
self.index += 1
return index
else:
raise S... |
cadd72a67b0b334785d9c398637f47eaceff9e6b | jack-x/HackerEarthCode | /E_MaximumOccurrence.py | 621 | 3.65625 | 4 |
def main():
statement = input()
d=dict()
for s in statement:
if s in d.keys():
d[s]+=1
else:
d[s] = 1
max=[]
for x in d.keys():
if(len(max)==0):
max.append([x,d[x]])
#print("max {}".format(max))
else:
if(d[x] == max[0][1]):
max.append([x,d[x]])
elif(d[x] > max[0][1]):
max=[[... |
2b1d2a89c44b48fdbae94b9480a6feeb7d7a4023 | jack-x/HackerEarthCode | /E_DontBeGreedy.py | 3,030 | 3.578125 | 4 | def main():
mou = int(input())
M = input().split(' ')
# if Mm[-1] != ' ':
# M = Mm.split(' ')
# else:
# M = Mm[0:len(Mm)-1].split(' ')
mouses = [0]*mou
sumMice = 0
sumKeyboards = 0
for m in range(0,mou):
mouses[m] = int(M[m])
sumMice += mouses[m]
mouses.sort()
K = int(input())
keyboard = ... |
1964c31f1578a4154ce6399cef3953c7d66670de | jack-x/HackerEarthCode | /E_DedicationLevel.py | 624 | 3.8125 | 4 |
def main():
T=int(input())
d = {'Largest': [None,0],'SecondLargest':[None,0],'ThirdLargest':[None,0]}
for case in range(0,T):
coder = input().split(' ')
X = int(coder[1])
if X > d['Largest'][1]:
d['ThirdLargest'] = d['SecondLargest']
d['SecondLargest'] = d['Largest']
d['Largest'] = [coder[0],X]
... |
8a2eb5ed35db1b8c7f18648e8f23c05eff06b34b | jack-x/HackerEarthCode | /E_LongATMQueue.py | 248 | 3.546875 | 4 |
N = int(input())
Queue = input().split()
for index,item in enumerate(Queue):
Queue[index] = int(item)
numberOfGroups = 1
for x in range(0,len(Queue)-1):
if (Queue[x] > Queue[x+1]):
numberOfGroups = numberOfGroups + 1
print(numberOfGroups)
|
04d5b88f8f58a74cadc46ad41edfb00d02263701 | gbrosman27/mini_projects | /web_scraping.py | 951 | 3.703125 | 4 | import requests
from bs4 import BeautifulSoup
from csv import writer
# Get the website html to be scraped.
response = requests.get("https://www.rithmschool.com/blog")
# Send the above response to beautiful soup and save in variable.
soup = BeautifulSoup(response.text, "html.parser")
articles = soup.find_all("article"... |
4281da213ffe4162488f57acee4988685f6105e9 | jarble/Polyglot-code-generator | /examples/speakingCountdownTimer.py | 1,050 | 3.515625 | 4 | #!/usr/bin/env python
from time import sleep
from subprocess import call
def say(toSay):
call(["espeak", toSay])
def waitAndSpeak(timeToWait, thingsToSay):
sleep(timeToWait)
say(thingsToSay)
def countDown(timeInMinutes, toSay, interval):
#if(timeInMinutes % interval != 0):
# raise Exception("T... |
321cb60befeebd95889763e272177d7cdfd9f1a0 | sureshrmdec/algorithms | /app/dp/knapsack.py | 1,105 | 4.1875 | 4 | """
Given a weight limit for a knapsack, and a list of items with weights and benefits, find the optimal knapsack
which maximizes the benefit, whilee the total weight being less than the weight limit
https://www.youtube.com/watch?v=ipRGyCcbrGs
eg -
item 0 1 2 3
wt 5 2 8 6
benefit 9 3 1 4
wt limit = 10
soln: ... |
f45faa385782d01190945ab84805c8c3eabb9ad4 | martin-kar/project_euler | /p19_counting_sundays.py | 2,061 | 4.125 | 4 | """
Counting sundays
Problem 19
How many sundays fell on the first of the month during the twentieth
century (1 Jan 1901 to 31 Dec 2000)?
"""
DAYS_PER_WEEK = 7
SUNDAY = 7
DAYS_PER_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
MONTHS_PER_YEAR = 12
def get_days_this_month(month, year):
if is_leap_day(mo... |
28d24e0531c3f15a5f79fd0501f8f58662452f0b | joaolrsarmento/university | /courses/CT-213/lab3_ct213_2020/hill_climbing.py | 1,841 | 4.1875 | 4 | from math import inf
import numpy as np
def hill_climbing(cost_function, neighbors, theta0, epsilon, max_iterations):
"""
Executes the Hill Climbing (HC) algorithm to minimize (optimize) a cost function.
:param cost_function: function to be minimized.
:type cost_function: function.
:param... |
4cfffb4311ebdceff6cbd777f706c19ae28876c8 | joaolrsarmento/university | /courses/CT-213/lab5_ct213_2020/simple_evolution_strategy.py | 3,679 | 3.796875 | 4 | import numpy as np
class SimpleEvolutionStrategy:
"""
Represents a simple evolution strategy optimization algorithm.
The mean and covariance of a gaussian distribution are evolved at each generation.
"""
def __init__(self, m0, C0, mu, population_size):
"""
Constructs th... |
4cce723dc041b418b232ba63f37461557cf00b42 | adiljay05/Information-Retrieval-and-Web-Services- | /Task1/5 - IR System.py | 9,375 | 3.921875 | 4 | from porterStemmer import PorterStemmer
import sys
import math
# function to remove punctuation
def remove_punctuation_and_numbers(line):
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~1234567890''' # these symbols and characters will be removed
no_punct = ""
for char in line:
if char not in punct... |
9940102a087639114e277124a89a3ce40ec5272d | JoseGtz/2021_python_selenium | /Module_01/reverse_int.py | 230 | 4.0625 | 4 | def reverse_int(number: int) -> int:
aux = str(number)
aux = aux[::-1]
if isinstance(number, int):
number = int(aux)
else:
number = float(aux)
return number
x = 12345.234
print(reverse_int(x)) |
bc5417d1f4b32ffe8b5e7c994deeb6b20734daa1 | mimi1296/ClaseListas-Luis-Miguel- | /quitar negativos.py | 296 | 3.703125 | 4 | def quitarNegativos(a):
cont =0
print("Lista original: ",a)
while cont<len(a):
if a[cont] < 0:
a[cont] = 0
else:
a[cont] =a[cont]
cont =cont +1
print("Lista sin negativos: ", a)
quitarNegativos([3, -2, -1, -10, 4, -5])
|
a495f72ad98eab53216db978ad7c354c163e0b17 | Danthriel/rock-paper-scissors | /infinite rock paper scissors.py | 1,485 | 4.09375 | 4 | from random import randrange
def beats(choice1, choice2):
if (choice1 == "rock" and choice2 == 'scissors') or (choice1 == "scissors" and choice2 == "paper") or (choice1 == "paper" and choice2 == "rock"):
return True
elif (choice1 == "rock" and choice2 == 'paper') or (choice1 == "scissors" and c... |
379791de37004dcd868c20cda752217f07f83251 | MadhuV99/moshcode | /loops.py | 391 | 3.90625 | 4 | def for_loops():
# for num in range(10):
# print(num)
for num in range(1, 10, 3):
print(num)
def while_loops():
names = ['sam', 'max', 'jon', 'jim', 'bob']
i = 0
while i < len(names):
print(names[i])
i += 1
def loops():
#for_loops()
while_loops()
if __na... |
b52a08808e17f1c9cc9b872836d4d22489c1cc77 | eventia/nypc2018_pre | /psum.py | 187 | 3.75 | 4 | stringnumber = input() # "1 2"
number = stringnumber.split() # number = [ "1" , "2" ]
numberA = int(number[0]) # "1" => 1
numberB = int(number[1]) # "2" => 2
print(numberA + numberB)
|
3afb46b68b24dfed89dfa1ee84961f67d335b0ac | strin/curriculum-deep-RL | /pyrl/tasks/pyale/games/pong.py | 6,243 | 3.59375 | 4 | #
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... |
e61ef0689beee20db011d46e64aeee1b41d1a278 | cwmacaulay/CS375-Analysis-of-Algorithms | /Hierholzer.py | 1,154 | 3.734375 | 4 | # Implementation of Hierholzer's Algorithm
# Charles Macaulay
# CS 481
# 12-19-15
# Sources I used to come up with this algorithm:
# Feynman Liang, Github: https://github.com/feynmanliang/Euler-Tour/blob/master/FindEulerTour.py
# Gregor Ulm, http://gregorulm.com/finding-an-eulerian-path/
from collections import defa... |
6f0767daf44258505b8da8b41a5fe5ec94934812 | varialus/jython-legacy | /sandbox/tobias/tests/parrotbench/b1.py | 675 | 3.515625 | 4 | def depth0(n):
try:
n = depth0(n+1)
except RuntimeError:
pass
return n
def depth1(n, pea):
p = (pea, pea)
for i in xrange(n):
p = (p, pea)
try:
n, p = depth1(n+1, p)
except RuntimeError:
pass
return n, p
def main():
print depth0(0) >= 996
... |
1166cb9f4cbe2fe0d04a5080e6461693281a9b5a | varialus/jython-legacy | /sandbox/tobias/tests/parrotbench/b4.py | 2,385 | 3.59375 | 4 | sample = '''
def heappush(heap, item):
heap.append(item)
_siftdown(heap, 0, len(heap)-1)
def heappop(heap):
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
else:
returnitem = l... |
57765cfd65215780eaf13bcbeb259e555056c53b | MelanieFR/Car-dataset-analysis | /Exploratory_Data_Analysis.py | 9,388 | 4.03125 | 4 | import pandas as pd
import numpy as np
# load the data from the DataFrame
filename = 'C:\\Users\\melan\\anaconda3\\PyCharmProject\\EdxCourse\\Module3_automobileEDA.csv'
df = pd.read_csv(filename)
print(df)
# Analyzing Individual Feature Patterns Using Visualization with sns and plt
# When visualizing individual varia... |
af3934947aca77e03b85e9b391ba893a40a6e8c0 | santoshr1016/OpenCV | /HRank/lists.py | 795 | 3.53125 | 4 | l = []
N = int(input().strip())
for i in range(N):
cmdArray = input().split(" ")
# print(cmdArray)
# if cmdArray[0] in dir(l):
if cmdArray[0] == "insert":
l.insert(int(cmdArray[1]), int(cmdArray[2]))
elif cmdArray[0] == "remove":
l.remove(int(cmdArray[1]))
elif cmdArray[0] == "ap... |
6f34b619b20f35567871e06f3d07a3193a656865 | EclipseCN/Omics2018 | /Alignment_full.py | 15,361 | 3.75 | 4 | #这是用于序列比对的code
#完整版
def alignment(str1,str2):
m=len(str1)
n=len(str2)
arr=[[None]*(m+1) for i in range(n+1)]
for i in range(m+1):
arr[0][i]=0
for i in range(n+1):
arr[i][0]=0
for i in range(1,n+1):
for j in range(1,m+1):
maxLength=-1
if arr[i-1][j]... |
f576f4de7407f6c194e43f88c4b3abcd9b396a5f | thebmo/messing_around | /snow.py | 3,578 | 3.96875 | 4 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""A tiny Python program to check that Python is working.
Try running this program from t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.