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
8140c9976f62897de473a493e095fa885ea25713
xiaojiangzhang/leetcode_Record
/力扣_牛客刷题/model-二分查找问题/二分边界查找.py
683
3.546875
4
def deFind(nums, target): left = 0 right = len(nums) while left < right: mid = int((left + right) / 2) if nums[mid] < target: left = mid + 1 elif nums[mid] > target: right = mid elif nums[mid] == target: right = mid return left def d...
23687639e5573c82c1008636b855465ca91c35e4
TabError/adventofcode2020
/05_solution.py
634
3.5625
4
with open("05seats") as f: seats = f.readlines() seats = [s.replace('\n', '') for s in seats] highest_seat = 0 lowest_seat = 2**10 id_list = [] binDict = {'F': 0, 'B': 1, 'L': 0, 'R': 1} for s in seats: id = 0 expo = 1 for c in s[-1::-1]: id += binDict[c] * expo expo *= 2 print(f"s...
3b99b8b8d44b8f9b1546dc9eb6b1db1a03fad3c2
jayckaiser/DataIncubator
/Challenge/Q1.py
6,337
4.15625
4
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Q1 (C) 2017 by Jay Kaiser <jayckaiser.github.io> Updated Oct 26 by Jay Kaiser run_experiment actually finds the results for each question, first using find_sequence to find an array of 100,000 iterations of this process which are then averaged together int...
8182f8e2ec6380802532e4b9ec9ea69a73ca71ef
micahpotts/pythonGuessingGame
/guessingGame.py
1,097
4.0625
4
#!/usr/bin/env python3 import random def main(): play = True while play: guessLimit = 0 topOut = input("Pick a number.\n") topOut = int(topOut) rando = random.randint(1, topOut) print( "Guess a number between 1 and " + str(topOut) ...
19da8c81fbbbde3d9e08038825566210a88ff341
AlexFue/Interview-Practice-Problems
/math/fizz_buzz.py
1,102
4.4375
4
# Problem: # Given an input, print all numbers up to and including that input, unless they are divisible by 3, then print "fizz" instead, or if they are divisible by 5, print "buzz". If the number is divisible by both, print "fizzbuzz". # For example, given 5: # 1 # 2 # fizz # 4 # buzz # Given 10: # 1 # ...
c0bbf25f0855f258bc7bec174de3e3fb607eee64
AlexFue/Interview-Practice-Problems
/math/palindrome_number.py
2,054
4.3125
4
Problem: Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Follow up: Could you solve it without converting the integer to a string? Example 1: Input: x = 121 Output: true Example 2: Input: x = -121 Output: false Explanation: From left to right, ...
256a03dcbc7e21268fcac16009241ae548e22f5a
AlexFue/Interview-Practice-Problems
/string/group_anagrams.py
1,935
4.4375
4
Problem: Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","na...
1854071bc16656f7b0af6840eee69df522768e14
AlexFue/Interview-Practice-Problems
/backtracking/generate_parentheses.py
2,322
3.953125
4
Problem: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] Solution: class Solution: def generateParenthesis(self, n: int) -> List[str...
bfc99065d0507b1f42a78e3f31b3737743f1d310
AlexFue/Interview-Practice-Problems
/search/search_matrix.py
3,085
4.03125
4
Problem: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [ [1, 3, 5, 7], [10, ...
9206e1d251d18298d7cfbe7e3205d7feef852a0b
AlexFue/Interview-Practice-Problems
/hashmaps/subarray_sum_equals_k.py
1,554
3.640625
4
Problem: Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2 Solution: class Solution: def subarraySum(self, nums: List[int], k: int) ->...
4bb9c049136e21b22c9ed3047e55559d766d8051
AlexFue/Interview-Practice-Problems
/math/power_of_three.py
688
4.6875
5
Problem: Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false Example 3: Input: 9 Output: true Example 4: Input: 45 Output: false Solution: import math def power_of_three(n): power = 0 while 3**power <= n: if 3*...
9933426d857511b693161f3d64b022634ebf1dbf
AlexFue/Interview-Practice-Problems
/array_manipulation/remove_duplicated_from_sorted_array.py
2,496
3.9375
4
Problem: Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Clarification: Confused why the returned value is an in...
33b4557bf9f070d6be3a4446691384ab813cd27a
AlexFue/Interview-Practice-Problems
/recursion/letter_combos_of_phone_num.py
2,704
4.09375
4
Problem: Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example 1: Input: dig...
f396cb3f64cc487ad75d3c5d2cceb84ccd7b1b00
AlexFue/Interview-Practice-Problems
/sorting_algorithm/median_two_sorted_arrays.py
2,137
4.15625
4
Problem: Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. Follow up: The overall run time complexity should be O(log (m+n)). Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2:...
370d01dfd0e87fbd0533285edd6bc40d64f940ee
flashypepo/myMicropython-Examples
/button/readingButton.py
1,179
3.9375
4
# readingButton - when button pressed LED is on. # # 2016-0903 PePo new, based upon Tony DiCola MicroPython serie. # https://learn.adafruit.com/micropython-hardware-digital-i-slash-o ########################################################################### # Setup code goes below, this is called once at the st...
69bce08cc02472e4ec62a8dfb78e586692574dfa
flashypepo/myMicropython-Examples
/displays/DisplaysDrawingText/drawtextnpmatrix.py
813
4.125
4
# 2016-1219 draw text on neopixel matrix # https://learn.adafruit.com/micropython-displays-drawing-text/software import neopixel import machine matrix = neopixel.NeoPixel(machine.Pin(13, machine.Pin.OUT), 64) # define the pixel function, which has to convert a 2-dimensional # X, Y location into a 1-dimensional loca...
21452f0eb8e7785fe804ffa8cb1a25e6b93e6e19
flashypepo/myMicropython-Examples
/robotica/robotcar/nodemcu-motorshield/bot.py
1,500
4
4
# MicroPython LOGO style robot. # Author: Tony DiCola # License: Public Domain import time class Robot: # Make a class to give a simple LOGO turtle style interface to the bot. #def __init__(self, motors, left_motor, right_motor): def __init__(self, left_motor, right_motor): # Save the motor contro...
4724eedddac978d9eb9eef4dfe86e83ca42e4205
flashypepo/myMicropython-Examples
/display-stuff/leds/blinkingLEDs.py
2,221
3.953125
4
# Example of blinking leds in micropython # Arduino style: setup and loop # 2017_0708 PePo - NodeMCU + led-bar # 2016_1002 PePo - Grove-LEDs on D1 (GPIO5) and D5 (GPIO14) # 2016-0823 PePo, based upon https://learn.adafruit.com/micropython-basics-blink-a-led/blink-led ###################################################...
7709e64f4edad19bd34f2c8c3342527ab71bad51
jacob975/deep_learning
/remove_null.py
1,577
3.671875
4
#!/usr/bin/python3 ''' Abstract: This is a program for removing any columns with null. Usage: remove_null.py [input table] Output: 1. The table without null column. 2. The index of columns without null. Editor: Jacob975 ################################## # Python3 # # This...
64291a7cb59c8e4de148a075ab0c0f59faf84b84
BlueBookBar/SchoolProjects
/Projects/PythonProjects/Project4.py
1,825
4.125
4
#used the factorial number system def Permutation(thisList): NumberofpossibleFactorial = [1]#Used to contain the number of factorial possiblities of the permutation for iterator in range(1,len(thisList)+1):#Populate the factorial list NumberofpossibleFactorial.append(NumberofpossibleFactorial[iterato...
6a6a2b7a48966e3a615891e27e104dff073e63c9
wonkim0512/BDM
/HW2/common_divisor.py
3,155
3.625
4
def commonDivisor(n): nums = list(range(2, n+1)) sum = 0 for idx, num in enumerate(nums): if num % 2 == 0 and num % 3 != 0 and num % 5 != 0: sum += 50 print(idx,num,sum) elif num % 2 != 0 and num % 3 == 0 and num % 5 != 0: sum += 33 print(id...
a3f9f6bb6c6a7ea361d8e4618e9d0dc859a84776
flabbet/Pybugger
/PyBugger/testing_algorithms.py
5,118
4.03125
4
from collections import defaultdict def bubble_sort(list): # Swap the elements to arrange in order for iter_num in range(len(list) - 1, 0, -1): for idx in range(iter_num): if list[idx] > list[idx + 1]: temp = list[idx] list[idx] = list[idx + 1] ...
4c88b320473c3a407feb5046c01bdb0228926118
ManishGulhane/My-Captain-python-1
/Area of circle.py
196
4.375
4
# Area-of-circle radius = float(input("Input the radius of circle : ")) area = 3.14*radius*radius display="The area of the circle with radius {} is : {}" A1=display.format(radius, area) print(A1)
968b6a37ecacc1e00cd20affa2fbeda24edd6049
sncodeGit/ML-and-DA
/Math_and_Python_for_DA/week3/Task1_3.py
785
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 14 22:26:23 2019 @author: inter000 """ import math import numpy as np import matplotlib.pyplot as plt from scipy import optimize def f(x): return math.sin(x / 5.) * math.exp(x / 10.) + 5 * math.exp(-x / 2.) def h(x): return int(f(x)) X = np.arange(1, 31, 0.01...
3fdaae003565fbfb4fc6bbf8fefb83b299f0add1
holdenweb/snakesandladders
/main013.py
4,357
3.578125
4
###### simple snakes-and-ladders simulation aim here to make a one-game function for module # version 0.13dev 20 09 16 # # this copy is testprog0.13 in dholden.snakesandladders # VERSION = 'Vn 0.13dev 19th September 2020' MAX_ROUNDS = 3000 # cutout in case of infinite loop #request the required...
de9c2886d5a2dc5a33b9f7871b88d4e490d37262
TanimaRanjan/python-practice
/milestone_2.2_DB/utils/database.py
1,451
3.859375
4
from typing import List, Dict, Union import sqlite3 from .database_connection import DatabaseConnection books_file = 'books.json' database = 'data.db' Book = Dict[str, Union[str, int]] def create_book_table() -> None: with DatabaseConnection(database) as connection: cursor = connection.cursor() ...
3bc56ec8b648780816251b49d04a82538a4e87ac
Rasujon3/pythonProject
/program7.py
120
4
4
n = input("Enter a text of numbers : ") list = n.split() sum = 0 for num in list: sum = sum + int(num) print(sum)
77b5b9dc64b670e700712d6d820f45f5dc5369b1
mipsmonsta/sudoku_solver
/sudoku.py
3,001
3.84375
4
class SudokuBrain: """ @param board: the board @return: whether the Sudoku is valid """ def isValidSudoku(self, board): #check rows for row in board: rowString = "".join(row) for chr in rowString: if chr.isnumeric(): testSpl...
2187791fadfa5b1c44be569a40573dbc3bc2507d
Vworri/be_exam_candidate_vw
/app.py
4,699
3.59375
4
import pandas as pd from numpy import NaN import json class RecordValidation(object): """A class to validate record entries using buisness rules""" def __init__(self, inputPath="data.csv", outputPath="output.json", errorPath="error.csv"): inputPath = input("Please input path for input file (default: ...
01b1774b44b8489fae980201a2139abbc459d849
alparslankorkutata/AdamAsmacaOyunu
/adamAsmaca/adamAsmaca.py
4,027
3.765625
4
import random soruListesi=["BAŞARI","ZAMAN YÖNETİMİ","PYTHON PROGRAMLAMA DİLİ","YAZILIM MÜHENDİSLİĞİ","TEKNOLOJİ FAKÜLTESİ","FIRAT ÜNİVERSİTESİ" "FONKSİYONEL PROGRAMLAMA","ALGORİTMA","ANALİTİK DÜŞÜNME","ELMA","ARMUT","ANANAS","DOMATES","BİBER","BİLGİSAYAR","İNTERNET"] def soruÜret(): s=random.choice(s...
4e40154bff628c6151408a6372762de2834c1742
DeathShadow171/PythonLesson
/Type of data.py
220
3.59375
4
a = 1 b = 1.2 c = "1" d = "apple" e = True f = False print("Type of a", type(a)) print("Type of b", type(b)) print("Type of c", type(c)) print("Type of d", type(d)) print("Type of e", type(e)) print("Type of f", type(f))
0487a9ac27ac3768599e54d8daf99d8b81ac0788
DeathShadow171/PythonLesson
/Type Casting.py
603
3.921875
4
my_str = "123" my_num = 10 print ("str to int =>",int(my_str) + my_num) my_str = "1.23" my_num = 10 print ("str to float =>",float(my_str) + my_num) my_str = "I am" my_num = 13 print ("int to str =>",my_str + str(my_num)) my_str = "I am" my_num = 13 my_age = my_str + str(my_num) print ("MY AGE =>", my_age) print ("...
5d02bbc9f04160f39391234dc5fabd25266c201b
1006269809/Data_mining
/digit.py
1,910
3.71875
4
# -*- coding: utf-8 -*- """ 本文件利用朴素贝叶斯分类实现手写数字识别 """ from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import BernoulliNB digits = load_digits() x = digits.dat...
e509ac3f460e88e5b536c0954e24b4ddce0a6928
ChampRot/mle
/aufgabe3.py
4,100
4
4
import random from math import exp import matplotlib.pyplot as pyplot def random_bits(len): """Returns a list containing a random combination of 0s and 1s""" return [random.randint(0, 1) for x in range(len)] def init_population(p, len): """Returns a list of random bit-lists""" return [random_b...
d65b98f535cc357e40276a7e2cb9988339a721b4
thecourtofowls/LeetCodeChallenges
/LeetCodeChallenges/searchInsertPosition.py
1,422
3.875
4
# -*- coding: utf-8 -*- """ 35. Search Insert Position Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Constraints: 1 <= num...
9c6719d2febfaf64900ef95c93814dfc42c6f51d
thecourtofowls/LeetCodeChallenges
/LeetCodeChallenges/ImplementstrStr().py
2,082
4.09375
4
# -*- coding: utf-8 -*- """ 28. Implement strStr() Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Clarification: What should we return when needle is an empty string? For the purpose of this problem, we will return 0 when needle is an empty string. This is...
e8c6ab10b81054fae2587720e4ec0c48b0735f07
qsyed/python-programs
/playlist/playlist.py
2,382
4.03125
4
from song import Song class Playlist: def __init__(self): self.all_songs = [] self.latest_id = 0 def create_song(self): artist = input("Enter the artist:") song_name = input("Enter the name of the song:") length = input("Enter the length of the song:") genre = input("Enter the genre of the...
469d35e7c3c3d7dbd7ef63c65af009e1e6b764ea
qsyed/python-programs
/leetcode/reverse_integer.py
1,282
4.15625
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the pu...
9738c94f4137a534f8c335a221ea769de00b4eac
qsyed/python-programs
/Rock_Paper_Scissor/Menu.py
1,644
3.75
4
import sys from Game import Game class Menu: def __init__(self): self.app = Game() self.options = { "1": self.playgame, "2": self.rules, "3": self.weaponMenu, "4": self.showResults, "5": self.endProgram } def display_options(self): prin...
6e9126df734b950627a21661d32c6e99ce738395
qsyed/python-programs
/sqlite3-python/sql_injection.py
1,313
4.375
4
import sqlite3 conn = sqlite3.connect("sqlite3-python/users.db") """ this execrise wa meant to show how sql injection can work if the query strings are not set up properly first we have to set up a data base and enter in seed data. the data base was created by using query = "CREATE TABLE user (username TEX...
74d2268b7683c0da087c8c2f6e4f7549e2788998
JulieRoder/Practicals
/Activities/prac_06/car.py
1,162
4.25
4
""" CP1404/CP5632 Practical - Car class example. Student name: Julie-Anne Roder """ class Car: """Represent a Car object.""" def __init__(self, name="Car", fuel=0): """Initialise a Car instance. fuel: float, one unit of fuel drives one kilometre """ self.name = name s...
dc37ecb1e5a2fd133bbae234ff4f9351ba608c97
JulieRoder/Practicals
/Activities/prac_06/guitar_class.py
823
4.125
4
""" Guitar Class Student name: Julie-Anne Roder """ class Guitar: """Represents a Guitar Object.""" CURRENT_YEAR = 2020 VINTAGE_THRESHOLD = 50 def __init__(self, name="", year=0, cost=0.0): """Initialises a guitar instance name: make & model year: year guitar was made ...
052e1f58d3ab4ad9e04c7a84ceba06db5040e997
JulieRoder/Practicals
/Activities/prac_08/taxi_simulator.py
2,474
3.78125
4
""" CP1404 Practicals Taxi Simulator program Student name: Julie-Anne Roder """ from Activities.prac_08.taxi import Taxi from Activities.prac_08.silver_service_taxi import SilverServiceTaxi MENU = "q)uit, c)hoose taxi, d)rive" MENU_OPTIONS = ["q", "c", "d"] def main(): """Taxi Simulator""" current_taxi = Non...
7a4a52ec9da041f16906bc0b92ecf247afc55e97
JulieRoder/Practicals
/Activities/prac_06/guitars.py
1,800
3.953125
4
""" Guitars Program file Student name: Julie-Anne Roder """ from Activities.prac_06.guitar_class import Guitar STARTING_VALUE = 0 COUNT_START = 1 COST_VALUE_LENGTH = 10 def main(): """Guitar Collection Program.""" print("My guitars!") my_guitars = [] guitar_name = input("Name: ") while guitar_nam...
43cbd4dbcea77e0e015bc5ab7a5ae2bc7327cd39
alexahdp/breadcrumbs
/tasks/redBlackTree/node.py
7,154
3.734375
4
from typing import Union import json RED = 0 BLACK = 1 # root is black # each red node has two black children # all paths to all leaves must contain similar number of black nodes class Node(): def __init__(self, val: int, parent: Union["Node", None] = None, color: Union["RED", "BLACK"] =...
ea4f171626fd50ae625404bcfcb8abcd90c420ff
jamarrhill/CS162Project-7
/LinkedList.py
4,853
4.0625
4
# Name: Jamar Hill # Date: 5/17/2021 # Description: CS 162 Project 7 class node: def __init__(self, data, next=None): # next is BY DEFAULT none self.__data = data self.__next = next # cur_node = node(5) # node(9, cur_node) # 9 -> 5 class linkedlist: def __init__(self):# Initiates the l...
3b7ad754a490be1f31f45fef8c0e4fecab0e7343
onedino/COMP3355_Assignment2
/bigInt.py
1,009
3.625
4
#Q2 part 1 import time import math #bigint = "71755440315342536873" bigint = "60884036363636410669" start = time.time() def isPrime(num): start = time.time() tmp = 0 for i in range(0,len(num)): tmp = tmp + int(num[i])*(10**(len(num)-1-i)) # print(tmp) if tmp == 1: return False if tmp % 2 =...
c5a24521af228fdaafc2082a75e3616cd07a1c2d
Jian-jobs/Jian-leetcode_python3
/Solutions/148_Sort List.py
1,731
3.859375
4
''' 148. Sort List https://leetcode.com/problems/sort-list/ similar problem: "147. Insertion Sort List" https://leetcode.com/problems/insertion-sort-list/ Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2->1->3 Output: 1->2->3->4 Example 2: Input: -1->5->3->4->0 Output:...
49ba6ea2fc6b0335b1a86f76869d907954c1b28f
Jian-jobs/Jian-leetcode_python3
/Solutions/704_Binary Search.py
1,555
3.875
4
''' 704. Binary Search https://leetcode.com/problems/binary-search/ similar problem: "35. Search Insert Position" https://leetcode.com/problems/search-insert-position/ Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, ...
4fb8c17e5922581379dd0bc65e9c29e46c364a47
Jian-jobs/Jian-leetcode_python3
/algorithm/BubbleSort.py
747
4.15625
4
# coding:utf-8 # 冒泡排序 # 1. 外层循环负责帮忙递减内存循环的次数【1, len-1】 # 2. 内层循环负责前后两两比较, index 的取值范围【0, len-2】 len-1-i 次,求最大值放到最后 def bubble_sort(nums): # [1, len-1] for i in range(1, len(nums)-1): print(i) # [0, len(nums)-i] j is index for j in range(len(nums)-i): if nums[j] > nums[j+1...
a40d676326657eff27f08885378c0347422f3ca7
pastaTree/Data-Structures-and-Algorithms
/107_work_break.py
1,963
3.65625
4
"""107 Word-break Algorithm: 1. 经典的DP题目,状态转移方程为: f(i) = f(i-j) is true + s[i-j:i] in dict 这里j为dict中最长的子串长度,在i的位置向前找寻不可能超过这个len(j) Note: 1. 用到了一些小trick,详见代码内注释 Complexity: O(n^2) """ class Solution: """ @param: s: A string @param: dict: A dictionary of words dict @return: A boolean """ def...
2a31feef55fdd75725f08521b077fab2004107e1
pastaTree/Data-Structures-and-Algorithms
/683_word_break_iii.py
1,288
3.8125
4
"""683 word break iii Algorithm: 1. 和word-break i的思路是一样的,用DP来做 Note: 1. 详见注释 Complexity: O(n^2) """ class Solution: """ @param: : A string @param: : A set of word @return: the number of possible sentences. """ def wordBreak3(self, s, dict): # 0 s = 'something' dict = '' ...
90637e053d794ec004f9332152b756e37bc4628d
pastaTree/Data-Structures-and-Algorithms
/521_remove_duplicate_numbers_in_array.py
1,385
3.796875
4
"""521 Remove Duplicate Numbers in Array 1. hash 把所有的数扔到 hash 表里,然后就能找到不同的整数有哪些。但是这种做法会耗费额外空间 O(n)O(n) # O(n) time, O(n) space 2. two pointers(十分巧妙,需要掌握) 首先将数组排序,这样那些重复的整数就会被挤在一起。然后用两根指针,一根指针走得快一些遍历整个数组, 另外一根指针,一直指向当前不重复部分的最后一个数。 快指针发现一个和慢指针指向的数不同的数之后,就可以把这个数丢到慢指针的后面一个位置,并把慢指针++。 # O(nlogn) time, O(1) extra space """...
2feff85ac758dcafa3d9f7dfdc3fac2acea55acc
pastaTree/Data-Structures-and-Algorithms
/453_flatten_binary_tree_to_linked_list.py
2,020
4.1875
4
"""453 Flatten Binary Tree to Linked List Algorithm: 1. 显然我们很难直接在数上操作达到in-place的flatten 2. 使用递归 3. 把right subtree挂到left subtree的最右边节点上,left subtree再挂到root的right上去。 这样不停操作,就可以达到把树向右边flatten的目的。 Note: 分治:(返回最后一个节点) 情况 操作 返回值 左有右有 swap right_last 左有右无 swap left_last 左无右有 N/A right_last 左无右无 N/A node 前序遍...
8c7eda59ec4cc9157d82b6baa1bd01c3245f00ce
jamesaud/Algorithems
/hackerrank-answer/week-6/medium-2.py
1,402
3.9375
4
from __future__ import print_function # Enter your code here. Read input from STDIN. Print output to STDOUTfrom __future__ import print_function #!/usr/bin/env python import sys from Queue import * def bfs_result(src, graph): adjacency_List = {src: 0} #bfs queue = Queue() queue.put(src) while (not ...
de614facb18a349cff36ed9f23d7d2d83599246a
jamesaud/Algorithems
/hackerrank-answer/week-6/easy_1.py
399
3.78125
4
from __future__ import print_function # Enter your code here. Read input from STDIN. Print output to STDOUT # https://www.hackerrank.com/challenges/array-left-rotation rotations = int(raw_input().split()[1]) ls = raw_input().split() rotations = rotations % len(ls) start_shift = ls[rotations:] end_shift = ls[:rotations...
61b19cce89717df72d8174e81a0c55ddbbae79ce
jamesaud/Algorithems
/hackerrank-answer/week-2/week-2-hard.py
725
3.96875
4
#Queue using stacks #https://www.hackerrank.com/challenges/queue-using-two-stacks # Enter your code here. Read input from STDIN. Print output to STDOUT nums = input() class Queue(object): def enqueue(self, num): self.queue.append(num) def dequeue(self): del self.queue[0] def __init__(s...
7cc4400938ab87eaffc5987a0ff8ed11d3485ca5
chengchungchen/pycon2015-tutorial-learn_python
/accountant_old.py
543
3.875
4
def _show_items(items): template = '{name:20}{price:>5}' if not items: print("No items. Use 'add' to add some!") return print() print(template.format(name='Item', price='Price')) print('-' * 25) for item in items: print(template.format( name=item['name'], price=item['price'], )...
a91b3ec51a02fd344f3d363ab971157788f246a9
fattorib/Monte-Carlo-Fractal-Dimensionality
/julia.py
5,857
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 2 11:33:18 2018 This code will estimate the fractal dimension of the dendrite julia set using Monte-Carlo methods. It will then plot either the change in dimension over number of iterates or the boxes that cover our fractal This code will also cre...
5ed5920b61a8cb52c77e885f35003de60fa669a5
AsgerMorville/Chess
/Classes/Piece.py
913
3.734375
4
# -*- coding: utf-8 -*- """ Created on Tue May 19 12:01:08 2020 @author: Asger """ class Piece: def __init__(self,position,type_piece): self.position = position self.type_piece = type_piece def flip_piece(self): diction={'a' : 'h', 'b' : 'g', 'c' ...
6a365b71532e73740ec3b623bcc3a971bc73f5ff
laoxu666/Socket
/server.py
492
3.734375
4
# 服务端的流程描述 import socket server = socket.socket() ip_port = ("10.0.114.55", 8081) server.bind(ip_port) server.listen(5) print("server waiting.......") conn, address = server.accept() print("连接成功") while True: client_data = conn.recv(1024) print("客户端对服务端说:" + client_data.decode("utf-8")) sendData ...
f651973887d2530d73ca8d2f1fdea1780ca404c9
santosh235/com_phy
/HW1/santosh_HW1/12/12.py
497
3.828125
4
#Recursion print("ANSWER TO PART A") def catalan(n): if n==0: return 1 else: c_n=((4*n-2)*catalan(n-1))/(n+1) return c_n n=input("Catalan number: enter the value of n:") n=int(n) c_n=catalan(n) print("Answer:%d" %(c_n)) print("ANSWER TO PART B") def gcd(m,n): if n==0: return m...
e7f374db7724d896bef6c300cc005246476d6fe5
santosh235/com_phy
/HW1/santosh_HW1/6/6.py
490
3.71875
4
#Planetary orbit import math G=6.67e-7 M=2.0e30 l1=input("Enter the distance to the sun:") v1=input("Enter the perihilion velocity") l1=float(l1) v1=float(v1) a_inverse=((2/l1)-(v1*v1)/(G*M)) a=1/a_inverse l2=2*a-l1 v2=(l1*v1)/l2 T_sq=(4.0*3.14*3.14*(a**(3))/(G*M)) T=math.sqrt(T_sq) x=l1/l2 e=(1-x)/(1+x) print("The a...
0ba48b9de780c8ce1add0dfdadddce69e4ce4e36
santosh235/com_phy
/HW1/santosh_HW1/3/3.py
382
4.1875
4
# Q3:TO PRINT POLAR COORDINATES import math import numpy as np x=input("Enter the X-cordinate:") y=input("\n Enter the Y-cordinate:") x=float(x) y=float(y) r=x*x+y*y r=math.sqrt(r) rad=np.arctan(abs(y)/abs(x)) theta=(360*rad)/(2*3.14) if x<0 and y>0 : theta=theta+90 if x<0 and y<0 : theta=theta+180 if x>0 and y<0 ...
66a63c5dd64164f2a34c31e5a0b890bfb4c5d077
avalanche-strategy/debugging_exercise
/python/prime_counter.py
1,798
4.03125
4
from cache_service import cache_function import math def count_non_trivial_factors(n): """ Counts the number of non trivial factors of the input n. All numbers have at least two factors, 1 and the number itself. This counts up all the remaining factors. """ count = 0 sqrt = math.sqrt(n) ...
f51cfaf6da8409a27d56afed18fb5330ca578bff
nikhilreddypathuri/Ngrams
/ngrams.py
11,225
4.125
4
# Team name: Evil Geniuses # Authors: # Vijayasaradhi Muthavarapu (Vijay) # Nikhil Reddy Pathuri (Nikhil) # Dilip Molugu (Dilip) # Date: 10/03/2018 # 1. This program implements the concept of ngrams to know the dependencies for each word with their next word in a document. After it trains from the document the ...
751627ebef789a911d50b90d2f398c6b49dbdf3d
ctostado/Python-Projects
/Ejemplos/Listas.py
618
4.21875
4
datos = [4, "Caracteres", -13, 3.1416, "otra cadena"] print (datos[0]) print (datos[3]) print (datos[0:2]) print (datos[2:]) #Añadiendo contendio a las listas pares = [0,2,4,5,8] pares[3] = 6 print(pares) pares.append(10) print(pares) pares.append(6*2) print(pares) #Modificando el contenido con Slicing le...
0c31c5c2ea54684dcd50653ffb60c403ccb0e4c5
wfhsiao/datastructures
/python/AEE0386-code/Chapter 12/ShellSort.py
1,120
3.796875
4
# 謝耳排序 # File Name: ShellSort.py # Version MAX = 9 def shell_sort(data): global MAX incr = MAX // 2 while incr > 0: for i in range(incr+1, MAX+1): j = i - incr while j > 0: if data[j] > data[j+incr]: # 比較每部分的資料 # 大小順序不對則交換 ...
d4ac5a96d7bb87e9016a975c4dacb1a3a49c30f8
wfhsiao/datastructures
/python/AEE0386-code/Chapter 05/Hanoi.py
1,719
3.9375
4
# 利用遞迴方式求河內塔問題之解 # File Name: Hanoi.py # Version # Rules : # 河內塔問題目的乃在三根柱子中,將n個盤子從 # A柱子搬到C柱中,每次只移動一盤子,而且必須 # 遵守每個盤子都比其上面的盤子還要大的原則。 # Ans : # 河內塔問題的想法必須針對最底端的盤子。 # 我們必須先把A柱子頂端n-1個盤子想辦法(借助C柱)移至B柱子 # 然後才能將最底端的盤子移至C柱。 # 此時C有最大的盤子,B總共n-1個盤子,A柱則無。 # 只要再借助A柱子,將B柱n-1個盤子移往C柱即可: # HanoiTow...
9bdb46cb7f8263c67a7f8d76643ebaf4e048883b
wfhsiao/datastructures
/python/classes/LinkedQueue.py
1,510
4.375
4
# Python3 program to demonstrate linked list # based implementation of queue # A linked list (LL) node # to store a queue entry class Node: def __init__(self, data): self.data = data self.next = None # A class to represent a queue # The queue, front stores the front node...
6e83e0f2974435d0ec08afc4bba85cebd0d8222c
wfhsiao/datastructures
/python/AEE0386-code/Chapter 03/CirQue.py
2,427
3.765625
4
# 使用環狀佇列處理資料──新增、刪除、輸出 # File Name: CirQue.py # Version import sys MAX = 10 cq = [''] * MAX front = MAX - 1 rear = MAX - 1 tag = 0 # 當tag為0時,表示沒有存放資料,若為1,則表示有存放資料 # 新增函數 def enqueue_f(): global MAX global cq global front global rear global tag if front == rear and tag == 1: # 當佇列已滿,則顯示錯誤 ...
6472e0d2e7f4e79406d4d41c47e8dcf020d4052a
wfhsiao/datastructures
/python/AEE0386-code/Chapter 02/OddMagic.py
1,853
3.625
4
# 奇數魔術方陣實作 # File Name: OddMagic.py # Version MAX = 15 Square = [[0] * MAX for row in range(MAX)] # 定義矩陣並將矩陣所有元素初始化為0 N = 0 # 矩陣行列大小變數 def anykey_f(): # 按任一鍵即繼續之Function try: tChar = input('\n\n Press any key to continue ...') except ValueError: pass def init(): global N # 讀取魔術矩陣的大小...
d919fc6cf9ca18caeff1677791775a431f1014d7
piroton/keeptalking-tools
/2-simonsays.py
1,832
3.71875
4
#! /usr/bin/env python3 colchart = { 'r': 'Red', 'b': 'Blue', 'g': 'Green', 'y': 'Yellow' } # VOWEL CONVERSION vowel0 = { 'r': 'Blue', 'b': 'Red', 'y': 'Green', 'g': 'Yellow' } vowel1 = { 'g': 'Blue', 'y': 'Red', 'r': 'Green', 'b': 'Yellow' } vowel2 = { 'r': 'Green'...
6904a6fcdfd023584d3a536f645c05779faec466
nikesh65/assignment1
/Greatest of 3 numbers.py
180
3.84375
4
a = int(raw_input()) b = int(raw_input()) c = int(raw_input()) if (a>b & a>c): print "a is greater", a elif b>c: print "b is greatest", b else: print "c is greater", c
793659f9af6a041b405096e43d2230ccd055e107
nikesh65/assignment1
/Empty list.py
94
3.765625
4
list1 = [1,2,4] if len(list1)>0: print "list in not empty" else: print "list is empty"
0ba44ef8e4017d9152f874ef190d2b09c4c58764
jfcjlu/APER
/Python/Ch. 07. Python - Normal Distribution - Probability of x between x1 and x2.py
585
4.125
4
# Python - NORMAL DISTRIBUTION - PROBABILITY OF x BETWEEN x1 AND x2 # http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html from scipy.stats import norm # Enter the following values mean = 4 # the mean stdev = 1 # and standard deviation of the distribution # Enter the values of the limit...
74db9ff2f8a6c33e488a28590f6473a772395614
jfcjlu/APER
/Python/Ch. 07. R - Normal Distribution - Inverse.py
423
3.578125
4
# NORMAL DISTRIBUTION - INVERSE # http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html from scipy.stats import norm # Enter the following values mean = 4 # the mean stdev = 1 # and standard deviation of the distribution # Enter the value of the cumulative probability, p: p = 0.6 # The...
7d79589efc8ce841a8a26906ab65818deca351d5
matthewesses/Doppler-Effect-Calculator
/Doppler effect.py
1,094
3.5625
4
f_s=6.66*10**14#frequency observed by source f_o=None #frequency observed by observer v_s=0 #velocity of the source v_o=-0.8 #velocity of the observer c=1# speed of the wave in the medium #algebra for the dopplar effect if f_s!=None and v_o!=None and v_s!=None: f_o=((c+v_o)/(c+v_s))*f_s elif v_o!=None and...
6b792fb21bee0c28274935ed713df3a642b6d16d
ahmedkfu2020/-
/ahmed26_4.py
1,066
3.609375
4
N = 8 marked = 1 L = [] for i in range(N): L = L + [1/(N**0.5)] # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) print_list(L,3) for i in range(10): ...
061af301de044f10ed3055dc7c593e398fa926c5
shahed-swe/python_practise
/exception_handle.py
815
4.09375
4
# exception handling # try except else finally # while True: # try: # age = int(input("Enter your age:")) #if error occurs then no variable will be made for it # break #to stop the loop if right input is given # except ValueError: # print("Invalid input") # else: # print(f"u...
09bae4b4fd74433d59a19694a3a7a9a0a672dbc1
shahed-swe/python_practise
/recursion.py
1,522
4.15625
4
# here we will discuss about recursion # factorial problem def factorial(n): '''this function return the factorial number''' if n == 1: return 1 return n * factorial(n-1) # out put will be the factorial of the number is given # reverse order problem def print_rev(i,n, a): '''this function basi...
62f0955d22accac585c67813ba6609bae5e1cef9
shahed-swe/python_practise
/practise_decorators.py
477
3.953125
4
from functools import wraps def decorator_function(any_function): @wraps(any_function) def wrapper_function(*args, **kwargs): print("you are calling {} function".format(any_function.__name__)) print(any_function.__doc__) return any_function(*args,**kwargs) return wrapper_function ...
fac43c6a8a78800de58a64caf1302c720ca17ccf
shahed-swe/python_practise
/file/file_handle.py
622
3.640625
4
# read file # open function # read method # seek method # tell method # readline method # readlines method # close method f = open('file.txt') # print(f.readline()) # print(f"curson position {f.tell()}") #tto know the position of curson # print(f.readline()) # f.seek(23) #seek method move the cursor # print(f.read()) ...
54f4b80e12de4d345d15a411e3f00e323637fddf
shahed-swe/python_practise
/game/bouncyball.py
652
3.78125
4
from random import * from turtle import * from base import vector #our self made vector class def value(): # this || generate value from [-5,-3] to [3,5] return (3+random()*2)*choice([-1,1]) ball = vector(0,0) aim = vector(value(),value()) # the projection or movement def draw(): # move the ball and dra...
062fd98fd1ddb6c1e8c27656413ab46e90867bd9
shahed-swe/python_practise
/advance_function.py
814
3.75
4
def list_sum(l1,l2,l3,l4): new_list = [] for pair in zip(l1,l2,l3,l4): new_list.append(sum(pair)/len(pair)) return new_list list_sum = lambda l1,l2,l3,l4 : [sum(pair)/len(pair) for pair in zip(l1,l2,l3,l4)] def list_sum(*args): new_list = [] for pair in zip(*args): new_list.append...
6e16b3b82f4942ed14679fa2b22e22ae527eb67e
shahed-swe/python_practise
/flexible_functions.py
2,624
4.40625
4
# intro to arguments means (args*) # make flexible function # *operator # *args def all_elem(*args): print(args) print(type(args)) def all_sum(*args): total = 0 for i in args: total += i return total if __name__ == '__main__': all_elem(2,3,4,5) print(all_sum(2,5,6,7,8,9)) #we can't write parame...
047ba5ec9b0ca73fe02f7dd6cf19c3e4a4522c1b
CV-MLI-CSU/ROBOTIC-VISION-APPLICATION
/P_3_6_median_filter.py
1,196
3.6875
4
# Author: Sisi(Scarlett) Liu <scarlett.liu@csu.edu.cn> # Uni: Central South University, Changsha, China # Online course: Robotic Vision and Applications # Created: 09-Sep-2020 Modified: 09-Sep-2020 Revision: 1.0 # Copyright © 2020 SR2V Ltd. All rights reserved # Lecture 3-6 Median Filter # import lib import cv2 i...
39b2155a9c92750260823dd462de10db6575be7b
alfiandika/tugas-alpro-tanggal-12-9-2019
/coba.py
257
3.84375
4
listgpa = [3,2.7,2.5,4] def hadiah (gpa): bonus = 500000 hadiah = gpa*bonus return hadiah for gpa in listgpa : if gpa > 3 : print("anda mendapatkan hadiah sebesar :",hadiah(gpa)) else: print("kurang beruntung")
dd32ed3a7e5687cd32ae54db5e76ff7f81e925ff
phmendesbh/CursoInnovationOne
/app_python/aula3_Condicoes.py
1,147
3.90625
4
a = int(input('Primeiro valor: ')) b = int(input('Segundo valor: ')) c = int(input('Terceiro valor: ')) if a > b and a > c: print('o maior número é {}'.format(a)) elif b > a and b > c: print('o maior número é {}'.format(b)) else: print('o maior número é {}'.format(c)) d = int(input('Quarto valor: ')) e = ...
62960d349418a139f2dbe16a607dbdbc2f012716
caiolucasw/pythonsolutions
/exercicio53.py
1,063
4.59375
5
'''Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: john@google.com Then, ...
d4b1fb5fc893df273b9c6a78a3d24495403f8605
caiolucasw/pythonsolutions
/exercicio46.py
313
3.546875
4
class American: @staticmethod def printNationality(nacionalidade): print(f"A nacionalidade é {nacionalidade}") class NewYorker(American): @staticmethod def printMinhaCidade(): print("Eu sou de New York") NewYorker.printNationality("Americana") NewYorker.printMinhaCidade()
65f418215ce8198f87b4bb9e15b1839663360cbf
caiolucasw/pythonsolutions
/exercicio31.py
268
4.1875
4
'''Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.''' dicionario = {i: i**2 for i in range(1,21)} print(dicionario) #exercicio32 for i in dicionario.keys(): print(i)
87fd825526f0b8bf8700de6f76790201e6424d16
caiolucasw/pythonsolutions
/exercicio67.py
758
3.953125
4
'''Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.''' def binary_search(valores, valor, ini, final): if ini > final or ini < 0: return -1 posicao = int((ini+final)/2) if valores[posicao] ...
4e6cf8a9b61318083b46139dfb5dc92452ea9629
caiolucasw/pythonsolutions
/exercicio23.py
165
4.09375
4
'''Write a method which can calculate square value of number''' def square(n): return n**2 numero = int(input('Digite um número: ')) print(square(numero))
dfa6bd7d2b5960e7968e448e2904912edadb2622
Topytops/poem_dictionary
/wordcount.py
579
3.734375
4
def count_words_in_poem(file_name): count_words = 1 poem_file = open(file_name) poem_dictionary = {} for line in poem_file: poem_bank = line.split(" ") for word in poem_bank: if word in poem_bank: count_words = poem_dictionary.get(word, 0) poem_dictionary[word] = count_words + 1 return poem_dicti...
e55fbf974a7611386848ae5228d8329d1d91c9f4
daye10003/daye10003
/게임/다예의_쩌는_가위바위보.py
1,557
3.734375
4
#-*- coding:UTF-8 -*- print "다예의 쩌는 가위바위보" import random def win(str): print "컴퓨터는 "+str+"를 냈다!" print print "니가 이겼다." print def draw(str): print "컴퓨터는 "+str+"를 냈다!" print print "승부가 나지 않았다..." print def lose(str): print "컴퓨터는 "+str+"를 냈다!" print print "컴퓨터가 승리했다!" prin...
c503db580cc567da8c45ecfa1135bd7ccd010d70
brpl20/buscador-de-documentos-interno
/path_cnh.py
942
3.59375
4
#importar caminhos from pathlib import Path from shutil import copyfile basepath = Path('/media/bruno/DATA/Dropbox') count = 0 #basepath = Path('/media/bruno/DATA/Auto-eproc/arquivos') files_in_basepath = basepath.glob('**/CNH.pdf') for item in files_in_basepath: count += 1 if item.is_file(): copyfi...
4ad7e2a55239aa20e2b00ac2bb44885a26621928
gyzap/python-projects
/hello.py
458
4.0625
4
print("welcome") name = input("who r u ?") name = name.strip().title() if name == 'Luke': print("hi luke") elif name == "Patrick": print("go home") elif name == 'Godzilla': print('how is tokyo and america for ya, ' + name) elif name == 'Pinky Pie': print('when is the next party') else: print("hi "...
e5c66b7aa75035596f96fbaa8030520c9304fa1a
VivekKumarSingh07/Tweet-producer-for-blog
/tweet_producer.py
1,453
3.71875
4
import random phrase1 = ["My latest blog post on ", " I just wrote a blog post on ", "Have you checked my last blog post on ", "My blog post on ", " I just wrote on ", "Did you guys checked my post on ", "Check my post on ", "Hello World my blog post on ", "Hey guys I wrote on ", "Check this blog post out. Its on " ]...
726c743ecb0c02603abec143a4c94da748af0963
jordanpolun/NBA-Python
/Salaries/money_per_hour.py
2,930
3.578125
4
""" This looks at all all-star seasons in the 3 point era Finds the best players from this set based on PER for that season Continues until all rosters are filled """ import time import urllib.request import string def main(): lines = [] lines.append("name,salary,minutes.played,hourly.wage\n") ...