blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
43a32ed4140ad523c65dfd6add279fd79c1f671c
rfugiel/chess-engine-python
/src/board.py
1,453
3.53125
4
from piece import Piece def check_oob(func): # TODO: if this is a wrapper how do I ensure which argument idx is? keyword? pass class Board: def __init__(self, board=None): # TODO: Is it incorrect to assign to None? self.board = board if board else [None for _ in range(64)] def piece_c...
63371da78b8e9357cdbf136bff27d3523b1ffde7
zlo17/Zoe-Lo
/turtles.py
584
4.375
4
# Zoe-Lo from turtle import * import math # Name your Turtle. t = Turtle() # Set Up your screen and starting position. ### Write your code below: var = input("how many sides?") var = int(var) t.fillcolor("blue violet") t.begin_fill() for sides in range (var): t.forward(200) t.right(360/(var)) for sides in ra...
c12e8beee0d3ee884783a9f6b071be3922f5c3fc
omshivpuje/Python_Basics_to_Advance
/Python 30 days/Day 7.py
3,124
4.25
4
""" split, join, and Slices """ # Join from typing import List project_authors = ["Mike", "Sofia", "Helen"] authors = ", ".join(project_authors) print(f"The people who worked on this project are: {authors}.") print(f"The people who worked on this project are: {', '.join(project_authors)}.") # Split user_numbers = i...
7434cbbdb32b37c968d1e99efa9289aa0d91a2c9
omshivpuje/Python_Basics_to_Advance
/Search.py
125
3.921875
4
import re name = 'My name is Omprakash!' d = re.search("name is ", name) print(name[d.end():]) print(name.find("name is "))
1f0e772354ffb95a15ca6c4c61321f0c31662228
naveen12124/lab2.0
/L5-assignment-binary search for suitable test cases.py
1,041
4.03125
4
#Defining the function binary Search def binary_Search (a, s): high = len(a) low = 0 mid = (low+high) //2 a.sort() if s not in a: print ( 'Element not found in the array! !') elif a [mid] == s: print (' Element found at index',mid) elif s < a[mid]: for i in range (low...
2ee5c7127ac313e3067247aa1d2f8f42617de5c3
jagruti8/data_structures
/file_recursion.py
3,028
4.375
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 1 23:55:18 2020 @author: JAGRUTI """ import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further su...
67bbead3edc58f006f38dfab0c1a13a02bf977dd
miriammariety/Rule-30
/Rule30.py
789
3.703125
4
from pylab import * import sys def rule30(x, y, z): string = str(x) + str(y) + str(z) number = int(string, 2) if number > 4 or number < 1: return 0 return 1 #Size of the automaton, specify before running #Best size is 35 (Depending how big the console is) try: num = int(sys.argv[1]) except Exception:...
db8bb1e6f80c8f36efe98c3e9543e242d7410c83
Tranphu121292/Zoro
/abc086.py
155
3.5625
4
''' s=input() tokens=s.split() a=int(tokens[0]) b=int(tokens[1]) ''' a,b=map(int,input().split()) if a*b%2==0: print('Even') else: print('0dd')
84c97d28409a887308d0e139f19397920508e270
AlhHadVanier2019/Encrypt
/Operators.py
8,097
4.3125
4
import os import struct def stringtobin(message): """ :param message: The string message to be turned into binary :return: returns the message converted to a string of bits """ # creates a variable called bits total where the bits will be stored bitstotal = "" # this loop runs the...
df9ca1c05ccf92b79b3c6ee1e1ecb248651c5480
cspickert/advent-of-code-2019
/day22.py
1,074
3.625
4
def deal_into_new_stack(deck): return list(reversed(deck)) def cut_cards(deck, n): return deck[n:] + deck[:n] def deal_with_increment(deck, n): deck_iter = iter(deck) result = [None] * len(deck) for i in range(0, len(deck) * n, n): result[i % len(deck)] = next(deck_iter) return resul...
5827e2b2095cbe1d4140fa73f587b217f07baae5
dengzoro/Simulation-for-Elevator-in-Building
/example.py
4,907
3.59375
4
from system import System from event import Event import rand ONE_DAY = 60 * 24 # in minutes # this event would have a Passenger entity passed to it upon creation class PassengerArriveEvent(Event): pass class PassengerDepartEvent(Event): pass class ElevatorSystem(System): def initialize(self): # this var...
3fea9bfdbf935d7b6393aa57f4022db7610231d9
PalaashSri/LeetCode_Practice
/233.py
481
3.96875
4
#Given an integer n, count the total number of digit 1 appearing in all non-negative #integers less than or equal to n. def countDigitOne(n): ''' Naive Implementation :param n: :return: ''' num_of_digit=0 for i in range(n+1): while i>=10: val = i//10 if val==...
da763101f6ab218bad8157a327903e1ba88fb63e
dan8919/python
/class/function.py
900
3.609375
4
def fn(): print("fn called") # 함수를 부르면 메모리에 올려놓음,다시 부르면 메모리에서 찾음 fn() def exp(x): return x ** 2 exp3 = exp(3) print(exp3) def get_fruits(): return ['a','b','c'] print(get_fruits()[0]) def get_name(): return 'kim','Beck' # 튜플로 받음 추가하거나 변경 불가능 name = get_name() print(get_name()) def full_name(firs...
bc92c890001263136ba92180488f2accd5b92f94
dan8919/python
/sort/sort/선택정렬.py
335
3.796875
4
#1.선택 정렬: 가장 작은 데이터를 제일 앞에 숫자와 바꾸는 것 array = [3,4,6,7,2,8,11,21] for i in range(len(array)): min_index = i for j in range(i+1,len(array)): if array[min_index]>array[j]: min_index = j array[i],array[min_index] = array[min_index],array[i] print(array)
72c18c42f955800bf7aa2c83840723b28a3bf4a0
dan8919/python
/sort/checkAlfabet/high_frequencey1.py
333
3.671875
4
#가장 많이 등장하는 문자 체크 word = "testk" def highFrequencyLetterCount(word): map = {} for alphabet in word: if map.get(alphabet) == None: map[alphabet] = 1 else: map[alphabet] += 1 print("2map=>", map) return -1 print(highFrequencyLetterCount(word))
7fb9f0b2d6af0c6f58c67192002b7e30d6199ad1
twu123200/ucsd-dsc80
/project02/project02.py
23,591
3.578125
4
import os import pandas as pd import numpy as np # --------------------------------------------------------------------- # Question #1 # --------------------------------------------------------------------- def get_san(infp, outfp): """ get_san takes in a filepath containing all flights and an file...
5c1500267f0c5179f6a9c1d9fed2b7deb3ae734d
Mayank-141-Shaw/Python-Repo
/Upload/staircase.py
362
4.0625
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 6 12:09:35 2020 @author: MAYANK SHAW """ def staircase(n): if 0<n<=100: for i in range(n,0,-1): for j in range(1,n+1): if j < i: print(' ',end="") else: print('...
9484d44b301af58a80ebd4e75baa67301543f05d
Mayank-141-Shaw/Python-Repo
/Upload/LongATMQueue.py
521
3.796875
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 2 19:10:56 2020 @author: MAYANK SHAW """ def find_groups(n, H): checker=[None] count = 1 if n == 0 : return 0 for i in range(n): if H[i] not in checker: count = count + 1 else: checker.appen...
246c1777e7b875cdad37a6de410dc663586f21ae
Mayank-141-Shaw/Python-Repo
/Upload/HackerInString.py
778
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 11 11:47:00 2020 @author: MAYANK SHAW """ def hackerrankInString(s): def returnPointer(s, char_to_search, start_index): ptr = start_index while ptr < len(s): if s[ptr] == char_to_search: return ptr ...
1e6d5db4f65c9e070f9066810fefdebcc46e4042
Mayank-141-Shaw/Python-Repo
/Upload/trial.py
283
3.8125
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 21 10:37:53 2020 @author: MAYANK SHAW """ import Combo as co a = int(input("Enter a no for n: ")) b = int(input("Enter a no for r: ")) print("Permutation : ",co.Permutation(a, b)) print("Combination : ",co.Combination(a, b))
ef2afc07c6325599a69bb7b84b1881e88c498e9f
Tomraydev-WFiIS/TI
/cgi-bin/zad03/read.py
919
3.640625
4
#!/usr/bin/env python3 def print_students(): with open("../../zad03/students.csv") as csv: data = csv.read().split("\n") for r in data: r = r.split(",") print("<tr>") for e in r: print("<td>" + e + "</td>") print("</tr>") # output pri...
929fc732820f98f13fd615c38c9e9b1905a32790
cschmer/fixed_income_analysis
/internal_rate_of_return.py
823
3.5
4
def present_value(futureValue, interestRate, numOfYears): return futureValue * (1 / pow(1 + interestRate, numOfYears)) def yield_calc(calcInfo, price, interestAssumption): interestAssumption = interestAssumption calcAmount = 0.00 for cashFlow in calcInfo: calcAmount += present_value(cashFlow[1], interestA...
12d1a2e4ebcb7fd8bbfc10127d6e42f0e5d2ef08
momentum-cohort-2019-02/w3d3-oo-pig-tlcpack
/pig_game.py
5,170
4.15625
4
import random class HumanPlayer(): """Creating the human player for Pig game""" def __init__(self): # self.roll_choice = roll_choice # self.die_roll = die_roll # self.rolls_this_turn = rolls_this_turn # self.current_turn_score = current_turn_score # self.overall_sc...
c4796ee551c1e39ef63ab07f30ef0199b4e0b295
gauravk268/Competitive_Coding
/Python Competitive Program/wrap nstring.py
212
3.9375
4
import textwrap #First line contains a string S S = input("Enter your string : ") #Second line contains the width w w = int(input("Please write which width you want in string : ")) print (textwrap.fill(S,w))
3d22da9b90ddad595d2855fc967aa08ff92faede
gauravk268/Competitive_Coding
/Python Competitive Program/2nd max. value in dictionary.py
199
4.15625
4
#find second maximum value in dictionary #input example_dict = {"A":3, "B":15,"C":9,"D":19} # sorting the given list and get the second last element print(list(sorted(example_dict.values()))[-2])
769e5b9915dee51bf60fd489faa3636c41ccfa76
gauravk268/Competitive_Coding
/Python Competitive Program/leap year.py
254
4.1875
4
def is_leap(year): if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True return False print(is_leap(int(input("Your function must return Boolean value (True/False) : "))))
1767ed91cd5ecb9dc4967b259a9c41f4baf56d84
gauravk268/Competitive_Coding
/Python Competitive Program/count occurance in tuple.py
138
4.46875
4
# Count occurrences of an element str=input("Enter the string : ") word_count={char:str.count(char) for char in str} print(word_count)
de84b5abb62000cd597a57806e435f76729922ee
gauravk268/Competitive_Coding
/Python Competitive Program/upcoming next greatest number.py
1,365
4.0625
4
# In this program we will have a given number and we have to find the next greater number using the same set of digits as in the original number def findGreaterNum(digits, n): # traverse the digits to find if they are in some order for i in range(n-1, 0, -1): if digits[i] > digits[i-1]: # this means di...
81d23be0a366a23f4a8b73be2cad12649ec92422
gauravk268/Competitive_Coding
/Python Competitive Program/salary.py
329
3.875
4
# ---- Clean the Messy salary # 1. method salary = '$876,001' old = "$" new = "" str1=salary.replace(old,new) old1="," new1="" str2=int(str1.replace(old1,new1)) print(str2) print(type(str2)) #2. method salary = '$876,001' str1=salary.replace('$','') str2=str1.split(',') str3=int(''.join(str2)) print(str3) print(typ...
2019d27a812b46e86f0591d9be1abe1d6e2744c7
gauravk268/Competitive_Coding
/Python Competitive Program/check fibonacci number or not.py
1,219
4.375
4
# Python 3 program to check whether the sum of fibonacci elements of the array is a Fibonacci number or not MAX = 100005 # Hash to store the Fibonacci numbers up to Max fibonacci = set() # Function to create the hash table to check Fibonacci numbers def createHash(): global fibonacci # Inserting the fir...
8cb30426d2fc7c256b2fa0934a3398e73e0a6b9c
Par4meter/Python-100-Days
/Day01-15/Day11/learning/binary_file_operation.py
472
3.546875
4
def move_file(original_file_path, target_file_path): try: with open(original_file_path, 'rb') as fs: data = fs.read() print(type(data)) with open(target_file_path, 'wb') as t_fs: t_fs.write(data) except FileNotFoundError: print('file not found!') e...
7f1aa843f45f10eb1a52d3e643efa124adfa4a99
dtg3/st_work
/hw1/calc.py
1,202
3.546875
4
import unittest def evaluate_single_digit(s): i = "0123456789".index(s) return i def evaluate_positive_number(s): n = 0 for c in s: d = evaluate_single_digit(c) n = n * 10 + d return n def evaluate_floating_point_number(s): in_decimal = False n = 0 v = 0.1 for c in...
198f4272d2c19074b638808ffd4b6380e8fd976d
riju18/Permutation-variation-combination
/1.3_combinations_without_repitition.py
1,002
3.890625
4
# """ # =================================================== # picking no of elements from a set in different ways # v = c x p ; v = variations without repetitions, c = combinations; p = permutations # =================================================== # """ import random from collections import Counter from math impor...
28bd31b3cb451b708886e52c75b1d3d4c3ed44f6
group6BCS1/BCS-2021
/src/chapter6/exercise4.py
98
3.90625
4
string = 'banana' count = 0 for char in string: count += 1 print('a>>', string.count('a', 1))
f0e85554b4b9edd090062b431af81035be91b56f
group6BCS1/BCS-2021
/src/chapter4/exercise7.py
763
4.3125
4
# A program that prompts a user to enter a score from 0 to 1 and prints the corresponding grade s = (input('enter score')) def compute_grade(score): # this makes sure that the user enters only float values otherwise an error message pops up try: score = float(s) if 0 <= score < 0.6: ...
d464074e34e07ab9dcfd279ca9c6bbbdcb7e1580
group6BCS1/BCS-2021
/src/chapter3/excercise3.py
498
4.1875
4
try: score = float(input('enter score')) # A program that prompts a user to enter a score from 0 to 1 and prints the corresponding grade if 0 <= score < 0.6: print(score, 'F') elif 0.6 <= score < 0.7: print(score, 'D') elif 0.7 <= score < 0.8: print(score, 'C') elif 0.8 <...
af31205ec522f6596e98cbbb73267135c63d49ed
group6BCS1/BCS-2021
/src/project2/project2_a.py
825
4.0625
4
# A program in “project2_a.py” will copy selected lines from “measles.txt” into a # file selected by the user try: file = open('measles.txt', 'r') output_file = (input('Output file name>>')).lower() year = input('Enter year >>') if '.txt' in output_file: pass else: print('Error,outpu...
a42e5a83bb33e32d0674d293150aa146b90d46aa
yufanglin/Basic-Python
/IntegersFloats.py
1,058
4.15625
4
# create an integer variable num_int = 3 print(type(num_int)) # create a float variable num_float = 3.14 print(type(num_float)) # Arithmetic Operations: add = 3 + 2 # should return 5 sub = 3 - 2 # should return 1 mult = 3 * 2 # should return 6 div = 3 / 2 # should return 1.5 floor_div = 3 // 2 # should return ...
3ce14bdbbe33723fe3574dc4b7f961fabe3f7628
yufanglin/Basic-Python
/dateTimeModule.py
3,041
3.859375
4
''' Datetime Module tutorial Followed: https://www.youtube.com/watch?v=eirjjyP2qcQ&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=24 ''' import datetime import pytz # two different types, naive (simple) and aware (considers timezones, etc) # create a datetime object (don't add 0's before dates, will cause error) d =...
ba874c8ab95ba22d349c3ad6685601e52d0ea341
yufanglin/Basic-Python
/conditionalsAndBool.py
1,844
4.34375
4
''' From Corey Schafer's tutorials on youtube ''' print("\n") if True: # will print this statement unless True was changed to False print('Conditional was True') # Comparisons: # Equal: == # Not Equal: != # Greater than: > # Less Than: < # Greater or Equal: >= # Less or Equal: <= # Object Identity: is pri...
fd8620c4df773314ab00089d6e9a7a3217836cb5
vipulwalunj/Games-turtle
/Space invaders.py
3,216
3.921875
4
import turtle import os import random win = turtle.Screen() win.title("Space Invaders") win.bgcolor("black") win.setup(width=800, height=800) win.tracer(0,0) #Create spaceship space = turtle.Turtle() space.speed(0) space.color("red") space.shape("triangle") space.penup() space.setheading(90) ...
5460d1433bcb3196f65e28a2dd0b0e2b31190d31
clarito2021/python-course
/12.-functions.py
526
3.5
4
x = 30.41 print("asdasdasdad") dir(x) type(12) print("*********************************") def hello(name="Dave"): print("Hello" + " " + name) hello("Carlos") hello("Lorena") print("*********************************") hello() print("*********************************") def add(numberOne, numberTwo): ...
9bbea537c809a92d0d985070e50b876930a53064
selym3/stuy-ray-marcher
/vec3.py
9,002
3.5
4
''' See examples.py, constants.py, or main.py for configurable code. ''' import math def IsVector(obj): return isinstance(obj, Vec3) def IsNumber(obj): return isinstance(obj, (int, float)) class Vec3: ##################### # Python Operations # ##################### def __init__(self, x, y...
02e7a92bee64fbda6b4bbbf0874fb233ec5edab2
leonlee2003/crimeAnalysis
/cleanCrimeData.py
1,196
3.546875
4
from getCrimeData import get_crime_data import pandas as pd def clean_data(): crimeData = get_crime_data() crimeData1 = crimeData.drop(crimeData[crimeData['Rape newDef'].isnull()].index).rename(columns={'Rape newDef':'Rape'}) del crimeData1['Rape oldDef'] crimeData2 = crimeData.drop(crimeData[crime...
bbefb5234905558e8d53d09b931d8142db41f852
tb1over/datastruct_and_algorithms
/number/palindrome.py
247
3.625
4
# -*- coding: utf-8 -*- # 求回文数 def ispn(num): origin = num t = 0 while num != 0: t = t*10 + num%10 num //= 10 if origin == t: return True return False print(ispn(32123)) print(ispn(321))
f0ee577e50bfd6ad3eb4ac066856c0c547836d6a
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/11.py
288
3.6875
4
# -*- coding: utf-8 -*- def get_min(lst): l = 0 h = len(lst) - 1 while l < h: m = (l+h) // 2 if lst[m] > lst[h]: l = m + 1 else: h = m return lst[l] if __name__ == '__main__': n = get_min([3, 4, 5, 1, 2]) print(n)
e80657b8ef8cc6842d75b0deefde92bb1d735553
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/30.py
584
3.6875
4
# -*- coding: utf-8 -*- """题目描述 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的 min 函数。 """ class Solution: def __init__(self): self.items = [] def push(self, node): # write code here self.items.append(node) def pop(self): # write code here return self.items.pop() def top(sel...
a5523b1c700142079ab75d34e49b15adc83e454b
tb1over/datastruct_and_algorithms
/dfs_bfs/subset.py
1,031
3.640625
4
# -*- coding: utf-8 -*- """题目描述 Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] 子集问题 """ ...
3dbe430d55dd91a91f186c10ff287cc128ef3272
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/10_1.py
681
3.875
4
# -*- coding: utf-8 -*- """题目描述 求菲波那契数列的第 n 项 """ # 1 递归 def fib1(n): if n < 2: return n return fib1(n-1) + fib1(n-2) # 2 缓存 from functools import lru_cache @lru_cache(None) def fib2(n): if n < 2: return n return fib1(n-1) + fib1(n-2) # 3 动态规划 def fib3(n): dp = [0]*(n+1) dp[...
0e4a0f97300acd6442d72ceb3bd57db9534466bf
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/25.py
1,292
4.15625
4
# -*- coding: utf-8 -*- """题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 """ class ListNode(object): def __init__(self, x, next=None): self.val = x self.next = next def merge(pHead1, pHead2): if pHead1 == None or pHead2 == None: return pHead1 if pHead1 else pHead2 if pHead1...
368b85aaefe6c65581c71daad6c9d8ed01efd40f
tb1over/datastruct_and_algorithms
/dp/Integer_Break/solution.py
454
3.84375
4
# -*- coding: utf-8 -*- import math def solution(n): if n <= 1: return None if n > 5: elsewise = 1 while n > 0: n = n-3 if n >= 3: elsewise *= 3 else: elsewise *= (n+3) break else: n1 = math...
0b326bbd88fd87e22fc2ddf335f85b3912923f3c
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/15.py
762
3.828125
4
# -*- coding: utf-8 -*- """题目描述 输入一个整数,输出该数二进制表示中 1 的个数。 """ def f(n): i = 0 if n < 0: """首先判断n是不是负数,当n为负数的时候,直接用后面的while循环会导致死循环,因为负数 向左移位的话最高位补1 ! 因此需要一点点特殊操作,可以将最高位的符号位1变成0,也就 是n & 0x7FFFFFFF,这样就把负数转化成正数了,唯一差别就是最高位由1变成0,因为少了 一个1,所以count加1。之后再按照while循环里处理正数的方法来操作就可以啦!""" i += 1 n &= 0...
25d88ee114568eb9b2928f68dc15413fa7de30bf
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/12.py
1,578
3.546875
4
# -*- coding: utf-8 -*- """题目描述 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 tips: 可用回溯法实现: 回溯法也是设计递归过程的一种重要方法,它的求解过程实质上是一个先序遍历一棵"状态树"的过程,只是这棵树不是遍历前预先建立的,而是隐含在遍历过程中 """ def find(mat, m, n, i, j, str, idx, flag): if (i<0 or j<0 or i>=m or j...
4f9f8d2fd2cb33b9cbaa4f36835913aafec3e41b
tb1over/datastruct_and_algorithms
/dp/Unique_paths/recursive.py
192
3.875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- def f(m, n): if m < 0 or n < 0: return 0 if m == 1 or n == 1: return 1 return f(m-1, n) + f(m, n-1) print(f(8, 6))
0483894449c21e3763898a2b6b829b7d6fd93c02
tb1over/datastruct_and_algorithms
/graph/DFS.py
857
3.671875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- from collections import defaultdict class Graph(object): def __init__(self): self.vertex = set() self.edge = defaultdict(list) def addEdge(self, u, v): self.vertex.add(u) self.vertex.add(v) self.edge[u].append(v) def DF...
978eeae72b98b3c1cc3f411d1b24f9c89cd832dd
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/8.py
774
3.84375
4
# -*- coding: utf-8 -*- """题目描述 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 """ class TreeNode(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def next_node(pNode): if pNode == None: return...
1188606e1648c2ad6d7c034aa38c990687de4cc3
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/29.py
2,070
3.609375
4
# -*- coding: utf-8 -*- """题目描述 下图的矩阵顺时针打印结果为:1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 # 题目分析:http://wiki.jikexueyuan.com/project/for-offer/question-twenty.html """ class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): # write code here if matrix is None: ...
9469dddd75b0e66ec79a7f4852d0a0d88322c228
tb1over/datastruct_and_algorithms
/dp/Fibonacci/recursive.py
110
3.546875
4
# !/usr/bin python # -*- coding: utf-8 -*- fib = lambda x: 1 if x<2 else fib(x-1) + fib(x-2) print(fib(30))
1938771cd9bdc5d0f5ebae228c533895ff5223d7
tb1over/datastruct_and_algorithms
/interview/tree/inorder_iter.py
607
3.78125
4
# -*- coding: utf-8 -*- """题目描述 迭代中序遍历二叉树 """ class TreeNode(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def inorder(pRoot): if pRoot is None: return None stack = [] while pRoot or len(stack) > 0: ...
d1a51caecd8f41dce23a3ba64355a0c5a20bc113
tb1over/datastruct_and_algorithms
/tree/find_post_order_by_pre_in_order.py
957
3.828125
4
# -*- coding:utf-8 -*- """根据先序遍历和中序遍历得到后序遍历,方法:重构树+后序遍历 """ class TreeNode(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def build(pre_order, in_order): if len(pre_order) == 0: return None root = TreeNode(pre_or...
e1cbc847463a2e1afa04015fba8e0b795b17a634
tb1over/datastruct_and_algorithms
/tree/is_full_bitree.py
508
3.8125
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ 判断一棵树是否满二叉树 """ class Node(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def check_full(root): if root == None: return True if root.left == None and root.righ...
c159f98d78821cb3778a45d47065459e5466d1b7
dazhouze/HelloWorld
/Algorithm/Alg_0531_DynamicArray.py
1,378
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import ctypes class DynamicArray(object): '''A dynamic array class akin to a simplified Python list''' def __init__(self): '''Create an empty array''' self._n = 0 # to count actual elements self._capacity = 1 # default array capacity self._A = self....
80ac8efac4d29c57b038f5e0934311069ad75434
dazhouze/HelloWorld
/Python/Prac_38_SQLite.py
453
3.765625
4
import sqlite3 ''' conn = sqlite3.connect('test.db') cursor = conn.cursor() cursor.execute('create table usr (id varchar(20) primary key, name varchar(20))') cursor.execute('insert into usr (id, name) values (\'1\', \'Michael\')') print(cursor.rowcount) cursor.close() conn.commit() conn.close() ''' conn = sqlite3.conne...
995db9120217caf41c83bb4a0a238a68e41a71e2
dazhouze/HelloWorld
/Python/Prac_09_function.py
1,395
3.75
4
f = abs print f(-10) print 'function name is varible' print 'Higher-order function has function as paramter' #r = map(x**2, [x for x in range(1, 11)]) '''first paramter has to be function name note cross lines test''' r = map(f, [x for x in range(-11, -1)]) print r print 'reduce function implement all items in Iterab...
60477f35e7fe9ae437931d52145e9537f8009890
dazhouze/HelloWorld
/Algorithm/Alg_0832_LinkedBinaryTree.py
7,085
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class LinkedBinaryTree(object): '''Linked representeation of a binary tree structure.''' class _Node(object): __slots__ = '_element', '_parent', '_left', '_right' def __init__(self, element, parent=None, left=None, right=None): self._element = element self._p...
38e2d86ddf257f7c10b139fab5f29afa811fd67c
dazhouze/HelloWorld
/Algorithm/Alg_0412_Ruler.py
890
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Engilsh rule ''' def draw_line(tick_length, tick_label=''): '''Draw one line with given length.''' line = '-' * tick_length if tick_label: line += ' ' + tick_label print(line) def draw_interval(center_length): '''Draw tick interval based upon a central tic...
1ee3f89585a57cab64cc4238aba1d9f676d47335
dazhouze/HelloWorld
/Python/Prac_28_pickling.py
424
3.53125
4
print ('Pickling processing make varible to be storible.') import pickle d = {'name': 'ZZ', 'age': 24, 'socre': 100} print (pickle.dumps(d)) f = open ('test.txt', 'wb') pickle.dump(d, f) f.close f = open ('test.txt', 'rb') d = pickle.load(f) f.close print (d) import json d = {'name': 'ZZ', 'age': 24, 'socre': 100} ...
cb6380bd0ed850143132ce9eb6ddbf6e24b6b01c
dazhouze/HelloWorld
/Algorithm/Alg_0730_DoublyLinkedList.py
1,505
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class _DoublyLinkedBase(object): '''A base class providing a doubly linked list representation.''' ##### _Node class ##### class _Node(object): '''Lightweigth, nonpublic class for storing a double linked node.''' __slots__ = '_element', '_prev', '_next' def __i...
caafd30520beb487c3971f3532179937f70b3c2a
ViniciusLucasM/Codigos-URI-Python
/Medio/2760 - Entrada-e-Saída-de-String.py
915
3.84375
4
var1, var2, var3 = '', '', '' countvar1, countvar2, countvar3 = 0, 0, 0 def verficCarac(var1, var2, var3): if var1 > 100: print('') print('A 1ª Frase ultrapassou os 100 caracteres') print('') elif var2 > 100: print('') print('A 2ª Frase ultrapassou os 100 caracteres') ...
89da0301a4b61524d900f95fff01c0f96054e58b
Pratik2711/Machine-Learning
/que8.py
201
3.578125
4
#8. Find indices of nonzeroelements from [1,2,0,0,4,0] import numpy as np arr= np.array([1,2,0,0,4,0]) result=np.where(arr!=0) print(result) '''OUTPUT: (array([0, 1, 4], dtype=int64),)'''
aa1ec63a363c592de47be83503342ba21771e476
colinbazzano/recursive-sorting-examples
/src/recursive.py
2,756
4.125
4
"""Recursive Recursive sorting: Merge Sort Quick Sort """ # Merge Sort # def merge_sort(arr): # merge_sort2(arr, 0, len(arr) - 1) # def merge_sort2(arr, first, last): # if first < last: # middle = (first + last) // 2 # merge_sort2(arr, first, middle) # merge_sort2(arr, middle + 1,...
e8a4cf47ef5eb884dfd9fe4de75071d68ee7b058
1139411732/AID2011
/day13/重复/zuoye1.py
520
3.671875
4
""" 求100000以内质数之和,写成一个函数 写一个装饰器求一个这个函数运行时间 将100000分成4等份 分别使用4个进程求 每一份的质数之和,四个进程同时执行 记录时间 将100000分成10等份 分别使用10个进程求 每一份的质数之和,10个进程同时执行 记录时间 """ list_number = [] for i in range(2, 1000 + 1): for j in range(2, i): if i % j == 0: break else: list_number.append(i) print(list_number) ...
1d4f381972d232474049369feec806a28e926001
1139411732/AID2011
/day11/lianxi1/tcp_server.py
1,010
3.59375
4
""" 练习: 使用tcp完成,将一个图片从客户端上传的服务端 注意,图片有可能比较大,不允许一次性 read()读取 在服务端以当前日期为名字存储 2020-10-16.jpg 思路 : 客户段读取文件内容发送 服务端接收内容,写入文件 """ from socket import * import time # 创建tcp套接字服务端 tcp_socket = socket() tcp_socket.bind(("172.40.83.120",8895)) tcp_socket.listen(1024) # 循环接收客户端连接 while True: print('等待连接... ...') con...
33d673dae9b5aa695b91563bab216521a5f7800d
kishorchouhan/Udacity-Intro_to_CS
/sudoku check.py
2,328
4.21875
4
# THREE GOLD STARS # Sudoku [http://en.wikipedia.org/wiki/Sudoku] # is a logic puzzle where a game # is defined by a partially filled # 9 x 9 square of digits where each square # contains one of the digits 1,2,3,4,5,6,7,8,9. # For this question we will generalize # and simplify the game. # Define a procedure, check_s...
5327aa148fc98db6d9a284dc49928eea32030897
wilderlopes83/RobotGame-Python
/main.py
1,093
3.75
4
import robot import reward import random robot1 = robot.Robot(5, 5) r1 = reward.Reward(random.randrange(1, 11, 1), random.randrange(1, 11, 1), "money") r2 = reward.Reward(random.randrange(1, 11, 1), random.randrange(1, 11, 1), "fuel") r3 = reward.Reward(random.randrange(1, 11, 1), random.randrange(1, 11, 1), "cake") r...
2f585789b317fbb0216243e965a311d542472220
AishwaryaJadhav9850/GeeksforGeeks-Mathematical-
/GeeksForGeek_Closest Number.py
639
3.703125
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 26 22:09:03 2020 @author: aishw """ #User function Template for python3 class Solution: def closestNumber(self, N , M): # code here n1=abs((abs(N)//M)*M) n2=abs(n1+M) if abs(abs(N)-n1) > abs(abs(N)-n2): ...
aaf4e46c4353f0b7e3542a31c9a9883fa3849c66
AishwaryaJadhav9850/GeeksforGeeks-Mathematical-
/GeeksForGeek_Pair cube count.py
595
3.96875
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 2 21:29:33 2020 @author: aishw """ import math #User function Template for python3 class Solution: def pairCubeCount(self, N): cnt=0 for i in range(0,round(math.pow(N, 1/3))+ 1): t=N-(i*i*i) ans=round...
66d643ef78dae763b80646c5abb187adf37b87cd
AishwaryaJadhav9850/GeeksforGeeks-Mathematical-
/GeeksForGeek_Largest prime factor.py
622
3.90625
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 1 23:59:56 2020 @author: aishw """ #User function Template for python3 class Solution: def largestPrimeFactor (self, N): if N==1: return 1 if N==2: return 2 p=N n=(N//2)+1 for i in ran...
0f9dc83772375961b73e054bf845a9588f2f76c6
omriazran/HtmlParser
/Html_Parser.py
3,139
3.765625
4
""" * omri azran * 316098979 * 01 * ass7 """ """ * Function Name:print_user_file * Input:links_dict * Output:- * Function Operation:print sort list for links in chosen file by the user """ def print_user_file(links_dict): user_file = input('enter file name:\n') links_dict[user_file].sort() ...
de9961f82eed305a67bc87a943651380519afa5a
xieyupengzZ/python3
/app1/utils/ProcessThread/ThreadQueue.py
963
3.640625
4
import queue import threading import time queue = queue.Queue() class Producer(threading.Thread): def run(self): global queue count = 0 while (True): if (queue.qsize() < 30): for i in range(15): count += 1 m = '生产商品' + str...
22514866def202df938af55b2f1eddb46137de1c
billxiong24/scrape
/place2scrape.py
1,280
3.625
4
"""scrape using kat57 api""" import sys import kat57 def main(argv=None): """main method""" if len(argv) < 3: print "Usage: url, folder name, file base name, number of pages (optional)" exit(1) url = argv[0] folder_name = argv[1] file_base = argv[2] print "Scraping url: " + url...
f95983c642af21954cc4c4134c9b61cada2cdfd6
chelsea-banke/p2-25-coding-challenges-ds
/vanilla/ex49.py
261
3.875
4
import random def shuffle(array): for i in range(len(array)-1): x = random.randint(0, len(array)-1) array[i], array[x] = array[x], array[i] return array print(shuffle(["I", "am ", "facing", "difficulties", "with", "this", "exercises"]))
409aab58be8631e18c78da8ed4709f9e3c14c031
chelsea-banke/p2-25-coding-challenges-ds
/Exercise_40.py
318
4.28125
4
# Implement the bubble sort algorithm for an array of numbers def bubbleSort(array): for i in range(len(array)-1): for j in range(0, len(array)-i-1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array print(bubbleSort([6,4,1,3,4,0,4]))
d00edbfa8620461a120ad948955a5459f96608c2
chelsea-banke/p2-25-coding-challenges-ds
/Exercise_34.py
182
4.03125
4
# Create a function that returns an array with words inside a text. def array_of_words(text): return text.split() print(array_of_words("Returns each word as element of array"))
570d81222d9ded91b483314452577acba5f2cf7c
chelsea-banke/p2-25-coding-challenges-ds
/Exercise_48.py
293
4.21875
4
# Create a function to return the longest word in a string def longestWord(string): list = string.split() long = 0; for elt in list: if len(elt) > long: long = len(elt) result = elt return result print(longestWord("Hi Serge this is supercalif"))
ad63ca202612a973e544ca7beecc17e21440d92f
chelsea-banke/p2-25-coding-challenges-ds
/vanilla/ex50.py
262
3.75
4
import random def array_of_random_numbers(n): result = [] count = 0 while count < n: x = random.randint(1, n) if x not in result: result.append(x) count += 1 return result print(array_of_random_numbers(10))
cb32f5098a91fa5317ccf65cf8ff06af45e5931e
chelsea-banke/p2-25-coding-challenges-ds
/vanilla/ex38.py
157
3.546875
4
def ASCIIToString(array): string = "" for val in array: string = chr(val) + string return string print(ASCIIToString([85, 63, 20, 50]))
97531662bac17ee3436389029ca491f662fc30c0
pascalleveltman/dataprocessing
/Homework/Week_2/eda.py
6,813
3.8125
4
#!/usr/bin/env python # Name: Pascalle Veltman # Student number: 11025646 """ This script clearifies given important data about countries. """ import csv import pandas as pd import numpy as np import statistics from statistics import mean from statistics import median import json import matplotlib matplotlib.use("TkAg...
fd5f86823f9eb50cfdbcf87c658bd036b152caaa
viktorpenelski/adventofcode2020
/day_1/day_1.py
1,100
3.65625
4
# https://adventofcode.com/2020/day/1 from collections import OrderedDict from functools import reduce target = 2020 def file_lines_as_int_list(file_name): with open(file_name, "r", encoding="utf-8") as file: return [int(line.rstrip("\n")) for line in file] expense_report = file_lines_as_int_list("day_...
49aaef07cab49fa936334a332f3dd3375e60ea62
mduda18/mynewrepository
/ex2.py
141
4.125
4
print " find sum of all multiples of 3 or 5 below 1000" sum=0 for x in range(1000): if (x % 3==0 or x % 5==0): sum +=x print sum
3a83c339d094157e707576451da0cfe987516575
vimalkkumar/Basics-of-Python
/Strings.py
711
4.125
4
print("Hello World!!!!!") print('Hello World!!!!!') print("Hello" + ' ' + "World") print("Hello" + "World") # Comment line print(75+12) print(12*12) print(12/2) print(55-5) splitStringDoubleQuote = """Hi, My self Vimal Kumar, CTO at DeScite. And I am from Kanpur India So, let's talk about little bit more about python""...
9737cd823d94a2241e49566c9c65a3c9a8e6a9ad
vimalkkumar/Basics-of-Python
/Range.py
1,492
4.15625
4
# print('Hello World') # # print(range(10)) # # # for even in range(0, 100, 2): # # print(even) # # even = list(range(0, 10, 2)) # print(even) # # # for odd in range(1, 100, 2): # # print(odd) # # odd = list(range(1, 10, 2)) # print(odd) # alphabets = 'abcdefghijklmnopqrstuvwxyz' # print(alphabets) # # print(a...
80fd68117c0924d2fa7a1bf75ace34ac29f80ee1
vimalkkumar/Basics-of-Python
/PrimeOrNot.py
476
4
4
def main(): # print('Hello World') def prime(num): for i in range(2, num // 2): if num % i == 0: print("{} is not a prime number".format(num)) break else: print("{} is a prime number".format(num)) number = int(input("Please, Enter a n...
ef993a975f96b1d1c0da6520decbb67719ea4f00
vimalkkumar/Basics-of-Python
/Inheritance.py
349
4.0625
4
class Date(object): # Inherits the object Class def get_date(self): return "2019-05-07" class Time(Date): # Inherits from the Date class def get_time(self): return "07:21 AM" date = Date() print(date.get_date()) time = Time() print(time.get_time(), time.get_date()) # ...
f729637591b870faa4159ff3c56b3f191b07e583
bnesposito/urban-transport-lima
/code/config.py
2,173
3.71875
4
import logging import time def config_logger(name, level=10): """ Config logger output with level 'level'. Args: name (str): name of the logger. level (int): level of severity displayed. Returns: object: configured logger. """ logging.basicConfig(level = level, format = '...
bd4ccb1642b75a5046530e9c5dad0efdd9db0c15
gueets/Projetos-da-faculdade
/Exame/Q4.py
230
4.0625
4
import math g = float(input('Digite valor para G: ')) f = float(input('Digite valor para F: ')) d = math.sqrt((g**2)+(f**2))/(5*g*f) print('\nEntradas:\ng: ', "%.3f" % g, '\nf:',"%.3f" % f) print('\nSaída: \nD = ', "%.3f" % d)
e00e801ceb8955c55366aa5f2f77d7a2213b0a33
jpryzby/Spiral-Pattern
/SpiralPattern.py
423
3.625
4
import turtle import random screen=turtle.Screen() screen.bgcolor("black") pen= turtle.Turtle() pen.speed(0) pen.tracer(100,100) size = 10 while(True): red = random.randint(0,255) green =random.randint(0,255) blue = random.randint(0,255) pen.color(red,green,blue) pen.forward(size) pen.right(45) pen...
32eef2127bbc86a7bec6598e8ecf594f1c6deecf
lf-coder/python
/01-basicLearning/04-数据类型.py
273
4.15625
4
""" 1.python的变量虽然没有类型,但是变量还是有数据类型 2.这里先简单的说int,float和bool """ """转换""" print(int('20')) print(float('20.5')) print(str(20) + str(20)) """获取数据的类型""" print(type(True)) print(isinstance(20, int))
7e0e8491328ac3581174a6f37b0646ac86535cbc
lf-coder/python
/01-basicLearning/06-数组.py
810
3.953125
4
""" 1.python中的数组和js中的数组一样,作用和java的链表差不多 2.方法:append、extend、insert 3.删除:arr.remove(元素)、del 数组/数组[index] 、arr.pop() 4.分片:arr[index1:index2] 前闭后开,返回原数组的浅拷贝 5.+号可以连接两个数组、*可以将数组元素复制、in和not in可以判断元素是否在数组中 6.dir可以查看对象的结构 """ arr = ['hello', 'world', 12, ['1', '2']] print(arr) arr.append('hello world') print(arr) arr.extend(...
fce2a6cef91fed7fb4278b9969e308e2744b31c0
Nathan575/KindleSearcher
/Searching-Files/KindleSearcher.py
2,829
3.734375
4
import csv from Book import Book file = "Kindle_Book_Dataset.csv" books = [] go_on = "y" with open(file) as myFile: kindle = csv.reader(myFile) for row in kindle: books.append(Book(row[0], row[1], row[2], row[3], row[14])) while go_on == "y" or go_on == "Y" or go_on == "ye" or go_on == "Ye" or "ye" ...