blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d0232f188cd2dc1505fa57d3bc48e6c12515cd73
xiaoluome/algorithm
/Week_01/id_3/recursion/101/test_101.py
675
3.71875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def build(nums): if not nums: return None return build_node(nums, 1) def build_node(nums, i): if len(nums) < i or nums[i-1] is None: return None node = TreeNode(nums[i-...
38b2a6418f232a88692f615946a99fa9cea0bf1f
pramodhsingh/python
/08_Table-Dynamic.py
315
3.625
4
import os os.system('cls||clear') a = int(input("***Print Table of a Number***\n\nEnter a Number: ")) b = int(input("Enter increment: ")) if (b==0 | b<a): print("\nInvalid Range, pleas try again...") for a in range(a,b+1): for i in range(1,11): print(a, "x",i ,"=", a*i) print('\t')
7b0cbdc232fcb050c30cf72d8c81ba1d20c77927
AnthonyRivers/CS136_Lab
/lab_10/Lab10_Antonio_Rios_Searching_and_Sorting_Algorithms.py
3,423
3.84375
4
# Antonio Rios # April 17, 2015 # CS 136 Lab # LAB 10: Searching and Sorting Algorithms # # This lab provides an opportunity to get an # understanding of how to perform some basic # profiling, i.e. you will measure the execution # time of some searching and sorting algorithms # that we covered in class. # -------------...
6bc09d62e8075e840edfd2cf1d741b14af0f514f
EwertonBar/CursoemVideo_Python
/mundo03/aulas/aula017c.py
238
4.03125
4
valores = list() for v in range (0,5): valores.append(int(input('Digite um valore: '))) for c, v in enumerate(valores): print(f'Na posição {c} encontrei o valor {v}.') print('Cheguei no final da lista.') print(valores)
8ef28d0af8f5986f795cab9c3e7b0dcc481d740e
nataliegarate/python_ds
/trees/k_dist_from_root.py
1,092
3.765625
4
# iterative def findKNodes(root, k): if root is None: return None def findKNodes(root, k): results = [] queue = [{'node': root, 'order': 0}] while len(queue) > 0: cur = queue.pop(0) if cur['order'] == k: results.append(cur['node'].val) ...
7e55242b569a138d0af9dc6e3e3e3141586f53e2
Rosebotics/PythonGameDesign2018
/camp/Z_2019_Solutions/TicTacToe/Solutions/TicTacToe0.py
1,763
4.34375
4
# TicTacToe Version 0 - draw a bsic 3x3 grid. # import pygame so we can use it import pygame # initialize constants BOARD_SIZE = 3 # number of rows and columns BOARD_RANGE = range(BOARD_SIZE) # range of rows and columns PPS = 150 # pixels per square WINDOW_SIZE = PPS * BOA...
0df76c213b7c33834068c94f9ee14b4343683a3c
Nilsonsantos-s/Python-Studies
/HackerRank/11.py
674
3.6875
4
# if __name__ == '__main__': pessoas = [] pessoa = [] scores = [] penultimo = [] for x in range(int(input().strip())): name = input().strip() score = float(input().strip()) pessoa.append(name) pessoa.append(score) scores.append(score) pessoas.append(p...
f5fadff37aad768e66a1753fbda120dab31f1c3f
abiswas20/Computational_Programming_in_Python
/Knapsack+Graph Optimization Problems/usingGreedyAlgo.py
1,393
4.15625
4
##Functions to use "greedy algorithm" to choose items. Their implementation is dependent on class 'Item' and function 'greedy'. Code is based on Fig.12.4. in John Guttag's book.## from classItem import Item from classItem import value,weightInverse,density from greedyAlgorithm import greedy def buildItems(): name...
53cb04551d8bb6dac449acd7867a46deb7f6e688
kbrain41/class
/stroki/stroki1.py
201
3.796875
4
a = "Строк бояться не нужно! Строки это всего лишь обьекты заключенные в ковычки." p = len(a) // 2 print(a[0:p].lower() + a[p::].upper())
2018dbb964523d14024a55c8ccddcded176a47c1
cccccyclone/Maleapy
/src/ex5/leacurve.py
1,977
3.59375
4
import sys sys.path.append('..') import numpy as np from ex1.linear import * def addOnes(x,m): """ Add a col of 1 at first column of x x: the number of rows """ n = x.size/m one = np.ones((m,1)) x = x.reshape((m,n)) judge = np.sum(x[:,0] == one.flatten()) if judge != m: x = ...
410d4b95329fafb4a5ecd1d6f43e8d0d46308dde
alex-ozerov/Python_starter
/007_Lists/task_1.py
131
3.59375
4
my_list = [1, 2, 3, 4, 5, 6, 7, 8] print(min(my_list)) print(max(my_list)) print(sum(my_list)) print((sum(my_list))/(len(my_list)))
83ec468a399464f462f5695f10202663b46365d8
SarthakSingh2010/PythonProgramming
/basics/List.py
2,708
4.375
4
kp=list(range(10))#make a list of 0-9 using range data type print(kp) nums = [25,12,16,95,43] print(nums) print('make a copy of nums') mp=nums.copy() print(mp) print('1st value ',nums[0]) print('from index 2 till last index') print(nums[2:]) print('last 3 element') print(nums[-3:]) print('negative indexing') print(nums...
e6c954556cbe0b0ea053648241e4d5255602dc1d
iKwesi/Labyrinth-Game-python
/Helpers/ILabyrinth.py
556
3.578125
4
from abc import ABC, abstractmethod class ILabyrinth(ABC): """ Interface for creating a maze object """ @abstractmethod def generate_grid(self): pass @abstractmethod def find_neighbours(self, row, col): pass @abstractmethod def _validate_neighbours_generate(self, neighbour_indices): pass...
388c0084041f974c32f4ebb0a5600c41246a8506
Linyameng/alphadata-dev
/appbak/app/core/test1.py
442
3.6875
4
# -*- coding: utf-8 -*- """ Created on 2018/8/2 @author: xing yan """ # -*- coding: utf-8 -*- # __author__="ZJL" #a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [{"a":1,"b":2,"c":3},{"d":4,"e":5},{"f":6,"g":7},{"h":8,"i":9}] def fenye(datas, pagenum, pagesize): if datas and isinstance(pagenum, int) and isinstance(pa...
1440519a0f3dd3c1576311823e32aa6a74ae79df
Syabz03/pythonCombinedProject
/mydata.py
3,808
4.03125
4
class Mydata: """Represents 1 day of data from Reddit or Twitter Attributes: topic: str Topic being searched source : str "reddit" or "twitter" date: datetime The day which the data is for interactionCount: int number of upvotes/do...
8f33a34b87856056390294dac9e622c4d083e92a
Sixpounder87/Intel_tasks
/intel_task_1/time_converter.py
984
3.71875
4
import sys def time_to_sec(s='1'): if not isinstance(s, str): raise TypeError('Wrong type of argument. Should be a string.') list_of_char_digits = list(map(str, range(10))) time_units = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400} for i in s[:-1]: if i not in list_of_char_digi...
1936510a8af69ed168f6ec496a597adcb3990991
MicheleAlladioAKAMich/Compiti_Vacanze
/ReverseString.py
250
4.1875
4
''' Author: Michele Alladio es: Reverse a string For example: input: "cool" output: "looc" ''' def main(): string = input("Inserisci una stringa: ") print(string[::-1]) #fastest way to reverse a string if __name__ == main(): main()
2f5210b00ce782bdca50f27ac9ee61fbff39c724
vinamrathakv/pythonCodesMS
/CountVowelsConsonantsInFile14_11.py
390
3.984375
4
# count vowels and consonants in file vowels = {"a", "e", "i", "o", "u"} fileName = input("Enter filename to count vowels and consonants : ") file = open(fileName, "r") fileData = file.read() print(len(fileData)) v = 0 c = 0 for i in fileData: i.lower() if i in vowels: v += 1 else:...
b1e6429edaa1beeb6060704b6074f379c742f351
N3CROM4NC3R/python_crash_course_exercises
/Lists/Slices/My pizzas,Your Pizzas.py
329
4.25
4
pizzas=["chesse pizza","cheddar pizza","detroit pizza"] friendPizzas=pizzas[:] pizzas.append("new york pizza") friendPizzas.append("greek pizza") print("My favorite pizzas are:") for pizza in pizzas: print(pizza) print("My friend's favorite pizzas are:",friendPizza) for friendPizza in friendPizzas: print(fri...
88e27f867e1e1cd87efa6911efa299dc8f76cf21
yshshadow/Leetcode
/151-200/190.py
1,894
3.859375
4
# Reverse # bits # of # a # given # 32 # bits # unsigned # integer. # # Example # 1: # # Input: 00000010100101000001111010011100 # Output: 00111001011110000010100101000000 # Explanation: The # input # binary # string # 00000010100101000001111010011100 # represents # the # unsigned # integer # 43261596, so # return 9641...
76f2df275391acb9452fe62c9f67fbf6069ad199
AlpineMeadow/GameOfLife
/GameOfLife.py
5,416
3.578125
4
#! /usr/bin/env python3 #A program to simulate The Game of Life by John Conway. def getNeighborsState(i, j, gOL) : #Get the inital conditions. iup = i - 1 idown = i + 1 jleft = j - 1 jright = j + 1 currentCellState = gOL[i, j] #Either live or dead. uleft = gOL[iup, jleft] ucenter = g...
c8acc2c8b6896c28146d3e1518793c7619d54598
daiyeyue/PythonExercise
/For/LY-04-For.py
226
4
4
for i in range(0,4): for j in range(0,5): print("*" , end=" ") print("\t") #简单图形打印 for i in range(0,4): if i == 0 or i ==3 : print("* " * 5); else: print("* *")
ebcdc63b14419b543bc777fd1c32b8ba2d31f11e
Omupadh/python3
/Desafios/desafio071.py
570
3.515625
4
from math import trunc print('=' * 37) print('{:^37}'.format('BANCO WJ')) print('=' * 37) valor = int(input('Qual valor você quer sacar? R$ ')) if valor >= 50: n50 = trunc(valor / 50) valor = valor % 50 print(f'Total de {n50} cédulas de R$50') if valor >= 20: n20 = trunc(valor / 20) valor = valor %...
c3d7035598ec023f8128a622a4157e7e31ff517b
lccastro9/hkr-6
/Point.py
533
3.765625
4
class Point(): def __init__(self,x,y): self.x=x self.y=y def move(self,x,y): self.x1=x self.y1=y def reset(self): self.x=0 self.y=0 def calculate_distance(self,otherPoint): a=(otherPoint.x-self.x)**2 + (otherPoint.y-self.y)**2 dista...
d0ab9d001660bc65eb034a260123274b82a94ea7
gautambp/codeforces
/1081-A/1081-A-48094617.py
75
3.734375
4
s = int(input()) if s == 2 or s == 1: print(s) else: print(1)
b525c63b12b0837474ef32a6be37baa1c21615f1
langlixiaobailongqaq/python-selenium
/Python3_Selenium3_BD/data_driven.py
464
3.796875
4
""" 5.2、数据驱动之参数化驱动和txt文件数据驱动 """ # coding:utf-8 from selenium import webdriver import time search_text = ['python', '中文', 'text'] for keys in search_text: driver = webdriver.Chrome() # 隐式等待 driver.implicitly_wait(10) driver.get("https://www.baidu.com/") driver.find_element_by_id('kw').send_keys(key...
4c2f4e9b9500fc8b2308ccf3bdbe9c789bf20de1
padhs/py-work
/newpy-project/q17.py
428
4.21875
4
# adding an element to the tuple def add_element(new_dance_form): dance_form = ("Samba", "Tango", "Ballet", "Tap", "Modern", "Jazz", "Hip-hop") list_dance_form = list(dance_form) print(f"These were the given dance forms:\n {dance_form}") list_dance_form.append(new_dance_form) print("These are the u...
4cd64efdbbf0a3eb06799f90d5904c735c72eddd
240302975/study_to_dead
/面向对象/21 绑定方法与非绑定方法介绍.py
1,091
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time :2020/1/1 21:35 """ 在类内部定义的函数,分为两大类: 一:绑定方法:绑定给谁,就应该由谁来调用,谁来调用就会把调用者当作第一参数自动传入 绑定到对象的方法:在类内定义的没有被任何装饰器修饰的 绑定到类的方法:在类内定义的被装饰器classmethod修饰的方法 二:非绑定方法:没有自动传值这么一说,就类中定义的一个普通工具,对象和类都可以使用 非绑定方法:不与类或者对象绑定 """ class Foo: def __in...
ee1aa1857bf79f58397701b512a3777566dd33cd
Createitv/BeatyPython
/08-python-books/intermediate python/map,filter,reduce.py
364
3.515625
4
items = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, items)) print(squared) # Output: [1, 4, 9, 16, 25] number_list = range(-5, 5) less_than_zero = list(filter(lambda x: x < 0, number_list)) print(less_than_zero) # Output: [-5, -4, -3, -2, -1] from functools import reduce product = reduce((lambda x, y: x * y)...
e58a48c3d1220a209361319b7c66244d71899249
croguerrero/pythonexercises
/ejercicio18.py
547
3.875
4
import numpy as np n = int(input("Introduce las filas A: ")) m = int(input("Introduce las columnas A: ")) p = int(input("Introduce las columnas B: ")) A = np.empty((n,m)) print("\n=======Matriz A========") for i in range(n): for j in range(m): A[i, j] = float(input("Introduce el elemento ({},{})".format...
912446cdae226f82f8a2e1d08accb9add960ac03
maolei1/ApiAutoTest
/day01/03.上传文件.py
978
3.765625
4
''' 接口的功能是上传文件,比如上传头像,附件等 ''' import requests url = "http://www.httpbin.org/post" file = r"D:\test.txt" with open(file, 'r') as f: #字典,上传的文件:文件相关参数组成的元祖 # text/plain 是文件的类型 load = {"file1": (file, f, "text/plain")} r = requests.post(url, files = load) #print(r.text) #上传图片 file1 = r"D:\a.jpg" with ...
a09634a235dbbd30908bfac185f7c6f3d38c4af5
XxWar-MachinexX/Computer_Science_Capstone
/Weather_Station.py
3,525
3.53125
4
# Jose F. Pina Jr. # Southern New Hampshire University # CS-350 Emerging Systems Architecture & Technology # Final Project __Weather Station__ import grovepi import math import json import time import datetime from grovepi import * # LED configuration green_led = 2 blue_led = 3 red_led = 4 # Temp / ...
e063305fc709976764dc32a65049db20f14025f2
relman/sort-list
/main.py
697
4.0625
4
import sys def sort_list(s): """ Returns sorted list. :param s: list of words and numbers """ for i in range(0, len(s)): for j in range(i + 1, len(s)): if compare(s[i], s[j]): s[i], s[j] = s[j], s[i] return s def compare(x, y): """ ...
07f718e76794a1dc07e26a7a02ca6ac0ea3871c0
grecoe/teals
/8_game_controller/games/collegechooser.py
1,856
4.1875
4
# Include the logger so we can output from here as well from utils.tracer import TraceDecorator @TraceDecorator def show_description(): print(""" Based on your choices, the program will help you pick a college that most suits you. Code is located at: /games/collegechooser.py """) @TraceDecorator def play(): ...
af62b8ebe36413c16a21e68beb7cf07a68570763
chayabenyehuda/LearnPython
/She Codes/guessing game.py
395
4.0625
4
Secret_name = "Chaya" guess = "" guess_count = 0 guess_limit = 3 out_of_guess = False while Secret_name != guess and not(out_of_guess): if guess_limit > guess_count: guess = input("enter a guess: ") guess_count += 1 else: out_of_guess = True if out_of_guess: pr...
fcc79b7bdca87f806ead2e7f708be911cbae139f
JoannaEbreso/PythonProgress
/FileReverse.py
361
3.703125
4
input_file=open("input.txt","r") output_file=open("output.txt","w") for line_str in input_file: new_str='' line_str=line_str.strip() for char in line_str: new_str=char+new_str print("new_str",file=output_file) print('Line: {:<12s} is reversed to {:>12s}'. format(line_str,new_str)) input_f...
cb707f001f803c1b7d3308654a097031dab87df4
Lucas130/leet
/dynamic-planning/122-best-time-to-buy-and-sell-stock-i.py
777
3.609375
4
""" 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 """ class Solution: def maxProfit(self, prices) -> int: if len(prices) < 2: return 0 sum_temp = 0 for i in range(1, len(prices)): if prices[i] > pri...
4d33c3b85eb632dc8c837b5b7c5c9541e4ad2d39
rmjohnson/programming
/python/euler/problem19.py
1,249
3.953125
4
def check(d): if d[0] == "S" and d[2] == 1: return "T" else: return "F" def monthdays(m,y): if m == "Jan" or m == "Mar" or m == "May" or m == "Jul" or m == "Aug" or m == "Oct" or m == "Dec": return 31 if m == "Feb" and y == 2000: return 29 elif m == "Feb": ...
f017bba9bbfc4f240d49636ecf9871fdad10d440
yysung1123/competitive_programming
/generator/GA.py
210
3.625
4
#!/usr/bin/env python3 import random n = 10000 arr = [i + 1 for i in range(n)] print(n) #random.shuffle(arr) print(' '.join([str(i) for i in arr])) #random.shuffle(arr) print(' '.join([str(i) for i in arr]))
ae3224a76bc63be70373c3436f88d9fec3ff29f4
sverchkov/generalizedtrees
/generalizedtrees/tree.py
5,978
3.921875
4
# Tree data structure # # Licensed under the BSD 3-Clause License # Copyright (c) 2020, Yuriy Sverchkov from collections.abc import Collection from collections import deque from typing import Iterable, Any from logging import getLogger logger = getLogger() class Tree(Collection): """ A container-like tree d...
6a1dcd57e7ba864558c3a823bd7e3d70fe146f68
Fashgubben/TicTacToe
/tic_tac_toe.py
5,522
3.5625
4
import game_functions from class_statistics import Statistics, Player from check_for_winner import check_for_winner from statistic_table import create_terminal_table, print_table, stat_gui from check_input import get_valid_coordinates def create_players(): """Creates and returns two player objects""" ...
dbc5eb8dbcb998b649574e1f06ef044a6231f2c2
godwon2095/python_algorithm
/class_3_recursive/merge_sort_recursive.py
1,142
4.125
4
#2015110417 수학과 장성원 # -*- coding: utf-8 -*- import pdb def MergePartial(left_list, right_list): sorted_list = [] while len(left_list) > 0 or len(right_list) > 0: if len(left_list) > 0 and len(right_list) > 0: if left_list[0] <= right_list[0]: sorted_list.append(left_list[0])...
c9e2b38f113e5dc3956a3b8fa9a6f6f0c88f65fb
rbhatta8/dota2-league-rep-learning
/rep-learning/scripts/visualization.py
1,219
3.78125
4
""" Script used to visualize results from any of the techniques authors : Rohit Bhattacharya, Azwad Sabik emails : rohit.bhattachar@gmail.com, azwadsabik@gmail.com """ # imports import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def visualize2d(X, Y, output_name): ''' Visualizes in 2d ...
f23b5aa702baed110c605e96533ca569cbd465d0
Prasad-Medisetti/STT
/My Python Scripts/BIN2OCT.py
764
4.1875
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 15 18:35:09 2020 @author: hp """ ''' Program to convert a binary number to octal number. Input: 11010 Output: 32 1. Valid Input: a) Only number consisting of 0s and 1s will be given as input 2. Invalid inputs: a) Decimal b) Fraction c) String d) Negative number ...
593c576dd4cd4cb4063ca8b9778d25119c08ff97
Nevilli/unit_three
/d4_unit_three_warmups.py
270
3.859375
4
def area_of_rectangle(length, width): """ This function calculate the area of a rectangle :param length: length of long side of rectangle :param width: length of small side of rectangle :return: area """ area = length * width return area
c44139ab22af877b3c699e3fbdb3f147ade5441b
fasna123/TheSparksFoundatiion
/TSF_task2.py
1,651
3.90625
4
#importing necessary libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing dataset data_set="http://bit.ly/w-data" data=pd.read_csv(data_set) #ploting dataset data.plot(x='Hours', y='Scores', style='o') plt.title('Hours vs Percentage') plt.xlabel('Hours Studied'...
fd4940111296beab6bf6b81ee9e30dd7ae1c6536
Rotsteinblock/main.python
/main.py
2,038
3.65625
4
import math; import collections; minSchritt = 1; """ muss 1 sein?""" L = 100; """ abstand der motoren in schritten""" actMotorLaengeA = 20; actMotorLaengeB = 70; def getLaengeA(x, y): return math.sqrt(x*x+y*y) def getLaengeB(x, y): return math.sqrt((L-x)*(L-x)+y*y) def beta (a, b): res = math....
059929bce0186fac00a5c472177383f3391976c4
yashhR/competitive
/LeetCode/258. Add Digits.py
449
3.734375
4
# def addDigits(num: int) -> int: # def sum_digits(n): # sumi = 0 # for digit in str(n): # sumi += int(digit) # return sumi # while len(str(num)) > 1: # num = sum_digits(num) # return num def add_digits(num): if len(str(num)) > 1: sumi = 0 f...
bfc2b396219f22c34fab31f4616111206b0a61fa
jadball/python-course
/Level 2/29 Work in progress/Physics/02_animate_particle.py
2,401
3.765625
4
import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np fig = plt.figure() fig.canvas.set_window_title("Planetary Orbits") ax = fig.gca(projection="3d") ax.set_title("Satellite Tracing Orbiting Earth") elevation = 75 viewing_angle = 125 ax.view_init(elev=elevation, azim=viewing_ang...
3f31550ffeebac06b70b55fd236f153e31d8d6a3
shiwanibiradar/10days_python
/day2/while/squareseries.py
110
3.625
4
#addition of square of first 10 digit num=int(input()) sa=0 for i in range(1,num+1): sa=sa+(i*i) print(sa)
49e3ca16cbee786301fd9eb83e257e05366369f9
luismelendez94/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
248
3.984375
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): new_list = my_list.copy() index = 0 for element in my_list: if element == search: new_list[index] = replace index += 1 return new_list
ffa913d15630ba72a90d919005816b034afb3121
Aasthaengg/IBMdataset
/Python_codes/p00001/s737543331.py
186
3.75
4
f, s, t = 3,2,1 for i in range(10): z = int(input()) if z >= f: f,s,t = z, f, s; elif z>=s: s,t = z,s; elif z>=t: t = z print(f);print(s);print(t)
da9250834a1a7c27dd61fd2f2a219bda6855900c
haukurarna/2018-T-111-PROG
/solutions_to_programming_exercises/assignment26_for.py
253
4.03125
4
turns = int(input("Input the number of turns: ")) number_of_negatives = 0 for number in range(turns) : choice = int(input("input a number: ")) if choice < 1 : number_of_negatives += 1 print("number of negatives:", number_of_negatives)
728b5f84bbac119a177bd349ebce521e34cf296a
zotochev/VSHE
/week 02/tasks_02/02_33_len_line.py
80
3.546875
4
n = 1 count = -1 while n != 0: count += 1 n = int(input()) print(count)
1d86f470b7ee5224a993cf06266f4d6a3c76e186
joaoo-vittor/estudo-python
/OrientacaoObjeto/aula23.py
1,109
4.3125
4
""" aula 23 Implementando um iterator """ class MinhaLista: def __init__(self): self.__items = [] self.__index = 0 def add(self, value): self.__items.append(value) def __getitem__(self, index): return self.__items[index] def __setitem__(self, index, value): ...
1b90f789fc56705aaa1eff9522c04e23f11b1751
javierllaca/strange-loops
/challenges/trees/reconstruct_tree/main.py
839
3.78125
4
""" Reconstruct a binary tree Input: inorder, preorder Output: root of constructed tree class Node: data (ints), leftChild, rightChild """ class Node: pass inorder = [2, 3, 5, 6, 7, 9] preorder = [5, 3, 2, 7, 6, 9] def binary_search(a, x, lo, hi): if lo == hi: return lo mid = lo + (hi - lo) / ...
58e254e381165aab723f8e39141a26a5a328490c
davkim1030/algorithm
/dbn/03_greedy/01_거스름돈.py
537
3.671875
4
""" 당신은 음식점의 계산을 도와주는 점원이다. 카운터에는 거스름돈으로 사용할 500원, 100원, 50원, 10원짜리 동전이 무한히 존재한다고 가정한다. 손님에게 거슬러 줘야 할 돈이 N원일 때, 거슬러줘야 할 동전의 최소 개수를 구하라. 단, 거슬러 줘야 할 돈 N은 항상 10의 배수이다. """ if __name__ == "__main__": n = int(input()) coin_types = [500, 100, 50, 10] count = 0 for coin in coin_types: count += n // coin n %= coin ...
ab66a0e0aab0962ba4f5add094537aa039d7c85e
4ELANC76/com404
/1-basics/3-decision/1-if/bot.py
288
3.96875
4
book = input("What is that type of book?") book = str(book) if (book == "adventure"): print("I like adventure books too!") if (book == "fiction"): print("Wow! A fiction book!") if (book == "fantasy"): print("My favourite fantasy book is Harry Potter") print("Finshed reading the book.")
d4f3620f7022f75ad28bf9defc350ec7b710a8ab
cmungioli/meteorite-temps-project
/Meteorite_Temps_Project.py
6,975
3.71875
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 15 10:41:02 2019 @author: Carlo Mungioli """ import math import sys def input_data(): #This section creates lists for the radii and thermal conductivities of each layer. #It also specifies necessary values such as temperatures and lengths of time. #We have m...
66364738f47ea07e4366fb78a014452e15392e60
nicolopinci/geneticTimetable
/geneticClassAllocation.py
13,828
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 25 14:48:41 2020 @author: nicolo """ from random import randrange import copy import random import math class Lecture: def __init__(self, id, description, numberPeople, timeslots, color): # Lecture constructor self.id = id # I...
3c101a692f1ed5c596c8b4c64ded2228adb18023
AyushVachaspati/Mnist_MultiLayerPerceptron_Class
/Mnist.py
6,065
3.65625
4
import numpy as np import tensorflow as tf class Mnist: num_pixels = 28*28 batch_size = 16 num_labels = 10 layers_cells = [800,] sess = tf.Session() #model global variables which are required to give input and get output minimize = None y_pred = None pixels = None labels = ...
2b06ca32a7c854f3458acfa7e6b330f25566ebfe
Billshimmer/blogs
/algorithm_problem/interleaving_string.py
855
3.53125
4
#!/usr/bin/python # -*- coding: latin-1 -*- # leetcode 97 class Solution(object): def isInterleave(self, s1, s2, s3): m, n = len(s1), len(s2) if len(s3) != m + n: return False dp = [[False for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m+1): ...
53053109050ae1d774688baab54d957bfa48fe1b
Isaac-Lee/BOJ-Algorithm
/Python_Solutions/test2.py
638
3.671875
4
from collections import deque def neighbors(current, grid): x, y = current for i in range(x-1, x+2): for j in range(y-1, y+2): if i == x and j == y: continue if 0 <= i < len(grid) and 0 <= j < len(grid[0]): yield i, j def bfs(grid, start, end): ...
e5aea9a3a280480983cf3a2df73fe7d1b186ad43
leoorshii/Udacity-samples
/entropy.py
354
3.5
4
import numpy as np # Write a function that takes as input two lists Y, P, # and returns the float corresponding to their cross-entropy. def cross_entropy(Y, P): R = np.multiply(Y, np.log(P)) + np.multiply(np.subtract(1,Y), np.log(np.subtract(1,P))) pass return np.sum(-R) P = [0.4, 0.6, 0.1, 0.5] Y = [1, 0...
d8aeb7d5e9e2210f16855882c5e036e40eb4be42
halkernel/data-structure-and-algorithms
/search-strategies/node.py
368
3.578125
4
class Node: def __init__(self, state, parent): self.state = state self.parent = parent def reveal(self): for i in range(3): print ("{} {} {}".format(*self.state[3*i:3*i+3])) print() def z_index(self): return self.state.index(0) def __repr__(self):...
27724aad83b927b8ee363bc54419ac0c6a83bc9a
MichelPinho/exerc-cios
/Desafio_70_Preço_de_Produto.py
945
3.875
4
# Crie um programa que leia o nome e o preço de vários produtos. O programa deverá # perguntar se o usuário vai continuar ou não. No final, mostre: # qual é o total gasto na compra. # quantos produtos custam mais de R$1000. # qual é o nome do produto mais barato. totmil = preço = soma = cont = 0 barato = ' ' while Tru...
7fe7c58a225358f4a23bd4e1ffd28055835321aa
anirudhbiyani-zz/random-scripts
/DuplicateFileChecker.py
1,394
3.8125
4
#!/usr/bin/env python ''' Checks for duplicate files in a particular given directory based on SHA256 hashes. ''' __author__ = "Aniruddha Biyani" __version__ = "1.0" __maintainer__ = "Aniruddha Biyani" __email__ = "contact@anirudhbiyani.com" __status__ = "Production" __date__ = "20150312" import hashlib, os, pprint, t...
7a7f7f473f83d2cdfd117459356e5cfb673f5439
polyguo/algomolbiol
/Graph.py
13,233
3.546875
4
from Bio import SeqIO # # Class Description Comming Soon # class Graph: """A simple Graph class""" # # This method create the empty members of the class # def __init__(self): self.vertexhash = [] self.a19merhash={} self.adjlist=[] self.reverse=[] # ...
c348a516c5d12783a19922a34b603d4c56606ec3
ziyaad18/LibariesPython
/addition.py
184
3.75
4
def add_numbers(x,y): ''' >>> add_numbers(1,1) 2 ''' answer = x + y return answer def sub_numbers(num1, num2): answers = num1 - num2 return answers
2af9dbc1ec89e9cf0ceddf2728efb2ab5a51d6e7
Arilonchik/Learning-python
/Eltech.py
693
3.609375
4
import math while True: com = input() if com == 'a': p, q = map(float, input().split('+j')) print('p=', p) print('q=j*', q) am = math.sqrt((p**2) + q**2) print('Am=', am) if p > 0: psi = math.degrees(math.atan(q/p)) if p < 0: psi =...
5376559a181ddbc12ce1bccf265984c31b279ffb
musungur/subClass_Private-Public_Methods
/empl-class.py
1,996
3.9375
4
# working with class class Employees: """This is employees records""" def __init__(self,name,idn,birth,status,dept,post): self.name = name self.id = idn self.birth = birth self.merital = status self.department = dept self.title = post pass # intro ...
7a73b64fb60c2029c8be49a37ac080e89e200967
minhduc9699/PhamMinhDuc-fundamental-c4e16
/S3/creat.py
191
3.609375
4
fthing = ['C', 'C++', 'C#', 'Java'] print('Hi there, here your favorite things so far') print(*fthing, sep=', ') fthing.append(input('name thing you want to add ')) print(*fthing, sep=', ')
642db91a5afb29e34a43249d4d04ec707df7e1d6
samuelcm/classes
/quadrado.py
431
4.0625
4
#Classe Quadrado: Crie uma classe que modele um quadrado: #Atributos: Tamanho do lado #Métodos: Mudar valor do Lado, Retornar valor do Lado e calcular Área class Quadrado(): def __init__ (self, lado = None): self.lado = lado def alterar_lado(self): lado = float(input("Lado: ")) self.lad...
4163cbd9e0971cb0f4131081c6304d235f0d83e9
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4312/codes/1671_1102.py
918
3.953125
4
# Teste todas as possibilidades de entradas 'H', 'h' e 'x' # Se seu programa funciona para apenas um caso de tese, isso não quer dizer que ele vai funcionar para todos os outros # Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigi...
a2ab1898246543f214a9719ed6b482eb2f4b4270
RyanLewisJr/Python-Tree
/binary_tree1.py
5,061
3.8125
4
class TNode: def __init__(self, elem=None, left=None, right=None): self.elem = elem self.left = left self.right = right class Tree: def __init__(self): self.root = TNode() def add(self, elem): node = TNode(elem) if not self.root: self.root = no...
c7c073b1cecc9157cac264fb89097e95847daf45
pyltsin/dlcourse_ai
/assignments/assignment2/model.py
2,783
3.5
4
import numpy as np from layers import FullyConnectedLayer, ReLULayer, softmax_with_cross_entropy, l2_regularization class TwoLayerNet: """ Neural network with two fully connected layers """ def __init__(self, hidden_layer_size, i, o, reg): """ Initializes the neural network Argument...
35c175bfa8e6c68bb5cb4996044e3a840e79bb23
binzi6/PythonStudy20200302-1
/PythonStudy20200302_1.py
1,457
4.3125
4
print ('Hello, Python!') # 第一个注释 print ("Hello, Python!") # 第二个注释 ''' 这是多行注释,使用单引号。 这是多行注释,使用单引号。 这是多行注释,使用单引号。 ''' """ 这是多行注释,使用双引号。 这是多行注释,使用双引号。 这是多行注释,使用双引号。 """ #作用域同时缩进 不用{} if True: print ("Answer") print ("True") else: print ("Answer") # 没有严格缩进,在执行时会报错 #print ("False") #数字类型计算 代码多行显示使用...
2f141778308a351b53577c8d923adf9b285dad2e
RichardRosario/python-workouts
/working_files.py
2,445
3.53125
4
import csv from datetime import datetime # Create a string called first_forty that is comprised of the first 40 characters of emotion_words2.txt. path = "D:\python-workouts\workouts\AAL_data.csv" file = open(path, newline='') reader = csv.reader(file) header = next(reader) # print(header) data = [] for row in ...
4505c69542bc8850c7e3a94cf54d1fb0d3562d58
pomacb/CursorPython
/YoungDevelopers/Homework3/arithmetic_2.2.py
236
3.84375
4
var1 = int(input ("Enter number1: ")) var2 = int(input ("Enter number2: ")) var3 = int(input ("Enter number3: ")) var4 = int(input ("Enter number4: ")) sum1 = var1+var2 sum2 = var3+var4 print ("Result is: {0:.2f}".format (sum1/sum2))
49311aae6e04a6e08dc69072120b9ae67b9f50d7
wenjiazhangvincent/cs131
/hw1_release/0.py
154
3.625
4
import numpy as np k1 = np.array((1,4,6,4,1)).reshape(5,1) k2 = np.array((1,4,6,4,1)).reshape(1,5) print (k1) print (k2) print (k1.shape) print (k2.shape)
16e5abb82fbdb55c173baf578ecbb7cdd6603c33
bharddwaj/Intro-CS-Course
/temp_conversion.py
1,464
4.25
4
''' Created on Jan 28, 2019 @author: Bharddwaj Vemulapalli username: bvemulap I pledge my honor that I have abided by the Stevens Honor System. ''' from smtpd import program ''' Put functions at the top of the program ''' def fahrenheit(celsius): '''Returns the input Celsius degrees in Fahrenheit''' return...
60b43031a410e8679c134aa695a892da52639d4d
pabloares/misc-python-exercises
/number-lines-file.py
454
3.546875
4
import sys NUM_LINES=10 if len(sys.argv) != 3: print("Missing file(s) name") quit() try: fd = open(sys.argv[1], "r") except FileNotFoundError: print("File does not exist") else: fdd = open(sys.argv[2], "w") line = fd.readline() count = 1 while line != "": # line = line.rstrip() ...
098d69057c1dce11dfed7a33f25be11a7a98da6b
soumilk/100DaysOfCode
/tanaymehta28/Day 07/tf mnist.py
3,002
3.953125
4
# This Neural Network is trained on MNIST image dataset. # But two great things about this model are: # 1. It classifies images but it is NOT a Convolutional Network. # 2. It uses no high-level Tensorflow API (like, tf.keras and tf.estimator or tf.learn) import tensorflow as tf from tensorflow.examples.tutorials.mni...
866bc66ac979726153fee2824bc19a7229a47a04
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/c2aaee6311944f41ad6ee958481af8b1.py
501
4.21875
4
# # Skeleton file for the Python "Bob" exercise. # def hey(what): #check if what is a string and if there is \t in what if not what or "\t" in what: return "Fine. Be that way!" #if what is upper we are screaming if what.isupper() == True: return "Whoa, chill out!" #if what stripped ...
c9d700dfb9323caec0f98542041700237dd526f2
waveman68/MIT6001x_Intro2CS_and_Python
/L6_ndigits.py
766
3.890625
4
__author__ = 'Sam Broderick' # Note to grader: the """DocString""" adheres to Python style guide. def ndigits(x): """ This function takes an integer and returns its number of digits :param x: int - input :rtype: int - number of digits in x """ if type(x) != int: # basic e...
2d0ff0bc69baf352a52e3b4ad57620f0127dc139
lmacionis/Exercises
/14. List Algorithms/Exercise_1.py
8,423
4.375
4
""" The section in this chapter called Alice in Wonderland, again! started with the observation that the merge algorithm uses a pattern that can be reused in other situations. Adapt the merge algorithm to write each of these functions, as was suggested there: a. Return only those items that are present in both lists. ...
e484633c0f69c018461f3df2d1a45e143768b9b6
RamaraoAllamraju/LowesTrainingSessionPYTHON
/day1Python/Test.py
1,771
3.828125
4
''' Created on Mar 18, 2019 @author: rallamr ''' from _ast import Num from selenium.webdriver import opera ### Removing spaces in between string ### a = "Lowes India PVT LTD " print(a.strip()) b="" mylist = a.split(" ") for lis in mylist: if(lis!=""): #print("It is not space") ...
735da1e22239288dead9cac41bdc7144dbaf8fd9
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/pdykey001/question1.py
1,179
3.75
4
"""Uct BBS program Keyoolin Padayachee 16 April 2014 """ #Creating of the 2 files file=["42.txt","1015.txt"] fileRef=["The meaning of life is blah blah blah ...","Computer Science class notes ... simplified\nDo all work\nPass course\nBe happy"] selection="" message="" while selection!="X": #display the me...
5ef0f240f4457900f50097e955f2c7dc47c1eeee
codingXllama/LearnToProgram
/Step1/HowImportIsYourBirthday.py
657
4.5625
5
# This program checks for how important is your birthday # Purpose of this program is to understand the purpose and usage of logical and/or operators , and multi if statements with the not keyword # Getting user's age userAge = eval(input("Enter your Age: ")) if userAge >= 1 and userAge <= 12: print("Your Birthda...
6877a40f9b4683a9c23a461adff0568b9be59710
MiyabiTane/myLeetCode_
/May_LeetCoding_Challenge/30_K_Closest_Points_to_Origin_2.py
1,051
3.515625
4
def kClosest(points, K): def partition(points, l, r): #一番右側の数字で分ける(左:小さい、右:大きい)時にその数字がどこにくるか pivot = points[r] a = l for i in range(l, r): if (points[i][0]**2 + points[i][1]**2) <= (pivot[0]**2 + pivot[1]**2): points[a], points[i] = points[i], points[a] ...
e83b2b9d28c57b4ba51a349488fbbf859c70f0d3
Alexvi011/CYPHugoPV
/libro/problemas_resueltos/capitulo2/problema2_2.py
283
3.765625
4
P=int(input("Introduce tu valor P: ")) Q=int(input("Introduce tu valor Q: ")) EXP= (P**3)+(Q**4)-(2*P**2) if EXP<680: print(f"Los valores P:{P}, y Q:{Q} satisfacen la expresion") else: print(f"Los valores P:{P}, y Q:{Q} no satisfacen la expresion") print("Fin del programa")
678bba897b6979955c02b136ccb500d755f81723
26Sir/ceshi
/fangfa/defaultpara.py
1,068
3.921875
4
#conding=utf-8 ''' # def student(age,naem,sex,guoji="中国"): # return age,naem,sex,guoji # # print("任伟","") def boy(profile,*mytuple): out_put = "" for parameter in mytuple: if not out_put: out_put = out_put + parameter else: out_put = out_put + "," + parameter re...
e36ba285d16f0676270d3833d1aa0880e54c8a17
Llontop-Atencio08/t07_Llontop.Rufasto
/Rufasto_Torres/Bucles.Mientras.py
1,427
3.96875
4
Ejercicio01 #Pedir edad de ingreso a la escuela PNP edad=10 edad_invalida=(edad<16 or edad >25) while(edad_invalida): edad=int(input("ingrese edad:")) edad_invalida=(edad<16 or edad >25) #fin_while print("edad valida:",edad) #Ejercicio02 #Pedir nota de sustentacion de tesis nota=0 nota_desaprobada=(nota<12 or...
7e041933596934a5337724b9ce9fb659474a538f
coucoulesr/leetcode
/1008-construct-binary-search/1008-construct-binary-search.py
1,440
4.09375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def bstFromPreorder(self, preorder): # Special case: input is empty list if not preorder: return None ...
2b87bf27245da12d816ec44c9421135a60dd3594
manutdmohit/pythonprogramexamples
/checktwostringsareanagramsornot.py
225
4.03125
4
s1=input('Enter first string:') s2=input('Enter second string:') #print(sorted(s1)) #print(sorted(s2)) if sorted(s1)==sorted(s2): print('Both strings are anagrams') else: print('Both strings are not anagrams')
d7d73cfbb8581a204e92522c995e5960295c498a
nsimsofmordor/PythonProjects
/Projects/Python_Tutorials_Corey_Schafer/PPBT6 Conditionals.py
544
4
4
language = 'Python' if language == 'Python': print('Language is Python') elif language == "Java": print('Language is Java') print(20*"-") user = "admin" logged_in = True if user == "admin" and not logged_in: print("Good Credits") else: print("Bad Credits") print(20*"-") a = [1, 2, 3] b = [1, 2...
c3aa7b4916d3dd8018d58b035ef9e5c91315205c
DavidRooban/savinpython
/arms range.py
302
3.828125
4
num=int(input("enter starting range")) n=int(input("enter ending range")) for i in range(num,n): if(i>100000): print("enter less than 100000") sum = 0 temp = i while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if i == sum: print(i)
6435492b816541028e17cf1e37306cc35c59b144
comodoro180/Python
/Course1/Excersice3_1.py
319
3.6875
4
INCREMENT = 1.5 TOP_HRS = 40.0 gross_pay = 0.0 bonus = 0.0 hrs = input("Enter hours:") hrs = float(hrs) rate = input("Rate:") rate = float(rate) if hrs > TOP_HRS: bonus = (hrs - TOP_HRS) * (rate * INCREMENT) gross_pay = bonus + (TOP_HRS * rate) elif hrs > 0.0: gross_pay = hrs * rate print(gross_pay)
7fa02099f75e64986e72554af9f62ccfff8c13e6
fakhirsh/QuranAnalysis
/Src/queries/testQueries.py
659
3.5625
4
import codecs # Split each ayah into words quran = codecs.open('../../Assets/QuranText/quran-simple-clean.txt', 'r', encoding="utf-8") ayahCount = 0 uniqueWordCount = 0 totalWordCount = 0 uniqueWords = set() for ayat in quran: a = ayat.split('|') chapterNo = a[0] ayahNo = a[1] ayahText = ...
b481fb93f6da6c78b1605deb53819faff88564f4
timvink/TransferBoost
/transferboost/dataset.py
1,137
3.578125
4
import pkgutil import io import pandas as pd def load_data(return_X_y=False, as_frame=False): """Loads a simulated data set with two targets, y_1 and y_2. y_1 and y_2 are generated Args: return_X_y: (bool) If True, returns ``(data, target)`` instead of a dict object. as_frame: (bool) giv...