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
3c337c5a29d43444e3b4c51af2dc22ea4284c5e7
theguythatdoes/coding-assignments
/EatingGood.py
499
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 15:43:53 2020 @author: reube """ def howMany(meals,restaurant): wyt=[] rest=[] numrest=0 for bob in range(len(meals)): if meals[bob] not in rest: rest+=[meals[bob] ] for k in range (len(rest)): wyt+=rest[k]...
a3908afeefdba6d570fdbea0dd5a5b20112a1593
hugessen/Advent-of-Code-2016
/Code/d3q1.py
628
3.53125
4
def is_valid(vals): max_side = max(vals) return sum(vals) > (2 * max_side) pinput = open('Inputs/d3.txt').read().split('\n') ...
17d9bf545ec17e744a53e7adc120100d293f3f40
hugessen/Advent-of-Code-2016
/Code/d1q1.py
951
3.609375
4
def turn(left_or_right): global c_dir if c_dir[X] == 1: c_dir = [0, -1*left_or_right] elif c_dir[X] == -1: c_dir = [0, 1*left_or_right] elif c_dir[Y] == 1: c_dir = [1*left_or_right, 0] elif c_dir[Y] == -1: c_dir = [-1*left_or_right, 0] pinput = open('Inputs/d1.txt').read().split(", ") X = 0 Y = 1 LEFT =...
c4a724e06eda95e28c9ad081698f1c08f0272467
tsixit/python
/PycharmProjects/formation/poo.py
10,517
3.75
4
unite1 = { 'nom': 'méchant', 'x': 12, 'y': 7, 'vie': 42, 'force': 9 } unite2 = { 'nom': 'gentil', 'x': 11, 'y': 7, 'vie': 8, 'force': 3 } def attaque(attaquant, cible): print("{} attaque {} !".format(attaquant['nom'], cible['nom'])) cible['vie'] -= attaquant['force'] ...
38c35c919afd61c749c0c521943d9fd821a44818
Tcake/py_leetcode
/leetcode/Guess Number Higher or Lower II.py
686
3.5
4
class Solution: def getMoneyAmount(self, n): """ :type n: int :rtype: int """ left = 1 right = n result = 0 while right - left >= 6: left = (right + left) // 2 result += left if left is not 1: left += 1 ...
599b529c6e4cfc0e0ce04753c26c2bd543ef3dcb
logotip123/py_merge
/merge.py
799
4.03125
4
"""Two list sort module""" from typing import List def merge(array1: List[int], array2: List[int]) -> List[int]: """ Two list sort function :param array1: first list for sort :param array2: second list for sort :return: array1 + array2 sorted list """ array1index = 0 array2index = 0 ...
95ecfbc9b444f09586e7fa1dbc8a752e846ef8f7
jaaaaaaaaack/xpilot-bots
/old-files/evstrat/neuralNet.py
5,221
3.734375
4
# Jack Beal and Lydia Morneault # COM-407 CI # 2018-05-07 Final project # Based on neuralnet.py by Jessy Quint and Rishma Mendhekar from random import* import math def sigmoid(x): return (1/(1+math.exp(-1*x))) def perceptron(thing, weights): summation = 0 # initialize sum counter = 0 # variable to assi...
9e0cd81ea1e65c22f141d4d08e4177860876a5c6
kutakieu/AI-class
/Assignment-1-Search-master-63318a771170bfa64d905052bc0e733cfd3b576e/code/heuristics.py
4,813
3.828125
4
# heuristics.py # ---------------- # COMP3620/6320 Artificial Intelligence # The Australian National University # For full attributions, see attributions.txt on Wattle at the end of the course """ This class contains heuristics which are used for the search procedures that you write in search_strategies.py. T...
ab79b8c878f465cac0131bf55f802a6b64cfdfb5
MatejBabis/AdventOfCode2k18
/day5/part1.py
799
3.765625
4
def read_input(filename): f = open(filename) # only one line, and remove '\n' output = f.readline().strip() f.close() return output # helper function that checks if two letters are equal are diffent case def conflict(a, b): return a.lower() == b.lower() and ((a.isupper() and b.islower()) or (a...
d5273f7320cae0c86a36327e9defa268b7bca045
MatejBabis/AdventOfCode2k18
/day4/part1.py
2,591
3.5
4
import re import numpy as np # strings to match ASLEEP = 'falls asleep' AWAKE = 'wakes up' GUARD = 'Guard' # process the input file def process_file(filename): f = open(filename) records_list = [] for line in f.readlines(): raw = line[6:-1] # first six letter carry no information month ...
bc7b865e579f10ee6632e9b10099d106727bdd14
petrakov1/foodbot
/dataAnal.py
3,617
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import _json import math def valueByTag(place,arrPerson): value = 0 for tag in arrPerson: if (tag in place): value += place[tag]*arrPerson[tag] return (value) def sortByValue(arr): for i in range(len(arr)): for j in range(l...
158450f4cb59c6890e6de4931de18e66a4f5ef48
FraserTooth/python_algorithms
/01_balanced_symbols_stack/stack.py
865
4.21875
4
class Stack: def __init__(self): self.items = [] def push(self, item): """Adds an item to end Returns Nothing Time Complexity = O(1) """ self.items.append(item) def pop(self): """Removes Last Item Returns Item Time Complexity = O(1)...
9ea5c9748f2a37bf51ed41905b601704b629c2d8
Alver23/CursoPython
/clase1/EjerciciosHechosClase/eres.py
191
4.09375
4
nombre = input("Cual es tu nombre") if nombre == "Alver": print ("Que man tan chevere") elif nombre == "Jorge": print ("Que Onda Jorge") else: print ("Eres Otro que no es Alver o Jorge")
462662bb1d616d434d6df18dabe53e424ac5b297
habc0d3r/100-Days-Of-Code
/Day-5/highest-score/main.py
323
3.75
4
student_scores = input("Input a list of student scores ").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(student_scores) heighest = 0 for score in student_scores: if score > heighest: heighest = score print(f"The heighest score in the class is: {heighest}") ...
98b239868170d72f40abdf73dc38172bfaf24f1d
habc0d3r/100-Days-Of-Code
/Day-18/challenge4.py
483
3.5
4
import turtle from turtle import Turtle, Screen import random as rd tim = Turtle() # tim.hideturtle() turtle.colormode(255) def random_color(): r = rd.randint(0, 255) g = rd.randint(0, 255) b = rd.randint(0, 255) final_color = (r, g, b) return final_color directions = [0, 90, 180, 270] tim.spee...
aac8aac901bd84af8b37b384aae3f0607e023c34
habc0d3r/100-Days-Of-Code
/Day-18/challenge3.py
571
3.890625
4
from turtle import Turtle, Screen import random as rd colors = ['chartreuse', 'deep sky blue', 'sandy brown', 'medium orchid', 'magenta', 'royal blue', 'burlywood'] tim = Turtle() tim.shape("arrow") def change_color(): tim.color(rd.random(), rd.random(), rd.random()) def draw_shape(num_of_sides): angle = ...
66c93a7b70637fd2ebbabe192b10d52cca68ee1c
karthikyadav09/deep_learning_for_vision
/ASN3/Solution/ASN3/lstmMNISTStarterCode.py
2,867
3.546875
4
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data from tensorflow.contrib import rnn mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #call mnist function learningRate = 0.0025 trainingIters = 100000 batchSize = 256 di...
447204f56fb361002c5d1ad231d25d8aaef4ff80
lerandc/project-euler
/python/p29.py
2,179
3.765625
4
""" Luis RD April 12, 2020 ------------------------------------------------ Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=3125 If they are then placed in numerical order, with any repeats...
1f2bf332f201dbede1ce368cb977533ff440bc0d
forest-data/luffy_py_algorithm
/算法入门/merge_sort.py
1,934
3.65625
4
#归并排序 时间复杂度 O(nlogn) # 假设左右已排序 def merge(li, low, mid, high): i = low j = mid + 1 ltmp = [] while i<=mid and j<=high: if li[i] < li[j]: ltmp.append(li[i]) i += 1 else: ltmp.append(li[j]) j += 1 # while 执行完,肯定有一部分没数了 while i <=...
dc55a27810a351d729e80b1ad96d09c5de314db3
forest-data/luffy_py_algorithm
/数据结构/stack.py
1,214
4.0625
4
# 栈: 是一个数据集合,只能在一段进行插入或删除操作 class Stack: def __init__(self): self.stack = [] def push(self, element): self.stack.append(element) # 删除栈顶元素 def pop(self): return self.stack.pop() # 获取栈顶元素 def get_top(self): if len(self.stack) > 0: return self.stack...
0e63b36d3102607cbc9735009e6bb07796d67e20
forest-data/luffy_py_algorithm
/算法入门/quick_sort.py
2,049
3.71875
4
# # 快速排序 def partition(li,left,right): tmp = li[left] while left < right: while left < right and li[right] >= tmp: # 找比左边tmp小的数,从右边找 right -= 1 # 往左走一步 li[left] = li[right] # 把右边的值写到左边空位上 while left < right and li[left] <= tmp: left += 1 li[rig...
0a953197aa82f1ee8ddfb16a4d8a12bb3977f9a0
forest-data/luffy_py_algorithm
/算法入门/查找算法/search.py
958
3.53125
4
import random # 查找: 目的都是从列表中找出一个值 # 顺序查找 > O(n) 顺序进行搜索元素 from 算法入门.cal_time import cal_time @cal_time def linear_search(li, val): for ind, v in enumerate(li): if v == val: return ind else: return None # 二分查找 > O(logn) 应用于已经排序的数据结构上 @cal_time def binary_search(li, val): left...
e737daceec599900b8e22c001f9288b5fb70ac25
karakorakura/Data-Structures-Practice
/btree.py
3,787
3.5
4
# Shivam Arora # 101403169 # Assignment 4 # Avl tree # COE7 #GlObal #degree t=2; class Node: def __init__(self,data=None,parent = None,pointers = None,leaf = True): self.keys = [] self.pointers=[] self.keysLength = 0 self.parent=parent self.leaf = leaf ...
5d003bd13085125d781ca29eb8060b3db3bfe3a3
kesicigida/python_example
/find_student_number.py
1,973
3.59375
4
def printLine(x): for i in range(0, x): print "=", print(" ") def isEven(x): if x%2 == 0: return True else: return False ''' x[len(x)] overflows array x[len(x) - 1] equals newline <ENTER> x[len(x) - 2] is what is desired ''' def isLastUnknown(x): if x[len(x)-2] == "n": ...
14d98d23d3617c08a2aefd1b4ced2d80c5a9378c
168959/Datacamp_pycham_exercises2
/Creat a list.py
2,149
4.40625
4
# Create the areas list areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Print out second element from areas" print(areas[1]) "# Print out last element from areas" print(areas[9]) "# Print out the area of the living room" print(areas[5]) "# Create the areas lis...
cdae0b35f271a30def8b69d9cb1f93731a10e99b
shane-kerr/pythonmeetup-bmazing
/players/astarplayer.py
9,728
4.4375
4
""" This player keeps a map of the maze as much as known. Using this, it can find areas that are left to explore, and try to find the nearest one. Areas left to explore are called "Path" in this game. We don't know where on the map we start, and we don't know how big the map is. We could be lazy and simply make a very...
1aa7609aca58c9f7546ab422239493c0d3a3b0a4
mmsolovev/python-basics
/Solovev_Mikhail_dz_3.3.py
271
3.625
4
def thesaurus(*args): people = {} for name in args: people.setdefault(name[0], []) people[name[0]].append(name) return people print(thesaurus("Иван", "Мария", "Петр", "Илья", "Михаил", "Алексей", "Павел"))
57dbfca3f3ddf3eaf18353b599fad9670b081ad2
longsube/longsube.github.io
/HVN_gitlab/exercises/07_module_class/LONGLQ_7.1.py
1,411
3.59375
4
class Trading: def __init__(self, **goods): #goods{name:(price, quantity, size)} self.goods = goods def buyer(self,money, bags): return (money,bags) def buy(self, buyer, **goods_quantity): #goods_quantity{name:quantity} amount_money = 0 amount_size = 0 ...
15f3f55bed1b55968cb3000d1abfe46952757031
jimohafeezco/nlp_ws
/bots/src/prayer_time.py
1,540
3.609375
4
# import required modules import requests, json from datetime import datetime # Enter your API key here def get_prayer(user_message): api_key = "0c42f7f6b53b244c78a418f4f181282a" # base_url variable to store url base_url = "http://api.aladhan.com/v1/calendarByCity?" city = "Innopolis" country...
f6e5c5eaa503f06c40806736159dd6b238943c35
sohanmithinti/p-1071
/correlation.py
679
3.5
4
import numpy as np import pandas as pd import plotly.express as px import csv def getdatasource(): icecream = [] temperature = [] with open("icecreamsales.csv") as f: reader = csv.DictReader(f) print(reader) for row in reader: icecream.append(float(row["Icec...
a65aa34ef32d7fced8a91153dae77e48f5cc1176
2019-fall-csc-226/a02-loopy-turtles-loopy-languages-henryjcamacho
/Camachoh- A02.py
1,133
4.15625
4
###################################################################### # Author: Henry Camacho TODO: Change this to your name, if modifying # Username: HenryJCamacho TODO: Change this to your username, if modifying # # Assignment: A02 # Purpose: To draw something we lie with loop ########...
9aaf6c575136295abbec00c59b5ce50fd0a02b7d
harishkumarhm/Python-Learning
/firstScript.py
146
3.515625
4
first_number = 1+1 print(first_number) second_number = 100 +1 print(second_number) total = first_number + second_number print(total) x = 3
c1facc994bca79947e20fe4adf7890d15ee16f41
zqhappyday/myleetcode
/hard/42接雨水.py
849
3.5
4
''' 经典题目,当初是通过这个题目学会了双指针 这题只要想到到了双指针就一点也不难 这题同样可以使用二分法来做,速度会快很多 ''' class Solution: def trap(self, height: List[int]) -> int: n = len(height) left = 0 right = n - 1 res = 0 leftmax = 0 rightmax = 0 while right > left + 1 : if height[left] <= heigh...
fbf1f445e45e174cc971321ab3f92adaa3de702b
DevRyu/Daliy_Code
/DataStructure/graph(DFS).py
1,896
3.765625
4
# 23-18 깊이우선 탐색 # BFS(Breadth First Search) : 노드들과 같은 레벨에 있은 노드들 큐방식으로 # DFS(Depth First Search) : 노드들의 자식들을 먼저 탐색하는 스택방식으로 # 스택 방식으로 visited, need_visited 방식으로 사용한다. # 방법 : visited 노드를 체우는 작업 # 1) 처음에 visited에 비어있으니 시작 노드의 키를 넣고 # 2) 시작 노드의 값에 하나의 값(처음또는마지막 인접노드들)을 need_visit에 넣는다, # 2-1) 인접노드가 2개 이상이면 둘 중 원하는 방향...
4f11d9065d690ab960835e56cb56788487d6aa3b
DevRyu/Daliy_Code
/Python/baekjoon_2920.py
1,293
3.65625
4
# 문제 # 다장조는 c d e f g a b C, 총 8개 음으로 이루어져있다. 이 문제에서 8개 음은 다음과 같이 숫자로 바꾸어 표현한다. c는 1로, d는 2로, ..., C를 8로 바꾼다. # 1부터 8까지 차례대로 연주한다면 ascending, 8부터 1까지 차례대로 연주한다면 descending, 둘 다 아니라면 mixed 이다. # 연주한 순서가 주어졌을 때, 이것이 ascending인지, descending인지, 아니면 mixed인지 판별하는 프로그램을 작성하시오. # 입력 # 첫째 줄에 8개 숫자가 주어진다. 이 숫자는 문제 설명에서 설명한 음이며,...
b30bbbdaad7f749a52eab049027fed4ccbb881d3
DevRyu/Daliy_Code
/Python/bubble_sort.py
441
3.5625
4
def bubble(data): for i in range(len(data) -1): result = False for j in range(len(data) -i-1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] result = True if result == False: break return data import rand...
aee0c755f6cc99568b1d0d258b800f91afa9c5c8
JenySadadia/Assignments-of-Python
/calc.py
685
3.984375
4
while True: op=int(input('''Enter the operation which you would like to b performed :- 1.Addition 2.Subtraction 3.Multiplication 4.Division''')) if op==1: x=int(input("enter x")) y=int(input("enter y")) print(x+y) elif op==2: x=int(inpu...
0e49ff158c9aacce1854660e39d4ef8c28266cc5
thewchan/python_crash_course
/python_basic/pizza1.py
477
4.09375
4
def make_pizza(*toppings): """Print the list of toppings that have been requested.""" print(toppings) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese') def make_pizza1(*toppings): """Summarize the pizza we are about to make""" print("\nMaking a pizza with the followi...
790c7add244f5bed8e7b70a400cfc61f6e82f1ad
thewchan/python_crash_course
/python_basic/admin.py
673
4.03125
4
usernames = ['admin', 'jaden', 'will', 'willow', 'jade'] if usernames: for username in usernames: if username == 'admin': print(f"Hello {username.title()}, would you like to see a status "+ "report?") else: print(f"Hello {username.title()}, thank you for l...
b8ac3fd6403e0903d4cee84188d0066548a26593
thewchan/python_crash_course
/python_basic/counting_lists.py
551
3.90625
4
#list exercises numbers = range(1, 21) #for number in numbers: # print(number) numbers = range(1, 1_000_001) #for number in numbers: # print(number) million_list = list(range(1, 1_000_001)) print(min(million_list)) print(max(million_list)) print(sum(million_list)) odd_numbers = range(1, 21, 2) for number in od...
91ea218914b1e1e678308f8f2dce8f2422e8af38
thewchan/python_crash_course
/python_basic/movie_tickets.py
341
4.09375
4
age = "" while age != 'quit': age = input("What is your age?\n(Enter 'quit' to exit program) ") if age == 'quit': continue elif int(age) < 3: print("Your ticket is free!") elif int(age) < 12: print("Your ticket price is $10.") elif int(age) >= 12: print("Your ticket ...
084d8fa68428b070de38472353b3517f5d0cdfa0
Shobhit05/Linux-and-Python-short-scripts
/csvfilereader.py
503
3.75
4
import csv with open('something.csv') as csvfile: readcsv=csv.reader(csvfile,delimiter=',') dates=[] colors=[] for row in readcsv: print row color=row[3] date=row[1] colors.append(color) dates.append(date) print dates print colors try: #...
5c703ed90acda4eaba3364b6f510d28622ddc4a0
ndenisj/web-dev-with-python-bootcamp
/Intro/pythonrefresher.py
1,603
4.34375
4
# Variables and Concatenate # greet = "Welcome To Python" # name = "Denison" # age = 6 # coldWeather = False # print("My name is {} am {} years old".format(name, age)) # Concatenate # Comment: codes that are not executed, like a note for the programmer """ Multi line comment in python """ # commentAsString = """ ...
590ea704b57b48282c9b8af409c5c5076244a434
ndenisj/web-dev-with-python-bootcamp
/Intro/listDict.py
436
3.90625
4
# LIST names = ['Patrick', 'Paul', 'Maryann', 'Daniel'] # # print(names) # # print(names[1]) # # print(len(names)) # del (names[3]) # names.append("Dan") # print(names) # names[2] = 'Mary' # print(names) for x in range(len(names)): print(names[x]) # DICTIONARY # programmingDict = { # "Name": "Tega", # "Pr...
6a34f3d820de100c471e0a8e82cb5372e2eced85
regi18/offset-chiper
/offset-chiper.py
1,914
4.03125
4
""" Decode and Encode text by changing each char by the given offset Created by: regi18 Version: 1.0.4 Github: https://github.com/regi18/offset-chiper """ import os from time import sleep print(""" ____ __ __ _ _____ _ _ / __ \ / _|/ _| | | ...
23bdbbe3a731836ff6897d7d15a9feebd191dea2
yongjoons/test1
/019.py
149
3.765625
4
try : num=int(input('enter : ')) print(10/num) except ZeroDivisionError : print('zero') except ValueError: print('num is not int')
d0ee097dd1a70c65be165d7911acfbc09659f199
dokurin/dokushokai
/season2-DDD/cargo-system/sample/customer.py
346
3.5
4
from typing import NewType ID = NewType("CustomerID", str) class Customer(object): """顧客Entity Args: id (ID): 顧客ID name (str): 氏名 Attrubutes: id (ID): 顧客ID name (str): 氏名 """ def __init__(self, id: str, name: ID) -> None: self.id = id self.name =...
313575eca38588d312890f248e02831afcdc65bb
yeming0923/12
/zh_即时标记/002_PYthon callable()函数.py
882
4.03125
4
''' 描述 callable() 函数用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。 对于函数、方法、lambda 函式、 类以及实现了 __call__ 方法的类实例, 它都返回 True。 语法 callable()方法语法: callable(object) >> > callable(0) False >> > callable("runoob") False >> > def add(a, b): ... return a + b ... >> > callable(add) # 函数返回...
4dedc11bbcb4cf48033088f8cb65e49f59faa0ed
budidino/AoC-python
/2020-d9.py
930
3.515625
4
INPUT = "2020-d9.txt" numbers = [int(line.rstrip('\n')) for line in open(INPUT)] from itertools import combinations def isValid(numbers, number): for num1, num2 in combinations(numbers, 2): if num1 + num2 == number: return True return False def findSuspect(numbers, preamble): for index, number in en...
019b895273e8298815a4547eb0dde193fd71b8a3
budidino/AoC-python
/2019-d3.py
1,152
3.640625
4
INPUT = "2019-d3.txt" wires = [string.rstrip('\n') for string in open(INPUT)] wire1 = wires[0].split(',') wire2 = wires[1].split(',') from collections import defaultdict path = defaultdict() crossingDistances = set() # part 1 crossingSteps = set() # part 2 def walkTheWire(wire, isFirstWire): x, y, st...
e9812329ff0bf1398fe67004e49a79a1d0075b6c
budidino/AoC-python
/2020-d2.py
443
3.5625
4
INPUT = "2020-d2.txt" strings = [string.strip('\n') for string in open(INPUT)] part1, part2 = 0, 0 for string in strings: policy, password = string.split(': ') numbers, letter = policy.split(' ') minVal, maxVal = map(int, numbers.split('-')) part1 += minVal <= password.count(letter) <= maxVal part2...
53c640630c6f2bdfc7199cbe241af57b58e77652
budgiena/domaci_projekty_ZuzkaV
/ukol4_13.py
854
3.765625
4
# --- domaci projekty 4 - ukol 13 --- pocet_radku = int(input("Zadej pocet radku (a zaroven sloupcu): ")) """ # puvodni varianta ##for cislo_radku in range(pocet_radku): ## if cislo_radku in (0,pocet_radku-1): ## for prvni_posledni in range(pocet_radku): ## print ("X", end = " ") ## print...
847cf25b568b9ced3123114bafa3e4088c5fb8ef
limiteddays/Programming-tips
/node.py
1,618
3.8125
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ...
461af0dc439dfcf33b2dd0bfcf6d4a684949171d
limiteddays/Programming-tips
/forge_rever.py
473
3.796875
4
class Tree(object): x = 0 l = None r = None def traverse(sub_tree, height): left_height = 0 right_height = 0 if sub_tree.l: left_height = traverse(sub_tree.l, height + 1) if sub_tree.r: right_height = traverse(sub_tree.r, height + 1) if sub_tree.l or sub_tree.r: ...
6929627ac4b226a8364a5708b8243b2f9eddf454
jaydeu/Python-Programs
/Aug_12_2015.py
2,815
3.65625
4
######################################################## ### Daily Programmer 226 Intermediate - Connect Four ### ######################################################## # Source: r/dailyprogrammer ''' This program tracks the progress of a game of connect-four, checks for a winner, then outputs the number of moves...
1c32272ef45f6e6958cee58d95088c5b475269b1
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Tuplas.py
808
4.28125
4
# La tupla luego de ser inicializada no se puede modificar frutas = ("Naranja", "Platano", "Guayaba") print(frutas) print(len(frutas)) print(frutas[0]) # Acceder a un elemento print(frutas[-1]) # Navegación inversa #Tambien funcionan los rangos igual que en las listas print(frutas[0:2]) # Una Lista se puede inici...
236756b3ed86fc33bb38ab279c03792e6aa312a6
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Clases.py
2,012
3.953125
4
class Persona: #Contructor def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad class Aritmetica: #Constructor def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def suma(self): return self.num1 + self.num2 class Retang...
3c004f1b944ab083ef565a4e48106303ee124904
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Metodos Privados.py
500
3.53125
4
class Persona: def __init__(self, nombre, apellido, apodo): self.nombre = nombre #Atributo public self._apellido = apellido #Atributo protected "_" self.__apodo = apodo #Atributo privado "__" def metodoPublico(self): self.__metodoPrivado() def __meto...
5ad72e3d56246bc745fb208eb7e8a74860c66a3d
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Manejo de Archivos.py
1,214
3.78125
4
#Abre un archivo # open() tiene dos parametros, el primero el archivo y el segundo lo que se desea hacer # r - Read the default value. Da error si no existe el archivo # a - Agrega info al archivo. Si no existe lo crea # w - Escribir en un archivo. Si no existe lo crea. Sobreescribe el archivo # x - Crea un archivo. Re...
409574344dcb3ca84b2da297f0dfa35d721fd7b2
gitter-badger/cayenne
/cayenne/results.py
7,558
3.625
4
""" Module that defines the `Results` class """ from collections.abc import Collection from typing import List, Tuple, Iterator from warnings import warn import numpy as np class Results(Collection): """ A class that stores simulation results and provides methods to access them Parameters ...
10194946199773e708b6a020c01dd7f01af2efee
FlyingSparkie/Raspberry-Pi-stuff
/gpioLed.py
1,582
3.75
4
import RPi.GPIO as GPIO #import the gpio library from time import sleep #import time library redLed=22 #what pin greenLed=23 blinkTimes=[0,1,2,3,4] button=17 inputButton=False range(5) GPIO.setmode(GPIO.BCM) #set gpio mode BCM, not BOARD GPIO.setup(greenLed, GPIO.OUT) #...
fefc1ce3e2a8afcb32c09d05242089acfba1d567
ZahedAli97/Py-DataStructures
/circularlinkedlist.py
1,829
3.75
4
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def taverse(self): temp = self.head if self.head is not None: while True: print(temp.data, end="") ...
ba2ac685e5bb3fa8a3632b8ddf46fb804113c8ca
Elmuti/tools
/downloader/downloader.py
346
3.5625
4
# File downloader - downloads files from a list # Usage: # python downloader.py links.txt /downloaddir/ import urllib, sys links = sys.argv[1] dldir = sys.argv[2] for line in open(links, "r"): filename = line.split("/")[-1].rstrip('\n') filepath = dldir+filename print "Downloading: ",filename urllib.ur...
d343dd2b8da73751e837c98ec58ec0fb7b734080
AYSEOTKUN/my-projects
/python/hands-on/flask-04-handling-forms-POST-GET-Methods/Flask_GET_POST_Methods_1/app.py
1,011
3.5625
4
# Import Flask modules from flask import Flask,render_template,request # Create an object named app app = Flask(__name__) # Create a function named `index` which uses template file named `index.html` # send three numbers as template variable to the app.py and assign route of no path ('/') @app.route('/') def index():...
f02b8bd1b982abd5bfa37caba9922ae191d9f551
tejashrikelhe/Collatz-conjecture
/collatez conjecture.py
1,214
3.8125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 22:46:10 2020 @author: TEJASHRI """ import matplotlib.pyplot as plt y=[] x=[] a=1 while(a==1): i=0 n=int(input("enter a no=")) x.append(n) while(n!=1): if(n%2==0): n=n/2 print(n) else: ...
4776ee86a215e14e367a14b74073c1c712233dc6
suyash248/ds_algo
/Array/flipZeroesMaximizeOnes.py
2,484
3.703125
4
# Time complexity: O(n) # Using sliding window strategy. from typing import List def flip_m_zeroes_largest_subarray_with_max_ones(arr, m): """ Algorithm - - While `zeroes_count` is no more than `m` : expand the window to the right (w_right++) and increment the zeroes_count. - While `zeroes_cou...
8212efa038c42c118856cb6a50b0d7e9ce1844d2
suyash248/ds_algo
/Tree/traversals.py
2,036
3.921875
4
from Tree.commons import insert, print_tree, is_leaf def preorder(root): if root: print(root.key, end=',') preorder(root.left) preorder(root.right) def inorder(root): if root: inorder(root.left) print(root.key, end=',') inorder(root.right) def postorder(root): ...
57bade1fd06c0bf6e9814bea60b5e4e6a8d35163
suyash248/ds_algo
/Queues/queueUsingStack.py
1,364
4.15625
4
class QueueUsingStack(object): __st1__ = list() __st2__ = list() def enqueue(self, elt): self.__st1__.append(elt) def dequeue(self): if self.empty(): raise RuntimeError("Queue is empty") if len(self.__st2__) == 0: while len(self.__st1__) > 0: ...
589fe67c8ae98e36a621432ab7abb275156172cd
suyash248/ds_algo
/Misc/sliding_window/count_good_strings.py
2,108
3.875
4
''' A string is good if there are no repeated characters. Given a string s and integer k, return the number of good substrings of length k in s​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string....
61e6633eeadf4384a18603640e30e0fa0a6998c8
suyash248/ds_algo
/Array/stockSpanProblem.py
959
4.28125
4
from Array import empty_1d_array # References - https://www.geeksforgeeks.org/the-stock-span-problem/ def stock_span(prices): # Stores index of closest greater element/price. stack = [0] spans = empty_1d_array(len(prices)) # Stores the span values, first value(left-most) is 1 as there is no previous g...
6e8ee71a88eb45d5849993481a375a0d6a625afa
suyash248/ds_algo
/DynamicProgramming/minJumpsToReachEndOfArray.py
960
3.65625
4
from Array import empty_1d_array, MAX # Time complexity: O(n^2) # https://www.youtube.com/watch?v=jH_5ypQggWg def min_jumps(arr): n = len(arr) path = set() jumps = empty_1d_array(n, MAX) jumps[0] = 0 for i in xrange(1, n): for j in xrange(0, i): if i <= j + arr[j]: ...
2439116226bb241f4f6d138e4725607724c6e343
suyash248/ds_algo
/Tree/segment_tree/base_segment_tree.py
599
3.6875
4
from Array import empty_1d_array from math import pow, log, ceil """ Height of segment tree is log(n) #base 2, and it will be full binary tree. Full binary tree with height h has at most 2^(h+1) - 1 nodes. Segment tree will have exactly n leaves. """ class SegmentTree(object): def __init__(self, input_arr): ...
dad7df39a66de05b8743e5b6a8e52de20b24531f
suyash248/ds_algo
/Array/nextGreater.py
1,602
3.90625
4
""" Algorithm - 1) Push the first element to stack. 2) for i=1 to len(arr): a) Mark the current element as `cur_elt`. b) If stack is not empty, then pop an element from stack and compare it with `cur_elt`. c) If `cur_elt` is greater than the popped element, then `cur_elt` is the next greater element for the...
c26340df6acd4f7cbe5fa2060212013b618b7f43
suyash248/ds_algo
/Tree/distanceBetweenNodes.py
1,301
3.984375
4
from Tree.commons import insert def distance_between_nodes(root, key1, key2): """ Dist(key1, key2) = Dist(root, key1) + Dist(root, key2) - 2*Dist(root, lca) Where lca is lowest common ancestor of key1 & key2 :param root: :param key1: :param key2: :return: """ from Tree.distanceFromR...
a8e3dc574a5a78960baaf96994c73f8ea5df4269
suyash248/ds_algo
/Tree/treeSerialization.py
1,906
3.53125
4
from commons.commons import insert, Node, print_tree class BinaryTreeSerialization(object): def __init__(self, delimiter=None): self.delimiter = delimiter self.index = 0 def __preorder__(self, root, serialized_tree=[]): if root is None: serialized_tree.append(self.delimiter...
576f7c47da643057c2643ba703b65e917a6597d4
suyash248/ds_algo
/Array/factorial.py
238
3.765625
4
def fact_rec(n): if n <= 1: return 1 return n * fact_rec(n-1) def fact_itr(n): fact = 1 for i in range(2, n+1): fact *= i return fact if __name__ == '__main__': print (fact_rec(5)) print (fact_itr(5))
d21394227d4390b898fc1588593e43616ed7e502
suyash248/ds_algo
/Misc/sliding_window/substrings_with_distinct_elt.py
2,324
4.125
4
''' Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c. Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abc...
447b5ce60dbe48b380de406540702ef28d034e84
suyash248/ds_algo
/Backtracking/allCombinations.py
2,187
3.53125
4
from Array import empty_1d_array # Time Complexity: O(2^n) def all_combinations(input_seq, combinations): for elt in input_seq: comb_len = len(combinations) for si in range(0, comb_len): combinations.append(combinations[si] + elt) """ {} a ...
bb174384697c54d507e314d4df23a66f32f10d0a
suyash248/ds_algo
/DynamicProgramming/stiver/climbingStairs.py
503
3.59375
4
def climbStairs(n: int) -> int: # dp = [-1 for i in range(n+1)] # def f(i, dp): # if i <= 1: # return 1 # if dp[i] != -1: # return dp[i] # dp[i] = f(i-1, dp) + f(i-2, dp) # return dp[i] # return f(n, dp) dp = [0 for i in range(n + 1)] for i in...
8df5ea6094331a9249b66ab3f1dd129d9f84957f
suyash248/ds_algo
/Tree/sumOfNodes.py
907
3.828125
4
from Tree.commons import insert, print_tree, is_leaf # fs(50) - 50, fs(30) # fs(30) - 80, fs(20) # fs(20) - 100 def find_sum_v1(root): if root is None: return 0 return root.key + find_sum_v1(root.left) + find_sum_v1(root.right) son = 0 def find_sum_v2(root): global son if root is N...
a23e6eb9e35e685b36de1e108a1734c750dfc093
suyash248/ds_algo
/Queues/PriorityQueue/pq.py
4,722
3.859375
4
from Heap.BinaryHeap.maxHeap import MaxHeap from copy import deepcopy class PriorityQueue(object): def __init__(self, pq_capacity=10): self._pq_capacity_ = pq_capacity self._pq_size_ = 0 self._pq_heap_ = MaxHeap(pq_capacity) # Time Complexity : O(log(n)) def insert(self, item, prio...
23f3e33d6028d9aaad652432996ff2570df7490c
DineshDDi/full-python
/hash.py
582
3.71875
4
''' my_dict = dict(dini='001',divi='002') print(my_dict) ''' ''' emp_details = {'employees':{'divi':{'ID':'001','salary':'1000','designation':'team leader'},'dini':{'ID':'002', 'salary':'2000','designation':'associate'}}} print(emp_details) ''' import pandas as pd e...
700a4945fee532f3f8e9c9ea6be562cb597a8d69
DineshDDi/full-python
/ATM.py
2,187
3.859375
4
print("Welcome to ICICI Bank ATM") Restart = 'Q' Chance = 3 Balance = 1560.45 while Chance >= 0: pin = int(input("Please enter your PIN: ")) if pin == (1004): while Restart not in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Press 1 for your Bank Balance \n') print('Press 2 to make ...
4d1f4252ebf1d0956f72f99824b1939e7741164c
DineshDDi/full-python
/mat.py
254
3.609375
4
import numpy as np #import pandas as pd import matplotlib.pyplot as plt time = np.arange(100) delta = np.random.uniform(10,10,size=100) y = 3*time - 7+delta plt.plot(time,y) plt.title("matplotlib") plt.xlabel("time") plt.ylabel("function") plt.show()
179bccd8b2796ea4c23ab39ccb490b7f59fb3689
DineshDDi/full-python
/Py_Tkinder/Dx_T1_S0028a(Tkinder_Horizontal Scale widget).py
575
3.65625
4
# Python program to demonstrate # scale widget from tkinter import * root = Tk() root.geometry("400x300") v1 = DoubleVar() def show1(): sel = "Horizontal Scale Value = " + str(v1.get()) l1.config(text=sel, font=("Courier", 14)) s1 = Scale(root, variable=v1, from_=0, to=100, orient=H...
a7475e64d4c78ab644791db9a969b0ad9e4025b7
ninkle/cracking-the-coding-interview
/fibonnaci.py
182
4.03125
4
#prints the fibonnaci sequence for length n def fib(n): seq = [1, 1] while len(seq) < n+1: next = seq[-1] + seq[-2] seq.append(next) print(seq) fib(8)
d9313b97da54f2393f533ab9ba382be423f1b486
gauriindalkar/nested-if-else
/exercise weather.py
373
4.09375
4
exercise=input("enter set alarm") if exercise=="6": print("wake up morning") weather=input("enter the weather") if weather=="cold": print("put on sokes,jarking,handglose") elif weather=="summer": print("don't put on sokes,jarking,handglose") else: print("i will not go down fo...
555d0e87fbb1e5116ecb0427737d9177bf13508a
freespace/arduino-ADS7825
/ads7825.py
9,627
3.703125
4
#!/usr/bin/env python """ Simple interface to an arduino interface to the ADS7825. For more details see: https://github.com/freespace/arduino-ADS7825 Note that in my testing, the ADS7825 is very accurate up to 10V, to the point where there is little point, in my opinion, to write calibration code. The codes produce...
68516328653c342ca1f8fc10bd452fa86833787d
shangkh/github_python_interview_question
/54.保留两位小数.py
163
3.765625
4
a = "%.2f" % 1.3335 print(a, type(a)) """ round(数值, 保留的数位) """ b = round(float(a), 1) print(b, type(b)) b = round(float(a), 2) print(b, type(b))
b09dd9b4ee31c95569dbed4125448b6894d26b80
shangkh/github_python_interview_question
/17.pyhton中断言方法举例.py
212
3.765625
4
""" assert():断言成功,则程序继续执行,断言失败,则程序报错 """ a = 3 assert (a > 1) print("断言成功,程序继续执行") b = 4 assert (b > 7) print("断言失败,程序报错")
80ebbfd1da7c991ac5810797b90fe493ec22b654
shangkh/github_python_interview_question
/11.简述面向对象中__new__和__init__区别.py
1,384
4.21875
4
""" __init__ 是初始化方法,创建对象后,就立刻被默认调用了,可以接收参数 """ """ __new__ 1.__new__ 至少要有一个参数 cls,代表当前类,此参数在实例化时由python解释器自动识别 2.__new__ 必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时要特别注意, 可以return父类(通过super(当前类名, cls))__new__出来的实例, 或者直接是object的__new__出来的实例 3.__int__有一个参数self,就是这个__new__返回的实例, __init__在__new__的基础上可以完成一些其他的初始化动作, ...
3ea7c9fc3f2670d89546b76d94c81782face9a2f
shangkh/github_python_interview_question
/80.根据字符串的长度排序.py
111
3.53125
4
s = ["ab", "abc", "a", "asda"] b = sorted(s, key=lambda x: len(x)) print(s) print(b) s.sort(key=len) print(s)
8aebc47e8ae2b71081771c8c069292f1795bc6f2
shangkh/github_python_interview_question
/89.用两种方法去空格.py
118
3.6875
4
str = "Hello World ha ha" res = str.replace(" ", "") print(res) list = str.split(" ") res = "".join(list) print(res)
eddce67f5ecab1fef1b56b2df5c1a707b390b0da
shangkh/github_python_interview_question
/6.python实现列表去重的方法.py
138
3.65625
4
my_list = [11, 12, 13, 12, 15, 16, 13] list_to_set = set(my_list) print(list_to_set) new_list = [x for x in list_to_set] print(new_list)
eda27ec0aba10380bb4f1625ce68bfc49c62142e
shangkh/github_python_interview_question
/76.列表嵌套列表排序,年龄数字相同怎么办.py
236
3.59375
4
my_list = [["wang", 19], ["shang", 34], ["zhang", 23], ["liu", 23], ["xiao", 23]] a = sorted(my_list, key=lambda x: (x[1], x[0])) # 年龄相同添加参数,按字母排序 print(a) a = sorted(my_list, key=lambda x: x[0]) print(a)
8510c5a27d2ed435e47d615d6c9955a388f61424
shangkh/github_python_interview_question
/75.列表嵌套元祖,分别按字母和数字排序.py
223
3.53125
4
my_list = [("wang", 19), ("li", 55), ("xia", 24), ("shang", 11)] a = sorted(my_list, key=lambda x: x[1], reverse=True) # 年龄从大到小 print(a) a = sorted(my_list, key=lambda x: x[0]) # 姓名从小到大 print(a)
abae063d758cc0302f666398f6c169627f66c319
sacremendev/Project-Euler
/Q14.py
363
3.8125
4
#!/usr/bin/python def count(n): k = 0 while n != 1: if (n % 2) == 0: n = n / 2 else: n = n * 3 + 1 k = k + 1 #print n #print k return k result = 0 for i in range(1, 1000000): num = count(i) if num > result: print ("update ", i, " "...
0c927b6c474351d757a631300070d4010d458afa
green-fox-academy/Angela93-Shi
/week-02/day-8/copy_file.py
537
3.6875
4
# Write a function that copies the contents of a file into another # It should take the filenames as parameters # It should return a boolean that shows if the copy was successful import shutil def copy_file(oldfile,newfile): shutil.copyfile(oldfile,newfile) f=open(oldfile,'r') f.seek(0) text1 = f.read(...
9d3b7f05c931cceb48d7c2e53fce9dfc35ca1f79
green-fox-academy/Angela93-Shi
/week-05/day-03/change_xy.py
335
3.984375
4
# Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars # have been changed to 'y' chars. def change_xy(str): if len(str) == 0: return str if str[0] == 'x': return 'y' + change_xy(str[1:]) return str[0] + change_xy(str[1:]) print(change_xy("xxsds...
f41c3b2d10e43b66cf7ea4ec8c7ad8f527facd28
green-fox-academy/Angela93-Shi
/week-03/day-01/foreat_simulator.py
1,830
3.953125
4
class Tree: def __init__(self,height=0): self.height = height def irrigate(self): pass def getHeight(self): return self.height class WhitebarkPine(Tree): def __init__(self,height=0): Tree.__init__(self , height) self.height = height def irrigate(self): ...