blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
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):
... |
d904f6ae14f31c7b284e39329a22a1e0a8ec91bf | green-fox-academy/Angela93-Shi | /week-02/day-7/oop/sharpie.py | 806 | 3.9375 | 4 | # Create Sharpie class
# We should know about each sharpie their color (which should be a string),
# width (which will be a floating point number), ink_amount (another floating point number)
# When creating one, we need to specify the color and the width
# Every sharpie is created with a default 100 as ink_amount
# W... |
0ff0c13459c83929d90c57a453cb8fdf5736af28 | green-fox-academy/Angela93-Shi | /week-01/day-3/python/print_even.py | 122 | 3.921875 | 4 | # Create a program that prints all the even numbers between 0 and 500
for i in range(500):
if i%2==0:
print(i) |
12562fa1658d275e15075f71cff3fac681c119ab | green-fox-academy/Angela93-Shi | /week-01/day-4/data_structures/data_structures/product_database.py | 715 | 4.34375 | 4 | map={'Eggs':200,'Milk':200,'Fish':400,'Apples':150,'Bread':50,'Chicken':550}
# Create an application which solves the following problems.
# How much is the fish?
print(map['Fish'])
# What is the most expensive product?
print(max(map,key=map.get))
# What is the average price?
total=0
for key in map:
total=total+map... |
fca1600839df5efa93b7f515b6323c1a32c9e2ce | green-fox-academy/Angela93-Shi | /week-01/day-4/function/summing.py | 238 | 4.03125 | 4 | # Write a function called `sum` that returns the sum of numbers from zero to the given parameter
given_num=10
def sum(num):
global given_num
for i in range(num+1):
given_num=i+given_num
print(given_num)
sum(given_num) |
c525397178d3cfa51ee9163724db2d8131c8601f | green-fox-academy/Angela93-Shi | /week-02/day-7/inheritance/student.py | 904 | 3.90625 | 4 | from person import Person
class Student(Person):
def __init__(self,name='Jane Doe',age=30,gender='female',previous_organization='The School of life',skipped_days=0):
Person.__init__(self,name='Jane Doe',age=30,gender='female')
self.previous_organization = previous_organization
self.skipped_... |
587a7726500b091aea4511e4036f8750c229ecaa | green-fox-academy/Angela93-Shi | /week-05/day-01/all_positive.py | 319 | 4.3125 | 4 | # Given a list with the following items: 1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14
# Determine whether every number is positive or not using all().
original_list=[1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14]
def positive_num(nums):
return all([num > 0 for num in nums])
print(positive_num(original_list)) |
7e84399b0ae345beb15e19b1e44663d4bc062138 | green-fox-academy/Angela93-Shi | /week-02/day-7/oop/petrol_station.py | 718 | 3.796875 | 4 | # Create Station and Car classes
# Station
# gas_amount
# refill(car) -> decreases the gasAmount by the capacity of the car and increases the cars gas_amount
# Car
# gas_amount
# capacity
# create constructor for Car where:
# initialize gas_amount -> 0
# initialize capacity -> 100
class Station():
def __init__(... |
8fcf16851182307c41d9c5dd77e8d42b783628c7 | green-fox-academy/Angela93-Shi | /week-01/day-4/function/factorial.py | 409 | 4.375 | 4 | # - Create a function called `factorio`
# that returns it's input's factorial
num = int(input("Please input one number: "))
def factorial(num):
factorial=1
for i in range(1,num + 1):
factorial = factorial*i
print("%d 's factorial is %d" %(num,factorial))
if num < 0:
print("抱歉,负数没有阶乘")
elif nu... |
c5d9cfe8cdda4d4fdc98f77221c15bb23da5e100 | green-fox-academy/Angela93-Shi | /week-01/day-4/data_structures/data_structures/telephone_book.py | 478 | 4.1875 | 4 | #Create a map with the following key-value pairs.
map={'William A. Lathan':'405-709-1865','John K. Miller':'402-247-8568','Hortensia E. Foster':'606-481-6467','Amanda D. Newland':'319-243-5613','Brooke P. Askew':'307-687-2982'}
print(map['John K. Miller'])
#Whose phone number is 307-687-2982?
for key,value in map.item... |
f0871075ce0fef62569e4ce443389d1c8c592480 | sajal203/dice-simulator | /dicesimulator.py | 641 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 20:26:46 2020
@author: sajal
"""
'''dice simulator'''
import random
import time
user_inp = 'yes'
while user_inp == 'yes' or user_inp == 'y':
print('dice is rolling...')
time.sleep(1)
dice1 = random.randint(1, 6)
dice2 = ran... |
6f5f64793115b2302e947c9f8ce5be419d5740e1 | johnrick10234/hello-world | /Homework-4/Homework_4_12.7.py | 484 | 3.921875 | 4 | #John Rick Santillan #1910045
def get_age():
age=int(input())
if age<18 or age>75:
raise ValueError('Invalid age.')
return age
def fat_burning_heart_rate(age):
h_rate=(220-age)*.70
return h_rate
if __name__=='__main__':
try:
age=get_age()
print('Fat burning heart rate ... |
cc78b79ef9732173ad7066b7c0474ce639bbe480 | Joseane772/exercicios_python | /pratice/B.py | 844 | 3.71875 | 4 | na = int(input('what is the total number of students?'))
NV = 0
Lx = 0
Lz = 0
EB = 0
EM = 0
Vb = 0
for n in range(0, na):
v = str(input('which list will you vote for(X or Z)'))
NE = str(input('what is your level of education (B or S)?'))
if v == 'x':
Lx = Lx + 1
elif v == 'z':
Lz = Lz +... |
b68d019707668a3a3a47b556afa389154e403274 | mnusicallity/Py-Pong | /Pong/paddle.py | 1,855 | 3.78125 | 4 | import pygame
from pygame.sprite import Sprite
class Paddle(Sprite):
def __init__(self, screen, ai_settings, player_paddle):
super(Paddle, self).__init__()
self.ai_settings = ai_settings
self.color = ai_settings.paddle_color
self.paddle_position = 400
self.paddle_s... |
31c2c7901dd994dea44ce68dea458bf8675926d3 | MAWA-Taka/SelfTaughtPgmr | /p156_apple.py | 291 | 3.703125 | 4 | class Apple:
def __init__(self, k, s, w, c):
self.kind = k
self. size = s
self.weight = w
self.color =c
a = Apple("ふじ", "L", 200, "yellow")
print("品種:{}、サイズ:{}、重さ:{}、色合い:{}".format(a.kind, a.size, a.weight, a.color))
|
856e1fe1bffc794ff217365ce83f1bfab6d9e094 | misssoft/Fan.PythonExercise | /src/assessment/estimate/binary_search_distribution.py | 724 | 4 | 4 | """
Distribute a depth value into the right bin by binary search
"""
def binary_search_distribution(boundaries, depth, lower, upper):
"""
:param boundaries: a list containing the boundary values of different bins in ascending order
:param depth: the depth value of a pixel
:param lower: position of lowe... |
5a48b2cc0ad944fafff7215e755a6af233ead39e | KrishnaAgarwal16/May-Leetcode-Challenge-2020 | /Week-1/MajorityElement.py | 419 | 3.671875 | 4 | #Problem Link: https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3321/
class Solution:
def majorityElement(self, nums: List[int]) -> int:
d = set(nums)
n = len(nums)
for i in d:
if nums.count(i)>(n/2):
return i
... |
3f3d0582c711859aae5b2999bf057b6cba2b88fd | LiamBrem/PythonProjects | /PassGen/main.py | 577 | 3.8125 | 4 | import random
import pyperclip
def generatePassword(chars, charList):
password = []
for i in range(chars):
nextChar = characterList[random.randint(0, len(charList))]
password.append(nextChar)
return ''.join(password)
def copyToClipBoard(copy):
pyperclip.copy(copy)
if __name__ == "_... |
6ca4a43e77389bcdec965fc1b9ced177f785c1a8 | rajes95/intensive_fundamentals_of_computer_science | /binary_search/binary_search_tree_Tests.py | 3,526 | 4.125 | 4 | # Author: Rajesh Sakhamuru
# Version: 3/28/2019
import unittest
import binary_search_tree
class Binary_Search_Tree_Tests(unittest.TestCase):
def testBinarySearchTreeAdd(self):
"""
# Purpose: This method adds a specified value to the binary tree
in the expected location. Lower... |
1b42ac0ff1735b7c01b53715a78feb9d6d525700 | rajes95/intensive_fundamentals_of_computer_science | /more_shapes_with_loops/moreShapes.py | 3,979 | 4.4375 | 4 | # Author: Rajesh Sakhamuru
# Version: 2/10/2019
def printLowerRight(size):
"""
This function prints a right-aligned triangle with an incrementing number of "*" in each
row until it reaches the specified size. A Lower Right triangle of size 6 would
look like this:
*
**
***
... |
5a094fde4286a2b7776be503ad866871330454bf | rajes95/intensive_fundamentals_of_computer_science | /repeating_shapes/repeatingShapesDriver.py | 2,088 | 4.03125 | 4 | # Author: Maria Jump
# Version: 2019-02-15
import repeatingShapes
def readInteger(prompt, error="Value must be a positive integer"):
""" Read and return a positive integer from keyboard """
value = -1
while(value == -1):
entered = input(prompt)
try:
value = int(entered)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.