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 |
|---|---|---|---|---|---|---|
4789d3e5ea7dae714483f2f25aed18792e2bbfd0 | Lyra2108/AdventOfCode | /2018/Day9/MarbleMania.py | 1,413 | 3.5625 | 4 | from collections import defaultdict
class Marble:
def __init__(self, number):
self.number = number
self.previous = self
self.next = self
def add_next(self, number):
next_marble = Marble(number)
self.next.previous = next_marble
next_marble.next = self.next
... |
8c440e1b948f841260b3befc74c8a9130e5e392a | aalvaradof/X-Serv-Python-Multiplica | /calculadora.py | 735 | 3.796875 | 4 | #!/usr/bin/python3
import sys
from sys import argv
def help():
print('Usage: calculadora.py function op1 op2')
print('Possible functions: sumar restar multiplicar dividir')
N_ARGS = 4
if len(sys.argv) != N_ARGS:
sys.exit("Invalid number of arguments")
func = argv[1]
op1 = argv[2]
op2 = argv[3]
try:
o... |
5306872900fb437bba82f703dc3a39fcfe2d2fc6 | anuj-chourasiya/Data-Sructure-in-C | /Trie.py | 1,373 | 3.875 | 4 |
from collections import defaultdict
class TrieNode:
def __init__(self,data):
self.data=data
self.children=defaultdict(lambda: None)
self.freq=0
self.isTerminal=False
def __str__(self):
return "hey "+(self.data)
class Trie:
def __init__(self,data):
self... |
ac539d583de0ec8897fcd603203f30db94bf7eb9 | sachin3496/PythonCode | /batch10_dec_2018/tic_tac_toe.py | 4,070 | 3.5625 | 4 | from itertools import permutations
import sys
import random
import os
import time
def win(data):
win_comb = [ (1,2,3), (1,4,7), (1,5,9), (2,5,8), (3,6,9), (3,5,7),(4,5,6), (7,8,9) ]
player_comb = list(permutations(sorted(data),3))
for comb in win_comb:
if comb in player_comb :
return... |
010a132e2ef0c05b75d9c72307d09ca94aa21732 | MeiJohnson/compmath | /newton.py | 1,395 | 3.609375 | 4 | import math
def f(arg):
return arg**3 - 2 * arg**2 + 3 * arg - 5
def df(arg):
return 3 * arg**2 - 4 * arg + 3
def ddf(arg):
return 6 * arg - 4
def newton():
a = 1
b = 2
e = 0.000001
cntA = 0
cntB = 0
x = a
xi = x-f(x)/df(x)
cntA += 1
print("a =", a, "b =", b, ... |
53db74810935731d80a071d178185dbe4f7cdd31 | SurajPatil314/Leetcode_Fundamental | /LinkedList/reverseLinkedList.py | 651 | 3.90625 | 4 | """
Reverse a singly linked list.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
temp = []
temp5 = head
while (head != None):
... |
1312a85c36066029066f2b3d9753b278bc4c4ee3 | SurajPatil314/Leetcode_Fundamental | /LinkedList/checkPalndromeLinkedList.py | 936 | 3.796875 | 4 | """
Given a singly linked list, determine if it is a palindrome.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
temp2 = head3
temp = []
... |
7bc5e5d8883fef3affe01b8dcfc80ce1845f46a8 | connorjclark/learn-code | /code/roll.py | 373 | 3.75 | 4 | import random
import sys
def roll(min, max):
return random.randint(min, max)
def play_round():
result = roll(1, 6)
print("You got " + str(result))
if result == 6:
print("Nice!")
if result == 1:
print("not good...")
play = True
while play:
play_round()
answer = input("Roll again? y/n: ")
... |
3f4fe3c9790c8839f9d3c32116fa12d1194e0933 | baschte83/os-synchronisation | /LibrarySynchronization.py | 4,776 | 4.0625 | 4 | from sys import argv
from time import sleep
import threading
# semaphore objects
# lock objects for book1 copies
semBook1 = threading.BoundedSemaphore(3)
# lock objects for book2 copies
semBook2 = threading.BoundedSemaphore(2)
# lock objects for book3 copies
semBook3 = threading.BoundedSemaphore(2)
# lock objects ... |
4718c3808d9323e5e39f1c76fa77b0ad5c175ed9 | DivyaraniPhondekar/PythonCode | /date and time.py | 425 | 3.515625 | 4 | import time;
import calendar;
ticks=time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
print (time.localtime())
localtime = time.asctime( time.localtime())
print ("Local current time :", localtime)
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)
... |
412efbd9c79764a161482cb43adcea5b50d0228d | DivyaraniPhondekar/PythonCode | /list.py | 538 | 3.875 | 4 | squares = []
for x in range(1, 11):
squares.append(x**2)
for x in squares:
print x
list1 = ['physics', 'chemistry', 'maths']
print max(list1) # checks ASCII value
list1.append('history')
print list1
print list1.count('maths')
print list1.index('maths')
list1.insert(2,'computer science')
... |
b245f8a691c067e69b89212cd9bb2fff8ee50128 | curiousTauseef/cryptography-codes | /diffiehellman.py | 1,943 | 3.578125 | 4 | import random
import math
def rabinMiller(num):
# Returns True if num is a prime number.
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for trials in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1: # this test does not apply ... |
aebe705c785b68173e4eb3ba196dd27297f6348f | Zhangchuchu1234/MH8811-G1902372H | /06/H1.py | 405 | 3.765625 | 4 | from passwordGenerator import genPassword
try:
password_length = int(input("Please input the password length (larger or equal to 4): "))
except:
print("Input error!")
exit()
if password_length < 4:
print("Input length should be larger or equal to 4! ")
exit()
password = genPassword(password_lengt... |
a1ea84b418022f06070c6155f758f9d980b519bb | moisescantero/keepcoding_bc5_reto_binario_entero | /bin_int_tests.py | 1,129 | 3.796875 | 4 | """módulo para hacer tests a módulo bin_int_module.py"""
import unittest#importar para test de pruebas
import bin_int_module#para comprobar funcionalidad
class bin_int_test(unittest.TestCase):
def test_bin_int(self):
self.assertEqual(bin_int_module.convert_bit_int("001"), 1)
self.assertEqual(bin_... |
f76c1e50db88f9f61b22f0a655faf0ff1ed817f7 | ryanhgunn/learning | /unique.py | 382 | 4.21875 | 4 | # A script to determine if characters in a given string are unique.
import sys
string = input("Input a string here: ")
for i in range(0, len(string)):
for j in range(i + 1, len(string)):
if string[i] == string[j]:
print("The characters in the given string are not unique.")
sys.exi... |
1146076cdd44cc42fe31f4b7ae3d4e36c670ffa9 | liramirez/setp01 | /Lab N°1/fibonacci.py | 832 | 4.0625 | 4 |
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Nombre : Lizzie Ramirez
#Fecha : 28-Abril-2013
#Actividad : 3 - Fibonacci Lab N°1
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Declaración de funciones
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
def fibo(n):
if(n==0):
return 0
else:
if (n==1):
... |
44e5468f266e9019b04d4b7e91812dbe87cc5a96 | AlexFSmirnov/Tanks | /py/maze_gen.py | 2,174 | 3.6875 | 4 | from random import randint
class Cell:
def __init__(self, state, right=0, bottom=0, color=0):
self.st = state
self.right = right
self.bottom = bottom
def copyline(prevline):
newline = []
for pc in prevline:
newcell = Cell(pc.st, pc.right, pc.bottom)
newline.appen... |
d279398b290a9f0320bacaa23864b3be614100c3 | AndrewGreen96/Python | /math.py | 1,217 | 4.28125 | 4 | # 4.3 Counting to twenty
# Use a for loop to print the numbers from 1 to 20.
for number in range(1,21):
print(number)
# 4.4 One million
# Make a list from 1 to 1,000,000 and use a for loop to print it
big_list = list(range(1,1000001))
print(big_list)
# 4.5 Summing to one million
# Create a list... |
bc890f0f40a7e9c916628d491e473b5ecfa9bb9b | JanaranjaniPalaniswamy/Safety-Monitoring-in-Restaurants-based-on-IoT | /Source_Code/Restaurant_Environment/simulatedtempiot.py | 1,492 | 3.734375 | 4 | from random import random
import numpy as np
class TemperatureSensor:
sensor_type = "temperature"
unit="celsius"
instance_id="283h62gsj"
#initialisation
def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature):
self.a... |
00ad5d687e667948ad3a0fa1c785dcce1454c33f | JanaranjaniPalaniswamy/Safety-Monitoring-in-Restaurants-based-on-IoT | /Source_Code/Restaurant_Environment/simulatedweightiot.py | 1,384 | 3.578125 | 4 | from random import random
import numpy as np
class WeightSensor:
sensor_type = "weight"
unit="kg"
instance_id="285h62gsj"
#initialisation
def __init__(self, average_weight, weight_variation, min_weight, max_weight):
self.average_weight = average_weight
... |
0fac9b063f054fbd85c04825690db77f865fcd27 | NayanJain09/TASK-2 | /class.py | 2,686 | 3.734375 | 4 | class Player(object):
def __init__(self, name, symbol, initial_score=0):
self.name= name
self.symbol= symbol
self.score= initial_score
def won_match(self):
self.score+= 100
def lost_match(self):
self.score-= 50
def show_score(self):
print('... |
823815fa2fcabe0bae5f0c341935f3d5d0a84c4f | DigantaBiswas/python-codes | /working_with_lists.py | 277 | 3.953125 | 4 | cat_names = []
while True:
print('Enter the name of cat '+str(len(cat_names)+1)+'or enter nothing to stop')
name = input()
if name =='':
break
cat_names= cat_names+[name]
print('the cat names are:')
for name in cat_names:
print(''+name)
|
84bc960c4519feff5a5f96d991f563f12d57f8a0 | GopiReddy590/python_code | /task1.py | 128 | 3.625 | 4 | n='abbabbaabab'
for i in range(1,len(n)):
for j in range(0,i):
a=n[i:j]
if a==a[::-1]:
print(a)
|
6317d6a640f443b471f457f053cc1a7daf58e468 | RadSebastian/AdventOfCode2018 | /day02/part_1.py | 822 | 3.8125 | 4 |
def result(string):
count_twos = 0
count_threes = 0
dict = {}
for word in string:
dict[word] = 0
for key in dict:
for _word in string:
if key == _word:
dict[key] += 1
for _key in dict:
if dict[_key] == 2:
count_twos = 1
... |
c57bf5de10396fb91422064e3a68639c048ee4da | dreamson80/Python_learning | /loop_function.py | 149 | 3.890625 | 4 | def hi():
print('hi')
def loop(f, n): # f repeats n times
if n <= 0:
return
else:
f()
loop(f, n-1)
loop(hi , 5)
|
ea9628aae7659d2c942568ad4f6bfca3c32a8cf9 | Harrywekesa/Classes | /classstudents.py | 747 | 4.03125 | 4 | class Student: #defining class
'Common base class for all students'
student_count = 0 #class variable accessible to all instances of the class
def __init__(self, name, id): # class constructor
self.name = name
self.id = id
Student.student_count =+ 1
def printStudent... |
f600c5a54d0e24daac47a3c576c10e54c97a75e3 | PaulLiang1/CC150 | /binary_search/searchinsert/search_insert_2.py | 647 | 3.953125 | 4 | class Solution:
"""
@param A : a list of integers
@param target : an integer to be inserted
@return : an integer
"""
def searchInsert(self, A, target):
# boundary case
if A is None or target is None:
return None
if len(A) == 0:
return 0
l... |
d01bc0fe676657ad68c0b3fdd3c3f5d13a7e8a36 | PaulLiang1/CC150 | /linklist/partition_list.py | 1,275 | 3.953125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@param x: an integer
@return: a ListNode
"""
def partition(self, head, x):
if h... |
0832f4bc298fe913b4cd09bfb1f976173e74f751 | PaulLiang1/CC150 | /linklist/remoev_nth_node_from_list.py | 925 | 3.765625 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@param n: An integer.
@return: The head of linked list.
"""
def removeNthFromEnd(self, h... |
3a6afb8dd2b80a53e0b1375c0d9212d486bcc62a | PaulLiang1/CC150 | /linklist/sort_link_list_merge_sort.py | 1,353 | 3.953125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the sorted linked list,
using constant ... |
7eb9f91582d5d33fd2d8d4a9cc604075b63bd44f | PaulLiang1/CC150 | /binary_tree/complete_binary_tree_iter.py | 1,085 | 3.78125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
from collections import deque
class Solution:
"""
@param root, the root of binary tree.
@return true if it is a complete binary tree, or false.
"""
def isC... |
6533ce18f884504f827c1bd6e96d9658d7a6d795 | PaulLiang1/CC150 | /binary_tree/binary_tree_level_order_traversal.py | 890 | 3.703125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
from collections import deque
class Solution:
"""
@param root: The root of binary tree.
@return: Level order in a list of lists of integers
"""
def levelOr... |
39e68074ff349b3c0b678957c5858ab9a7987833 | PaulLiang1/CC150 | /array/sort_colors.py | 632 | 3.71875 | 4 | class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
if nums is None or len(nums) == 0:
return nums
zero_idx = 0
two_idx = len(nums) - 1
i = 0
while i <= two_idx:
if n... |
36d89924222e0e22a0c1b77dd71a77102a64c7d9 | kiwanter/Python-Workspace | /work5/5-2.py | 375 | 3.5 | 4 | f=open('log.txt','w')
f.close()
def outer(func):
def inner(*args):
f=open('log.txt','a')
f.write('start %s(%s)'%(func.__name__,args))
f.write('\n')
f.close()
return func(*args)
return inner
@outer
def fun1(i):
print(i+1)
return i
@outer
def fun2(n,s):
for i ... |
198d10d5bfedd6d8de05492324b991c7d5172f0a | kiwanter/Python-Workspace | /work1/1-1.py | 430 | 3.84375 | 4 | odd=[]
even=[]
prime=[]
user1=[]
for i in range(0,50):
if(i%2==0):
even.append(i)
if(i%3)==0:
user1.append(i)
if(i%2!=0):
odd.append(i)
isprime=1
for j in range(2,i):
if(i%j==0):
isprime=0
if(i>=2 and isprime==1):
prime.append(i)
print(... |
033707f7e7982db2fc97a110263d385005f6223e | kiwanter/Python-Workspace | /work6/6-1.py | 1,057 | 4.09375 | 4 | #一、定义一个狗类,里面有一个 列表成员变量(列表的元素是字典), 分别记录了 3种颜色的狗的颜色, 数量,和价格;实现狗的买卖交易方法; 打印输出经过2-3次买卖方法后,剩下的各类狗的数量;
class dog():
__data=[]
def __init__(self,r:int,g:int,b:int):
self.__data.append({'color':'red','number':r,'price':30})
self.__data.append({'color':'green','number':g,'price':20})
self.__data... |
fd9dad0af1812ba52f121ceb27cdac565a1441df | zilinwujian/sgFoodImg | /fileHandle.py | 1,119 | 3.734375 | 4 | # #coding:utf-8
import os
# def fileRead(filePath):
# fileList = list()
# with open(filePath,"r") as f:
#
# # for line in f.readline():
# # line = line.strip() # 去掉每行头尾空白
# # print line
# # if not len(line) or line.startswith('#'): # 判断是否是空行或注释行
# # ... |
fb62ce8b5b142244e6ad9e8ac4a0ea62bec28689 | OleKabigon/test1 | /Nested loop.py | 124 | 4.09375 | 4 | for x in range(4): # This is the outer loop
for y in range(3): # This is the inner loop
print(f"{x}, {y}")
|
43e3cb0d6e43924b778e04ac8e6aa2234bba0a7b | kishoreganth-Accenture/Training | /python assessment 3/rationalMultiplication2.py | 249 | 4.03125 | 4 | import math
t = int(input("enter the number of rrational numbers needed to multiply :"))
product = 1
num = 1
den = 1
for i in range(t):
a = int(input())
b = int(input())
product= product * a/b
print(product.as_integer_ratio()) |
7676428ccc068cb340ac724f2a4a7df6c288b250 | kishoreganth-Accenture/Training | /python assessment 3/cartesianProduct7.py | 115 | 3.5 | 4 |
A = [1, 2]
B = [3, 4]
for i in set(A):
for j in set(B):
print("(",i,",",j,")",end = "")
|
37aa1112ee4933613e016e886a874f31b3c76685 | PrasTAMU/SmartStats | /weatherUtil.py | 1,472 | 3.84375 | 4 | import requests
import config
#Uses the OpenWeatherMap API to get weather information at the location provided by the car
WEATHER_KEY=config.openweathermapCONST['apikey']#'741365596cedfc98045a26775a2f947d'
#gets generic weather information of the area
def get_weather(lat=30.6123149, lon=-96.3434963):
url ... |
4f0ed2eb6105138360c8b2c165cfe5550c797fcb | NielsRoe/ProgHw | /Huiswerk/28.09 Control Structures/1. If statements.py | 213 | 3.765625 | 4 | score = float(input("Geef je score: "))
if score > 15 or score == 15:
print("Gefeliciteerd!")
print("Met een score van %d ben je geslaagd!" % (score))
else:
print("Helaas, je score is te laag.") |
4eb84d42d875ac7d4d69ca9fb3682b799b71ea50 | YuvalLevy1/ImageProcessing | /src/slider.py | 2,576 | 3.515625 | 4 | import math
import pygame
SLIDER_HEIGHT = 5
VALUE_SPACE = 50
class Circle:
def __init__(self, x, y, radius, color):
self.x = x
self.y = y
self.radius = radius
self.color = color
class Slider:
def __init__(self, coordinates, min_value, max_value, length, text):
self.... |
f003dd889cdce228f66dbad8f66955c9c32563c0 | csgray/IPND_lesson_3 | /media.py | 1,388 | 4.625 | 5 | # Lesson 3.4: Make Classes
# Mini-Project: Movies Website
# In this file, you will define the class Movie. You could do this
# directly in entertainment_center.py but many developers keep their
# class definitions separate from the rest of their code. This also
# gives you practice importing Python files.
# https://w... |
967a8757c9139a9b7614956677620f3697443938 | HenkT28/GMIT | /my-first-program-new.py | 339 | 3.984375 | 4 | # Henk Tjalsma, 03-02-2019
# Calculate the factorial of a number.
# start wil be the start number, so we need to keep track of that.
# ans is what the answer will eventually become. It started as 1.
# i stands for iterate, something repetively.
start = 10
ans = 1
i = 1
while i <= start:
ans = ans * i
... |
d2ea6ef4b341d5071a0adb05dd72d4f9995b677e | ncmarian/prediction | /archive/formatter.py | 4,918 | 3.578125 | 4 | #Owen Chapman
#first stab at text parsing
import string
#Premiership
#Championship
#opening files.
def getFiles (read, write):
"""
read: string of filename to be read from.
write: string name of file to be written to.
returns: tuple of files (read,write)
"""
r=open(read)
w=open(write,'w')... |
16415d6886a2bc38110cdb9df667adb99a78b638 | Mounik007/Map-Reduce | /mounik_muralidhara_squared_two_1.py | 1,823 | 3.53125 | 4 | import MapReduce
import sys
import re
"""
Matrix 5*5 Multiplication Example in the Simple Python MapReduce Framework using two phase
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
class MapValueObject(object):
"""__init__() functions as class const... |
140675932ae15b2421f6ca7a1f7cbf6babab74f6 | Ludwig-Graef/webserver | /webserver_v3/WebServer.py | 1,154 | 3.671875 | 4 |
import sys
import argparse
import www
if __name__ == "__main__":
if sys.version_info[0] is not 3:
print("ERROR: Please use Python version 3 !! (Your version: %s)"
% (sys.version))
exit(1)
def type_port(x):
x = int(x)
if x < 1 or x > 65535:
raise argp... |
f3a0ae3922cf341c118cb36ca0fdd6ca2d9ea521 | lucasgameiroborges/Python-lista-1---CES22 | /item10.py | 133 | 3.59375 | 4 | def sum(A, B):
(x, y) = A
(z, w) = B
return (x + z, y + w)
X = (1, 2)
Y = (3, 4)
print("{0}".format(sum(X, Y))) |
d3abb379287051f91e29c3bc69fc07df400b5573 | MathAdventurer/Python-Algorithms-and-Data-Structures | /Codes/chapter_1/chapter_1_solution.py | 2,116 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: Wang,Xudong 220041020 SDS time:2020/11/25
class Fraction:
def gcd(m: int, n: int):
if n != 0 and m != 0:
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
... |
4af35eb512097893fbb7cd211b0bb5cbdc60d5fb | camiladlsa/Recursividad | /FactorialTR.py | 445 | 3.984375 | 4 | n = int(input("\nIngrese un entero positivo para tomar el factorial: "))
def factorial(n):
if not isinstance(n, int):
print("Error: el valor debe ser un entero\n")
elif n < 0:
print("\nError: el factorial no existe para n < 0.\n")
else:
return factorial_process(n, 1);
def factorial_process(n, accm):
if ... |
8dd4b348fd8210b3ca0c49a097bb52b97fefab2c | williamabreu/esp8266-micropython | /thermistor.py | 999 | 3.53125 | 4 | import machine, math
def get_temp(_pin):
# Inputs ADC Value from Thermistor and outputs temperature in Celsius
raw_ADC = machine.ADC(_pin).read()
# Assuming a 10k Thermistor. Calculation is actually: resistance = (1024/ADC)
resistance=((10240000/raw_ADC) - 10000)
# ****************************... |
faab5b174ee26be0d7355a29476d7d4af0d96418 | rmmo14/pyforloopbasic2 | /for_loop_basic_2.py | 3,023 | 3.890625 | 4 | # 1. Big size
# def biggie(mylist):
# empty = []
# for x in range (0,len(mylist)):
# if mylist[x] > 0:
# empty.append('big')
# else:
# empty.append(mylist[x])
# print(empty)
# return empty
# holder = biggie([-1, 2, 3, -5])
# 2. count positives
# def counting(my_l... |
9f3dd5176c949bf0cf35fd32d81900aca0665e64 | mglowacz/algorithms | /ch4/quickSort.py | 422 | 3.953125 | 4 | from random import randint
def quickSort(arr) :
if (len(arr) < 2) : return arr
pivot = randint(0, len(arr))
less = [val for idx, val in enumerate(arr) if val <= arr[pivot] and idx != pivot]
greater = [val for idx, val in enumerate(arr) if val > arr[pivot] and idx != pivot]
return quickSort(less) + [arr[pivot... |
2d451bac8c45fbacd81c9074a9261463d67fbf52 | mglowacz/algorithms | /ch4/binarySearch.py | 741 | 3.84375 | 4 | def binarySearch(arr, item) :
if arr == [] : return -1
if len(arr) == 1 : return 0 if item == arr[0] else -1
mid = len(arr) // 2
if arr[mid] == item : return mid
sublist = arr[:mid] if arr[mid] > item else arr[mid + 1:]
subindex = 0 if arr[mid] > item else mid + 1
bs = binarySearch(sublist, item)
ret... |
8e52b22c8ed94bac68be42c51785e6333690d415 | SirBman/Prac5 | /listWarmUp.py | 305 | 3.90625 | 4 | """List Warm Up"""
numbers = [3, 1, 4, 1, 5, 9, 2]
print (numbers[0], numbers[-7], numbers[3], numbers[:-1], numbers[3:4], 5 in numbers, 7 in numbers, "3" in numbers, numbers + [6, 5, 3])
numbers [0] = "ten"
print(numbers[0])
numbers[-1] = 1
print(numbers[-1])
print(numbers[2:])
print(9 in numbers) |
bcab1361c0719abacf15a91b0ae627330749501e | rottenFetus/Algorithms-4-everyone | /Data Structures/Binary Search Tree/Python/BinarySearchTree.py | 4,827 | 4.28125 | 4 | from TreeNode import *
class BinarySearchTree:
def __init__(self, root):
"""
This constructor checks if the root is a TreeNode and if it is not
it creates a new one with the data being the given root.
"""
if not isinstance(root, TreeNode):
root = TreeNode(root)
... |
4a86095a7680c8066a0ef6e8c6cb54b0e121b08c | rottenFetus/Algorithms-4-everyone | /Algorithms/Searching Algorithms/Binary Search/Python/BinarySearch.py | 620 | 3.75 | 4 | class BinarySearch():
def search(self, haystack, needle):
middle = 0
lower_bound = 0
higher_bound = len(haystack)
while (lower_bound <= higher_bound):
middle = lower_bound + (higher_bound - lower_bound) / 2
if (haystack[middle] == needle):
ret... |
a6abf1f12cc09aeb393630d5c59219e9ae0c479b | chill133/BMI-calculator- | /BMI.py | 310 | 4.25 | 4 | height = input("What is your height?")
weight = input("What is your weight?")
BMI = 703 * (int(weight))/(int(height)**2)
print("Your BMI " + str(BMI))
if (BMI <= 18):
print("You are underweight")
elif (BMI >= 18) and (BMI <= 26):
print("You are normal weight")
else:
print("You are overweight")
|
bb17f8db4c2707099517d4cf4c748135b5fe5a31 | MarvelICY/LeetCode | /Solutions/multiply_strings.py | 1,247 | 3.921875 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Multiply Strings] in LeetCode.
Created on: Nov 27, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param num1, a string
# @param num2, a string
# @return a string
# @ICY: bi... |
9f62f466d3d580c12d4c2c93dc9cfd3d8ac93924 | MarvelICY/LeetCode | /Solutions/validate_binary_search_tree.py | 1,007 | 3.84375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Validate Binary Search Tree] in LeetCode.
Created on: Nov 12, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# sel... |
c21f43947cb50c668b37bb9eee7624154a6e0653 | MarvelICY/LeetCode | /Solutions/unique_path.py | 1,515 | 3.734375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Unique Paths II] in LeetCode.
Created on: Nov 18, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param obstacleGrid, a list of lists of integers
# @return an integer
def uniqu... |
399f740052feeccdebd601c1bda14a24e04f64ed | MarvelICY/LeetCode | /Solutions/next_permutation.py | 1,261 | 3.609375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Next Permutation] in LeetCode.
Created on: Nov 20, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param num, a list of integer
# @return a list of integer
# @ICY: reprint
... |
e5b13a2f77a66c8d33fea1c19bccc02d04e972a4 | MarvelICY/LeetCode | /Solutions/longest_valid_parentheses.py | 1,142 | 3.78125 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Longest Valid Parentheses] in LeetCode.
Created on: Nov 27, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param s, a string
# @return an integer
# @ICY: reprint,stack,O(n)
... |
2419795a51efcdbe1d5ce3a3a2045f807dc00f5c | MarvelICY/LeetCode | /Solutions/sum_root_to_leaf_numbers.py | 978 | 3.734375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Sum Root to Leaf Numbers] in LeetCode.
Created on: Nov 12, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.v... |
6ed224ce0268e3ccfb8a2ea8e361b4435e28cbb5 | MarvelICY/LeetCode | /Solutions/edit_distance.py | 1,138 | 3.703125 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Edit Distance] in LeetCode.
Created on: Nov 20, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @return an integer
# @ICY: dp
def minDistance(self, word1, word2):
row_ma... |
5570392d12ebeada71dc57c0d7dc812012579dba | MarvelICY/LeetCode | /Solutions/length_of_last_word.py | 900 | 3.8125 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Length of Last Word] in LeetCode.
Created on: Nov 13, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
... |
8904731c0bd6c47eebe2dd98d3c0296f6bdd3d99 | MarvelICY/LeetCode | /Solutions/binary_tree_level_order_traversal.py | 1,332 | 3.859375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Binary Tree Level Order Traversal] in LeetCode.
Created on: Nov 13, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
sel... |
79acb839e91a261e3bf2974608c3fa527efe1387 | MarvelICY/LeetCode | /Solutions/spiral_matrix_2.py | 1,641 | 3.890625 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Spiral Matrix II] in LeetCode.
Created on: Nov 18, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
if n == 0:... |
e75ff35b0086a8ef4a610ed3a737d756e3efc6c5 | MarvelICY/LeetCode | /Solutions/string_to_integer.py | 2,079 | 3.84375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Srting to Integer] in LeetCode.
Created on: Nov 10, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @return an integer
# hints: space sign and overflow
# take care when : no-dig... |
1103ddc9f5b00fad29a428a1c962a7f1fc52b53e | rbpdqdat/osmProject | /phones.py | 1,181 | 3.6875 | 4 | import re
import phonenumbers
#convert alphabet phone characters to actual phone numbers
#
missphone = '+19999999999'
def phone_letter_tonum(alphaphone):
char_numbers = [('abc',2), ('def',3), ('ghi',4), ('jkl',5), ('mno',6), ('pqrs',7), ('tuv',8), ('wxyz',9)]
char_num_map = {c:v for k,v in char_numbers for c ... |
2e0b65f9be804d132dd15c781ce5bca69d3c7ff4 | niketanmoon/Data-Science | /Data Preprocessing/Day6-Final Data Preprocessing Template/final.py | 1,678 | 3.96875 | 4 | #No need to do missing data, categorical data, Feature Scaling
#Feature Scaling is implemented by some of the algorithms, but in some cases you need to do feature scaling
#This is the final template of the data preprocessing that you will be needed to do each and every time
#Step 1 importing the libraries
import nump... |
02092a3692fc1dca4d02a0aededb730650683d54 | cindykhris/temperature_convertor | /tem_conv.py | 1,593 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Authors: Cindy Pino
Date: 3/26/2020
Description: Kelvin, Celsius, Farenheight Temperature Convertor"""
import sys
def tempConvertor():
while True:
inp1 = (input("Temperature one? (c = celsius, f = fahrenheit, k = kelvin) "))
if inp1 == "c" or inp1 == "f" or inp1 ... |
73367dc10875863ceac9026f5292a5e4dccb6a21 | paulan94/Intermediate-Python-Tutorials | /listcomp_generators.py | 887 | 3.828125 | 4 |
##xyz = [i for i in range(5000000)] #list takes longer because its stored into memory
##print 'done'
##xyz = (i for i in range(5000000)) #generator doesnt store as list or into memory
##print 'done' #this is almost instant after list is created
input_list = [5,6,2,10,15,20,5,2,1,3]
def div_by_five(num):
return n... |
55ef5cc09c7bdabe692af9783837faf6f5cfbc31 | paulan94/Intermediate-Python-Tutorials | /argparse_cli.py | 900 | 3.765625 | 4 | import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--x', type=float,default=1.0,
help='What is the first number?')
parser.add_argument('--y', type=float,default=1.0,
help='What is the second number?')
parser.add... |
839de1b8a63762d56ab6c3d9f17a825bce6f410a | mucel/python-1 | /eksperiment.py | 749 | 3.625 | 4 | saraksts = ['a']
vardnica = {'black': 'melns', 'white': 'balts'}
vardnica['blue'] = 'zils'
print(vardnica['black'])
personaA = {
'vards' : 'Mara',
'dzimums':'s',
'gads': 2002
}
personaB = {
'vards': 'Linda',
'dzimums': 's',
'gads': 1999
}
cilveki = [personaA, personaB]
while True:
task ... |
8ce4fb9950dc61d3b59664aee815d5b0cb8dca3f | bkwong1990/PygamePrimerFishBomb | /score_helper.py | 1,990 | 3.734375 | 4 | import json
ENEMY_SCORES = {
"missile": 1000,
"tank": 10000,
"laser": 100000
}
SCORE_PER_LIVING_TANK = 10
SCORE_COUNT = 5
NAME_CHAR_LIMIT = 10
score_file_name = "scores.json"
# Defaults to an empty list
scores = []
'''
Loads scores from a JSON file
'''
def load_scores():
global scores
try:
with o... |
e2bed78a5631d38dfdbbffe383bb5f09cac17e9e | bkwong1990/PygamePrimerFishBomb | /my_events.py | 1,090 | 3.5 | 4 | import pygame
ADDMISSILE = pygame.USEREVENT + 1
ADDCLOUD = pygame.USEREVENT + 2
ADDTANK = pygame.USEREVENT + 3
ADDLASER = pygame.USEREVENT + 4
MAKESOUND = pygame.USEREVENT + 5
ADDEXPLOSION = pygame.USEREVENT + 6
RELOADBOMB = pygame.USEREVENT + 7
SCOREBONUS = pygame.USEREVENT + 8
TANKDEATH = py... |
6070edc3bdc5fd7757edb7632903a78a56c12d06 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeDecisao - PythonBrasil/exec14.py | 542 | 3.609375 | 4 | def conceito(med):
if med >= 9:
idx = 0
elif med >= 7.5 and med < 9:
idx = 1
elif med >= 6 and med < 7.5:
idx = 2
elif med >= 4 and med < 6:
idx = 3
else:
idx = 4
con = ['A', 'B', 'C', 'D', 'E']
return con[idx]
n1, n2 = int(input('Insira a nota 1: '))... |
b5a78563e656e4617132516dd50a6ca328f29c25 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeDecisao - PythonBrasil/exec16.py | 709 | 3.796875 | 4 | import math
def calculaDelta(a, b, c):
delt = math.pow(b, 2) - 4*a*c
if delt >= 0:
print('O valor de delta é:', delt)
print(' X`:', calculaValorX1(delt, a, b))
print(' X``:', calculaValorX2(delt, a, b))
else:
print('Não há raizes para a equação.')
def calculaValorX1(de... |
525d2a568cba6cfa8a127e781f53e09b56cff1bb | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec36.py | 206 | 3.9375 | 4 | num = int(input('Digite um numero: '))
inicio = int(input('Digite o inicio: '))
fim = int(input('Digite o final: '))
for i in range(inicio,(fim+1)):
res = num * i
print('%d X %d = %d'%(num, i, res)) |
90a33d10723fa9f4cac04339dca95e9ebde4d0bb | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec41.py | 512 | 3.71875 | 4 | cont = 0
valorParcela = 0
parcela = 1
valorDivida = float(input('Insira o valor da divida: '))
print('\nValor da Dívida | Valor dos Juros | Quantidade de Parcelas | Valor da Parcela')
for i in [0,10,15,20,25]:
dividaTotal = valorDivida
valorJuros = valorDivida*(i/100)
dividaTotal += valorJuros
valorParc... |
e742c028b56006a536127f23b6697000620b2923 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec22.py | 325 | 3.984375 | 4 | num = int(input('Digite um numero: '))
cont = 1
divisor = []
primo = 0
while cont <= num:
if num % cont == 0:
primo += 1
divisor.append(cont)
cont += 1
if primo == 1:
print(num, 'é primo, pois é divisivel apenas por', divisor)
else:
print(num, 'não é primo pois é divisivel por', divisor) |
c1d8a5f4962f68ac43d139ab714655917c5c4068 | flaviojussie/Exercicios_Python-Inciante- | /ExerciciosListas - PythonBrasil/exer05.py | 361 | 3.734375 | 4 | vetor = []
impares = []
pares = []
for i in range(20):
vetor.append(int(input('Digite o %d número: '%(i+1))))
for i in vetor:
if i % 2 == 0:
pares.append(i)
else:
impares.append(i)
print('O vetor é formado pelos numeros:',vetor)
print('Os numeros pares do vetor são: ', pares)
print('Os nume... |
588f92fcd4309b777bf0f75be9a4bd6e9b99f8c4 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeDecisao - PythonBrasil/exec05.py | 272 | 3.828125 | 4 | n1, n2 = int(input('Nota 1: ')), int(input('Nota 2: '))
media = (n1 + n2)/2
if media >= 7:
print('Aluno nota,', media, 'Aprovado')
elif media == 10:
print('Aluno nota,', media ,'Aprovado com distinção')
elif media < 7:
print('Aluno Repovado, nota:', media)
|
2a3f669de150632c4a096455723c8a44d32dc43c | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec44.py | 1,062 | 3.84375 | 4 | sair = 's'
print('''Complete seu voto.
1 - para votar em Fulano
2 - para votar em Cicrano
3 - para votar em Beltrano
4 - para votar em Zezinho
5 - para nulo
6 - para branco''')
fulano = 0
cicrano = 0
beltrano = 0
zezinho = 0
nulo = 0
branco = 0
totalEleitores = 0
while sair == 's':
voto = int(input('Digite seu vot... |
93a61b2e40b4d8f0662b8e856d50d4648ac20ee6 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec42.py | 605 | 3.796875 | 4 | numVezes = int(input('Quantos numeros você que inserir: '))
intervalo1 = 0
intervalo2 = 0
intervalo3 = 0
intervalo4 = 0
for i in range(numVezes):
num = int(input('Digite o %d numero: '%(i+1)))
if num >= 0 and num <= 25:
intervalo1 += 1
elif num >=26 and num <= 50:
intervalo2 += 1
elif nu... |
209f266a0c58dac79b4ad6cd2d585a798c4ce3f7 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeDecisao - PythonBrasil/exec19.py | 850 | 3.515625 | 4 | def grafiaExtensso(num, quant):
c = 'centena'
d = 'dezena'
u = 'unidade'
compl = ''
if num == 0:
return compl
elif num == 1:
if quant == 100:
compl = ','
return str(num)+' '+ c + compl
elif quant == 10:
compl = ' e'
return ... |
2cc8395ee00da81c09d43db8800ecd08f1045542 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec26.py | 706 | 3.78125 | 4 | eleitores = int(input('Insira o numero de eleitores: '))
print('''\nPara votar em fulano - 1
Para votar em cicrano - 2
Para votar em beltrano - 3
Para votar em branco - 4\n''')
cont = 0
fulano = 0
cicrano = 0
beltrano = 0
branco = 0
nulos = 0
candidatos = ['Fulano','Cicrano','Beltrano']
while cont < eleitores:
v... |
09ebe4d259f873fbc9a53fe8710e30081ec29d2e | SachinMCReddy/810homework | /HW02(SSW-810).py | 3,147 | 3.71875 | 4 | ''' python program that includes class fractions , plus , minus, times,
divide ,equal to perform tasks on calculator'''
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
if self.denominator <=0 :
raise Valu... |
e8e71c47bd34a628562c9dfcd351bcd336a99d70 | endar-firmansyah/belajar_python | /oddevennumber.py | 334 | 4.375 | 4 | # Python program to check if the input number is odd or even.
# A number is even if division by given 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number
# div = 79
div = int(input("Input a number: "))
if (div % 2) == 0:
print("{0} is even Number".format(div))
else:
print("{0} is Odd Number".... |
b928d3b1b8bfac3efa68e1bccaa9347c16482bd8 | JianHui1208/Code_File | /Python/Lists.py | 291 | 4.15625 | 4 | thislist = ["a", "b","c"]
print(thislist)
thislist = ["a", "b", "c"]
print(thislist[1])
# same the array start for 0
thislist = ["a", "b", "c"]
print(thislist[-1])
# -1 is same like the last itme
# -2 is second last itme
thislist = ["a", "b", "c", "d", "e", "f", "g"]
print(thislist[2:5]) |
48de21f792a50fa63d62e5656c123a20a551acd1 | acado1986/cs50 | /pset6_2016/crack.py | 2,617 | 3.96875 | 4 | import crypt
import argparse
import itertools
import time
def main():
# running time mesurements
start_time = time.time()
# path to default dictionary in Ubuntu distros
default_dictionary = '/usr/share/dict/american-english'
# ensure correct usage of the program
parser= argparse.... |
0ce3f5ef67b779ef85eade0c4457a38a50dc9c44 | wecchi/univesp_com110 | /Sem2-Strings.py | 404 | 3.921875 | 4 | # Videoaula 7 - Strings
nome = input('Digite o seu nome completo: ')
nome2 = input('Qual o nome da sua mãe? ')
nome = nome.strip()
nome2 = nome2.strip()
print('é Marcelo? ', 'Marcelo' in nome)
print('Seu nome e de sua mãe são diferentes? ', nome != nome2)
print('Seu nome vem depois da sua mãe? ', nome > nome2)
... |
5d175c14c2438c669efe9fd451e0c88ace14ce7b | wecchi/univesp_com110 | /contar_letras.py | 288 | 3.890625 | 4 | def countLetter(textAsCount, l):
x = textAsCount.count(l)
return x
frase = input('digite uma frase qualquer ')
letra = input('que letra deseja contar? ')
print('\n','''Encontramos %d letras "%s"s no seu texto "%s"'''%(countLetter(frase, letra), letra, frase[:8] + '...'))
|
7a539c585cf9adca8dc788fea5295f99a65b5e92 | wecchi/univesp_com110 | /Sem2-Texto22.py | 1,217 | 4.15625 | 4 | '''
Texto de apoio - Python3 – Conceitos e aplicações – uma abordagem didática (Ler: seções 2.3, 2.4 e 4.1) | Sérgio Luiz Banin
Problema Prático 2.2
Traduza os comandos a seguir para expressões Booleanas em Python e avalie-as:
(a)A soma de 2 e 2 é menor que 4.
(b)O valor de 7 // 3 é igual a 1 + 1.
(c)A soma de ... |
2681542783b3751bd885d3f5d829d6bf2ccde4be | code-wiki/Data-Structure | /Array/(Manacher's Algoritm)Longest Palindromic Substring.py | 1,046 | 4.125 | 4 | # Hi, here's your problem today. This problem was asked by Twitter:
# A palindrome is a sequence of characters that reads the same backwards and forwards.
# Given a string, s, find the longest palindromic substring in s.
# Example:
# Input: "banana"
# Output: "anana"
# Input: "million"
# Output: "illi"
# class Solut... |
e466c0aab2dbbe4e0a661609f0f7421ab23dc967 | xpessoles/Cycle_01_DecouverteSII | /Chaine_Fonctionnelle/02_Fonction_Traiter/TP_Traiter_Pyhon_Arduino/Librairie py2duino v4/py2duino.py | 22,737 | 3.53125 | 4 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: py2duino
# Purpose: Programming arduino from python commands
#
# Author: David Violeau, Alain Caignot
#
# Created: 01/01/2014
# Modified : 01/03/2016 D. Violeau
# Copyright: (c) Demo... |
09c24a1dce6f40409993005a582dafc018ce3d3e | adykumar/Leeter | /python/206_reverse-linked-list.py | 1,281 | 3.890625 | 4 | """
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
"""
class Node(object):
def __init__(self, x):
self.val= x
self.next= None
class Solution(object):
def createLL(self, lis):
if len(lis)<1:
return None
head= Node(lis... |
f503e91072d0dd6c7402e8ae662b6139feed05e0 | adykumar/Leeter | /python/104_maximum-depth-of-binary-tree.py | 1,449 | 4.125 | 4 | """
WORKING....
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.