blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
88e8a541384d5011d840f7ed7745897a0a98b317 | prabhupavitra/NumPy-Guide-for-Data-Science | /pyFiles/NumPyCodeFiles_Basic Array Manipulation.py | 11,449 | 3.671875 | 4 | # Importing required libraries
import numpy as np
from datetime import datetime
import matplotlib.pylab as plt
# Creating 1D, 2D and 3D arrays
# One-Dimensional Array
one_dim_array = np.random.randint(12, size=7)
# Two-Dimensional Array
two_dim_array = np.array([["Cupcake","Donut"],
["Eclair","Froyo"],
["Gingerbread","Honeycomb"],
["Ice Cream Sandwich","Jelly Bean"],
["KitKat","Lollipop"],
["Marshmallow","Nougat"],
["Oreo","Pie"]])
# Three-Dimensional Array
three_dim_array = np.array([[["Civic","Accord","Pilot","FR-V"],
["Odyssey","Jazz","CR-V","NSX"]],
[["Insight","Ridgeline","Legend","HR-V"],
["Passport","S660","Clarity","Mobilio"]],
[["Airwave","Avancier","Beat","Shuttle"],
["Concerto","Element","Logo","Stream"]]])
# Array Indexing
# 1D Array Indexing
print("Original 1D array :\n{}\n".format(one_dim_array))
print(f'9th item can be indexed by one_dim_array[4]: {one_dim_array[4]}')
print(f'one_dim_array[-3]: {one_dim_array[-3]}')
# 2D Array Indexing
print("Original 2D array :\n{}\n".format(two_dim_array))
print(f'5th row,2nd column can be indexed by two_dim_array[4,1]: {two_dim_array[4,1]}')
print(f'Using Negative indexing, two_dim_array[-3,-1]: {two_dim_array[-3,-1]}')
# 3D Array Indexing
print("Original 3D array :\n{}\n".format(three_dim_array))
print(f'2nd slab, 1st row, 3rd column can be indexed by three_dim_array[1,0,2]: {three_dim_array[1,0,2]}')
print(f'Using Negative indexing, three_dim_array[-2,-2,-2]: {three_dim_array[-2,-2,-2]}')
# Array Slicing
# 1D Array Slicing (Format -> start:stop:step)
print("Original 1D array :\n{}\n".format(one_dim_array))
# Some common examples of 1D array slicing; Starting at 0 and stop is exclusive
print(f"First 3 elements :{one_dim_array[:3]}")
print(f"Last 4 elements :{one_dim_array[-4:]}")
print(f"Elements from 2,3,4,5 :{one_dim_array[2:6]}")
print(f"Alternating Elements 1,3,5 :{one_dim_array[0:6:2]}")
print(f"Reversed array :{one_dim_array[::-1]}")
# 2D Array Slicing
print("Original 2D array :\n{}\n".format(two_dim_array))
print(f"Second column elements :\n{two_dim_array[:,1:]}")
# print(f"Second column elements :\n{two_dim_array[:,-1:]}")
print(f"Fourth row elements :\n{two_dim_array[3:4,:]}")
print(f"Fourth row elements till end of array :\n{two_dim_array[3:,:]}")
print(f"Alternating even rows :\n{two_dim_array[::2,:]}")
print(f"Alternating odd rows :\n{two_dim_array[1::2,:]}")
print(f"Reversed array :\n{two_dim_array[::-1,::-1]}")
# 3D Array Slicing
print("Original 3D array :\n{}\n".format(three_dim_array))
print(f"Alternating slabs :\n{three_dim_array[::2,:,:]}")
print(f"Alternating odd rows of all slabs :\n{three_dim_array[::,1::2,:]}")
print(f"Alternating odd columns of all slabs :\n{three_dim_array[::,::,::2]}")
# Negative Indexing
print(f"Alternating slabs :\n{three_dim_array[-3::2,:,:]}")
print(f"Alternating odd rows of all slabs :\n{three_dim_array[::,-1::2,:]}")
print(f"Alternating odd columns of all slabs :\n{three_dim_array[::,::,::-2]}")
# Reversed
print(f"Reversed 3D array :\n{three_dim_array[::-1,::-1,::-1]}")
# Creating Copies of Arrays
# Case 1 : Using "=" sign to create a reference of the original array
ref_two_dim_array = two_dim_array[:,:]
# Changing value of one of the array elements will change original array
ref_two_dim_array[3,0] = "Pie Android"
# All cell values are True; Changing value of referenced array changed the original array
ref_two_dim_array == two_dim_array
# Reinitializing Original array
two_dim_array = np.array([["Cupcake","Donut"],
["Eclair","Froyo"],
["Gingerbread","Honeycomb"],
["Ice Cream Sandwich","Jelly Bean"],
["KitKat","Lollipop"],
["Marshmallow","Nougat"],
["Oreo","Pie"]])
# Case 2 :Creating copy of the array using copy()
copy_two_dim_array = two_dim_array[:,:].copy()
copy_two_dim_array[3,0] = "Pie Android"
# Created a copy and hence the original array did not change
copy_two_dim_array == two_dim_array
# Reshaping Arrays
"""
>> Using reshape function
>> Raveling and Flattening : Collapsing a multi-dim array to 1D array
>> Adding dimensions to an array using np.newaxis
>> Repeating elements or as tiles
>> Joining Arrays using concatenate, stack, vstack, hstack and dstack
>> Permuting Dimensions of arrays
>> Swapping Axes of an array using transpose
>> Splitting Arrays using split, vsplit, hsplit and dsplit
>> Finding array Diagonals using np.diagonal
"""
# Lets consider a Random 3D integer array
threedim_arr = np.random.randint(1,50,(3,4,5))
# Using reshape() to change the shape of the array
threedim_arr.reshape(5,1,12)
# Raveling
"""
Raveling : Returns a contiguous flattened array;
Default order 'C'(Also called Column Major which means it will Traverse Higher dimension first)
Order 'F' (Also called Row Major which means Traverses higher dimensions last)
>> It is a library-level function
>> Creates a reference/view of original array ; Faster than flatten
"""
# Using ravel() ; Default order 'C' :
threedim_arr.ravel() # Uses default order of 'C'
threedim_arr.ravel('F') # axis 0 before advancing on axis 1
# Flattening
"""
Flattening : Same as Raveling other than those listed below,
>> ndarray object method
>> It creates copy of original and thus occupies memory; hence slower
"""
# Using flatten()
threedim_arr.flatten()
threedim_arr.flatten('F')
# Adding dimensions to an array
# Reshapes array of (x,y,z) shape to (1,x,y,z)
print(f'\n\tShape of array threedim_arr[np.newaxis,:].shape : {threedim_arr[np.newaxis,:].shape}')
# Reshapes array of (x,y,z) shape to (x,1,y,z)
print(f'\n\tShape of array threedim_arr[:,np.newaxis].shape : {threedim_arr[:,np.newaxis].shape}')
# Repeating individual elements and tiles
# Repeating Individual elements
threedim_arr.repeat(2) # Repeats elements twice and array is flattened
threedim_arr.repeat(2,axis=0) # Repeats slabs twice
# Repeating whole array or rows/columns/slabs without collapsing structure
# Repeats over axis 2
threedim_arr.repeat(2,axis=2)
# Repeats slabs; For a 3D array of shape (3,y,z)
threedim_arr.repeat([1,2,3],axis=0)
# Repeats rows; For a 3D array of shape (x,4,z)
threedim_arr.repeat([1,2,3,4],axis=1)
# Repeats columns ; For a 3D array of shape (x,y,5)
threedim_arr.repeat([1,2,3,4,5],axis=2)
# Repeating Specified array as a tile using np.tile(array,reps)
# Case 1: When Array dim is greater than reps dim
np.tile(threedim_arr,2)
# is same as np.tile(threedim_arr,(1,1,1,2))
np.tile(threedim_arr,(2,2))
# is same as np.tile(threedim_arr,(1,2,2))
np.tile(threedim_arr,(1,2))
# is same as np.tile(threedim_arr,(1,1,2))
# Case 2: When reps dim is greater than array dim; arr is promoted to 2D
np.tile(np.array([1,2,3]),(2,3))
# is same as np.tile(np.array([[1,2,3]]),(2,3))
# Concatenating arrays using np.concatenate
# Concatenating a 1D array
print(f'\nConcatenating 1D arrays: \
{np.concatenate((np.ones(4),np.zeros(3)))}')
# Concatenating a 2D array
# For more info please visit : https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.dtypes.html
# Lets load a datafile of Crude oil prices and the date on which it was recorded
# Use the path of your dataset
arr_one = np.loadtxt("/Users/pavitragajanana/development/2. Data Files/CrudeOil_Daily_Cushing_OK_WTI_Spot_Price_FOB.csv",
dtype={'names':('Day','WTISpotPrice'),
'formats':('<U12','f4')},
delimiter=",",
skiprows=1, # Header
usecols=(0,1))
# unpack=True
# Convert into an ndarray and parsing "Day" to datetime format
arr_one = np.array([[day,nominal] for (day,nominal) in arr_one])
arr_two = np.array([datetime.strptime(x, "%m/%d/%y").strftime('%Y-%m-%d') for x in arr_one[:,0]])
# Concatenating a 2D array with a 1D array of similar shape except for concatenating axis
concat_arr = np.concatenate([arr_one,arr_two[:,np.newaxis]],axis=1)
# Using stack,vstack,hstack and dstack
# Using vstack ; which will stack row-wise i.e. concatenate with axis 0
concat_vstack = np.vstack([arr_one.T,arr_two[np.newaxis,:]]).T
# is same as np.stack([arr_one,arr_two],axis=0)
# Using hstack ; which stacks column-wise i.e. concatenate with axis 1
concat_hstack = np.hstack([arr_one,arr_two[:,np.newaxis]])
# Using dstack ; which stacks depth-wise i.e. concatenate with axis 2
concat_dstack = np.dstack([arr_one[:,0],arr_two,arr_one[:,1]])
# 3D array
# Lets load an image to work with 3D array
img_arr = plt.imread("/Users/pavitragajanana/development/5. InternalFiles/Image1.jpg")
img_dup = img_arr.copy()
np.concatenate([img_arr,img_arr],axis=0)
## Transposing arrays
"""
An array with shape (w,x,y,z) will have a shape (z,y,x,w) when transposed
"""
threedim_arr.T
## Axes Swapping using transpose()
""" For higher dimensional arrays, transpose will accept
a tuple of axis numbers to permute the dimensions of the array """
# Original Array has shape (0,1,2)
# Transpose (2,1,0) has the same shape as threedim_arr.T
threedim_arr.transpose((2,1,0))
# Useful for permuting the axes for higher dimensional arrays
threedim_arr.transpose((1,2,0))
## Splitting arrays
"""Split an array into multiple sub-arrays
>> np.split
>> np.hsplit is same as np.split(axis=1)
>> np.vsplit is same as np.split(axis=0)
>> np.dsplit is same as np.split
"""
# Lets create a 3D array
periodic_table = np.array([[["Hydrogen","Helium","Lithium","Beryllium"],
["Boron","Carbon","Nitrogen","Oxygen"],
["Flourine","Neon","Sodium","Magnesium"]],
[["Aluminium","Silicon","Phosphorus","Sulfur"],
["Chlorine","Argon","Potassium","Calcium"],
["Scandium","Titanium","Vanadium","Chromium"]],
[["Manganese","Iron","Cobalt","Nickel"],
["Copper","Zinc","Gallium","Germanium"],
["Arsenic","Selenium","Bromine","Krypton"]]])
# Using split,vsplit,hsplit and dsplit
# np.vsplit splits array along axis 0
print(f'{np.vsplit(periodic_table,[1,2])}')
print(f'{np.split(periodic_table,[1,2],axis=0)}')
# np.hsplit splits array along axis 1
print(f'{np.hsplit(periodic_table,[1,2])}')
print(f'{np.split(periodic_table,[1,2],axis=1)}')
# np.dsplit splits array along axis 2
print(f'{np.dsplit(periodic_table,[2])}')
print(f'{np.split(periodic_table,[2],axis=2)}')
# Finds the diagonal elements of an array; np.diagonal(offset,axis1,axis2)
"""
a(i,i) gives diagonal elements of an array; offset is applied on axis 2
For higher dimensions, 2D subarray is made of axis 1 and 2 passed in the input
a(i,i+offset) offsets diagonal elements on axis 2;
"""
arr_diagonal = np.arange(48).reshape(4,3,4)
print(f'Original array :\n {arr_diagonal}')
# Diagonal array with axis 2 and axis 0; offsetting axis 0 by 1
# [(1,0)(2,1)(3,2)] for each of the axis 1 rows
print(f'\nDiagonal array :\n\n{arr_diagonal.diagonal(1,2,0)} ')
|
d338e529b9a38f19cefceb736106ce5c09b9b6f6 | sean7130/pseudo-encryption-toys | /solitaireEncryptionFinal/chiper_cli.py | 1,850 | 3.578125 | 4 | import sys
import argparse
import chiper
from generateKeyStream import generate_keystream
parser = argparse.ArgumentParser(description='Encrpyt or decrypt using a (simulated) deck of cards')
parser.add_argument('--verbose', "-v", action='store_true', help='verbose mode')
parser.add_argument('mode', choices=["e", "encrypt", "d", "decrypt"],
help='the mode the program should execute in. e/encrypt \
for encrypting text, d/decrypt for decrypting')
parser.add_argument('seed', help='the seed used to encrypt and decrypting \
(you can treat as password)')
parser.add_argument('--infile', nargs='?', metavar='filename',
help='text file input, use this option to omit writing on \
the command line')
parser.add_argument('--outfile', nargs='?', type=argparse.FileType('w'),
metavar='filename', default=sys.stdout, help="output file,\
if unspecified, the program writes to stdout instead")
parser.add_argument('text', nargs="*", help="text to be encrypted/decrypted")
args = parser.parse_args()
if args.mode == 'e' or args.mode == 'encrypt':
do_decrypt = False
else:
do_decrypt = True
if args.verbose:
if do_decrypt:
print("program mode set to decrypt.")
else:
print("program mode set to encrypt.")
print(args)
print(args.mode)
print(args.seed)
print(args.text)
ks = generate_keystream(94, args.seed)
# determine to read text from commandline or from file
if (args.infile):
in_file = open(args.infile, "r")
text = []
for line in in_file.readlines():
# remove the newline in the end
text.append(line[:-1])
else:
text = [" ".join(args.text)]
for line in text:
args.outfile.write(chiper.chiper(ks, line, do_decrypt)+"\n")
|
d9560432ec966b017ec8790bca44002d1f4aef4c | SanjibM99/sorting | /mergesort .py | 807 | 3.859375 | 4 | def mergesort(arr):
if len(arr)>1:
mid=len(arr)//2
#print(arr[mid])
lefthalf=arr[:mid]
righthalf=arr[mid:]
#print(lefthalf,righthalf)
mergesort(lefthalf)
mergesort(righthalf)
i=j=k=0
while i<len(lefthalf) and j<len(lefthalf):
if lefthalf[i]<righthalf[j]:
arr[k]=lefthalf[i]
i=i+1
k=k+1
else:
arr[k]=righthalf[j]
j=j+1
k=k+1
while i<len(lefthalf):
arr[k]=lefthalf[i]
i=i+1
k=k+1
while j<len(righthalf):
arr[k]=righthalf[j]
j=j+1
k=k+1
arr=[5,11,2,178,3,111]
mergesort(arr)
print(arr) |
122df6cd441049257b3ac6dde2c4664335d507d0 | Aashray24092000/programmingpython | /PartV_ToolsTechniques/datastructures_lib/sort.py | 970 | 3.515625 | 4 | def sort(list, field):
res = []
for x in list:
i = 0
for y in res:
if x[field] <= y[field]:
break
i += 1
res[i:i] = [x]
return res
def sort_generic(sequence, func=(lambda x,y: x <= y)):
res = sequence[:0]
for j in range(len(sequence)):
i = 0
for y in res:
if func(sequence[j], y):
break
i += 1
res = res[:i] + sequence[j:j+1] + res[i:]
return res
def testSort():
table = [{'name':'john', 'age':25}, {'name':'doe', 'age':32}]
print(sort(table, 'name'))
print(sort(table, 'age'))
table = [('john', 25), ('doe', 32)]
print(sort(table, 0))
print(sort(table, 1))
def testSortGeneric():
table = ({'name': 'doe'}, {'name': 'john'})
print(sort(list(table), (lambda x, y: x['name'] > y['name'])))
print(sort(tuple(table), (lambda x, y: x['name'] <= y['name'])))
print(sort('xybaz'))
|
e5feb9d5ea514583b80c2df2c61e76158929c81f | zrjaa1/Berkeley-CS9H-Projects | /Project2B_Basic web programming/find_all.py | 583 | 4.3125 | 4 | # Function Name: find_all
# Function Description: In a string, find the position of all the substrings.
# Function Input:
# -a_str: the string's name
# -sub: sub string that we are searching for
# Function Output:
# -a list that record all the start indexs of the sub string.
import string
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub) # use start += 1 to find overlapping matches
print list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]
|
c27f36149a3209128032cc147e3159d67d57a394 | GalyaBorislavova/SoftUni_Python_OOP_June_2021 | /3_inheritance/Lab/6_Stacks_of_strings.py | 565 | 3.75 | 4 | class Stack:
def __init__(self):
self.data = []
def push(self, element):
self.data.append(element)
def pop(self):
return self.data.pop()
def top(self):
return self.data[-1]
def is_empty(self):
if len(self.data) > 0:
return False
return True
def __str__(self):
return f"[{', '.join(reversed(self.data))}]"
custom_s = Stack()
custom_s.push("5")
custom_s.push("7")
custom_s.push("8")
custom_s.push("2")
print(custom_s.pop())
print(custom_s.is_empty())
print(custom_s)
|
c1dc89d5b76c9299942488ebdf65db36baa9a775 | Aswinraj-023/Python_CA-1 | /Assessment_1/Substitution_Cipher.py | 1,527 | 4.625 | 5 | #3) Substitution Cipher
encrypt="" # assigning encrypt variable to an empty string
decrypt="" # assigning decrypt variable to an empty string
string_1 = input("String 1 : ").upper() # getting plain text from user & converting to uppercase
string_2 = input("String 2 : ").lower() # getting encrypted text from user & converting to lowercase
letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] # creating a list of 26 alphabets in uppercase
code = ['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'] # creating a list of 26 alphabets in reverse order in lowercase
for i in string_1: #accessing each values of string_1
if i in letters: #if value in i is in 'letters'
index = letters.index(i) #accessing the index values in letters using index values of string_1
encrypt = encrypt + code[index] # encrypting the plain text
decrypt = decrypt + letters[index] #decrypting the encrypted text
if string_2==encrypt: #comparing if user's encrypted text is equal to the encrypted text found
print("String 2 is the encoded version of String 1") #if they are equal string_2 is the encoded text
else: # if they aren't equal string_2 is not encoded text
print("String 2 is not encoded version of String 1") #printing string_2 is not encoded text
print("Plain Text : ",string_1) # printing the plain text
print("Encrypted Text is : ",encrypt) # printing the encrypted text
|
d91e8e8fcc16d6e0bc8d407812c5c7f297404322 | zouzou6900/Python3.7 | /matrice.py | 256 | 3.59375 | 4 | import numpy as np
n = int(input("nombre de ligne : "))
m = int(input("nombre de colone : "))
a = np.arange(n*m).reshape(n,m)
i = 0
while i<n:
j=0
while j<m:
b=int(input("entre B :"))
a[i][j]= b
j+=1
i+=1
print(a)
|
7396584eacdc05f5b94255b144b4f9e0a0ad50de | heildever/leetcode | /python/easy/self-dividing-numbers.py | 659 | 3.890625 | 4 | # question can be found on leetcode.com/problems/self-dividing-numbers/
from Typing import List
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def isSelfDividing(num):
digits = set(str(num))
dividers = 0
if "0" in digits:
return False
for digit in digits:
if num % int(digit) == 0:
dividers += 1
return len(digits) == dividers
potentials = []
for num in range(left, right + 1):
if isSelfDividing(num):
potentials.append(num)
return potentials
|
2c73f3b3d3c558c41425f728dc96d8615423162b | TenzinJam/pythonPractice | /freeCodeCamp1/grids_and_loop.py | 497 | 3.65625 | 4 | #grid and nested loop is similar to js as well.
# "in" is the syntax equivalent to .includes in js.
number_grid = [
[1,2,3],
[4,5,6],
[7,8,9],
[0]
]
print(number_grid[0][0])
for row in number_grid:
for column in row:
print(column)
def translate(phrase):
translated = ""
for letter in phrase:
if letter in "aeiouAEIOU":
translated = translated + "g"
else:
translated = translated + letter
return translated
print(translate(input("Enter a phrase: ")))
|
25f1dea6646c218d213171f276cc0ceb47564371 | junjiezhou99/Python_Casa | /UF1_clase/binary.py | 346 | 4.03125 | 4 | def main():
decimal = int(input("introdueix el decimal"))
count=1
binary=0
while decimal!=0:
if decimal%2==0:
count*=10
decimal/=2
else:
binary+=count
count *= 10
decimal-=1
decimal/=2
print(binary)
if __name__ == '__main__':
main() |
9bfcbb3a694d3dd883a4ce26a6542199b949e89d | vladnire/jetbrains | /rock_paper_scissors.py | 2,220 | 3.921875 | 4 | import random
def get_score():
"""Enter name, read score file
Return the score if in file or 0 if not"""
player_name = str(input("Enter your name: "))
print(f"Hello, {player_name}")
scores_list = []
with open('rating.txt', 'r') as f:
scores_list = f.read().splitlines()
for line in scores_list:
if player_name in line:
return int(line.split(' ')[1])
return 0
def get_options():
"""Get game options"""
options = str(input())
if options:
options = options.split(',')
else:
options = ["scissors", "paper", "rock"]
print("Okay, let's start")
return options
def user_input(options):
"""Get user input and check if it's valid"""
player_choice = str(input())
valid_choices = options[::]
valid_choices.append('!exit')
valid_choices.append('!rating')
if player_choice not in valid_choices:
return "Invalid input"
return player_choice
def check_result(player, options):
"""Choose an option for computer and return number of points"""
default_options = ["scissors", "paper", "rock"]
computer = random.choice(options)
if options == default_options:
loose = {
"rock": "paper",
"scissors": "rock",
"paper": "scissors"
}
else:
loose = {}
for n, i in enumerate(options):
loose[i] = (options[n + 1:] + options[:n])[:(len(options) // 2) + 1]
if player == computer:
print(f"There is a draw ({player})")
points = 50
elif player in loose[computer]:
print(f"Well done. The computer chose {computer} and failed")
points = 100
else:
print(f"Sorry, but the computer chose {computer}")
points = 0
return points
if __name__ == "__main__":
score = get_score()
game_options = get_options()
while True:
user = user_input(game_options)
if user == "Invalid input":
print(user)
elif user == '!exit':
break
elif user == "!rating":
print(f"Your rating: {score}")
else:
score += check_result(user, game_options)
print("Bye!")
|
e67ae2f1772b5aacf33a79a8a72e8f40bb774acf | smohapatra1/scripting | /python/practice/start_again/2020/12082020/generate_two_random_nums.py | 266 | 3.8125 | 4 |
#Problem 2
#Create a generator that yields "n" random numbers between a low and high number (that are inputs).
import random
random.randint(1,10)
def num(low,high,n):
for i in range(n):
yield random.randint(low,high)
for x in num(1,10,12):
print (x) |
042f568b741300491e3c8e9208c3e76baf97bef7 | li-MacBook-Pro/li | /static/Mac/play/调用/字符串公共前缀.py | 662 | 3.59375 | 4 | def subString(strs):
result=strs[0]
for i in range(1,len(strs)):
while (strs[i].startswith(result)==False):
result=result[0:len(result)-1]
if len(result)==0:
return "无公共前缀"
return result
try:
while 1:
a = input('请输入字符串,用空格隔开:')
a = a.split()
result = subString(a)
print(result)
except:
pass
# def longstCommonPrefix(*strs):
# import os
# return os.path.commonprefix(strs)
# print(longstCommonPrefix('abcacc','abvasd','abaaa'))
# while True:
# try:
# for i in range(len(n)):
# if n[i][j]!=n |
9a118191b74242f2dfd2683e860cb17193f2eab3 | AaronGoyzueta/Re.search-Loop | /re_search_loop.py | 581 | 3.578125 | 4 | # Function for re.search loop
import re
def main(exp, text):
cont = False
output = re.search(exp, text)
if output:
cont = True
lb = output.span()[0]
rb = output.span()[1]
print(output.span())
while cont:
new_output = re.search(exp, text[rb:])
if new_output:
lb += new_output.span()[1]
rb += new_output.span()[1]
print((lb, rb))
else:
cont = False
else:
print("None found") |
d6c5962ba4fe9cbfd6e091524ffcf642ab5cf852 | Sujan-Kandeepan/Exercism | /exercism/python/prime-factors/prime_factors.py | 358 | 4 | 4 | def prime_factors(num):
primes = []
factor = 2
while factor <= num:
if num % factor == 0 and num == factor:
primes.append(factor)
factor += 1
elif num % factor == 0 and num != factor:
primes.append(factor)
num = num // factor
else:
factor += 1
return primes
|
4b1c3e6773a01e1fb02fd4b58b15559e6d9fce22 | maybemichael/Graphs | /projects/ancestor/ancestor.py | 7,155 | 3.921875 | 4 | import collections
# Naive First Pass Iterative Solution
# def earliest_ancestor(ancestors, node):
# # we want the earliest ancestor aka the deepest ancestor so I will use a dfs search
# # loop through ancestors to create graph
# # standard dfs add starting node to stack
# # while stack isn't empty pop last
# # loop through parents adding them to a list
# # keep track of generations by using a 2d list and adding parents list into 2d list
# # get last list in 2d list and check count
# # if count is 2 compare which value is smaller
# stack = []
# dict = {}
# for parent, child in ancestors:
# if child not in dict:
# dict.setdefault(child, list([parent]))
# else:
# dict[child].append(parent)
# print(dict)
# stack.append(node)
# generations = []
# while stack:
# child = stack.pop()
# parents = []
# if child in dict:
# for parent in dict[child]:
# if parent in dict:
# stack.append(parent)
# if len(parents) < 2:
# parents.append(parent)
# generations.append(parents)
# print(f"Parents: {generations}")
# else:
# generations.append(parents)
# break
# earliest_gen = generations[-1]
# print(f"Earliest gen: {earliest_gen}")
# earliest_ancestor = None
# if len(earliest_gen) is 0:
# return -1
# else:
# for parent in earliest_gen:
# if earliest_ancestor is None:
# earliest_ancestor = parent
# if parent < earliest_ancestor:
# earliest_ancestor = parent
# print(f"Earliest Ancestor: {earliest_ancestor}")
# return earliest_ancestor
# Second Pass Recursive Solution
# def earliest_ancestor(ancestors, node, dict=None, generations=None):
# if dict is None:
# dict = {}
# generations = []
# for parent, child in ancestors:
# if child not in dict:
# dict.setdefault(child, list([parent]))
# else:
# dict[child].append(parent)
# if node in dict:
# if len(dict[node]) is 2:
# smallest = dict[node][0]
# if dict[node][1] < smallest:
# smallest = dict[node][1]
# generations.append(smallest)
# if dict[node][0] in dict:
# return earliest_ancestor(ancestors, dict[node][0], dict, generations)
# if dict[node][1] in dict:
# return earliest_ancestor(ancestors, dict[node][1], dict, generations)
# else:
# generations.append(dict[node][0])
# if dict[node][0] in dict:
# return earliest_ancestor(ancestors, dict[node][0], dict, generations)
# else:
# generations.append(-1)
# return generations[-1]
# 3rd Pass Recursive Solution Accounting for some edge cases
# def earliest_ancestor(ancestors, node, dict=None, generations=[]):
# if dict is None:
# dict = {}
# for parent, child in ancestors:
# if child not in dict:
# dict.setdefault(child, list([parent]))
# else:
# dict[child].append(parent)
# if node in dict:
# if len(dict[node]) is 2:
# if dict[node][0] < dict[node][1]:
# generations.append(dict[node][0])
# else:
# generations.append(dict[node][1])
# if dict[node][0] and dict[node][1] in dict:
# earliest_ancestor(ancestors, dict[node][0], dict, generations)
# return earliest_ancestor(ancestors, dict[node][0], dict, generations)
# elif dict[node][0] in dict and dict[node][1] not in dict:
# return earliest_ancestor(ancestors, dict[node][0], dict, generations)
# elif dict[node][1] in dict and dict[node][0] not in dict:
# return earliest_ancestor(ancestors, dict[node][1], dict, generations)
# else:
# generations.append(dict[node][0])
# if dict[node][0] in dict:
# return earliest_ancestor(ancestors, dict[node][0], dict, generations)
# else:
# generations.append(-1)
# return generations[-1]
# 4th pass just restructured existing code from 3
# def earliest_ancestor(ancestors, node, dict=None, generations=[]):
# if dict is None:
# dict = {}
# for parent, child in ancestors:
# if child not in dict:
# dict.setdefault(child, list([parent]))
# else:
# dict[child].append(parent)
# if node not in dict:
# generations.append(-1)
# elif len(dict[node]) is 1:
# generations.append(dict[node][0])
# if dict[node][0] in dict:
# return earliest_ancestor(ancestors, dict[node][0], dict, generations)
# else:
# if dict[node][0] < dict[node][1]:
# generations.append(dict[node][0])
# else:
# generations.append(dict[node][1])
# if dict[node][0] and dict[node][1] in dict:
# earliest_ancestor(ancestors, dict[node][0], dict, generations)
# return earliest_ancestor(ancestors, dict[node][0], dict, generations)
# elif dict[node][0] in dict and dict[node][1] not in dict:
# return earliest_ancestor(ancestors, dict[node][0], dict, generations)
# elif dict[node][1] in dict and dict[node][0] not in dict:
# return earliest_ancestor(ancestors, dict[node][1], dict, generations)
# return generations[-1]
# My dfs solutions passed the test but did not account for some edge cases
# After a little advice from a friend implemented a bfs solution
# Fifth Pass Solution Breadth First Search
def earliest_ancestor(ancestors, node):
dict = {}
generations = []
for parent, child in ancestors:
if child not in dict:
dict.setdefault(child, list([parent]))
else:
dict[child].append(parent)
queue = collections.deque([])
queue.append(node)
if node not in dict:
return -1
while queue:
child = queue.popleft()
if child in dict:
if len(dict[child]) is 2:
queue.append(dict[child][0])
queue.append(dict[child][1])
if dict[child][0] < dict[child][1]:
generations.append(dict[child][0])
else:
generations.append(dict[child][1])
elif len(dict[child]) is 1:
queue.append(dict[child][0])
generations.append(dict[child][0])
else:
generations.append(-1)
return generations[-1]
test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]
# test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1), (20, 4), (21, 20)]
# print(earliest_ancestor(test_ancestors, 6)) # should be 21
print(earliest_ancestor(test_ancestors, 9)) |
1a5a1016bf26263dc56c7b94a07d4329a553a6d1 | dishant470266/hacker_rank | /add_list_append.py | 1,171 | 4.25 | 4 | # fruits = ['banana','apple']
# fruits.append('mango')
# print(fruits)
#=======================================
#more method to add data
# fruits1 = ['banana','apple']
# fruits1.insert(1,'mango')
# print(fruits1)
#========================================
#extend_method
# fruits1 = ['banana','mango']
# fruits2 = ['grapes','orange']
# fruits1.extend(fruits2)
# print(fruits1)
# print(fruits2)
#======================================
#delete_method using pop
# fruits = ['banana', 'mango', 'grapes', 'orange']
# fruits.pop(1)
# print(fruits)
#=================================
#in_keyword chck list present or not
# fruits = ['banana', 'mango', 'grapes', 'orange']
# if 'mango' in fruits:
# print('present')
# else:
# print('not present')
# print(fruits)
#=================================================
#count_method
# fruits = ['banana', 'mango', 'grapes', 'orange','apple','mango']
# print(fruits.count('mango'))
#=====================================================
#sort_method
fruits = ['banana', 'mango', 'grapes', 'orange','apple','mango']
fruits.sort()
print(fruits)
|
7e7272784e386b9912ad1c3560b5d23f84e0d568 | dorianivc/Introduccion_al_pensamiento_computacional_python | /busqueda_binaria_de_una_raiz_cuadrada.py | 465 | 3.765625 | 4 | objetivo =int(input('Escoge un numero: '))
epsilon = 0.01
bajo=0.0
alto= max(1.0, objetivo)
respuesta = (alto + bajo)/2
print(f'La raiz cuadradra de {objetivo} es: {respuesta}')
while abs(respuesta**2 -objetivo)>= epsilon:
print(f'bajo={bajo}, alto={alto}, respuesta={respuesta}')
if respuesta**2 <objetivo:
bajo=respuesta
else:
alto=respuesta
respuesta= (alto + bajo) / 2
print(f'La raiz cuadradra de {objetivo} es: {respuesta}') |
e07f111905f7082b464f7c6b8fbf84ed756f5f4a | Alwayswithme/LeetCode | /Python/054-spiral-matrix.py | 889 | 4.28125 | 4 | #!/bin/python
#
# Author : Ye Jinchang
# Date : 2015-06-17 13:57:41
# Title : 54 spiral matrix
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
#
# For example,
# Given the following matrix:
#
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
#
# You should return [1,2,3,6,9,8,7,4,5].
class Solution:
# @param {integer[][]} matrix
# @return {integer[]}
def spiralOrder(self, matrix):
spiral = []
try:
while True:
spiral += matrix.pop(0)
for i in range(len(matrix)):
spiral.append(matrix[i].pop(-1))
spiral += reversed(matrix.pop(-1))
for i in range(len(matrix) - 1, -1, -1):
spiral.append(matrix[i].pop(0))
except:
pass
return spiral
|
ae96224e3deb544565a19f354a704e103094ee77 | MrZakbug/MITx-6.00.1x | /Midterm Exam/Problem 4.py | 716 | 3.84375 | 4 | def closest_power(base, num):
'''
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return the smaller value.
Returns the exponent.
'''
exponent = 0
result = 0
previousResult = 0
while result < num:
previousResult = base ** (exponent - 1)
result = base ** exponent
exponent += 1
if abs(num - previousResult) > abs(num - result):
return exponent - 1
else:
return exponent - 2
print(closest_power(4, 62)) # example |
cee24afff7c23fee28b3ffc1c9e054c9a9662383 | AaronTho/Python_Notes | /for_loops.py | 337 | 4.125 | 4 | # for item in 'Python':
# print(item)
# for item in ['Aaron', 'John', 'Sarah']:
# print(item)
# for item in [1, 2, 3, 4]:
# print(item)
# for item in range(5, 10, 2):
# print(item)
'''
Shopping Cart price project
'''
prices = [10, 20, 30]
total = 0
for price in prices:
total += price
print(f'Total: {total}')
|
7ea557b614c2cfd4a0576d3c6e244ed25d7d017e | ManoVikram/The-Turtle-Crash | /car_manager.py | 880 | 3.84375 | 4 | from turtle import Turtle
import random, time
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
super(CarManager, self).__init__()
self.allCars = []
self.carSpeed = STARTING_MOVE_DISTANCE
def createNewCars(self):
randomCance = random.randint(1, 6)
if randomCance == 1:
newCar = Turtle("square")
newCar.penup()
newCar.shapesize(stretch_len=2, stretch_wid=1)
newCar.color(random.choice(COLORS))
randomY = random.randint(-250, 250)
newCar.goto(300, randomY)
self.allCars.append(newCar)
def moveCars(self):
for car in self.allCars:
car.backward(self.carSpeed)
def levelUp(self):
self.carSpeed += MOVE_INCREMENT
|
c2b233e53b3894dfe32be70223f9b2053b56478d | Mark24Code/Leetcode-200 | /53.py | 781 | 3.59375 | 4 | # 输出版
nums = [-2,1,-3,4,-1,2,1,-5,4]
max_sum = nums[0]
cur_sum = nums[0]
for i in range(1, len(nums)):
if nums[i] > cur_sum + nums[i]:
cur_sum = nums[i]
else:
cur_sum = cur_sum + nums[i]
if max_sum < cur_sum:
max_sum = cur_sum
print(max_sum)
# 类版
# class Solution(object):
# def maxSubArray(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# max_sum = nums[0]
# cur_sum = nums[0]
# for i in range(1, len(nums)):
# if nums[i] > cur_sum + nums[i]:
# cur_sum = nums[i]
# else:
# cur_sum = cur_sum + nums[i]
# if max_sum < cur_sum:
# max_sum = cur_sum
#
# return max_sum |
fa2be65e4cb49d6f48c1e6d46e3ab5efd3ce4782 | JTamarit/Apuntes_clase_Python | /Actividades_Evaluables/Actividad_1/Actividad_1_2.py | 192 | 3.625 | 4 | nombre = str(input("\n Introduce un nombre: "))
edad = int(input("\n Introduce edad: "))
persona= dict(name= nombre, age= edad)
print(f"\n {persona['name']} tiene {persona['age']} años. \n")
|
0d305bdb36053c73e3237b6f11f52a84b2b9e938 | luoming1224/Data-mining | /K-Means/Point.py | 545 | 3.515625 | 4 | __author__ = '25691'
from math import hypot
class Point:
def __init__(self, x, y, className = None):
self.x = x
self.y = y
self.className = className
self.distance = 0
def computeDistance(self, p):
self.distance = hypot((self.x - p.x), (self.y - p.y))
# self.distance = (self.x - p.x) * (self.x - p.x) + (self.y - p.y) * (self.y - p.y)
if __name__ == '__main__':
point1 = Point(5.02, 4.01)
point2 = Point(4.01, 3.00)
point1.computeDistance(point2)
print point1.distance
|
26bf856be1aad4d09387867d3dfaa20245442a20 | supreman2/project_python | /сортировка_слиянием.py | 694 | 3.890625 | 4 | def merge(a:list, b:list):
c=[0]*(len(a)+len(b))
i=k=n=0
while i<len(a) and k<len(b):
if a[i]<=b[k]:
c[n]=a[i]; i+=1; n+=1
else:
c[n]=b[k]; k+=1; n+=1
while i<len(a):
c[n]=a[i]; i+=1; n+=1
while k<len(b):
c[n]=b[k]; k+=1; n+=1
return c
def merge_sort(a:list):
if len(a)<=1:
return
middle = len(a)//2
L=[a[i] for i in range(0, middle)]
R=[a[i] for i in range(middle, len(a))]
print("***")
print(L)
print(R)
merge_sort(L)
merge_sort(R)
print(L)
print(R)
c=merge(L,R)
for i in range(len(a)):
a[i]=c[i]
res = [4,2,3,5,1]
merge_sort(res)
print(res)
|
9f35029fa763c311d04307468d86a490da8ec4a1 | cmontalvo251/Python | /lockbox/lockbox_combo.py | 1,055 | 4.15625 | 4 | import numpy as np
##Ok I figured it out.
#We need a function that return the possible
#combinations of a set of digits but using recursion
# for example if the possibilities are '012'
# the possible combinations are [0 + combos('12'),1 + combos('02'),2 + combos('01')]
def combos(digits):
#First, all we do is loop through the keys
possibilities = []
for d in digits:
possibilities.append(d)
print('Pressing the ',d,' key')
remaining_digits = digits.replace(d,'')
print('Remaining Digits',remaining_digits)
#Then if there are remaining digits we need to loop through combinations
#of those keys but only if the length of the remaining digits is greater than
#1
if len(remaining_digits) >= 1:
possibilities.append(combos(remaining_digits))
return possibilities
##Let's test it
possible_digits = '012'
print('Possible Keys')
print(possible_digits)
#print('Possible Combinations')
possibilities = combos(possible_digits)
print(combos(possible_digits))
|
56665532c48b2be4e69fcbba3905441963fc2114 | hieuvanvoW04/Python | /In Class/261018_2.py | 208 | 3.859375 | 4 |
#enumeate
def hour():
hours=[8,1,13,1,4,7]
counter=1
for h in hours:
print(h)
print(counter)
counter=counter+1
print(f"I've done the {counter} times")
hour() |
f705d436ca78deee31f5de097c4f40cd4fc8d2b5 | RBeltran12358/RockPaperScissorsPython | /RPS.py | 4,055 | 4.03125 | 4 | import random
# 2/3 3/5 4/5
def main():
# declaring and initializing some variables
up_to = int(input("How many points do you want to play to? "))
comp_scr = 0
while up_to < 1:
up_to = int(input("Invalid Number of Games. How many points do you want to play to? "))
player_scr = 0
comp_options = ["rock", "paper", "scissor"]
comp = comp_options[random.randrange(0, 3, 1)]
play_again = True
print(False and True and True)
# print(type(i))
while play_again and comp_scr < up_to and player_scr < up_to:
i = input("rock, paper, or scissor? ")
while i != "rock" and i != "Rock" and i != "paper" and i != "Paper" and i != "Scissor" and i != "scissor":
i = input("Wrong Input, try again. rock, paper, scissor? ")
if i == "rock" or i == "Rock":
if comp == "rock":
print("Tie! Choose again:) ")
elif comp == "paper":
player_scr += 1
if player_scr != up_to:
print("Horray! You've won, " + str((up_to - player_scr)) + " more points to go!")
else:
comp_scr += 1
if comp_scr != up_to:
print("Close! the computer won this round. Don't let it get " + str(
(up_to - comp_scr)) + " more points! ")
elif i == "paper" or i == "Paper":
if comp == "paper":
print("Tie! Choose again:) ")
elif comp == "rock":
player_scr += 1
if player_scr != up_to:
print("Horray! You've won, " + str((up_to - player_scr)) + " more points to go!")
else:
comp_scr += 1
if comp_scr != up_to:
print("Close! the computer won this round. Don't let it get " + str(
(up_to - comp_scr)) + " more points! ")
else:
if comp == "scissor":
print("Tie! Choose again:) ")
elif comp == "paper":
player_scr += 1
if player_scr != up_to:
print("Horray! You've won, " + str((up_to - player_scr)) + " more points to go!")
else:
comp_scr += 1
if comp_scr != up_to:
print("Close! the computer won this round. Don't let it get " + str(
(up_to - comp_scr)) + " more points! ")
if comp_scr == up_to:
print("Oops! The computer seems to have won this one!")
again = input("Do you want to play again? y for yes , n for no ")
if again == "n":
play_again = False
#i = None
if again == "y":
comp_scr = 0
player_scr = 0
elif player_scr == up_to:
print("Yay you beat the computer!")
again = input("Do you want to play again? y for yes , n for no ")
if again == "n":
play_again = False
#i = None
if again == "y":
comp_scr = 0
player_scr = 0
print("Thank you for playing!")
"""
if comp_scr == up_to:
print("Oops! The computer seems to have won this one!")
again = input("Do you want to play again? y for yes , n for no ")
if again == "n":
play_again = False
i = None
if again == "y":
comp_scr = 0
player_scr = 0
elif player_scr == up_to:
print("Yay you beat the computer!")
again = input("Do you want to play again? y for yes , n for no ")
if again == "n":
play_again = False
i = None
if again == "y":
comp_scr = 0
player_scr = 0
else:
i = input("rock, paper or scissor? ")
comp = comp_options[random.randrange(0, 3, 1)]
"""
if __name__ == "__main__":
main()
|
e6f7c776442edeeaf6699ffcff800dfa4316f15e | ChosunOne/Python-Deep-Learning-SE | /ch02/chapter_02_001.py | 1,037 | 4.09375 | 4 | # The user can modify the values of the weight w
# as well as bias_value_1 and bias_value_2 to observe
# how this plots to different step functions
import matplotlib.pyplot as plt
import numpy
weight_value = 1000
# modify to change where the step function starts
bias_value_1 = 5000
# modify to change where the step function ends
bias_value_2 = -5000
print("Block function approximation with a neural network")
# plot the
plt.axis([-10, 10, -1, 10])
print("The step function starts at {0} and ends at {1}"
.format(-bias_value_1 / weight_value,
-bias_value_2 / weight_value))
inputs = numpy.arange(-10, 10, 0.01)
outputs = list()
# iterate over a range of inputs
for x in inputs:
y1 = 1.0 / (1.0 + numpy.exp(-weight_value * x - bias_value_1))
y2 = 1.0 / (1.0 + numpy.exp(-weight_value * x - bias_value_2))
# modify to change the height of the step function
w = 7
# network output
y = y1 * w - y2 * w
outputs.append(y)
plt.plot(inputs, outputs, lw=2, color='black')
plt.show()
|
4d9d78e521b1d2b02c740f720c6d5925373ac489 | ZubritskiyAlex/Python-Tasks | /hw_9/task 9_01.py | 419 | 4.15625 | 4 | """Дан список строк. Отформатировать все строки в формате {i}-{string}, где
i это порядковый номер строки в списке. Использовать генератор списков."""
list_of_string = [
"Ihar",
"Zeka",
"wolf",
"cat",
"dog"
]
print([f"{index} : {element}" for index, element in enumerate(list_of_string)])
|
3e316a18ba430281146d9895122aeee5d40b3f56 | DagnyTagg2013/CTCI-Python | /LIST/ReverseIt.py | 4,916 | 3.5625 | 4 |
import logging
# Reversing Linked List!
class Node:
def __init__(self, value):
self.value = value
# ATTN: to RESERVED syntax hilite!
self.nextPtr = None
def __repr__(self):
if (self is not None):
status = "Value and Next Ptr: {0}, {1}".format(self.value, self.nextPtr)
else:
status = "None"
return status
class List:
# ATTN: RESERVED hiliting for DOUBLE __!
# ATTN: front and end point to FIRST node-value!
# ATTN: self reference in signature and member assignment!
def __init__(self):
self.front = None
self.end = None
# ATTN: case of EMPTY list, then update BOTH state ptrs to be consistent!
def append(self, value):
if (self.front is None):
self.front = Node(value)
self.end = self.front
else:
newItem = Node(value)
self.end.nextPtr = newItem
self.end = newItem
def find(self, value):
foundPtr = None
scanPtr = self.front
while (scanPtr is not None):
if (scanPtr.value == value):
foundPtr = scanPtr
break
scanPtr = scanPtr.nextPtr
if (foundPtr is not None):
return foundPtr.value
else:
return None
# ATTN: lookbak needs tracking!
def remove(self, item):
lookbak = None
scanPtr = self.front
foundPtr = None
while (scanPtr is not None):
if (scanPtr.value == item):
foundPtr = scanPtr
break
#ATTN: track lookbak ptr!
lookbak = scanPtr
scanPtr = scanPtr.nextPtr
# print "FOUND and BAK: {0}:{1}", foundPtr, lookbak
# CASE 1: NOT FOUND
if (scanPtr is None) and (foundPtr is None):
foundPtr = None
# CASE 2: FOUND, first item of list
elif (lookbak is None) and (foundPtr == self.front):
# ATTN: unlink the FRONT
self.front = foundPtr.nextPtr
foundPtr.nextPtr = None
# CASE 3, 4: FOUND, middle item of list; or last item of list
elif (lookbak is not None):
# ATTN: UNLINK foundPtr via lookback to found.next connection!
lookbak.nextPtr = foundPtr.nextPtr
foundPtr.nextPtr = None
# ATTN: update END
if (foundPtr == self.end):
self.end = lookbak
return foundPtr
def display(self):
print '\nLIST CONTENTS: '
curr = self.front
# ATTN: end at None!
while (curr is not None):
print curr.value
# ATTN: iterate ptr or INFINITE LOOP -- DOH!
curr = curr.nextPtr
print '\n'
def reverse(self):
# ATTN: 3 ptrs,
# - PRE-INIT lookback, curr; OUTSIDE LOOP
# - DRIVE LOOP via CURRENT
# - @ BOTTOM LOOP: UPDATE lookbak, curr Ptrs!
# - @ TOP LOOP: UPDATE lookfwd!
lookbak = None
curr = self.front
# ATTN: UPDATE LATEST STATE REF POINTERS!
self.front = self.end
self.end = self.front
# ATTN: while
while (curr is not None):
lookfwd = curr.nextPtr
# ATTN: KEY operation here
curr.nextPtr = lookbak
# ATTN: UPDATE ITERATOR SCAN PTRS!
lookbak = curr
curr = lookfwd
# DRIVER
print 'CASE0: EMPTY LIST'
list0 = List()
list0.display() # ATTN: UPDATE LATEST STATE REF POINTERS!
print 'CASE1: ONE-ITEM LIST'
list1 = List()
list1.append(1)
list1.display()
print 'CASE2: THREE-ITEM LIST'
list1.append(2)
list1.append(3)
list1.display()
print 'CASE3: REVERSE LIST'
list1.reverse() # ATTN: UPDATE LATEST STATE REF POINTERS!
list1.display()
print 'CASE4: REVERSE EMPTY LIST'
list0.reverse()
list0.display()
print 'CASE 5: REVERSE one-element List!'
list3 = List()
list3.append(5)
list3.reverse()
list3.display()
print 'CASE6: FIND in Empty, 1-element, 3-element List'
found51 = list0.find(5)
# None
print found51
found52 = list3.find(5)
# 5
print found52
found53 = list3.find(4)
# None
print found53
found54 = list1.find(2)
# 2
print found54
print '\nCASE7: REMOVE from Empty, 1-element, 3-element list MID, 3-element List END'
try:
print "\n7.1\n"
# list0.display()
del71 = list0.remove(5)
# None
print del71
print "\n7.2\n"
del72 = list3.remove(5)
#5
print del72
print "\n7.3\n"
del73 = list1.remove(2)
# 2
print del73
print "\n7.4\n"
del74 = list1.remove(3)
# 3
print del74
print "\n7.5\n"
del75 = list1.remove(1)
# 1
print del75
except Exception as ex:
# logging.info('YIKES!', exc_info=True)
logging.exception("YIKES!")
finally:
'GRACEFUL EXIT?!'
|
1ebd0f2ad763852d4e7f19057b5197e56a025808 | maryoohhh/leetcodelearn | /Array/Check-if-exist.gyp | 783 | 3.96875 | 4 | # Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
# More formally check if there exists two indices i and j such that :
# i != j
# 0 <= i, j < arr.length
# arr[i] == 2 * arr[j]
# Example 1:
# Input: arr = [10,2,5,3]
# Output: true
# Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
s = set()
for i in arr:
# Checks if i * 2 is in the s list
if i * 2 in s: return True
# Checks if i is divisible by 2 and if the quotient is in the s list
if i % 2 == 0 and int(i/2) in s: return True
# add i in the s list
s.add(i)
return False
|
5d44c887b5975e4f8afdf28e125f806ca4cee3b2 | Anik2069/python_basic | /hi1.py | 270 | 4.03125 | 4 | print("Hello");
number=[1,2,3,4,56,7,8]
friend=["Anik","Shuvo","Dipu","Rasel"]
print(friend)
print(number[0])
print(friend[1:3])
friend.extend(number)
print(friend)
friend.append("Ashik")
print(friend)
friend.insert(3,"Suman")
print(friend)
print(friend.index("Suman")) |
fcf1055e6b29e5dcd2d411b1c71d0deb775cb172 | Hrishikesh-3459/leetCode | /prob_1550.py | 578 | 3.75 | 4 | class Solution:
def threeConsecutiveOdds(self, arr):
if len(arr) < 3:
return False
start = 0
stop = start + 3
q = arr[start : stop]
if self.count_odd(q):
return True
while stop < len(arr):
q.pop(0)
q.append(arr[stop])
stop += 1
if self.count_odd(q):
return True
return False
def count_odd(self, arr):
if arr[0] & 1 == 1 and arr[1] & 1 == 1 and arr[2] & 1 == 1:
return True
return False |
747249001d522782d1042f4097c370d5989011eb | Shinrei-Boku/kreis_academy_python | /lesson07.py | 817 | 4.125 | 4 | #class 抽象クラス lesson07.py
import abc
class Person(metaclass=abc.ABCMeta):
def __init__(self,name,age):
print("create new Person")
self.__name = name
self.__age = age
def myname(self):
print("my name is {}".format(self.__name))
def myage(self):
print( "{}の{}歳です。".format(self.__name,str(self.__age)))
@abc.abstractmethod
def department(self):
pass
def __del__(self):
print("bye")
class KreisPerson(Person):
def __init__(self,name,age):
super().__init__(name,age)
self.__department = "kreis"
def department(self):
print("所属は{}".format(self.__department))
if __name__ == "__main__":
kon = KreisPerson("kondo","20")
kon.myname()
kon.myage()
kon.department() |
09f0521a41f2ae60bb0eeebf8c200344317229da | lorenz-gorini/Python-Programs | /iss/main.py | 983 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 12:50:19 2019
@author: loreg
"""
import lib.path as path
#There's is a library to calculate the distance between two points of the ISS using the
# Haversine formula. This library is made by Bartek Gorny and is free software.
#There's also some little libraries written by me (called osm) to receive the
#json from the server and calculate the distance.
#If you redistribute the software. Please do it under GPLv3 or use another
# library to calculate the direct line distance.
tot_time = int(input("insert the total time after which the program measures the average speed (in seconds)\n"))
num_values,avg_speed,points=path.avg_speed(tot_time)
if (num_values!=0):
print("During the last {} seconds, the program detected {} positions of the ISS.".format(tot_time,num_values+1),
"The average speed of the ISS is: {} km/h".format(avg_speed))
print(points)
# draw.drawISS(points)
|
cf752982ddcd8f53d3fdac41df51b669462f7b22 | luffmama/99-CapstoneProject-201920 | /src/m3_extra.py | 5,230 | 3.53125 | 4 | """
Code for sprint 3
Authors: Conner Ozatalar.
Winter term, 2018-2019.
"""
import time
# feature 1: going into deep sea
def m3_marlin_deep_sea(robot, check_box_dory_mode, dory_mode_excitement_entry):
print('Marlin deep sea activated')
robot.drive_system.go(50, 50)
while True:
if robot.sensor_system.color_sensor.get_reflected_light_intensity() <= 5:
robot.drive_system.stop()
break
elif dory_mode_toggle(robot, check_box_dory_mode):
dory_mode_activated(robot, dory_mode_excitement_entry)
return
robot.sound_system.speech_maker.speak('stay in the shallow water')
robot.drive_system.go(-30, -30)
time.sleep(1.8)
robot.drive_system.stop()
def m3_nemo_deep_sea(robot, check_box_dory_mode, dory_mode_excitement_entry):
# nemo in the black circle
print('Nemo deep sea activated')
robot.drive_system.go(50, 50)
while True:
if robot.sensor_system.color_sensor.get_reflected_light_intensity() <= 5:
robot.drive_system.stop()
break
elif dory_mode_toggle(robot, check_box_dory_mode):
dory_mode_activated(robot, dory_mode_excitement_entry)
return
robot.sound_system.speech_maker.speak('Time for an adventure')
nemo_on_the_run(robot, check_box_dory_mode, dory_mode_excitement_entry)
def nemo_on_the_run(robot, check_box_dory_mode, dory_mode_excitement_entry):
# nemo running out of the black circle
robot.drive_system.go_straight_for_inches_using_encoder(25, 100)
robot.drive_system.go(-50, 50)
start_time = time.time()
while True:
if robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() <= 9:
stop_from_sees_something(robot)
break
elif time.time() - start_time >= 2.8:
stop_from_time(robot)
break
elif dory_mode_toggle(robot, check_box_dory_mode):
dory_mode_activated(robot, dory_mode_excitement_entry)
return
def stop_from_sees_something(robot):
# nemo sees something after exiting the black circle
print('stop_from_sees_something')
robot.drive_system.stop()
robot.drive_system.go(70, 70)
while True:
# print(robot.sensor_system.ir_proximity_sensor.get_distance_in_inches())
if robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() <= 3:
robot.drive_system.stop()
break
def stop_from_time(robot):
# nemo returns to the black circle after leaving it and spinning
print('stop from time')
robot.drive_system.stop()
robot.drive_system.go_straight_for_inches_using_encoder(25, 70)
def m3_find_nemo(robot, find_nemo_speed_entry, find_nemo_turn_time, check_box_dory_mode, dory_mode_excitement_entry):
robot.drive_system.go(find_nemo_speed_entry, find_nemo_speed_entry)
while True:
# print(robot.sensor_system.ir_proximity_sensor.get_distance_in_inches())
if robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() <= 3:
obstacle_found(robot, find_nemo_speed_entry, find_nemo_turn_time)
robot.drive_system.go(find_nemo_speed_entry, find_nemo_speed_entry)
elif robot.sensor_system.touch_sensor.is_pressed():
found_nemo(robot)
break
elif dory_mode_toggle(robot, check_box_dory_mode):
dory_mode_activated(robot, dory_mode_excitement_entry)
return
def obstacle_found(robot, find_nemo_speed_entry, find_nemo_turn_time):
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
robot.drive_system.go(find_nemo_speed_entry, -find_nemo_speed_entry)
time.sleep(find_nemo_turn_time/25)
robot.drive_system.stop()
robot.arm_and_claw.lower_arm()
time.sleep(.1)
robot.drive_system.go(-find_nemo_speed_entry, find_nemo_speed_entry)
time.sleep(find_nemo_turn_time/25)
robot.drive_system.stop()
time.sleep(.1)
def found_nemo(robot):
robot.drive_system.stop()
robot.sound_system.speech_maker.speak('I found nemo')
def dory_mode_toggle(robot, check_box_dory_mode):
# print('dory mode toggle', check_box_dory_mode)
if check_box_dory_mode is True:
# print(robot.sensor_system.camera.get_biggest_blob().get_area())
if robot.sensor_system.camera.get_biggest_blob().get_area() > 50:
return True
return False
def dory_mode_activated(robot, dory_mode_excitement_entry):
robot.drive_system.stop()
print('Dory mode has been activated')
song = notes(dory_mode_excitement_entry)
start_time = time.time()
while True:
robot.sound_system.tone_maker.play_tone_sequence(song).wait()
if robot.sensor_system.touch_sensor.is_pressed():
print('stopped from push sensor')
break
elif time.time() - start_time >= 10:
print('stopped from time')
break
time.sleep(.75)
def notes(dory_mode_excitement_entry):
c = 262.626
d = 293.665
b = 246.943
e = 329.628
t = 60000/(dory_mode_excitement_entry + 100)
song = [(c, t, 5), (e, t, 5), (c, t, 5), (e, t, 5), (c, t, 5), (d, t / 2, 5), (d, t / 2, 5), (b, t, 5), (c, t, 5)]
return song
|
03a99049fc957028707609f7253fdc4b3b2d83b2 | Yifei-Deng/myPython-foundational-level-practice-code | /19.py | 1,089 | 4.1875 | 4 | '''
视频中老师演示的代码
python开发基础19-math模块的使用
'''
import math #import the module
print(math.ceil(3.15)) #天花板,取大于3.15的最小的整数值
print(math.ceil(-3.15)) #天花板,取大于-3.15的最小的整数值
print(math.floor(3.15)) #地板,取小于3.15的最大的整数值
print(math.floor(-3.15)) #地板,取小于-3.15的最大的整数值
print(math.ceil(5),math.floor(5)) #如果变量是一个整数,则返回其本身
print(math.fabs(-10)) #取变量的绝对值,返回的是一个浮点数
print(math.fsum([1,2,3,4])) #对列表里面的每个元素求和,返回的是浮点数
print(math.pow(8,2)) # 8**2等价,返回的是浮点数
print(math.sqrt(64)) #对64开方,返回的是浮点数,
a=(math.sqrt(5))
print("%.2f" %a) #可以通过 %.xf 来改变能显示的小数点后的数位
print("{:.2f}".format(a)) #可也以通过.format 来改变能显示的小数点后的数位
'''
Output:
4
-3
3
-4
5 5
10.0
10.0
64.0
8.0
2.24
2.24
'''
|
d50a42634478c8ba579d97bb60d73e7904f49639 | 2kindsofcs/daily-algo-challenge | /2kindsofcs/191213-fair-candy-swap.py | 626 | 3.53125 | 4 | class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
Asum = sum(A)
Bsum = sum(B)
A = set(A)
B = set(B)
halfDiff = (Asum - Bsum) / 2
for num in B:
target = halfDiff + num
if target in A:
return [int(target), num]
# Runtime: 408 ms, faster than 80.23% of Python3 online submissions for Fair Candy Swap.
# Memory Usage: 15.6 MB, less than 8.33% of Python3 online submissions for Fair Candy Swap.
# 핵심은 크게 2가지였다. 최소한의 연산으로, 중복되는 요소 없이 확인하기.
|
180d439135cb3e781106b5f8b11d12b7e89cd452 | hiys/PYTHON | /pythonScripts/PyScripts/PyScripts4/guess2.py | 331 | 3.84375 | 4 | import random
num = random.randint(1, 10) # 随机生成一个10以内的数字
running = True
while running:
result = int(input("guess the number: "))
if result > num:
print('猜大了')
elif result < num:
print('猜小了')
else:
running = False
print('猜对了')
print(num)
|
d3e404302c3acf2bd9e7a31e35ae96028fd3fb4c | bhostetler18/TuneCoach | /TuneCoach/gui/Timer.py | 990 | 3.671875 | 4 | from datetime import datetime
import time
# Big thanks to https://stackoverflow.com/questions/60026296/how-to-make-a-pausable-timer-in-python
class Timer:
def __init__(self):
self.started = None
self.paused = None
self.is_paused = False
def start(self):
self.started = datetime.now()
def pause(self):
self.paused = datetime.now()
self.is_paused = True
def resume(self):
pause_time = datetime.now() - self.paused
self.started += pause_time
self.is_paused = False
def get(self):
if self.is_paused:
return int((self.paused - self.started).total_seconds())
else:
return int((datetime.now() - self.started).total_seconds())
def clear(self):
self.started = None
self.paused = None
self.is_paused = False
def has_started(self):
if self.started is None:
return False
else:
return True
|
7b0393f46eb55417a210a7da6d3609606867ea2e | madhurijain97/Machine-Learning-Assignments | /homework1/decisiontree.py | 12,746 | 3.703125 | 4 | import sys
from math import log
import csv
import numpy as np
import os
#if all the decisions in the set belong to the same class, then this value will be returned
ifSetPure = 0
#the predictions of the test data are stored in this list too along with being written to the predctions file
testedPredictions = []
'''the structure of the tree
left- left subtree
right - right subtree
value - the value of the node at which it is split
entropy - entropy if the dataset is split at that value
leftDecision - if the left children do not need to be split further, then add a decision to the left decision of the node
rightDecision - if the right children do not have to be split further, then add a decision to the right decision of the node
'''
class Tree:
def __init__(self):
self.left = None
self.right = None
self.value = None
self.entropy = None
self.leftDecision = None
self.rightDecision = None
self.columnNumber = None
'''this calculates the entropy of the entire dataset
entropy = (-plogp - nlogn)'''
def calculateIndividualEntropy(positive, negative, totalSamples):
positiveProbability = float(positive) / float(totalSamples)
negativeProbability = float(negative) / float(totalSamples)
individualEntropy = 0
if positive != 0 and totalSamples != 0:
individualEntropy -= ((positiveProbability * log(positiveProbability) / log(2)))
if negative != 0 and totalSamples != 0:
individualEntropy -= ((negativeProbability * log(negativeProbability) / log(2)))
return individualEntropy
#calculates the number of samples have decision as 1(positive) and 0(negative)
def calculatePositiveNegative(dataset):
positive, negative = 0, 0
for row in dataset:
if (row[-1] == '1'):
positive += 1
else:
negative += 1
return positive, negative
'''Calculates the entropy if a there are left and right children of a node
entropy = (leftSample/totalSample)(-leftp*log(leftp)-(leftn*log(leftn))) + (rightSample/totalSample)(-rightp*log(rightp)-(rightn*log(rightn)))
'''
def getEntropy(groups):
totalSample = 0
leftRightChildEntropies = []
# get the total samples in the two dataset
for group in groups:
totalSample += len(group)
totalSample = float(totalSample)
for group in groups:
individualGroupLength = len(group)
if individualGroupLength == 0:
continue
entropy = 0
positive, negative = calculatePositiveNegative(group)
leftRightChildEntropies.append(
(float(len(group)) / float(totalSample)) * calculateIndividualEntropy(positive, negative,
individualGroupLength))
return sum(leftRightChildEntropies)
'''We don't want to split on the same nodes again and again
Hence getting the unique values and then splitting
This reduces the number of redundant computations'''
def getUniqueValues(dataset, columnNumber):
duplicateValuedList = []
for row in dataset:
duplicateValuedList.append(int(row[columnNumber]))
uniqueValuesList = np.unique(duplicateValuedList)
return uniqueValuesList
'''
This function iterates through the entire dataset
All the values that are less than or equal to nodeValue are added to the leftChildren and
all the values that are greater than nodeValue are added to the rightChildren
'''
def getLeftAndRightChildren(dataset, value, columnNumber):
left, right = [], []
for row in dataset:
if int(row[columnNumber]) <= int(value):
left.append(row)
else:
right.append(row)
return left, right
'''
Iterates through every value, gets the left and right children, calculates entropy
The value with the least entropy is chosen as the splitNode
'''
def calculateSplitPoint(dataset, entropyOfParent):
splitColumn = float('inf')
splitValue = float('inf')
minimumEntropy = float('inf')
leftRightChildrenGroups = None
positive, negative = calculatePositiveNegative(dataset)
datasetEntropy = calculateIndividualEntropy(positive, negative, positive+negative)
# running for the first two columns
for columnNumber in range(2):
uniqueList = getUniqueValues(dataset, columnNumber)
for i in range(len(uniqueList)-1):
number1 = uniqueList[i]
number2 = uniqueList[i+1]
number = (number1+number2)/2
groups = getLeftAndRightChildren(dataset, number, columnNumber)
entropy = getEntropy(groups)
if entropy < minimumEntropy and entropy < datasetEntropy:
minimumEntropy = entropy
splitColumn = columnNumber
splitValue = number
leftRightChildrenGroups = groups
#if no node could be found with lesser entropy than the entropy of the entire dataset, then return 2(invalid) as the columnNumber
if splitValue == float('inf'):
return {'columnNumber': 2}
#return the details needed for a node
return {'columnNumber': splitColumn, 'splitValue': splitValue, 'groups': leftRightChildrenGroups,
'entropy': minimumEntropy}
'''Calculates the number of positives and negatives in the dataset and returns the decision that has the maximum count'''
def assignLeafNode(group):
positive, negative = 0, 0
for row in group:
if row[-1] == '1':
positive += 1
else:
negative += 1
if (positive > negative):
return 1
return 0
'''
decides if a node has to be split further or a decision can be assigned'''
def decideLeafOrSplit(treeNode, leftChildrenList, rightChildrenList, maxDepth, depth):
#if the current depth is greater than the maximum depth or entropy < 0.01, assign decision nodes and return
if (depth >= maxDepth or treeNode.entropy < 0.01):
treeNode.leftDecision = assignLeafNode(leftChildrenList)
treeNode.rightDecision = assignLeafNode(rightChildrenList)
return
#calculate entropy of the leftDataset
positive, negative = calculatePositiveNegative(leftChildrenList)
datasetEntropyLeft = calculateIndividualEntropy(positive, negative, positive+negative)
#calculate entropy of the right dataset
positive, negative = calculatePositiveNegative(rightChildrenList)
datasetEntropyRight = calculateIndividualEntropy(positive, negative, positive+negative)
#if the left entropy < 0.01, no need to split further and a decision node can be assigned
if datasetEntropyLeft < 0.01:
treeNode.leftDecision = assignLeafNode(leftChildrenList)
else:
#else, get the split point
newTreeNodeDict = calculateSplitPoint(leftChildrenList, treeNode.entropy)
#if no new node could be found, assign a decision to the current node
if(newTreeNodeDict['columnNumber'] == 2):
treeNode.leftDecision = assignLeafNode(leftChildrenList)
else:
#else, create a new node and call this function recursively
newTreeNode = Tree()
treeNode.left = newTreeNode
newTreeNode.value = newTreeNodeDict['splitValue']
newTreeNode.columnNumber = newTreeNodeDict['columnNumber']
newTreeNode.entropy = newTreeNodeDict['entropy']
toBeLeftChildren, toBeRightChildren = None, None
if(newTreeNodeDict['groups'] != None):
toBeLeftChildren = newTreeNodeDict['groups'][0]
toBeRightChildren = newTreeNodeDict['groups'][1]
decideLeafOrSplit(newTreeNode, toBeLeftChildren, toBeRightChildren, maxDepth, depth + 1)
# if the right entropy < 0.01, no need to split further and a decision node can be assigned
if datasetEntropyRight < 0.01:
treeNode.rightDecision = assignLeafNode(rightChildrenList)
else:
# else, get the split point
newTreeNodeDict = calculateSplitPoint(rightChildrenList, treeNode.entropy)
# if no new node could be found, assign a decision to the current node
if (newTreeNodeDict['columnNumber'] == 2):
treeNode.rightDecision = assignLeafNode(rightChildrenList)
else:
# else, create a new node and call this function recursively
newTreeNode = Tree()
treeNode.right = newTreeNode
newTreeNode.value = newTreeNodeDict['splitValue']
newTreeNode.columnNumber = newTreeNodeDict['columnNumber']
newTreeNode.entropy = newTreeNodeDict['entropy']
toBeLeftChildren, toBeRightChildren = None, None
if (newTreeNodeDict['groups'] != None):
toBeLeftChildren = newTreeNodeDict['groups'][0]
toBeRightChildren = newTreeNodeDict['groups'][1]
decideLeafOrSplit(newTreeNode, toBeLeftChildren, toBeRightChildren, maxDepth, depth + 1)
#this function is called while classifying the test data
def classify(root, x, y):
#if root is None, means that the entire dataset is pure. Hence returning that value
if root == None or root is None:
return ifSetPure
#do down the tree as per the conditions that are being satisfied
if root is not None:
while (True):
if (root.columnNumber == 0):
if int(x) <= int(root.value):
if root.leftDecision != None:
return root.leftDecision
root = root.left
else:
if root.rightDecision != None:
return root.rightDecision
root = root.right
elif(root.columnNumber == 1):
if int(y) <= int(root.value):
if root.leftDecision != None:
return root.leftDecision
root = root.left
else:
if root.rightDecision != None:
return root.rightDecision
root = root.right
else:
return -1
#gets the root value of the tree and recursively constructs the tree using decideLeafOrSplit function
def buildDecisionTree(dataset, maxDepth, minimumEntropy):
if(minimumEntropy == 0):
return None
rootDict = calculateSplitPoint(dataset, minimumEntropy)
root = Tree()
root.value = rootDict['splitValue']
root.columnNumber = rootDict['columnNumber']
root.entropy = rootDict['entropy']
toBeLeftChildren, toBeRightChildren = None, None
if rootDict['groups'] != None:
toBeLeftChildren = rootDict['groups'][0]
toBeRightChildren = rootDict['groups'][1]
decideLeafOrSplit(root, toBeLeftChildren, toBeRightChildren, maxDepth, 1)
return root
#open the file that contains the training data and store it in a list
def readingCsvFile(fileName):
fileHandle = open(fileName)
with fileHandle as csvFile:
csvReader = csv.reader(csvFile)
globalDataset = list(csvReader)
count = 0
for row in globalDataset:
ifSetPure = int(row[-1])
count += 1
if(count > 0):
break
positive, negative = calculatePositiveNegative(globalDataset)
fileHandle.close()
return globalDataset, calculateIndividualEntropy(positive, negative, positive+negative)
#Open the file that contains the test data and write your predictions to a file
def testPredictionsOnDecisionTree(root, testingFile):
testedPredictions.clear()
fileHandle1 = open(testingFile)
basePathName = os.path.basename(testingFile)
wordsList = basePathName.split('_')
blackBoxNumber = wordsList[0]
myPredictionsFileName = blackBoxNumber + "_" + "predictions.csv"
#print("predictionsFilename is:", myPredictionsFileName)
fileHandle2 = open(myPredictionsFileName, 'w')
with fileHandle1 as csvFile:
csvReader = csv.reader(csvFile)
testingDataSet = list(csvReader)
for data in testingDataSet:
decision = classify(root, int(data[0]), int(data[1]))
fileHandle2.write(str(decision) + '\n')
testedPredictions.append(decision)
fileHandle1.close()
fileHandle2.close()
'''gets the training and testing file names and calls buildDecisionTree to start the process of building a tree,
Calls testPredictionsOnDecisionTrees to start classifying the data
'''
if __name__ == "__main__":
trainingDataPath, testingDataPath = sys.argv[1], sys.argv[2]
globalDataset, minimumEntropy = readingCsvFile(trainingDataPath)
finalRoot = None
if minimumEntropy != 0:
finalRoot = buildDecisionTree(globalDataset, 9, minimumEntropy)
testPredictionsOnDecisionTree(finalRoot, testingDataPath)
|
054c44e7efd33d04e7e7415e6133cf1a1ca96222 | GuilhermeRamous/python-exercises | /reverse_list.py | 191 | 3.96875 | 4 | def reverse_list(lista):
if len(lista) == 1:
return [lista[0]]
else:
topo = lista.pop()
return [topo] + reverse_list(lista)
print(reverse_list([1, 2, 3]))
|
71e6566da2abb705d5c2e379628539f53ef405c1 | zkydrx/pythonStudy | /study/pythonMethod/pythonAdvancdeFeatures20181108.py | 1,671 | 4.09375 | 4 | # -*- coding: UTF-8 -*-
# 匿名函数
# 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。
#
# 在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8]))) # =>[1, 4, 9, 16, 25, 36, 49, 64]
# 通过对比可以看出,匿名函数lambda x: x * x实际上就是:
def f(x):
return x * x
# 关键字lambda表示匿名函数,冒号前面的x表示函数参数。
#
# 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
#
# 用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
f = lambda x: x * x
print(f) # =><function <lambda> at 0x00000120D9BB9510>
print(f(6)) # =>36
# 同样,也可以把匿名函数作为返回值返回,比如:
def build(x, y):
return lambda: x * x + y * y
f1 = build(1, 2)
print(f1) # => <function build.<locals>.<lambda> at 0x0000024948E19620>
print(f1()) # =>5
# 小结
# Python对匿名函数的支持有限,只有一些简单的情况下可以使用匿名函数。
# 请用匿名函数改造下面的代码:
def is_odd(n):
return n % 2 == 1
L = list(filter(is_odd, range(1, 20)))
L1 = list(filter(lambda x: x % 2 == 1, range(1, 20)))
print(L) #=>[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
print(L1)#=>[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
|
2ee3665dcdd39a22cf2fa1c494323dadd61bf259 | arthurDz/algorithm-studies | /SystemDesign/multithreading and concurrency/barber_shop.py | 3,715 | 3.90625 | 4 | # A similar problem appears in Silberschatz and Galvin's OS book, and variations of this problem exist in the wild.
# A barbershop consists of a waiting room with n chairs, and a barber chair for giving haircuts. If there are no customers to be served, the barber goes to sleep. If a customer enters the barbershop and all chairs are occupied, then the customer leaves the shop. If the barber is busy, but chairs are available, then the customer sits in one of the free chairs. If the barber is asleep, the customer wakes up the barber. Write a program to coordinate the interaction between the barber and the customers.
from threading import Thread, Condition, Lock
import time
import collections
class BarberShop:
def __init__(self, num_chairs):
self.chairs = [True] * num_chairs
self.lock = Lock()
self.available_barbers = collections.deque()
self.barber_to_lock = {}
self.customer_lock = Condition()
def barber(self, name):
with self.lock:
self.available_barbers.append(name)
self.barber_to_lock[name] = Condition()
print(f"Barber {name} joins the barber shop")
self.barber_to_lock[name].acquire()
while True:
print(f"Barber {name} goes to sleep.")
while name in self.available_barbers:
self.barber_to_lock[name].wait()
print(f"Barber {name} wakes up and starts working!")
while name not in self.available_barbers:
self.barber_to_lock[name].wait()
def customer_walks_in(self):
self.customer_lock.acquire()
if not any(self.chairs):
print(f"Customer leaves as he/she couldn't find a chair")
self.customer_lock.release()
return;
for i in range(len(self.chairs)):
if self.chairs[i]:
chair_id = i
self.chairs[i] = False
break
print(f"Customer took chair {chair_id}")
while not self.available_barbers:
self.customer_lock.wait()
barber_name = self.available_barbers.popleft()
self.barber_to_lock[barber_name].acquire()
self.barber_to_lock[barber_name].notify()
self.barber_to_lock[barber_name].release()
self.customer_lock.release()
time.sleep(0.1)
self.customer_lock.acquire()
self.chairs[chair_id] = True
self.barber_to_lock[barber_name].acquire()
print(f"{barber_name} has done one haircut!")
self.available_barbers.append(barber_name)
self.barber_to_lock[barber_name].notify()
self.barber_to_lock[barber_name].release()
self.customer_lock.notify_all()
self.customer_lock.release()
if __name__ == "__main__":
barber_shop = BarberShop(3)
barber_thread = Thread(target=barber_shop.barber, args=("Mike",))
barber_thread.setDaemon(True)
barber_thread.start()
barber_thread_2 = Thread(target=barber_shop.barber, args=("Andrew",))
barber_thread_2.setDaemon(True)
barber_thread_2.start()
# intially 10 customers enter the barber shop one after the other
customers = list()
for _ in range(0, 10):
customers.append(Thread(target=barber_shop.customer_walks_in))
for customer in customers:
customer.start()
time.sleep(0.5)
# second wave of 5 customers
late_customers = list()
for _ in range(0, 5):
late_customers.append(Thread(target=barber_shop.customer_walks_in))
for customer in late_customers:
customer.start()
for customer in customers:
customer.join()
for customer in late_customers:
customer.join()
|
05a4a1a44e2587b466819f831b3c10d40a87510c | soutem-debug/object_orientated_programming | /object -oriented - programming/dog_tutorial.py | 605 | 3.546875 | 4 | class Dog:
def __init__(self, name, age, gender, breed):
self.name = name
self.age = age
self.gender = gender
self.breed = breed
def description(self):
print(self.name + " is" + " " + str(self.age) + "years old.")
def breeding(self):
print(self.name + " is a " + self.gender + " " + self.breed)
def birthday(self):
self.age += 1
navi = Dog("Navi", 5, "Female", "Shitzu")
atlantis = Dog("Atlantis", 3, "Male", "Poodle")
navi.description()
navi.breeding()
atlantis.description()
atlantis.breeding()
|
6f89570eeb1b66bcd7c02625a885f51b60ad9274 | Tavares-NT/Curso_NExT | /MóduloPython/Ex04.py | 358 | 3.9375 | 4 | '''Faça um Programa que peça as 4 notas bimestrais e mostre a média.'''
nota1 = float(input("Digite a 1ª nota: "))
nota2 = float(input("Digite a 2ª nota: "))
nota3 = float(input("Digite a 3ª nota: "))
nota4 = float(input("Digite a 4ª nota: "))
media = (nota1 + nota2 + nota3 + nota4) / 4
print(f"A média das notas informadas é: {round(media, 2)}") |
fa487002afd5ccc268a737a75e71c3586f766bb2 | Shubh0794/PyCodeNotes | /3_Intro_to_List_comprehension_and_generators.py | 4,966 | 4.75 | 5 | ### Objective : Introduction to List Comprehension and Generators and Generator Expressions ###
###############################################################
############ CREATING A FUNCTION TO GENERATE LIST OF NUMS ####
###############################################################
def GetListOfNums(max):
nums_list = []
for i in range(max):
nums_list.append(i)
return nums_list
nums_list_ = GetListOfNums(5)
print(" Printing List of nums ")
print(nums_list_)
###############################################################
###############################################################
############ CREATING A LIST COMPREHENSION ###################
###############################################################
## Using a List comprehension technique to generate a list of numbers.
## A single line format to populate a list.
## Use of square brackets is important []. If () are used, it becomes generator expresion.
## Remember it like list is defined in [], so is list comprehension.
## Syntax for a list comprehension :
## <op_list> = [ <expression> for i in <iterable> < conditional_statements > < nested_looping> ]
## The expression is evaluated an appended to the list.
## < conditional statement : is evaluated and if its op is true, then only expr is evaluated.
## <nested looping> a chain of for loops can be added.
nums_list = [i for i in range(5)]
print(" Using List Comprehension ")
print(nums_list)
# The statement is a list comprehension and is equivalent to :
nums_list = []
for i in range(5):
nums_list.append(i)
###############################################################
###############################################################
# Iterating over a list using a for -loop vs list comprehension.
###############################################################
# 1.) using for -loop
for i in nums_list:
print(i)
### print (i) < Still prints 4
# 2.) using list comprehension
[print(i) for i in nums_list]
### print (i) < error
# both work fine.
# list comprehension is used to write a 1-liner for loops as above.
# Bit the variable 'i' taken to iterate on both the cases has different lifetime
# IN 1. 'i' is still valid after for-loop ends and is equal to its last value in loop. (here 4)
# In 2. 'i' goes out of scope as soon as iteration in list comprehension ends.
###############################################################
###############################################################
############ CREATING A GENERATOR FUNCTION ###################
###############################################################
### Define a Generator Function which will generate numbers from 0 to max.
# Generators are functions with a 'yield' statement ( Return statement if encountered marks the end of the function)
def NumberGenerator(max):
start = 0
while (start <= max):
yield start
start += 1
return
### Create a number generator object.
nums = NumberGenerator(5)
### Function execution will not start right now.
### It will start when a 'next()' function is called on generator_object. ( 'next' is automaticcally called by the for loop )
### Function execution pauses as it reaches yield statement and value after that is returned. When the 'next' is again called on generator object, execution continues from the line following yield statement. ( State of the function like local vars etc. is preserved )
### This helps us avoid saving numbers in memory.
print(' Printing using Generator Function ')
for num in nums:
print(num)
###############################################################
###############################################################
############ CREATING A GENERATOR EXPRESSION ################
###############################################################
# A generator expression is a short way of creating a generator function ( as shown previosuly )
## Create a generator expression object.
## Now we can iterate on this object
nums_generator = (i for i in range(5))
print(" Printing using Generator expression object ")
for num in nums_generator:
print(num)
###############################################################
########################################
############ CONCLUSION ###############
########################################
# List Comprehension is a short way to create a list.
# since a list is created, use this when you need to store elements in the memory.
# Iterating over an iterable in a normal for loop : the iterating variable (generally 'i') still exists after the loop ends and value = last value in for loop.
# Iterating over an iterable in a list comprehension : the varible 'i' has lifetime only of that line.
# Generator Expression is a short way to create generator function.
# An iterable object is created on which we can iterate.
# Elements are not stored in memory.
########################################
########################################
|
077b4110c5fb2818335dbb72e1984610f89765f9 | igoodin/NeuronResearch | /main.py | 855 | 3.71875 | 4 | """
Author: Isaac Goodin
Date Created: 1/12/2010
Last Updated: 8/31/2010
Program to interface with the Neuron.py class and allow simple configuration and execution of the simulation.
"""
from neuron import *
file = open("neuron.txt",'w')
steps = 100000 #Total Time(Ms)
skip = 10000 #Time to Skip(Ms)
#Creating Neuron Objects
N1 = Neuron("Neuron 1")
N2 = Neuron("Neuron 2")
N3 = Neuron("Neuron 3")
#Making a list of all the Neurons
Neuron_list = [N1,N2,N3]
#Setting Initial values
N1.X =[-21.0,0.11,0.41,0.11]
N2.X =[-22.0,0.12,0.42,0.12]
N3.X =[-23.0,0.13,0.43,0.13]
#Changing Neuron Parameters
N1.gsr = 0.42
N2.gsr = 0.40
N3.gsr = 0.38
#Setting Neuron Inputs and correlation strength
N2.Input([[N1,0.0035]])
N3.Input([[N2,0.003]])
#Run the simulation and output data
Run_rk4(file,steps,skip,Neuron_list)
|
36b96e467d3b21f02e6d498c7239d68b07023df6 | antonyaraujo/Listas | /Lista04/Questao7.py | 290 | 4.03125 | 4 | ''' Faça uma função que, dado um número representando uma temperatura em graus Fahrenheit, retorne a
temperatura em Celsius. Obs: C=(5/9)*(F-32).'''
def conversao(fahrenheit):
return (5/9)*(fahrenheit-32)
F = float(input("Fahrenheit: "))
print("Celsius: %.1fºC" %(conversao(F)))
|
a831d531d43bf6315012dc53d4ee85456ac52d31 | tusharsadhwani/intro-to-python | /2. Data Structures/4-examples.py | 1,183 | 4.375 | 4 | # Practical examples of what we have learned so far:
# 1. generating a set of prime numbers
# upper_limit = 100
# primes = set()
# for n in range(2, upper_limit):
# primes.add(n) # assume it is a prime
# for p in primes:
# # if n is divisible by a prime (other than itself):
# if n % p == 0 and n != p:
# primes.remove(n)
# break # we know it's not a prime so we can stop the loop
# print(primes)
# 2. Employee directory:
# employees = []
# while True:
# # Ask for a command
# print('''Choose:
# 1. View employees
# 2. Add employee
# 3. Exit
# ''')
# inp = input('> ')
# inp = int(inp)
# # Execute that command
# if (inp == 1):
# print('Current Employees:')
# for emp in employees:
# print(emp['name'], '-', emp['salary'])
# print('-------------------------------------')
# elif inp == 2:
# emp_name = input('Enter employee name: ')
# emp_salary = float(input('Enter employee salary: '))
# new_employee = {'name': emp_name, 'salary': emp_salary}
# employees.append(new_employee)
# else:
# exit()
|
e849b9a728cdd7d98e22c05158b61aa1ce8c52a4 | jtcass01/codewars | /Python/4 kyu/Range Extraction/Solution.py | 940 | 3.78125 | 4 | def solution(args):
recent = []
ranges = []
result = ""
last = args[0]
for argument in args:
if argument == last+1 or argument == last-1:
recent.insert(0,argument)
else:
if(len(recent) > 0):
ranges.append(appendRange(recent))
recent = clear(recent)
recent.insert(0,argument)
last = argument
if(len(recent) > 0):
ranges.append(appendRange(recent))
return ",".join(ranges)
def appendRange(nums):
if(len(nums) == 1):
return str(nums[0])
elif(len(nums) == 2):
return str(nums[1]) + "," + str(nums[0])
else:
return str(nums[len(nums)-1]) + "-" + str(nums[0])
def clear(arr):
for value_i in range(0,len(arr)):
arr.pop(0)
return arr
def printArray(arr):
string = "["
for value in arr:
string += str(value) + ","
print(string[:-1] + "]")
|
0d3b79b5d7739547d998f91679618eb9e0f24f1a | marusheep/python-course-practice | /course-3-string-1/3-2-concatenation.py | 673 | 4.15625 | 4 | # Concatenation "" + ""
print("tomato" + " " + "juice")
# String Exercise
# Do all of this in a .py file in Pycharm
# 1. Create a variable and assign it the string "Just do it!"
# 2. Access the "!" from the variable by index and print() it
# 3. Print the slice "do" from the variable
# 4. Get and print the slice "it!" from the variable
# 5. Print the slice "Just" from the variable
# 6. Get the string slice "do it!" from the variable and concatenate it with the string "Don't ". Print the resulting string.
varLine = 'Just do it!'
print(varLine[10])
print(varLine[5:7])
print(varLine[8:11])
print(varLine[:5])
varConcate = "Don't"
print(varConcate + " " + varLine[5:]) |
8cb54958c6623c20044aa791ec9cddee5a75783d | gsudarshan1990/Training_Projects | /Classes/class_example138.py | 358 | 4.125 | 4 | """This is another python example"""
class Product:
def __new__(cls, *args, **kwargs):
new_product = object.__new__(cls)
print('Product __new__ is called')
return new_product
def __init__(self, name, price):
self.name = name
self.price = price
print('__init__ is called')
p1 = Product('vaccum', 150) |
b34464a06002b214176c646d9c5989090b70217d | Alekceyka-1/algopro21 | /part1/LabRab/labrab-02/03.py | 137 | 3.90625 | 4 | x = int(input('Введите от 1 до 9 - '))
while x < 1 or x > 9:
x = int(input('Введите от 1 до 9 - '))
print(x)
|
1db84a813b07f1f16629059dd11bd81534243508 | feldhaus/python-samples | /hangman/hangman.py | 4,078 | 4.03125 | 4 | import random, string
WORDLIST_FILENAME = "words.txt"
def loadWords():
'''
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
returns (list): all words loaded
'''
print("Loading word list from file...")
inFile = open(WORDLIST_FILENAME, 'r')
line = inFile.readline()
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def chooseWord(wordlist):
'''
Returns a word from wordlist at random.
wordlist (list): list of words (strings)
'''
return random.choice(wordlist)
def isWordGuessed(secretWord, lettersGuessed):
'''
Returns if all letters was discovered.
secretWord (string): the word the user is guessing
lettersGuessed (list): what letters have been guessed so far
returns (boolean): True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
l = list(secretWord)
for c in lettersGuessed:
while c in l:
l.remove(c)
return len(l) == 0
def getGuessedWord(secretWord, lettersGuessed):
'''
Returns the guessed word, with underscore in the letters not guessed.
secretWord (string): the word the user is guessing
lettersGuessed (list) what letters have been guessed so far
returns (string): comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
guessedWord = []
for c in secretWord:
guessedWord.append(c if c in lettersGuessed else '_')
return " ".join(guessedWord)
def getAvailableLetters(lettersGuessed):
'''
Returns all available letters.
lettersGuessed (list): what letters have been guessed so far
returns (string): comprised of letters that represents what letters have not
yet been guessed.
'''
availableLetters = list(string.ascii_lowercase)
for c in lettersGuessed:
if c in availableLetters:
availableLetters.remove(c)
return "".join(availableLetters)
def hangman(secretWord):
'''
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
secretWord (string): the secret word to guess.
'''
guesses = 8
lettersGuessed = []
print("Welcome to the game, Hangman! ")
print("I am thinking of a word that is {0} letters long.".format(len(secretWord)))
while(guesses > 0):
guess = input("Please guess a letter: ")
if guess in lettersGuessed:
continue
else:
lettersGuessed.append(guess.lower())
if guess in secretWord:
if isWordGuessed(secretWord, lettersGuessed):
break
else:
guesses -= 1
guessedWord = getGuessedWord(secretWord, lettersGuessed)
availableLetters = getAvailableLetters(lettersGuessed)
print("{0} ♥({1}) [{2}]".format(guessedWord, guesses, availableLetters))
print("-------------")
if guesses > 0:
print("Congratulations, you won! The word was: '{0}'".format(secretWord))
else:
print("Sorry, you ran out of guesses. The word was: '{0}'".format(secretWord))
# load the list of words into the variable wordlist
wordlist = loadWords()
# choose a word
secretWord = chooseWord(wordlist).lower()
# start the hangman game
hangman(secretWord) |
761fdba3ce3acbaf5aef76f7e195db382edebd58 | Rossel/Solve_250_Coding_Challenges | /chal113.py | 128 | 3.765625 | 4 | x = "The days of Python 2 are almost over. Python 3 is the king now."
if "z" in x or x.count("y") >= 2:
print("True!") |
1c9005a2f10ae16ee82c6c1164f154d34ac8b8d2 | devopshndz/curso-python-web | /Python sin Fronteras/Python/7- Gestion de archivos/2- Escribiendo en los archivos.py | 838 | 3.625 | 4 | ### escribiendo archivos
# si queremos escribir en este archivo de chancho, debemos utilizar los permisos.
# 'a'
d = open('Python/7- Gestion de archivos/chancho.txt', 'a')
d.write('\nAgregaremos una nueva linea a nuestro archivo')
# debemos colocar \n para salto de linea ya que se agg el texto al final pero no hacia abajo.
d.close()
x = open('Python/7- Gestion de archivos/chancho.txt')
print(x.read())
# NOTA IMPORTANTE!
# despues de hacer todo lo que hicimos arriba, si cambiamos el permiso de 'a' -> 'w' nos va a permitir
# escrbir en el archivo, pero, 'w' modifica (elimina) el contenido del archivo y escribiría lo del
# d.write, al imprimir, solo se imprime lo escrito en el d.write, por eso hay que tener mucho cuidado
# con los permisos que le demos a los archvos.
# primero leer y luego hacer modificaciones, siempre. |
284d383d621e384847638eb02acfb20e410c005e | khanshoab/pythonProject1 | /concatenation+ope.py | 246 | 4.21875 | 4 | # Concatenation operator is used to join the two string.
print("khan"+"bro")
print()
str1 = "khan"
str2 = "bhaii"
str3 = str1 + str2
print(str3)
print()
str4 = "are you"
print("Hello How "+str4)
print("hello how",str4)
print("hello"+str4+"happay") |
436697395a6a1150e0e77ab0fb246a581ac1e23c | wsbresee/Playground | /Python/hello_world.py | 138 | 3.890625 | 4 | lunch = raw_input("What do you want for lunch? Pizza? ")
if lunch == "pizza":
print("Good choice!")
else:
print("that's stupid")
|
65a9e8945d0c694c07c67360696eb829628cf571 | jianhui-ben/leetcode_python | /15. 3Sum.py | 2,087 | 3.796875 | 4 |
#15. 3Sum
#Given an array nums of n integers, are there elements a, b, c in nums such
#that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
#Notice that the solution set must not contain duplicate triplets.
#Example 1:
#Input: nums = [-1,0,1,2,-1,-4]
#Output: [[-1,-1,2],[-1,0,1]]
#Example 2:
#Input: nums = []
#Output: []
#Example 3:
#Input: nums = [0]
#Output: []
class Solution:
# ## recursion: O(len(nums) !)
# def threeSum(self, nums: List[int]) -> List[List[int]]:
# result=[]
# nums.sort()
# def recursion(cur_list, cur_sum,next_index):
# if len(cur_list)==3 and cur_sum==0:
# if cur_list not in result:
# result.append(list(cur_list)) ## why this list is important
# if len(cur_list)<3:
# for i in range(next_index, len(nums)):
# cur_list.append(nums[i])
# recursion(cur_list, cur_sum+nums[i], i+1)
# cur_list.pop()
# recursion([], 0, 0)
# return result
## iteration: for loop + two sum
# time O(n**2); space O(1) or O(n) depends on the sorting algorithm
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums)<3: return []
result=[]
nums.sort()
for i in range(len(nums)-2):
##deal with replicates of the first value
if i > 0 and nums[i]==nums[i-1]:
continue
head, tail= i+1,len(nums)-1
target= 0- nums[i]
while head<tail:
if nums[head]+nums[tail]==target:
result.append(list([nums[i], nums[head], nums[tail]]))
head+=1
##deal with the replicates of the second and third value
while nums[head]==nums[head-1] and head<tail:
head+=1
elif nums[head]+nums[tail]<target:
head+=1
else: tail-=1
return result
|
30a23a9f2bd5629bee6ec0e152a84dba89d4309b | SteveGeyer/Firefly | /src/experiments/drive.py | 2,888 | 3.6875 | 4 | #!/usr/bin/env python3
"""Drive the quadcopter from a command line for testing.
b -- bind the quadcopter
a -- arm the quadcopter for flight
d -- disarm and stop flying
A line of one to four numbers in the range of 0.0 to 1.0 separated by
spaces. They are in the order of throttle, direction, forward/backwards,
and rotation. Missing numbers will be filled in with the value 0.5.
q -- quit program
"""
__author__ = "Steve Geyer"
__copyright__ = "Copyright 2019, Steve Geyer"
__credits__ = ["Steve Geyer"]
__license__ = "BSD 3-Clause License"
__version__ = "1.0.0"
__status__ = "Development"
import argparse
import command
def help():
print('b -- bind the quadcopter\n')
print('a -- arm the quadcopter for flight')
print('d -- disarm and stop flying\n')
print('A line of one to four numbers in the range of 0.0 to 1.0 separated\n'
+'by spaces. They are in the order of throttle, direction,\n'
+'forward/backwards, and rotation. Missing numbers will be filled\n'
+ 'in with the value 0.5.\n')
print('q -- quit program')
print('h, ? -- this help')
def execute(c, text):
"""Grab values and command quad."""
parts = text.split()
if not parts:
print("Must have at least one number")
return
try:
throttle = float(parts[0])
if len(parts) > 1:
direction = float(parts[1])
else:
direction = 0.5
if len(parts) > 2:
forward = float(parts[2])
else:
forward = 0.5
if len(parts) > 3:
rotation = float(parts[3])
else:
rotation = 0.5
print(('throttle:%.2f direction:%.2f '
+'forward:%.2f rotation:%.2f') % (throttle, direction,
forward, rotation))
c.command(throttle, direction, forward, rotation)
except ValueError:
print('Bad number')
def main():
"""Execute the command"""
parser = argparse.ArgumentParser(description='Drive quadcopter from a command line')
parser.add_argument('-t', '--ttyname',
help='Serial tty to transmitter.',
required=False,
default='/dev/ttyACM0')
args = parser.parse_args()
c = command.Command(args.ttyname)
while True:
text = input('> ')
if text == 'a':
c.arm()
print('Armed')
elif text == 'b':
print('Binding...')
c.bind()
print(' done')
elif text == 'd':
c.disarm()
print('Disarm')
elif text == '':
continue
elif text == 'q':
break
elif text == 'h':
help();
elif text == '?':
help();
else:
execute(c, text)
if __name__ == "__main__":
main()
|
a21b332ae7406e1a1fdbc9311151dea6805dcf02 | rcchen0526/UVA | /uva_10006.py | 905 | 3.609375 | 4 | def mod(a, n):
N=n
ans=a if n%2 else 1
while int(n/2):
n=int(n/2)
temp=(a*a)%N
if n%2:
ans=(ans*temp)%N
a=temp
return ans
def check(a, n):
if mod(a, n)==a:
return True
else:
return False
prime=[False for _ in range(65001)]
prime[0], prime[1] = True, True
for i in range(2, 65001):
if not prime[i]:
j=2*i
while j<=65000:
prime[j]=True
j+=i
while True:
try:
n=int(input())
except:
break
if not n:
break
isCarmichael = True
if not prime[n]:
isCarmichael = False
for i in range(2, n):
isCarmichael = isCarmichael and check(i, n)
if not isCarmichael:
break
if isCarmichael:
print("The number {} is a Carmichael number.".format(n))
else:
print("{} is normal.".format(n)) |
57c9d16ed7a19d88badc7541e5c941ccc742ee86 | zyanwei2011/Automated-Testing | /python10/class_0910_object/class_0910_3.py | 615 | 3.703125 | 4 | __author__ = 'zz'
class MathMethod:
def __init__(self,a,b):#初始化函数 通过他可以传递属性值进来
self.a=a
self.b=b
def add(self):
return self.a+self.b
def sub(self):
return self.a-self.b
def chengfa(self):
return self.a*self.b
def div(self):
return self.a/self.b
t_1=MathMethod(6,3)#如果有初始化函数 创建实例的时候传递对应初始化函数的参数个数
res=t_1.sub()
print("运行结果是:{}".format(res))
#类没有定义属性
#初始化函数 创建实例的时候去传递
#def __int__() 没有return |
cc7eff26e3bc57e077fba51d44b86530f4ee445c | CharlyJeffrey/SemaineInfo2019 | /Activités/Tic-Tac-Toe/tic-tac-toe.py | 3,739 | 4.28125 | 4 | """
Jeu «Tic-Tac-Toe» pour la semaine Informatique tous âges.
Auteur: Fermion & Bérillium
"""
# VARIABLES GLOBALES
SYMBOLES = ["X", "O"] # Symboles possibles
JOUEUR_1 = input("Joueur 1, quel est votre nom? ") # Nom du joueur 1
JOUEUR_2 = input("Joueur 1, quel est votre nom? ") # Nom du joueur 2
JOUEURS = [JOUEUR_1, JOUEUR_2]
QUI_JOUE = False # Joueur qui joue (False == 0; True == 1)
# DÉFINITIONS DES FONCTIONS
def affiche_grille(grille):
"""Affiche la grille (liste) fournie en argument
Args:
grille (list): Grille de jeu (3x3)
"""
print(" 0 1 2 ")
print(" *---*---*---*")
# Boucle pour afficher les éléments de la grille
for i in range(3):
# Affiche la ie rangée
print(i,"| {} | {} | {} |".format(grille[3*i], grille[i*3 + 1], grille[i*3 + 2]))
print(" *---*---*---*")
# Fin de la fonction
return
def choix_joueur(grille):
"""Obtient la case ou le joueur veut jouer.
Args:
grille (list): Grille de jeu (3x3)
"""
# Boucle infinie
while True:
# Affihce la grille de jeu
affiche_grille(grille)
# Demande au joueur où il veut jouer
print("{} où voulez-vous joueur?".format(JOUEURS[QUI_JOUE]))
print("Entrez l'indice de la rangé espace de celle de la colone. Exemple: 0 1.\n")
# Sépare le input aux espacements
choix = input().split()
# Vérifie si le input n'est pas composé de 2 éléments
if len(choix) != 2:
print("Votre choix doit être de la forme suivante: i j")
print("'i' est le numéro de la rangé et 'j' celle de la colonne.\n")
# Sinon, poursuit la procédure
else:
# Obtient la rangé/colonne
row, col = choix[0], choix[1]
# Essaie de convertir en 'int'
try:
row, col = int(row), int(col)
# Obtient l'indice associé à row et col
indice = 3 * row + col
# Vérifie si les nombres entrés sont valides
if (row < 0 or 2 < row) or (col < 0 or 2 < col):
print("Vous devez entrer des chiffres entre 0 et 2.")
# Vérifie si la case est libre
elif (grille[indice] != '?'):
print("La case choisie n'est pas libre!")
# Sinon, retourne le choix du joueur
else:
return indice
# Exception
except ValueError:
print("Vous devez entrer des nombres!")
def gagnant(grille):
"""Détermine si le joueur présent a gagné la partie.
Args:
grille (list): Grille de jeu
"""
# Obtient la chaine gagnanate
chaine = SYMBOLES[QUI_JOUE] * 3
# Combinaisons gagnantes possibles
combinaisons = [ [0 ,1, 2],[3, 4, 5],[6, 7, 8],
[0, 3, 6],[1, 4, 7],[2, 5, 8],
[0, 4, 8],[2, 4, 6]]
# Boucle sur les combinaisons gagnantes
for comb in combinaisons:
# Vérifie si une combinaison est gagnante
if chaine == grille[comb[0]] + grille[comb[1]] + grille[comb[2]]:
return True
# Sinon, n'est pas encore gagnant
return False
# Grille de jeu; initialement vide
grille = ["?", "?", "?", "?", "?", "?", "?", "?", "?"]
# Boucle de jeu
while True:
# Obtient le choix du joueur
indice = choix_joueur(grille)
# Place le symbole du joueur à la position désirée
grille[indice] = SYMBOLES[QUI_JOUE]
# Vérifie si le joueur a gagné
if gagnant(grille):
print("{} a gagné la partie! Félication!".format(JOUEURS[QUI_JOUE]))
break
QUI_JOUE = not QUI_JOUE |
1a4b7559b45b9d1dccc1b687501b4a7f44c00ef9 | kingbj940429/Coding_Test_Solution | /beak_joon/b_3568.py | 576 | 3.53125 | 4 | ''' 3568번 iSharp '''
def remove_comma(input_data):
result_list = []
for val in input_data:
if(val.find(",") > 0):
val = val.replace(",","")
result_list.append(val)
return result_list
basic_type = ['[]', '&', '*']
if __name__ == "__main__" :
input_data = input()
input_data = input_data.split(" ")
removed_comma_data = remove_comma(input_data)
common_data_type = removed_comma_data[0]#공통 변수형 선언
removed_comma_data.remove(common_data_type)#리스트에서 공통 변수형 제거
|
32ab90bbe2ced17dc0fe076659dabd33d393e1fd | Mattnolan45/College-Work | /CA116-CA117 Programming 1 & 2/2017-02-07/ca117/nolanm45/league_12.py | 541 | 3.65625 | 4 | import sys
teams=sys.stdin.readlines()
largest=0
for team in teams:
team=( " ".join(team.split()[1:-8]))
if len(team)>largest :
largest=len(team)
print("{:3s} {:{}s}{:>3s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}".format("POS","CLUB",largest,"P","W","D","L","GF","GA","GD","PTS"))
for team in teams:
team=team.split()
print("{:>3s} {:{}s}{:>3s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}".format(team[0]," ".join(team[1:-8]),largest,team[-8],team[-7],team[-6],team[-5],team[-4],team[-3],team[-2],team[-1]))
|
a85b2eb1f984997874c8b91b24dfbcdf8fa90b48 | deo1/deo1 | /Legacy/AddressBook/Tests.py | 3,749 | 3.875 | 4 | __author__ = 'jfb_000'
from AddressBook import Book
def testbook(bookobj, firstname=None, lastname=None, phonenumber=None, emailaddress=None, street=None, city=None,
state=None, country=None):
print("----------------TEST-------------------")
# create book
print("This is " + bookobj.ownerid + "'s address book")
print("The maximum amount of contacts is " + str(bookobj.maxContacts()))
print("Number of contacts in address book: " + str(bookobj.numberOfContacts()))
# add contact with all values
bookobj.addContact(firstname, lastname, phonenumber, emailaddress, street, city, state, country)
print("Number of contacts in address book: " + str(bookobj.numberOfContacts()))
# find contact via phone number
if phonenumber:
testphonenumber = phonenumber
contactkeylist = bookobj.findContacts(phonenumber=testphonenumber)
if contactkeylist:
print("The contact(s) with phone number " + testphonenumber + " is:")
for key in contactkeylist:
bookobj.findContactByKey(key).dispContact()
else:
print("No contact with the phone number " + testphonenumber + " was found.")
# find contact via street and city
if street and city:
teststreet = street
testcity = city
contactkeylist = bookobj.findContacts(street=teststreet, city=testcity)
if contactkeylist:
print("The contact(s) with address " + teststreet + " " + testcity + " is:")
for key in contactkeylist:
bookobj.findContactByKey(key).dispContact()
else:
print("No contact with the address " + teststreet + " " + testcity + " was found.")
# testemail = 'jfb@u.northwestern.edu'
# contact = bookobj.findContact(email=testemail)
# if contact:
# print("The contact with email " + testemail + " is " + contact.firstname + " " + contact.lastname)
# else:
# print("No contact with the email " + testemail + " was found.")
# contact = bookobj.findContactByName(newcontact.firstname, newcontact.lastname)
# contact2 = bookobj.findContactByName('Jesse')
# contact.dispContact()
# bookobj.removeContact(contact2)
# contact.delLastName()
# bookobj.removeContact(contact)
# print("Number of contacts in address book: " + str(bookobj.numberOfContacts()))
# num = bookobj.maxContacts()
# print("The maximum amount of contacts is " + str(bookobj.maxContacts()))
# def testcontact(firstname=None, lastname=None, phonenumber=None, emailaddress=None, street=None, city=None,
# country=None):
# print("----------------TEST-------------------")
# contactobj = Contact(firstname, lastname, phonenumber, emailaddress, street, city, country)
# print("Contact's first name is " + contactobj.firstName)
# if contactobj.lastname is not None:
# print("Contact's last name is " + contactobj.lastname)
# else:
# print('No last name')
# if contactobj.phonenumber is not None:
# print("Contact's phone number is " + contactobj.phonenumber)
# else:
# print('No phone number')
# if contactobj.emailaddress is not None:
# print("Contact's email address is " + contactobj.emailaddress)
# else:
# print('No email address')
# if contactobj.street is not None:
# print("Contact's street is " + contactobj.street)
# else:
# print('No street')
# if contactobj.city is not None:
# print("Contact's city is " + contactobj.city)
# else:
# print('No city')
# if contactobj.country is not None:
# print("Contact's country is " + contactobj.country)
# else:
# print('No country') |
acfee2ea1b9d05a5e200cd19b66a697625418f4c | Rivarrl/leetcode_python | /leetcode/algorithm_utils.py | 5,078 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# 算法辅助类
import time
from typing import List
null = None
class Trie:
def __init__(self, x):
self.val = x
self.children = [None] * 26
class Employee:
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
self.subordinates = subordinates
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
class NextNode:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
class NeighborNode:
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
class QuadNode:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
class RandomNode:
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
class Bucket:
def __init__(self,m=0,M=0,isempty=True):
self.m = m
self.M = M
self.isempty = isempty
def list_node_print(head, cnt=20):
if not head:
print(None)
return
while head.next and cnt > 0:
print(head.val, end='->')
head = head.next
cnt -= 1
print(head.val)
def construct_list_node(arr):
res = ListNode(None)
p = res
for x in arr:
p.next = ListNode(x)
p = p.next
return res.next
def binary_fills(i):
if i == 0: return 0
x = 1
while x <= i:
x <<= 1
return x - i - 1
def split_tree_list(arr):
depth = pow((len(arr) + 1), 2)
arrl, arrr = [], []
for i in range(1, depth):
l = 2 ** i
r = l * 2 - 1
m = (l + r) // 2
arrl += arr[l - 1 : m]
arrr += arr[m: r]
return arrl, arrr
def construct_tree_node(arr):
arr += [None] * binary_fills(len(arr))
if len(arr) == 0 or arr[0] == None: return None
root = TreeNode(arr[0])
arrl, arrr = split_tree_list(arr)
left = construct_tree_node(arrl)
right = construct_tree_node(arrr)
root.left = left
root.right = right
return root
# deprecated
def construct_tree_node_v2(arr):
if not arr: return
def _construct(i):
if i >= len(arr):
return None
root = TreeNode(arr[i])
root.left = _construct(i*2+1)
root.right = _construct(i*2+2)
return root
return _construct(0)
def tree_node_print(root):
def inner(root):
res = None
if root:
res = []
res.append(root.val)
left, right = inner(root.left), inner(root.right)
if left or right:
res += [left, right]
return res
res = inner(root)
print(res)
def deconstruct_tree_node(root):
res = []
if root:
res.extend([root.val])
stk = [root]
while stk:
cur = []
for each in stk:
if each:
cur.append(each.right)
cur.append(each.left)
if cur != []:
res.extend([None if not x else x.val for x in cur][::-1])
stk = [x for x in cur]
return res
def matrix_pretty_print(matrix, b=0):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
x = int(matrix[i][j]) if b else matrix[i][j]
print(x, end=' ')
print()
print()
def timeit(f):
def inner(*args, **kwargs):
t1 = time.time()
x = f(*args, **kwargs)
t2 = time.time()
print("{0} runs: {1:.4f} sec".format(f.__name__, t2 - t1))
if isinstance(x, ListNode):
list_node_print(x)
elif isinstance(x, TreeNode):
tree_node_print(x)
else:
if x and isinstance(x, List) and isinstance(x[0], List):
matrix_pretty_print(x)
else:
print(x)
return x
return inner
if __name__ == '__main__':
# x = [4,1,6,3,5,2]
# heap_sort(x)
# print(x)
# matrix_pretty_print([[1,2,3],[4,5,6]])
# a = [5,4,2,3,6,1,7,9]
# quick_sort(a, 0, len(a) - 1)
# print(a)
# a = construct_list_node([1,2,3,4,5,6])
# print_list_node(a)
# b = construct_tree_node([8,12,2,None,None,6,4,None,None,None,None])
# print_tree_node(b)
# c = deconstruct_tree_node(b)
# print(c)
pass
|
de59bb6375281515f61085b097cba7b65b07b446 | willydavid1/python-basic | /strings.py | 399 | 3.90625 | 4 | name = 'willy'
print(name.upper())
print(name.capitalize())
print(name.strip())
print(name.lower())
print(name.replace('y', 'i'))
print(name[0])
print(len(name))
print(name[0:3]) # 'wil'
print(name[:3]) # 'wil'
print(name[3:]) # 'ly'
print(name[1:4]) # 'ill'
print(name[1:4:2]) # 'il' / access the letters two by two
print(name[::]) # 'willy'
print(name[::2]) # 'wly'
print(name[::-1]) # 'ylliw'
|
925f020380e95d19eb61b20a450ea669fd6c8588 | Yellineth/Algoritmos-Python | /n_impares.py | 213 | 3.625 | 4 | #calcula cuantos numeros impares hay en un total de 100 numeros enteros
c=0
for i in range (5):
n=int(input(" ¿cual es el numero? "))
n1=n % 2
if n1<0:
c=c+1
print("Hay",c,"numeros impares") |
2ca98a7aca3fbfa90552e1fb7a4933d8f6fae22a | KTingLee/Python100D | /100D_1/Day01To07/EX6_2_Is_Scheherazade_Numbers.py | 491 | 3.8125 | 4 | # 2020/02/19 Is a Scheherazade Numbers?
#
# 對稱數又稱回文數(Scheherazade Numbers, palindromic number)
# 意即該數顛倒,仍得到相同數字。
#
# 例如 12321 顛倒仍為 12321
def is_palindromic(num):
res=0
temp=num
while temp > 0:
res = res*10 + temp%10
temp = temp // 10
if res == num:
print('%d 為對稱數' % num)
return 1
else:
print('%d 不為對稱數' % num)
return 0
is_palindromic(12321) |
2fdc32f7f246323392979ed61d134c5a788891c2 | swarnim321/ms | /dataStructures_Algorithms/k_sorted_array.py | 465 | 3.734375 | 4 | import heapq
from heapq import heappop, heappush
def sort_k_sorted_arr(list,k):
pq=list[0:k+1]
heapq.heapify(pq)
index =0
for i in range (k+1, len(list)):
list[index]=heappop(pq)
index+=1
heappush(pq,list[i])
while pq:
list[index]=heappop(pq)
index+=1
if __name__ == '__main__':
list = [1, 4, 5, 2, 3, 7, 8, 6, 10, 9]
k = 2
sort_k_sorted_arr(list, k)
print(list)
|
f74f98d9d5018b04534a8df239833921d97a0907 | Rudra-Patil/Programming-Exercises | /LeetCode/src/121 - Best Time to Buy and Sell Stock.py | 421 | 3.5625 | 4 | """
Topics: | Array | Dynamic Programming |
"""
class Solution:
def maxProfit(self, prices):
"""
Time: O(n)
Space: O(1)
"""
min_seen = float('inf')
max_profit = 0
for price in prices:
if price < min_seen:
min_seen = price
else:
max_profit = max(max_profit, price - min_seen)
return max_profit
|
aec68ff30245a2d399bd5644c81f88d149d7ee4a | Ch-sriram/python-advanced-concepts | /oop/polymorphism.py | 1,390 | 4.3125 | 4 | class User:
# this class doesn't have an __init__
def sign_in(self):
return 'logged in'
# we can have same method names, but in different instances
# of the same class/sub-class, they can be overridden.
# For example, attack() method is defined here, which is
# again defined in Wizard and Archer classes too
def attack(self):
return f'do nothing'
# Wizard is subclass of User
class Wizard(User):
def __init__(self, name, power):
self.name = name
self.power = power
def attack(self):
return f'attacking with power of {self.power}'
# Archer is also a derived/sub class of User
class Archer(User):
def __init__(self, name, num_arrows):
self.name = name
self.num_arrows = num_arrows
def attack(self):
return f'attacking with arrows: arrows-left are {self.num_arrows}'
w1 = Wizard('Merlin', 50)
a1 = Archer('Robinhood', 100)
# Demonstration of Polymorphism
def player_attack(obj):
return obj.attack();
print(player_attack(w1)) # attacking with power of 50
print(player_attack(a1)) # attacking with arrows: arrows-left are 100
# Demo 2 of Polymorphism:
for obj in [w1, a1]:
print(player_attack(obj))
'''
Output:
------
attacking with power of 50
attacking with arrows: arrows-left are 100
attacking with power of 50
attacking with arrows: arrows-left are 100
''' |
e2a575c9bd7dfc4dc0affff950ad1b8a88865076 | jairock282/pythonWorshop | /Clase6/claseObject.py | 819 | 4.3125 | 4 | ##Herencia
"""
En python todas las clases heredan por default de la clase Object, la cual,
cuenta con un alista de atributos y metodos para poder utilizar
__init__ no es un constructor, solo es un metodo que permite definir
los atributos
"""
class Gato:
def __init__(self, nombre):
self.nombre = nombre
#Metodo que nos permitira regresar el atributo que hace referencia
#al objeto, es similar a los getters y setters en java
def __str__(self):
return self.nombre
class Pato(object):
def __init__(self, nombre):
self.nombre = nombre
def __str__(self):
return self.nombre
gato = Gato("Gardfield")
gato.edad = 6
pato = Pato("Lucas")
"""
print(gato)
print(pato)
"""
##Con el metodo __dict__ nos regresara un diccionario con los valores
#correspondientes
print(gato.__dict__)
print(pato.__dict__)
|
013f8fff43f21f25d0e04a6c5ba47cb07f7a7723 | flackbash/morse-code-translator | /morse.py | 5,531 | 3.546875 | 4 | import keyboard
import time
import sys
import argparse
morse = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---',
'-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-',
'..-', '...-', '.--', '-..-', '-.--', '--..', '.----', '..---',
'...--', '....-', '.....', '-....', '--...', '---..', '----.',
'-----']
alpha = [ch for ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890']
morse_to_alpha = dict(zip(morse, alpha))
alpha_to_morse = dict(zip(alpha, morse))
def text_from_morse(morse):
"""Convert morse code to alphabet.
Arguments:
morse -- A string containing '.' for short, '-' for long and ' ' for a new
char.
>>> text_from_morse(".. -.-. .... / -- --- .-. ... . ")
'ICH MORSE'
>>> text_from_morse(".")
'E'
"""
text = ""
for i, word in enumerate(morse.split("/")):
for char in word.split(" "):
if char in morse_to_alpha:
text += morse_to_alpha[char]
if i < len(morse.split("/")) - 1:
text += " "
return text
def morse_from_text(text):
"""Convert morse code to alphabet.
Arguments:
text -- A string.
>>> morse_from_text("Ich morse")
'.. -.-. .... / -- --- .-. ... .'
"""
text = text.upper()
morse = ""
for i, char in enumerate(text):
if char in alpha_to_morse:
morse += alpha_to_morse[char]
if char == " ":
morse += "/"
if i < len(text) - 1:
morse += " "
return morse
def show_morse_table():
"""Print the morse code table.
"""
for i, ch in enumerate(alpha):
if i != 0 and i % 6 == 0:
print()
if ch == "1":
print()
print("\t\t%s %s" % (ch, alpha_to_morse[ch]), end="")
print()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='store_true',
help="Print morse code as you send it.")
parser.add_argument('-s', '--show_table', action='store_true',
help="Print morse table for each new line.")
parser.add_argument('-d', '--dit_length', default=0.2, type=float,
help="Time in seconds of smallest unit, the dit '.'. "
"A dah '-' is 3 dits long, A pause between symbols is"
" one dit, A pause between characters is 3 dits, a "
"pause between words is 7 dits.")
parser.add_argument('-dw', '--delta_word', type=float,
help="Time in seconds after which a pause is treated"
" as inter-word-pause.")
parser.add_argument('-dc', '--delta_char', type=float,
help="Time in seconds after which a pause is treated"
" as inter-character-pause.")
parser.add_argument('-t', '--text_to_morse', action='store_true',
help="Entered text is converted to morse code.")
args = parser.parse_args()
verbose = args.verbose
show_table = args.show_table
dit_length = args.dit_length
d_char = args.delta_char if args.delta_char else dit_length * 3
d_word = args.delta_word if args.delta_word else dit_length * 7
text_to_morse = args.text_to_morse
pressed = None
released = None
char_pause = False
morse_code = ""
enter_pressed = False
if not text_to_morse:
print("Use 'ctrl' as on-key.")
print("Press enter to convert the sended code to text")
if show_table:
show_morse_table()
while True:
next_symbol = ""
if keyboard.is_pressed("ctrl") and not pressed:
pressed = time.time()
released = None
char_pause = False
elif not keyboard.is_pressed("ctrl") and pressed:
# Print . or - depending on how long the button was pressed
delta = time.time() - pressed
if delta < dit_length:
next_symbol = "."
else:
next_symbol = "-"
# Reset times
pressed = None
released = time.time()
if released and time.time() - released > d_word:
# Print a slash when the button was released for more than
# <d_word> seconds indicating a new word
next_symbol = "/ "
released = None
elif released and time.time() - released > d_char \
and not char_pause:
# Print a space indicating a new character
next_symbol = " "
char_pause = True
morse_code += next_symbol
if verbose and next_symbol:
print(next_symbol, end="")
if keyboard.is_pressed("enter") and not enter_pressed:
# Print morse as alphabetical text on enter press
if verbose:
print()
print(text_from_morse(morse_code))
print()
if show_table:
show_morse_table()
morse_code = ""
enter_pressed = True
released = None
pressed = None
elif not keyboard.is_pressed("enter"):
enter_pressed = False
sys.stdout.flush()
else:
while True:
pass
|
0ec82b8886f9adfedd2f099d3820dbe66a7f48e5 | liangg/edocteel | /src/Python/leetcode2.py | 56,114 | 3.96875 | 4 | #
# Leetcode questions on Tree, List
#
# Queestions 650 - 850
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Q-222: Count Complete Binary Tree Nodes
class CountCompleteBinaryTreeNodes(object):
def countCompleteTreeNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
left_depth = 0
n = root
while n is not None:
left_depth += 1
n = n.left
right_depth = 0
n = root
while n is not None:
right_depth += 1
n = n.right
# optimization - both heights are same so it is complete tree
if left_depth == right_depth:
return 2**left_depth - 1
return self.countCompleteTreeNodes(root.left) + self.countCompleteTreeNodes(root.right) + 1
@staticmethod
def test():
print "Count Complete Tree Nodes"
n0 = TreeNode(0)
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n0.left = n1
n0.right = n2
n1.left = n3
cc = CountCompleteBinaryTreeNodes()
print cc.countCompleteTreeNodes(n0)
CountCompleteBinaryTreeNodes.test()
# Q-236: LCA in binary tree
class BinaryTreeLCA(object):
def findLCA(self, root, p, q):
if root is None:
return (None, False, False)
isP = (root is p) # reference equality
isQ = (root is q)
left = self.findLCA(root.left, p, q)
if (left[0] is not None):
return (left[0], True, True)
right = self.findLCA(root.right, p, q)
if (right[0] is not None):
return (right[0], True, True)
foundP = left[1] or right[1] or isP
foundQ = left[2] or right[2] or isQ
if foundP and foundQ:
return (root, True, True)
return (None, foundP, foundQ)
def lowestCommonAncestor(self, root, p, q):
result = self.findLCA(root, p, q)
return result[0]
@staticmethod
def test():
print "LCA"
lca = BinaryTreeLCA()
p = TreeNode(1)
q = TreeNode(2)
p.left = q
print lca.lowestCommonAncestor(p,p,q)
BinaryTreeLCA.test()
# Q-257 Binary Tree Path
class BinaryTreePath(object):
def traverse(self, root, path, result):
if root is None:
return
p = path + "->" + str(root.val)
if root.left is None and root.right is None:
result.append(p)
return
self.traverse(root.left, p, result)
self.traverse(root.right, p, result)
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
result = []
if root is None:
return result
p = str(root.val)
if root.left is None and root.right is None:
result.append(p)
self.traverse(root.left, p, result)
self.traverse(root.right, p, result)
return result
@staticmethod
def test():
print "Q-257 Binary Tree Path"
btp = BinaryTreePath()
n1 = TreeNode(1)
print btp.binaryTreePaths(n1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n1.left = n2
n1.right = n3
n2.right = n4
print btp.binaryTreePaths(n1)
# Q-328 Odd Even List
class OddEvenList(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
oddHead, oddTail, evenHead, evenTail = None, None, None, None
idx, n = 1, head
while n is not None:
if idx % 2 != 0:
if oddTail is None:
oddHead, oddTail = n, n
else:
oddTail.next = n
oddTail = n
else:
if evenTail is None:
evenHead, evenTail = n, n
else:
evenTail.next = n
evenTail = n
n = n.next
idx += 1
if evenHead is not None:
oddTail.next = evenHead
evenTail.next = None
n = oddHead
while n is not None:
print n.val, ","
n = n.next
return oddHead
# Q-387 First Unique Character in String
#
# Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist,
# return -1. You may assume the string contain only lowercase letters.
class FirstUniqueCharInString(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return -1
memo = [len(s) for i in xrange(26)]
for i in xrange(len(s)):
pos = ord(s[i]) - ord('a')
if memo[pos] == len(s):
memo[pos] = i
else:
memo[pos] = -1
smallest = len(s)
for i in xrange(26):
if memo[i] >= 0 and memo[i] < len(s) and memo[i] < smallest:
smallest = memo[i]
return -1 if smallest == len(s) else smallest
# Q-392 Is Subsequence (2 pointers)
#
# Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower
# case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a
# short string (<=100).
class IsSubsequence():
def isSubsequence(self, s, t):
tidx = 0
for i in xrange(len(s)):
match = False
for j in xrange(tidx, len(t)):
if t[j] == s[i]:
match = True
tidx = j+1
break
tidx = j+1
if tidx >= len(t) and not match:
return False
return True
@staticmethod
def test():
print "Is Subsequence"
sub = IsSubsequence()
print sub.isSubsequence("b", "c")
print sub.isSubsequence("ace", "abcde")
print sub.isSubsequence("axc", "ahbgdc")
IsSubsequence.test()
# Q-437 Path Sum III
#
# You are given a binary tree in which each node contains an integer value. Find the number
# of paths that sum to a given value. The path does not need to start or end at the root or
# a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
class PathSum:
def path(self, root, sum, prefixSum):
if root is None:
return
prefixSum.append(prefixSum[-1] + root.val)
for i in xrange(1, len(prefixSum)):
if prefixSum[-1] - prefixSum[i-1] == sum:
self.count += 1
self.path(root.left, sum, prefixSum)
self.path(root.right, sum, prefixSum)
prefixSum.pop()
def pathSum(self, root, sum):
prefix = [0]
self.count = 0
self.path(root, sum, prefix)
return self.count
# Q-445 Add Two Numbers II
class AddTwoNumbers(object):
def reverse(self, l):
head, tail, p = None, None, l
while p is not None:
next = p.next
if head is None:
p.next = None
head, tail = p, p
else:
p.next = head
head = p
p = next
return head
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p1, p2 = self.reverse(l1), self.reverse(l2)
head, carry = None, 0
while p1 is not None and p2 is not None:
p12 = p1.val + p2.val + carry
n, carry = ListNode(p12 % 10), p12 / 10
n.next = head
head = n
p1, p2 = p1.next, p2.next
p3 = p1 if p1 is not None else p2
while p3 is not None:
s = p3.val + carry
n, carry = ListNode(s % 10), s / 10
n.next = head
head, p3 = n, p3.next
if carry > 0:
n = ListNode(carry)
n.next = head
head = n
return head
@staticmethod
def test():
l1,l2,l3,l4,l5,l6,l7 = ListNode(7), ListNode(2), ListNode(4), ListNode(3), ListNode(5), ListNode(6), ListNode(4)
l1.next = l2
l2.next = l3
l3.next = l4
l5.next = l6
l6.next = l7
atn = AddTwoNumbers()
atn.addTwoNumbers(l1, l5)
# Q-543 Diameter of Binary Tree
class DiameterOfBinaryTree(object):
def depth(self, root):
if root.left is None and root.right is None:
return 0
left_len = (1 + self.depth(root.left)) if root.left is not None else 0
right_len = (1 + self.depth(root.right)) if root.right is not None else 0
if left_len + right_len > self.max_path:
self.max_path = left_len + right_len
return left_len if left_len > right_len else right_len
def diameterOfBinaryTree(self, root):
self.max_path = 0
if root is not None:
self.depth(root)
return self.max_path
@staticmethod
def test():
print "Diameter of Binary Tree"
dia = DiameterOfBinaryTree()
n0 = TreeNode(0)
n1 = TreeNode(1)
n2 = TreeNode(2)
n0.left = n1
n0.right = n2
n3 = TreeNode(3)
n4 = TreeNode(4)
n1.left = n3
n1.right = n4
n5 = TreeNode(5)
n2.left = n5
print dia.diameterOfBinaryTree(n0)
n10 = TreeNode(0)
n11 = TreeNode(1)
n10.left = n11
n12 = TreeNode(2)
n11.left = n12
n13 = TreeNode(3)
n14 = TreeNode(4)
n12.left = n13
n12.right = n14
print dia.diameterOfBinaryTree(n10)
DiameterOfBinaryTree.test()
# Q-521 Longest Uncommon Subsequence I & II
#
# Crap question that is hard to understand
class LongestUncommonSubsequence(object):
def findLUSlength1(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
"""
return -1 if a == b else max(len(a), len(b))
def isSubsequence(self, s, t):
tidx = 0
for i in xrange(len(s)):
match = False
for j in xrange(tidx, len(t)):
if t[j] == s[i]:
match = True
tidx = j+1
break
tidx = j+1
if tidx >= len(t) and not match:
return False
return True
def findLUSlength(self, strs):
"""
:type strs: List[str]
:rtype: int
"""
counts = {}
for s in strs:
counts[s] = 1 if s not in counts else counts[s]+1
sorted_strs = sorted(strs, key=lambda s:len(s))
for i in xrange(len(sorted_strs)-1, -1, -1):
s = sorted_strs[i]
if counts[s] > 1:
continue
for j in xrange(len(sorted_strs)-1, -1, -1):
if len(sorted_strs[j]) <= len(s):
return len(s)
elif self.isSubsequence(s, sorted_strs[j]):
break
return -1
@staticmethod
def test():
print "Longest Uncommon Subsequence"
lus = LongestUncommonSubsequence()
print lus.findLUSlength1("aaa", "aaa") # -1
print lus.findLUSlength1("aefawfawfawfaw", "aefawfeawfwafwaef") # 17
print lus.findLUSlength(["aba","cdc", "eae"]) # 3
print lus.findLUSlength(["aabbcc","aabbcc","b","bc"]) # -1
print lus.findLUSlength(["aabbcc", "aabbcc","bc","bcc","aabbccc"]) # 7
LongestUncommonSubsequence.test()
# Q-524 Longest Word in Dictionary through Deleting
#
# Given a string and a string dictionary, find the longest string in the dictionary that can be formed by
# deleting some characters of the given string. If there are more than one possible results, return the
# longest word with the smallest lexicographical order. If there is no possible result, return the empty
# string.
class LongestWordInDictionaryThruDeleting(object):
def isSubsequence(self, s, t):
tidx = 0
for i in xrange(len(s)):
match = False
for j in xrange(tidx, len(t)):
if t[j] == s[i]:
match = True
tidx = j+1
break
tidx = j+1
if tidx >= len(t) and not match:
return False
return True
def findLongestWord(self, s, d):
max_len = 0
max_words = [""]
for t in d:
if self.isSubsequence(t, s):
if len(t) > max_len:
max_len = len(t)
max_words = [t]
elif len(t) == max_len:
max_words.append(t)
max_words = sorted(max_words)
return max_words[0]
@staticmethod
def test():
print "Longest Word in Dictionary Thru Deleting"
lwdtd = LongestWordInDictionaryThruDeleting()
print lwdtd.findLongestWord("abpcplea", ["ale","apple","monkey","plea"])
print lwdtd.findLongestWord("bab", ["ba","ab","a","b"])
LongestWordInDictionaryThruDeleting.test()
# Q-532 K-diffs Pairs in a Array
#
# Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the
# array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the
# array and their absolute difference is k.
class KDiffsPairsInArray(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0: # absolute diff is positive
return 0
targets = {}
for n in nums:
targets[n] = 1 if n not in targets else targets[n]+1
res = 0
checked = set()
for n in nums:
if n in checked:
continue
if k == 0:
res += 0 if targets[n] == 1 else 1
else:
res += (0 if n-k not in targets else 1)
res += (0 if n+k not in targets else 1)
checked.add(n)
return res if k == 0 else res/2
@staticmethod
def test():
print "K-diffs Unique Pairs in Array"
kdp = KDiffsPairsInArray()
print kdp.findPairs([3,1,4,1,5], 2) # 2 unique pairs
print kdp.findPairs([1,3,1,5,4], 0) # 1
print kdp.findPairs([1,1,1,2,1], 1) # 1
KDiffsPairsInArray.test()
# Q-554 Brick Wall (hashmap)
class BrickWall(object):
def leastBricks(self, wall):
"""
:type wall: List[List[int]]
:rtype: int
"""
edgesCounts = {}
for i in xrange(len(wall)):
edge = 0
for j in xrange(len(wall[i])-1):
edge += wall[i][j]
count = 1
if edgesCounts.has_key(edge):
count = edgesCounts.get(edge) + 1
edgesCounts[edge] = count
maxCount = 0
for k,v in edgesCounts.items():
if v > maxCount:
maxCount = v
return len(wall) - maxCount
@staticmethod
def test():
print "Q-554 Brick Wall"
bw = BrickWall()
print bw.leastBricks([[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]) # 2
BrickWall.test()
# Q-583 Convert BST to Greater Tree
#
# Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original
# BST is changed to the original key plus sum of all keys greater than the original key in BST.
class ConvertBstToGreater(object):
# return subtree sum of unique tree node values
def greaterTree(self, root, parVal):
if root is None:
return 0
treeSum = root.val
if root.right is not None:
sameRight = True if root.val == root.right.val else False
treeSum += self.greaterTree(root.right, parVal)
if sameRight:
treeSum -= root.val
newRootVal = treeSum + parVal
if root.left is not None:
parentSum = newRootVal if root.val != root.left.val else newRootVal - root.val
treeSum += self.greaterTree(root.left, parentSum)
root.val = newRootVal
return treeSum
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.greaterTree(root, 0)
return root
@staticmethod
def test():
print "Greater Tree"
n0 = TreeNode(5) # -> 21
n1 = TreeNode(2) # -> 23
n2 = TreeNode(5) # -> 21
n0.left = n1
n0.right = n2
n3 = TreeNode(2) # -> 23
n1.left = n3
n4 = TreeNode(10) # -> 10
n2.right = n4
n5 = TreeNode(6) # -> 16
n4.left = n5
n6 = TreeNode(3) # -> 26
n3.right = n6
ctg = ConvertBstToGreater()
print ctg.convertBST(n0).val
ConvertBstToGreater.test()
# Q-331 Verify Preorder Serialization of a Binary Tree
class BinaryTreePreorderTraversal(object):
def traversePreorder(self, root):
if root is None:
print "#,"
return
print root.val, ","
self.traversePreorder(root.left)
self.traversePreorder(root.right)
def reconstruct(self, preorder):
"""
:type preorder: str
:rtype: root: TreeNode
"""
stack = [] # [node, whether left child is set]
serialized = preorder.split(',')
root = None
# skip an empty binary tree, i.e. a single "#"
if len(serialized) == 1 and serialized[0] == "#":
return root
for ss in serialized:
node = None
if ss != "#":
node = TreeNode(int(ss))
# set up the root of the tree
if root is None:
root = node
stack.append([node, False])
continue
if len(stack) == 0:
print "Error: malformed serialization"
return None
# link tree node (incl. None for #) with the parent node, and remove the parent
# once it has been completed right child
par = stack[-1][0]
if not stack[-1][1]:
par.left = node
stack[-1][1] = True
else:
# remove linked tree node from the stack
par.right = node
stack.pop()
if node is not None:
stack.append([node, False])
return root
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
stack = [] # [node, whether left child is set]
serialized = preorder.split(',')
# skip an empty binary tree, i.e. a single "#"
if len(serialized) == 1 and serialized[0] == "#":
return True
root = None
for ss in serialized:
node = None
if ss != "#":
node = int(ss)
# set up the root of the tree
if root is None:
root = node
stack.append([node, False])
continue
if len(stack) == 0:
return False
# link tree node (incl. None for #) with the parent node, and remove the parent
# once it has been completed right child
par = stack[-1][0]
if not stack[-1][1]:
stack[-1][1] = True
else:
# remove parent since its right child is linked
stack.pop()
if node is not None:
stack.append([node, False])
return True if len(stack) == 0 else False
@staticmethod
def test():
print "Binary Tree Preorder Traversal"
bpt = BinaryTreePreorderTraversal()
root = bpt.reconstruct("9,3,4,#,#,1,#,#,2,#,6,#,#")
print bpt.isValidSerialization("#") # True for empty tree
print bpt.isValidSerialization("#,#") # False
print bpt.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#") # True
print bpt.isValidSerialization("9,3,4,#,5,1,#,#,2,#") # False
print bpt.isValidSerialization("9,#,2,#,#,3") # False
BinaryTreePreorderTraversal.test()
# Q-404 Sum of Left Leaves
class SumLeftLeaves:
def sumLeftLeaves(self, root, leftChild):
if root == None:
return 0
if root.left == None and root.right == None and leftChild:
return root.val
sum = self.sumLeftLeaves(root.left, True)
sum += self.sumLeftLeaves(root.right, False)
return sum
def sumOfLeftLeaves(self, root):
return self.sumLeftLeaves(root, False)
# Q-414 Third Maximum Number
#
# Given a non-empty array of integers, return the third maximum number in this array. If it does
# not exist, return the maximum number. The time complexity must be in O(n).
class ThirdMaximumNumber(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
import sys
if (len(nums) == 0):
return 0
M = [-sys.maxsize for i in xrange(3)]
for i in xrange(len(nums)):
if nums[i] >= M[0]:
if nums[i] != M[0]:
M[2] = M[1]
M[1] = M[0]
M[0] = nums[i]
elif nums[i] >= M[1]:
if nums[i] != M[1]:
M[2] = M[1]
M[1] = nums[i]
elif nums[i] >= M[2]:
M[2] = nums[i]
print M
return M[2] if M[2] > -(sys.maxsize) else M[0]
@staticmethod
def test():
print "Q-414 Third Maximum Number"
tmn = ThirdMaximumNumber()
print tmn.thirdMax([2,2,3,1]) # 1
print tmn.thirdMax([2,2,2,2]) # 2
print tmn.thirdMax([1,2,2,4,3]) # 2
# Q-454 4 Sum II
#
# Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that
# A[i] + B[j] + C[k] + D[l] is zero.
class FourSum2(object):
def fourSumCount(self, A, B, C, D):
"""
:type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int
"""
if (len(A) == 0):
return 0
N, result = len(A), 0
AB = {}
for i in xrange(N): # O(N^2)
for j in xrange(N):
ab = A[i] + B[j]
count = 1
if AB.has_key(ab):
count = AB[ab] + 1
AB[ab] = count
for i in xrange(N): # O(N^2)
for j in xrange(N):
cd = C[i] + D[j]
if 0-cd in AB:
result += AB[0-cd]
return result
@staticmethod
def test():
print "Q-454 4Sum II"
fs = FourSum2()
print fs.fourSumCount([1,2],[-2,-1],[-1,2],[0,2]) # 2
print fs.fourSumCount([-1,-1],[-1,1],[-1,1],[1,-1]) # 6
FourSum2.test()
# Q-455 Assign Cookies
#
# Assume you are an awesome parent and want to give your children some cookies. But, you should give
# each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a
# cookie that the child will be content with; and each cookie j has a size s[j]. If sj >= gi, we can
# assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the
# number of your content children and output the maximum number. Note: You may assume the greed factor
# is always positive. You cannot assign more than one cookie to one child.
class AssignCookies(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g.sort()
s.sort()
# greedy
result, sidx = 0, 0
for i in xrange(len(g)): # children greedy factors
for j in xrange(sidx, len(s)): # pick the smallest cookie
if s[j] >= g[i]:
result += 1
sidx = j+1
break
return result
# Q-470 Implement Rand10 Using Rand7 (rejection sampling)
#
# Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function
# rand10 which generates a uniform random integer in the range 1 to 10.
class Rand10UsingRand7(object):
def rand10(self):
"""
:rtype: int
"""
n = 0
while True:
r = rand7()
c = rand7()
n = (r-1)*7 + c
if n <= 40:
break
return 1 + n % 10
# Q-513: Find Bottom Left Tree Value
class FindBottomLeftTreeValue:
def findBottomLeftValue(self, root):
import Queue
if root == None:
return None
queue = Queue.Queue()
queue.put((root, 0))
leftmost = (root, 0)
while not queue.empty():
e = queue.get()
if e[1] != leftmost[1]:
leftmost = e
n = e[0]
if not (n.left is None):
queue.put((n.left, e[1]+1))
if not (n.right is None):
queue.put((n.right, e[1]+1))
return leftmost[0].val
@staticmethod
def test():
print "Bottom Left Tree Value"
fblt = FindBottomLeftTreeValue()
n0 = TreeNode(0)
n1 = TreeNode(1)
n2 = TreeNode(2)
n0.left = n1
n0.right = n2
n3 = TreeNode(3)
n1.left = n3
n4 = TreeNode(4)
n5 = TreeNode(5)
n2.left = n4
n2.right = n4
n6 = TreeNode(6)
n4.left = n6
print fblt.findBottomLeftValue(n0)
FindBottomLeftTreeValue.test()
# Q-530 Minimum Absolute Difference in BST
# Q-783 Minimum Distance Between 2 BST Nodes
#
# Given a binary search tree with non-negative values, find the minimum absolute difference between
# values of any two nodes.
class MinAbsoluteDiffBST(object):
def inorder(self, root, nodes):
if root is None:
return
self.inorder(root.left, nodes)
nodes.append(root.val)
self.inorder(root.right, nodes)
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
import sys
if root is None:
return 0
nodes = []
self.inorder(root, nodes)
result = sys.maxsize-1
for i in xrange(1, len(nodes)):
if nodes[i] - nodes[i-1] < result:
result = nodes[i] - nodes[i-1]
return result
# Q-541 Reverse String II
class ReverseString2(object):
def reverse(self, s, l, r):
while l < r:
t = s[l]
s[l] = s[r]
s[r] = t
l += 1
r -= 1
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
ls = list(s)
i = 0
while i + k < len(s):
self.reverse(ls, i, i+k-1)
i += 2*k
if i < len(s):
self.reverse(ls, i, len(s)-1)
return "".join(ls)
@staticmethod
def test():
rs = ReverseString2()
print rs.reverseStr("abcdefg", 2)
# Q-572 Subtree of Another Tree
class SubtreeOfAnotherTree(object):
def match(self, r1, r2):
if r1 is None and r2 is None:
return True
if r1 is None or r2 is None:
return False
if r1.val != r2.val:
return False
return self.match(r1.left, r2.left) and self.match(r1.right, r2.right)
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if t is None:
return True
if s is None:
return False
if s.val == t.val:
if self.match(s, t):
return True
return True if self.isSubtree(s.left, t) else self.isSubtree(s.right, t)
# Q-623 Add One Row to Tree
class AddOneRowToTree(object):
def helper(self, root, v, d, currLevel):
if root is None:
return
if currLevel == d - 1:
n1 = TreeNode(v)
n1.left = root.left
root.left = n1
n2 = TreeNode(v)
n2.right = root.right
root.right = n2
return
self.helper(root.left, v, d, currLevel+1)
self.helper(root.right, v, d, currLevel+1)
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode
"""
if d == 1 or root is None:
newRoot = TreeNode(v)
newRoot.left = root
return newRoot
self.helper(root, v, d, 1)
return root
# Q-628 Maximum Product of Three Numbers
class MaxProductThreeNumbers(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 3:
return 0
nums.sort()
p1 = nums[0]*nums[1]*nums[-1]
p2 = nums[-1]*nums[-2]*nums[-3]
return p1 if p1 > p2 else p2
# Q-637 Average of Levels of Binary Tree
class AverageLevelsBinaryTree(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
import Queue
result = []
if root is None:
return result
queue = Queue.Queue()
queue.put((root, 0)) # (node, level)
lvl, lvl_count, lvl_sum = 0, 0, 0
while not queue.empty():
e = queue.get()
n = e[0]
if e[1] != lvl: # level change
result.append(float(lvl_sum) / float(lvl_count))
lvl, lvl_count, lvl_sum = e[1], 1, n.val
else:
lvl_sum += n.val
lvl_count += 1
if not (n.left is None):
queue.put((n.left, e[1]+1))
if not (n.right is None):
queue.put((n.right, e[1]+1))
# the last row
result.append(float(lvl_sum) / float(lvl_count))
return result
# Q-643 Maximum Average Subarray I
class MaximumAverageSubarray(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
if len(nums) < k:
return 0
maxsum = 0
for i in xrange(k):
maxsum += nums[i]
s = maxsum
for i in xrange(k, len(nums)):
s = s - nums[i-k] + nums[i]
if s > maxsum:
maxsum = s
print maxsum
return float(maxsum)/float(k)
# Q-645 Set Mismatch
#
# The set S originally contains numbers from 1 to n. But unfortunately, due to the
# data error, one of the numbers in the set got duplicated to another number in the
# set, which results in repetition of one number and loss of another number. Given
# an array nums representing the data status of this set after the error. Your task
# is to firstly find the number occurs twice and then find the number that is missing.
# Return them in the form of an array.
class SetMismatch(object):
def findErrorNums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = [None, None]
for i in xrange(len(nums)):
index = abs(nums[i]) - 1
if nums[index] < 0:
result[0] = index+1
else:
nums[index] = 0 - nums[index]
for i in xrange(len(nums)):
if nums[i] > 0:
result[1] = i+1
break
return result
@staticmethod
def test():
print "Q-645 Set Mismatch"
sm = SetMismatch()
print sm.findErrorNums([2,1,4,5,2])
SetMismatch.test()
# Q-650 2 Keys Keyboard (math)
class TwoKeysKeyboard(object):
def minSteps(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 0
nsteps = n
for i in xrange(n-1, 1, -1):
if n % i == 0:
ns = self.minSteps(n/i) + i
if ns < nsteps:
nsteps = ns
return nsteps
@staticmethod
def test():
print "2 Keys Keyboard"
kk = TwoKeysKeyboard()
print kk.minSteps(6) # 5 cppcp
print kk.minSteps(10) # 7 cppppcp
print kk.minSteps(12) # 7
TwoKeysKeyboard.test()
# Q-655 Print Binary Tree
class PrintBinaryTree(object):
def treeDepth(self, root, level):
if root is None:
return level
if root.left is None and root.right is None:
return level+1
left = self.treeDepth(root.left, level+1)
right = self.treeDepth(root.right, level+1)
return left if left > right else right
# pass recursive (left, right) that specify the node index range
def fill(self, root, matrix, level, left, right):
if root is None:
return
col = left + (right-left)/2
matrix[level][col] = str(root.val)
self.fill(root.left, matrix, level+1, left, col-1)
self.fill(root.right, matrix, level+1, col+1, right)
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
depth = self.treeDepth(root, 0) # nrows
if depth == 0:
return [[]]
ncols = 2**depth-1
matrix = [["" for i in xrange(ncols)] for j in xrange(depth)]
self.fill(root, matrix, 0, 0, ncols-1)
print matrix
return matrix
@staticmethod
def test():
print "Q-655 Print Binary Tree"
pbt = PrintBinaryTree()
n1,n2,n3,n4,n5,n6,n7 = TreeNode(1), TreeNode(2), TreeNode(5), TreeNode(3),TreeNode(6),TreeNode(4),TreeNode(7)
n1.left = n2
n1.right = n3
n2.left = n4
n3.left = n5
n4.left = n6
n5.right = n7
pbt.printTree(n1)
# Q-657 Judge Route Circle
class JudgeRouteCircle(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
counts = [0 for i in xrange(4)]
for i in xrange(len(moves)):
if (moves[i] == 'U'):
counts[0] += 1
elif (moves[i] == 'D'):
counts[1] += 1
elif (moves[i] == 'L'):
counts[2] += 1
else:
counts[3] += 1
return True if counts[0] == counts[1] and counts[2] == counts[3] else False
@staticmethod
def test():
jrc = JudgeRouteCircle()
print jrc.judgeCircle("ULLURDDR")
print jrc.judgeCircle("UULLURDDR")
# Q-659 Split Array into Consecutive Subsequences
#
# You are given an integer array sorted in ascending order (may contain duplicates), you need to split
# them into several subsequences, where each subsequences consist of at least 3 consecutive integers.
# Return whether you can make such a split.
class SplitArrayIntoConsecutiveSubsequences(object):
def isPossible(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
freq = {}
for i in xrange(len(nums)):
cnt = 1 if nums[i] not in freq else freq[nums[i]]+1
freq[nums[i]] = cnt
endAt = {}
for i in xrange(len(nums)):
n = nums[i]
if freq[n] == 0:
continue
# greedy, append to an existing subsequence
if n in endAt and endAt[n] > 0:
endAt[n] -= 1
endAt[n+1] = 1 if n+1 not in endAt else endAt[n+1]+1
freq[n] -= 1
# check if it can start a new sequence
elif n+1 in freq and freq[n+1] > 0 and n+2 in freq and freq[n+2] > 0:
freq[n] -= 1
freq[n+1] -= 1
freq[n+2] -= 1
endAt[n+3] = 1 if n+3 not in endAt else endAt[n+3]+1
else:
return False
return True
@staticmethod
def test():
print "Q-659 Split Array into Consecutive Subsequences"
sa = SplitArrayIntoConsecutiveSubsequences()
s0 = [1,2,3,3,4,5] # True
print sa.isPossible(s0)
s1 = [1,2,3,3,4,4,5,5] # True
print sa.isPossible(s1)
s2 = [1,2,3,4,4,5] # False
print sa.isPossible(s2)
s3 = [1,2,3,3,5,6,7] # False
print sa.isPossible(s3)
s4 = [4,5,6,7,7,8,8,9,10,11] # True
print sa.isPossible(s4)
SplitArrayIntoConsecutiveSubsequences.test()
# Q-662 Maximum Width of Binary Tree
#
# Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree
# is the maximum width among all levels. The binary tree has the same structure as a full binary tree,
# but some nodes are null. The width of one level is defined as the length between the end-nodes (the
# leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are
# also counted into the length calculation.
class MaximumWidthOfBinaryTree(object):
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
import Queue
if root is None:
return 0
queue = Queue.Queue()
queue.put((root, 0, 0)) # (node, level, index)
currLevel, leftmost, right, maxWidth = 0, -1, 0, 1
while not queue.empty():
e = queue.get()
n = e[0]
if e[1] != currLevel:
if right-leftmost+1 > maxWidth:
maxWidth = right-leftmost+1
currLevel = e[1]
leftmost = -1 # reset
if n.left is not None:
queue.put((n.left, e[1]+1, e[2]*2+1))
if leftmost == -1:
leftmost = e[2]*2+1
right = e[2]*2+1
if n.right is not None:
queue.put((n.right, e[1]+1, e[2]*2+2))
if leftmost == -1:
leftmost = e[2]*2+2
right = e[2]*2+2
return maxWidth
@staticmethod
def test():
print "Q-662 Maximum Width of Binary Tree"
n1,n2,n3,n4,n5,n6,n7 = TreeNode(1), TreeNode(3), TreeNode(2), TreeNode(5),TreeNode(4),TreeNode(9),TreeNode(8)
n1.left = n2
n1.right = n3
n2.left = n4
#n2.right = n5
n3.right = n5
n4.left = n6
n5.right = n7
mwbt = MaximumWidthOfBinaryTree()
print mwbt.widthOfBinaryTree(n1)
MaximumWidthOfBinaryTree.test()
# Q-680 Valid Palindrome II
class ValidPalindrome2(object):
def checkPalindrome(self, s, l, r, removed):
while (l < r):
if s[l] == s[r]:
l += 1
r -= 1
continue
if (removed):
return False
leftPalin = self.checkPalindrome(s, l+1, r, True)
rightPalin = self.checkPalindrome(s, l, r-1, True)
return True if leftPalin or rightPalin else False
return True
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
return self.checkPalindrome(s, 0, len(s)-1, False)
@staticmethod
def test():
print "Q-680 Valid Palindrome II"
vp = ValidPalindrome2()
print vp.validPalindrome("abaca") # False
print vp.validPalindrome("abbca") # True
ValidPalindrome2.test()
# Q-713 Subarray Product Less Than K
#
# Your are given an array of positive integers nums. Count and print the number of (contiguous)
# subarrays where the product of all the elements in the subarray is less than k.
class SubarrayProductLessThanK(object):
def numSubarrayProductLessThanK(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result, prod = (1, nums[0]) if nums[0] < k else (0, 1)
l = 0
for r in xrange(1, len(nums)):
prod *= nums[r]
if prod >= k:
while l <= r and prod >= k:
prod /= nums[l]
l += 1
result += r-l+1
return result
@staticmethod
def test():
print "Q-713 Subarray Product Less Than K"
spltk = SubarrayProductLessThanK()
print spltk.numSubarrayProductLessThanK([10,5,2,6], 100) # 8
SubarrayProductLessThanK.test()
# Q-735 Asteriod Collision (stack)
#
# We are given an array asteroids of integers representing asteroids in a row. For each asteroid,
# the absolute value represents its size, and the sign represents its direction (positive meaning
# right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the
# asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both
# are the same size, both will explode. Two asteroids moving in the same direction will never meet.
class AsteroidCollision(object):
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
result = []
stack = []
for i in xrange(len(asteroids)):
if asteroids[i] >= 0:
stack.append(asteroids[i])
continue
# left-bound asteroid
exploded = False
while len(stack) > 0:
pnum = stack.pop()
# larger right-bound asteroid wins, everything else explodes
if abs(asteroids[i]) <= pnum:
exploded = True
if abs(asteroids[i]) < pnum:
stack.append(pnum)
break
if (not exploded and len(stack) == 0):
result.append(asteroids[i])
result.extend(stack)
return result
@staticmethod
def test():
print "Q-735 Asteroid Collision"
ac = AsteroidCollision()
print ac.asteroidCollision([10,5,-5,-10]) # []
print ac.asteroidCollision([-2,-1,2,1])
AsteroidCollision.test()
# Q-763 Partition Labels
#
# A string S of lowercase letters is given. We want to partition this string into as
# many parts as possible so that each letter appears in at most one part, and return
# a list of integers representing the size of these parts.
class PartitionLabels(object):
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
charRange = {}
for i in xrange(len(S)):
if S[i] in charRange:
charRange[S[i]][1] = i
else:
charRange[S[i]] = [i,i]
curr = [charRange[S[0]][0], charRange[S[0]][1]]
result = []
for i in xrange(1, len(S), 1):
ir = charRange[S[i]]
if curr[1] < ir[0]: # not overlap
result.append(curr[1] - curr[0] + 1)
curr = [ir[0], ir[1]]
else:
# adjust range rightmost index
curr[1] = max(curr[1], ir[1])
result.append(len(S)-curr[0])
print result
return result
@staticmethod
def test():
print "Q-763 Partition Labels"
pl = PartitionLabels()
pl.partitionLabels("ababcbacadefegdehijhklij")
PartitionLabels.test()
# Q-767 Reorganize String (max heap priority queue)
#
# Given a string S, check if the letters can be rearranged so that two characters that
# are adjacent to each other are not the same. If possible, output any possible result.
# If not possible, return the empty string.
class ReorganizeString(object):
class CharCountItem:
def __init__(self, key, count):
self.key = key
self.count = count
# max heap
def __cmp__(self, other):
return self.count < other.count
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
import heapq
result = ""
chars = [0 for i in xrange(26)]
for i in xrange(len(S)):
chars[ord(S[i]) - ord('a')] += 1
items = []
for i in xrange(26):
if chars[i] > 0:
heapq.heappush(items, self.CharCountItem(chr(ord('a')+i), chars[i]))
while len(items) >= 2:
i1 = heapq.heappop(items)
i2 = heapq.heappop(items)
result += i1.key + i2.key
i1.count -= 1
i2.count -= 1
if i1.count > 0:
heapq.heappush(items, i1)
if i2.count > 0:
heapq.heappush(items, i2)
if len(items) > 0:
it = heapq.heappop(items)
if it.count > 1:
return ""
result += it.key
return result
@staticmethod
def test():
print "Q-767 Reorganize String"
rs = ReorganizeString()
print rs.reorganizeString("aabba")
print rs.reorganizeString("aaaabb") # empty
print rs.reorganizeString("aaaabcb")
ReorganizeString.test()
# Q-787 Cheapest Flights within K stops (shortest path)
#
# There are n cities connected by m flights. Each fight starts from city u and arrives
# at v with a price w. Now given all the cities and flights, together with starting city
# src and the destination dst, your task is to find the cheapest price from src to dst
# with up to k stops. If there is no such route, output -1.
class CheapestFlightsWithinKStops(object):
class StopCost:
def __init__(self, stop, nflights, cost):
self.stop = stop
self.nflights = nflights
self.cost = cost
# min heap
def __cmp__(self, other):
return self.cost > other.cost
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
import heapq
flightEdges = {}
# put in adjacency list
for e in flights:
ev = flightEdges.get(e[0]) if e[0] in flightEdges else []
ev.append([e[1],e[2]])
flightEdges[e[0]] = ev
workQueue = []
heapq.heappush(workQueue, self.StopCost(src, 0, 0))
while len(workQueue) > 0:
s = heapq.heappop(workQueue)
if s.stop == dst:
return s.cost
if s.stop in flightEdges:
for e in flightEdges.get(s.stop):
# K stops means K+1 flights
if s.nflights < K+1:
heapq.heappush(workQueue, self.StopCost(e[0], s.nflights+1, s.cost + e[1]))
return -1
@staticmethod
def test():
print "Q-787 Cheapest Flights within K Stops"
cfwk = CheapestFlightsWithinKStops()
print cfwk.findCheapestPrice(3, [[0,1,100],[1,2,100],[0,2,500]], 0, 2, 1) # 200
print cfwk.findCheapestPrice(5, [[0,1,100],[0,2,500],[1,2,100],[1,3,500],[2,3,300],[2,4,100],[3,4,200]], 0, 4, 4) # 300
print cfwk.findCheapestPrice(15, [[10,14,43],[1,12,62],[4,2,62],[14,10,49],[9,5,29],[13,7,53],[4,12,90],[14,9,38],[11,2,64],[2,13,92],[11,5,42],[10,1,89],[14,0,32],[9,4,81],[3,6,97],[7,13,35],[11,9,63],[5,7,82],[13,6,57],[4,5,100],[2,9,34],[11,13,1],[14,8,1],[12,10,42],[2,4,41],[0,6,55],[5,12,1],[13,3,67],[3,13,36],[3,12,73],[7,5,72],[5,6,100],[7,6,52],[4,7,43],[6,3,67],[3,1,66],[8,12,30],[8,3,42],[9,3,57],[12,6,31],[2,7,10],[14,4,91],[2,3,29],[8,9,29],[2,11,65],[3,8,49],[6,14,22],[4,6,38],[13,0,78],[1,10,97],[8,14,40],[7,9,3],[14,6,4],[4,8,75],[1,6,56]],1,4,10) # 169
CheapestFlightsWithinKStops.test()
# Q-795 Number of Subarrays With Bounded Maximum
class NumerOfSubarraysWithBoundedMaximum(object):
def numSubarrayBoundedMax(self, A, L, R):
"""
:type A: List[int]
:type L: int
:type R: int
:rtype: int
"""
result = 0
for i in xrange(len(A)):
if A[i] > R:
continue
inRange = False
for j in xrange(i, len(A)):
if A[j] > R:
break
if A[j] >= L:
inRange = True
if inRange:
result += 1
return result
@staticmethod
def test():
print "Q-795 Number of Subarrays With Bounded Maximum"
nsbm = NumerOfSubarraysWithBoundedMaximum()
print nsbm.numSubarrayBoundedMax([2,1,4,3], 2, 3) # 3
print nsbm.numSubarrayBoundedMax([2,1,3,4,3], 2, 3) # 6
NumerOfSubarraysWithBoundedMaximum.test()
# Q-797 All Paths from Source to Target
#
# Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1,
# and return them in any order.
#
# The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list
# of all nodes j for which the edge (i, j) exists.
class AllPathsFromSourceToTarget(object):
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
reachable = [[] for i in xrange(len(graph))]
for i in xrange(len(graph)):
for d in graph[i]:
reachable[d].append(i)
result = []
queue = [[len(graph)-1]]
while len(queue) > 0:
t = queue.pop(0)
for s in reachable[t[0]]:
p = list(t)
p.insert(0, s)
if s == 0:
result.append(p)
else:
queue.append(p)
return result
@staticmethod
def test():
print "Q-797 All Paths from Source to Destination"
ap = AllPathsFromSourceToTarget()
print ap.allPathsSourceTarget([[1,2], [3], [3], []])
AllPathsFromSourceToTarget.test()
# Q-807 Max Increase to Keep City Skyline
#
# In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located
# there. We are allowed to increase the height of any number of buildings, by any amount (the amounts
# can be different for different buildings). Height 0 is considered to be a building as well. At the
# end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and
# right, must be the same as the skyline of the original grid. A city's skyline is the outer contour
# of the rectangles formed by all the buildings when viewed from a distance. See the following example.
# What is the maximum total sum that the height of the buildings can be increased?
class MaxIncreaseKeepingSkyline(object):
def maxIncreaseKeepingSkyline(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rowMax = [0 for i in xrange(len(grid))]
colMax = [0 for i in xrange(len(grid[0]))]
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if rowMax[i] < grid[i][j]:
rowMax[i] = grid[i][j]
if colMax[j] < grid[i][j]:
colMax[j] = grid[i][j]
total = 0
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
h = min(rowMax[i], colMax[j])
total += h - grid[i][j]
return total
@staticmethod
def test():
print "Q-807 Max Increase to Keep City Skyline"
mikcl = MaxIncreaseKeepingSkyline()
grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] # 35
print mikcl.maxIncreaseKeepingSkyline(grid)
grid2 = [[3,0,8,4]] # 0
grid3 = [[3],[2],[9],[0]] # 0
print mikcl.maxIncreaseKeepingSkyline(grid2)
MaxIncreaseKeepingSkyline.test()
# Q-814 Binary Tree Pruning
#
# We are given the head node root of a binary tree, where additionally every node's value is either
# a 0 or a 1. Return the same tree where every subtree (of the given tree) not containing a 1 has
# been removed.
class BinaryTreePruning(object):
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is None:
return None
if root.val == 0 and root.left is None and root.right is None:
return None
if root.left is not None:
root.left = self.pruneTree(root.left)
if root.right is not None:
root.right = self.pruneTree(root.right)
if root.val == 0 and root.left is None and root.right is None:
return None
return root
PrintBinaryTree.test()
# Q-821 Shortest Distance to a Character
#
# Given a string S and a character C, return an array of integers representing the shortest distance
# from the character C in the string. C is guaranteed to be in S.
class ShortestDistanceToCharacter(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
dist = [len(S) for i in xrange(len(S))]
pos = -1
for i in xrange(len(S)):
if S[i] == C:
pos = i
if pos > -1:
dist[i] = i - pos
pos = len(S)
for i in xrange(len(S)-1, -1, -1):
if S[i] == C:
pos = i
if pos < len(S) and pos - i < dist[i]:
dist[i] = pos - i
return dist
@staticmethod
def test():
print "Q-821 Shortest Distance to a Character"
sdc = ShortestDistanceToCharacter()
print sdc.shortestToChar("loveleetcode", 'e')
ShortestDistanceToCharacter.test()
# Q-841 Keys and Rooms (BFS)
class KeysAndRooms(object):
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
import Queue
if len(rooms) == 0:
return True
visited = set()
queue = Queue.Queue()
queue.put(0)
while not queue.empty():
room = queue.get()
for i in xrange(len(rooms[room])):
if rooms[room][i] not in visited:
queue.put(rooms[room][i])
visited.add(room)
return True if len(visited) == len(rooms) else False
@staticmethod
def test():
print "Q-841 Keys and Rooms"
kr = KeysAndRooms()
print kr.canVisitAllRooms([[1],[2],[3],[]]) # True
print kr.canVisitAllRooms([[1,3],[3,0,1],[2],[0]]) # False
KeysAndRooms.test()
# Q-971 Reverse Only Letters
class ReverseOnlyLetters(object):
def is_letter(self, c):
cv = ord(c)
return (cv >= ord('a') and cv <= ord('z')) or (cv >= ord('A') and cv <= ord('Z'))
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
l, r = 0, len(S)-1
chars = list(S)
while l < r:
while l < len(S)-1 and not self.is_letter(chars[l]):
l += 1
while r >= 0 and not self.is_letter(chars[r]):
r -= 1
if l < r:
t = chars[l]
chars[l] = chars[r]
chars[r] = t
l += 1
r -= 1
return ''.join(chars)
@staticmethod
def test():
print "Q-971 Reverse Only Letters"
rol = ReverseOnlyLetters()
print rol.reverseOnlyLetters("a-bC-dEf-ghIj")
ReverseOnlyLetters.test()
|
d1ae2599e0cad0363de2c45ce66cf28a8588f783 | shyamkumar2412/player | /55.py | 100 | 3.53125 | 4 | s=list(map(str,input().split(' ')))
if len(s[0])==len(s[1]):
print('yes')
else:
print('no')
|
a6a57dd3c02d981c96b9e3200134ecffd136fb7c | brennomaia/CursoEmVideoPython | /ex011.py | 303 | 3.875 | 4 | largura = float(input('Largura da Parede: '))
altura = float(input('Altura da Parede: '))
dimensao = largura*altura
tinta = dimensao/2
print('Sua parede possui a dimensão de {}x{} e sua area é de {}m²\n Para pintar está parede você precisa de {}l de tinta'.format(largura, altura, dimensao, tinta)) |
6c91ab08667064830c6f67759aae7f2726349377 | rigogsilva/sqldf | /sqldf/sqldf.py | 2,706 | 3.5625 | 4 | from pyspark import SparkContext
from pyspark import RDD
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from sqldf import templating
import os
os.environ["SPARK_HOME"] = "/usr/local/spark/"
os.environ["PYSPARK_PYTHON"] = "/usr/local/bin/python3"
# Set spark context to be used throwout
sc = SparkContext("local", 'sqldf')
sqlContext = SQLContext(sc)
def get_column_names(dataframe) -> list:
"""
Returns the column names for the RAW dataframe
:param dataframe:
RAW, pyspark, or pandas dataframe.
"""
columns = []
for row in dataframe:
columns = [k for (k, v) in row.items()]
return columns
def convert_to_row(list_of_dictionaries: list) -> RDD:
"""
Converts list of dictionaries to pyspark supported RDD format.
:param list_of_dictionaries:
A list of dictionaries. E.g.: [{'name': 'Rigo', 'age': 33}, {...}]
"""
return sc.parallelize(list_of_dictionaries).map(lambda _: [
v for (k, v) in _.items()])
def register_pyspark_df(pyspark_df: DataFrame, table: str = None):
"""
Register the dataframe as a table so it can be query using sql
:param pyspark_df:
A pyspark DataFrame
:param table:
The table name used in the query
"""
sqlContext.registerDataFrameAsTable(pyspark_df, table)
def convert_to_pyspark_df(dataframe) -> DataFrame:
"""
Converts the DataFrame into a pyspark DataFrame
:param dataframe:
A RAW, pyspark, or pandas dataframe
"""
# Is the DataFrame a list of dictionaries? RAW?
if type(dataframe) is DataFrame:
return dataframe
elif type(dataframe) is list:
for row in dataframe:
if type(row) is dict:
columns = get_column_names(dataframe)
rdd: RDD = convert_to_row(dataframe)
return sqlContext.createDataFrame(rdd, columns)
elif type(dataframe) == 'pandas.core.frame.DataFrame':
return sqlContext.createDataFrame(dataframe)
else:
raise ValueError(f'Invalid DataFrame type: {type(dataframe)}')
def sql(query: str, dataframe=None, table: str = None, **kwargs) -> DataFrame:
"""
Returns a pyspark Dataframe
Example (RAW DataFrame):
dataframe = [{'Name': 'Rigo', 'age': 3}, {'Name': 'Lindsay', 'age': 5}]
sql('select Name, sum(age) from dataframe group by Name', dataframe).show()
:param query:
The query to run against the dataframe
:param dataframe:
A RAW, pyspark, or pandas dataframe
:param table:
The table name used in the query
:param kwargs:
Any rendering variables to inject into the SQL query file prior to executing the query.
"""
if dataframe:
pyspark_df: DataFrame = convert_to_pyspark_df(dataframe)
if table:
register_pyspark_df(pyspark_df, table)
rendered_query = templating.render(query, **kwargs)
return sqlContext.sql(rendered_query)
|
fbddac9a4ef48c1ca9f77c20d930ee62be908295 | BryanFriestad/ee-raspi-fun | /7seg_decoder_driver.py | 2,038 | 3.5 | 4 | import RPi.GPIO as GPIO
import time
x0_pin = 24 #blue
x1_pin = 25 #green
x2_pin = 26 #yellow
x3_pin = 27 #orange
display_state = 0 #unused currently
display_value = 0
def setup():
global display_value
#using broadcom mode for gpio numbering
GPIO.setmode(GPIO.BCM)
#set up pins
GPIO.setup(x0_pin, GPIO.OUT, initial = display_value & 1)
GPIO.setup(x1_pin, GPIO.OUT, initial = display_value & 2)
GPIO.setup(x2_pin, GPIO.OUT, initial = display_value & 4)
GPIO.setup(x3_pin, GPIO.OUT, initial = display_value & 8)
def clean_up():
GPIO.cleanup([x0_pin, x1_pin, x2_pin, x3_pin])
def set_display(value):
global display_value
if(value < 16 and value >= 0):
display_value = value
x0_value = value & 1
x1_value = value & 2
x2_value = value & 4
x3_value = value & 8
GPIO.output(x0_pin, x0_value)
GPIO.output(x1_pin, x1_value)
GPIO.output(x2_pin, x2_value)
GPIO.output(x3_pin, x3_value)
return 0
else:
return -1
def reset_display():
set_display(0)
def increment_display():
global display_value
return set_display(display_value + 1)
def decrement_display():
global display_value
return set_display(display_value - 1)
def get_display_value():
global display_value
return display_value
def main():
setup()
for x in range(16):
set_display(x)
time.sleep(0.5)
for x in range(16):
decrement_display()
time.sleep(0.5)
var = 0
while(True):
var = input("Input a number (0 - 15), \"g\" to get the displayed value, \"r\" to reset, or \"q\" to quit")
if(var == 'q'):
break
elif(var == 'r'):
reset_display()
elif(var == 'g'):
print("Currently displayed value is: ", get_display_value())
else:
set_display(int(var))
clean_up()
if __name__ == "__main__":
main()
|
d932ce1b9ceeb81b312fd15e6e8b82ff4dd53ca1 | ryosuzuki/hint-pilot | /data/006.py | 279 | 3.53125 | 4 | def repeated(f, n):
def h(x):
if n==0:
return x
else:
return f(repeated(h, n-1)(x))
return h
def main():
print('repeated(triple, 5)(1) should return 243')
print(repeated(triple, 5)(1))
#=> ExternalError: RangeError: Maximum call stack size exceeded
|
8ae10377b4916d732c2839c5e2df016c9ea19891 | Infosharmasahil/python-programming | /unit-6/process_nhl.py | 1,118 | 3.765625 | 4 | import json
with open('nhl.json', 'r') as nhl_file:
data = json.load(nhl_file)
print(data.keys())
#how many teams are in the nhl
team_count = len(data['teams'])
print(team_count)
'''
if team not in team_total_count.keys():
team_total_count[team_count] = []
team_total_count[team_count].append(team)
print(team_total_count)
def team_count():
return (team[team.valuefor team
data['team_count'].value()
'''
eastern_conf_teams = []
oldest_year = '2019'
oldest_name = ''
#when was the boston bruins started
for team in data['teams']:
if team['name'] == 'Boston Bruins':
print(team ['firstYearOfPlay'])
#what is the oldest team in the nhl
if team['firstYearOfPlay'] < oldest_year:
oldest_year = team['firstYearOfPlay']
oldest_name = team['name']
#what are the teams in the eastern conference
if team['conference']['name'] == 'Eastern' :
eastern_conf_teams.append(team['name'])
print('Eastern conference teams: ', end= ' ')
print(eastern_conf_teams)
print('Oldest team is {}, started in {}'.format(oldest_name, oldest_year))
|
8756d07a102af02e4c6c3b38f9d2f2c102a1528f | L3ftsid3/Classes | /Big-Data/Hadoop/Intro-to-Hadoop-Udacity/Project--Week-3/ex1mapper.py | 656 | 3.515625 | 4 | #!/usr/bin/python
#Excercise 1 - The three questions that you have to answer about this data set are:
# Instead of breaking the sales down by store, instead give us a sales breakdown by product category across all of our stores.
# Format of each line is:
# date\ttime\tstore name\titem description\tcost\tmethod of payment
#
# We want elements 4 (item) and 5 (cost) [KEY = item descr., VALUE = cost]
# We need to write them out to std output, separated by a tab
import sys
for line in sys.stdin:
data = line.strip().split("\t")
if len(data) == 6:
date, time, store, item, cost, payment = data
print"{0}\t{1}".format(item, cost)
|
8fdaa62e4211d480c7c2a2baca58543b958edf5e | Gitosthenes/exercises | /sorting.py | 1,232 | 3.953125 | 4 | from random import randint
from random import seed
def generate_array():
test = []
for num in range(20):
seed(randint(0, 1000))
test.append(randint(0, 100))
return test
def selection_sort(my_list):
for i in range(len(my_list) - 1):
minVal = i
for j in range(i + 1, len(my_list)):
if my_list[j] < my_list[minVal]:
minVal = j
if(minVal != i):
swap(i, minVal, my_list)
def insertion_sort(my_list):
for i in range(len(my_list)):
for j in range(i, 0, -1):
if my_list[j] < my_list[j-1]:
swap(j, j-1, my_list)
def swap(first, second, my_list):
temp = my_list[first]
my_list[first] = my_list[second]
my_list[second] = temp
# Generate random array of integers:
selection_test = generate_array()
insertion_test = generate_array()
# Record before:
s_test_before = str(selection_test)
i_test_before = str(insertion_test)
# Sort:
selection_sort(selection_test)
insertion_sort(insertion_test)
# Show results:
print('Selection Sort:\n' + s_test_before + '\n' + str(selection_test))
print('---------------------')
print('Insertion Sort:\n' + i_test_before + '\n' + str(insertion_test))
|
f52f06ea67bfccf67025fd704cc23492045a4da4 | aalamgeer/python_basic_tutorial | /arthmetic.py | 149 | 3.5 | 4 | print("sum of 3+2 ", 3+2)
print("product of 3*3", 3*3)
print("divide of 10/3 ",10/3)
print("modules of 10%3 ",10%3)
print("square of 10**3 ",10**3)
|
a4e02ad8dd7e7d39f1051c5dc32eeb512a4a2e34 | mkrasnitski/project-euler | /035.py | 528 | 3.625 | 4 | import math
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def rotr(n):
n = str(n)
if len(n) == 1:
return n
return n[-1:] + n[:-1]
def rotate_prime(n):
p = [str(n)]
i = rotr(n)
while int(i) != n:
if not is_prime(int(i)):
return False
p.append(i)
i = rotr(i)
return True
rp = []
for i in range(2, 1000000):
if is_prime(i):
if rotate_prime(i):
rp.append(i)
print(rp, sum(rp), len(rp)) |
05582e0bf00c820cd0605ba50d5109a4dac6a196 | jeffzhangding/study | /letcode/字节跳动章节/数组与排序/最长连续递增序列.py | 969 | 3.5 | 4 | __author__ = 'jeff'
"""
输入: [1,3,5,4,7]
输出: 3
解释: 最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。
"""
class Solution:
def findLengthOfLCIS(self, nums) -> int:
""""""
max_lenth = 0
current_lenth = 0
last_number = None
for i in nums:
if last_number is None:
current_lenth += 1
max_lenth = current_lenth
last_number = i
continue
if i > last_number:
current_lenth += 1
else:
current_lenth = 1
last_number = i
if current_lenth > max_lenth:
max_lenth = current_lenth
return max_lenth
if __name__ == '__main__':
l = [1,3,5,4,7]
# l = [2,2,2,2,2]
res = Solution().findLengthOfLCIS(l)
print('=====%s', res)
|
c4db143ae0a008a5a857be0f62517307bcebd968 | ksomemo/Competitive-programming | /atcoder/abc/053/C.py | 279 | 3.546875 | 4 | def main():
"""
1 <= x <= 10**15
どのパターンで得点が一番多いか
(5) -> 6 -> 5 > 6 -> 5 ...
"""
x = int(input())
d1, r1 = divmod(x, 11)
ans = d1 * 2 + (r1 // 6) + (r1 % 6 > 0)
print(ans)
if __name__ == '__main__':
main()
|
338f62cbdb1d96d3a46d3345b5f0cfcf3b131eaf | jao11/curso-em-video | /mundo01/aula008/des021.py | 309 | 3.65625 | 4 | # Faça um programa em python que abra e reproduza o áudio de um arquivo mp3.
import pygame
print('Gostariamos que você ouvisse essa música')
pygame.mixer.init()
pygame.mixer.music.load('des021.mp3')
pygame.mixer.music.play()
print('Por favor ouça...')
input('Para parar digite algo e de enter:')
|
53dc17b3ef84d762b4fa758818278e0e6925cd2b | M4573R/Interviewbit2 | /Arrays/PASCAL1.py | 1,611 | 3.828125 | 4 | """Given numRows, generate the first numRows of Pascal’s triangle.
Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
Example:
Given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """
"""Analysis : 1. The first and last element in each row is 1
2. The other elements are the sum of the two elements in the previous row which are right above it.
3. So we add 1 to the first and last element of each row and for other elements we sum the appropriate
two elements in the previous row """
class Solution:
# @param A : integer
# @return a list of list of integers
def generate(self, A):
result = []
if(A==0):
return result
if(A==1):
return [[1]]
elif(A==2):
result.append([1])
result.append([1,1])
return result
else:
result.append([1])
result.append([1,1])
# create the rows and set the first and last element of the row to one
for i in xrange(3,A+1):
newrow = [0]*i
newrow[0] = 1
newrow[i-1] = 1
result.append(newrow)
# for each row from 2 to the last one we set the elements from 1 to the one before last
#(excluding first and last) the sum of the upper rows elements
for i in xrange(2,A):
for j in xrange(1,i):
result[i][j] = result[i-1][j-1] + result[i-1][j]
return result
|
5f7bcfb242403487dc43b90dcb8dea0a97c6d941 | ajara123/CS-1 | /task 7/7.2.py | 907 | 4.375 | 4 | #Exercise 2: Write a program to prompt for a file name,
#and then read through the file and look for lines of the form:
#X-DSPAM-Confidence:0.8475
#When you encounter a line that starts with "X-DSPAM-Confidence:" pull
#apart the line to extract the floating-point number on the line.
#Count these lines and then compute the total of the spam confidence
#values from these lines. When you reach the end of the file, print out
#the average spam confidence.
fname=input('Enter the file name: ')
try:
fhand=open(fname)
except:
print('File cannot be opened:', fname)
exit()
count=0
summa=0
for line in fhand:
if line.startswith ('X-DSPAM-Confidence:'):
count=count+1
number=line.find(':')
try:
float_number=float(line[number+1:])
summa=summa+float_number
except:
print('Error')
print('Average spam confidence:', summa/count)
|
6e3b9da87c2a94aec42e8b779c614ccd26ca8f3f | CleitonFurst/python_Blueedtech | /Exercicios_aula_10/Desafio_01.py | 1,645 | 4.0625 | 4 |
'''#DESAFIO:
Em uma eleição presidencial existem quatro candidatos. Os votos são informados por meio de código.
Os códigos utilizados são:
1 , 2, 3, 4 - Votos para os respectivos candidatos (você deve montar a tabela ex: 1 - Jose/ 2- João/etc)
5 - Voto Nulo
6 - Voto em Branco
Faça um programa que calcule e mostre:
O total de votos para cada candidato;
O total de votos nulos;
O total de votos em branco;'''
candi1 = 0
candi2 = 0
candi3 = 0
candi4 = 0
nulos = 0
branco = 0
x = 1
while x != 0:
op = int(input('*************QUAL SERÁ SEU VOTO*********************\n'
'1 -> Jose \n'
'2 -> João \n'
'3 -> Marina \n'
'4 -> Lula \n'
'5 -> Nulo \n'
'6 -> Em Branco \n'
'0 -> Sair\n'
'Escolher :'))
if op == 1:
candi1 += 1
elif op == 2:
candi2 += 1
elif op == 3:
candi3 += 1
elif op == 4:
candi4 += 1
elif op == 5:
nulos += 1
elif op == 6:
branco += 1
else:
x = 0
print(f'****Distribuição dos votos !!*****')
print(f'Total de votos no candidato Jose -> {candi1}')
print(f'Total de votos no candidato João -> {candi2}')
print(f'Total de votos no candidata Marina -> {candi3}')
print(f'Total de votos no candidato Lula -> {candi4}')
print(f'Total de votos Nulos -> {nulos}')
print(f'Total de votos Em Branco -> {branco}')
|
720efed1a77df24a21257faea7d02b7e52352eab | Karthikkk-24/ShapeAI_Python-NetworkSecurity_Project | /Algorithm#2(SHA384).py | 198 | 3.734375 | 4 | import hashlib
#Python code for SHA256 algorithm
string01 ="Cybersecurity"
SHA256algorithm = hashlib.sha384(string01.encode())
print("The hexidecimal value : ",SHA256algorithm.hexdigest()) |
56a1a960c7acdd0942f3fc3b20326415d52fcd98 | shepherdjay/reddit_challenges | /challenges/challenge364_ez.py | 607 | 3.984375 | 4 | from typing import Tuple
import random
def roll(number: int) -> int:
return random.randint(1, number)
def dice_roller(input_string: str) -> Tuple:
rolls, sides = input_string.split('d')
results = [roll(int(sides)) for _ in range(0, int(rolls))]
return sum(results), results
if __name__ == '__main__':
try:
print("Welcome to dice roller, type ctrl+c to quit")
while True:
ndm = input("Please input dice roll in format NdM: ")
total, rolls = dice_roller(ndm)
print(f"{total}: {rolls}")
except KeyboardInterrupt:
exit()
|
397b55cf75d77cd624304e79a981332c0891c46a | pausanchezv/Estructura-de-dades-UB | /Pràctiques/Heaps i hash/Codi_i_texts/HashMapWordFinder.py | 3,484 | 3.640625 | 4 | from HashMap import *
import time
class HashMapWordFinder(object):
def __init__(self, file):
'''Mtode constructor'''
self._hashMap = HashMap()
self.appendText(file)
def appendText(self, file):
'''Llegeix el fitxer i el desglossa en lnies i paraules per lnia'''
try:
with open(file, 'r') as reader:
numLine = 1
t1 = time.clock()
array = []
for line in reader.readlines():
numWord = 1
if (line):
for word in line.split():
item = word.lower()
array.append(item)
numWord += 1
numLine += 1
self._hashMap.prepareTable(HashMapWordFinder.nextPrime(len(array)))
for item in array:
self._hashMap.insertWord(TextWord(item, numLine, numWord))
t2 = time.clock()
print u"\nS'han insertat les paraules del text a la taula hash. El temps d'inserci ha estat de {} ms.".format((t2-t1)*1000)
except IOError: print "El nom de l'arxiu donat no existeix."
def findOcurrencesInFile(self, file):
'''mostra les aparicions de les paraules d'un text en la taula hash'''
try:
print u"\nLes aparicions de paraules de {} a la taula hash sn:".format(file)
t1 = time.clock()
with open(file, 'r') as reader:
for word in reader.read().split():
item = word.lower()
self._hashMap.findOcurrences(item)
t2 = time.clock()
print "El temps de cerca ha estat de {} ms.".format((t2-t1)*1000)
except IOError: print "El nom de l'arxiu donat no existeix."
def showHashData(self):
'''mostra el nombre de collisions de la taula hash, quants elements t la cella amb ms elements i el percentatge de celles buides'''
print u"\nEl nombre de collisions ha estat de", self._hashMap.getCollisionAmount()
print u"El nombre d'elements en la cella de ms elements s de", self._hashMap.getMaxElemAmountInSlot()
print u"El percentatge de celles buides s de", self._hashMap.calcEmptyPercentage()
@staticmethod
def askFile():
''' demana un arxiu'''
file = raw_input ("Entra el nom d'un fitxer (Ex: smallText.txt) --> ")
return file
@staticmethod
def main():
'''mtode principal de l'aplicaci. Crea el cercador, demana a l'usuari el nom d'un text i en ell cerca i mostra les paraules d'un diccionari trobades, a ms de mostrar ordenades alfabticament les paraules i mostrar certes dades de la taula hash'''
h = HashMapWordFinder(HashMapWordFinder.askFile())
h.findOcurrencesInFile('dictionary.txt')
h.showHashData()
@staticmethod
def isPrime(n):
'''retorna si un nombre s primer'''
return not any(n % i == 0 for i in range(2, n))
@staticmethod
def nextPrime(n):
'''retorna el primer nombre primer a partir del nmero indicat'''
found = False
result = 0
while not found:
if HashMapWordFinder.isPrime(n):
found = True
else: n += 1
return n
if __name__ == "__main__":
HashMapWordFinder.main() |
07c9895fe98380095b2f7827b634e17aa9e30d57 | hangwudy/leetcode | /100-199/106. 从中序与后序遍历序列构造二叉树.py | 1,434 | 3.875 | 4 | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
n = len(inorder)
hm = dict()
for i, v in enumerate(inorder):
hm[v] = i
return self.construct(inorder, 0, n - 1, postorder, 0, n - 1, hm)
def construct(self, inorder: List[int], in_start: int, in_end: int,
postorder: List[int], post_start: int, post_end: int, hashmap: dict) -> TreeNode:
if in_start > in_end:
return
root_val = postorder[post_end]
root = TreeNode(root_val)
if in_start == in_end:
return root
else:
root_index = hashmap[root_val]
left_nodes = root_index - in_start
right_nodes = in_end - root_index
root.left = self.construct(inorder, in_start, root_index - 1,
postorder, post_start, post_start + left_nodes - 1,
hashmap)
root.right = self.construct(inorder, root_index + 1, in_end,
postorder, post_end - right_nodes, post_end - 1,
hashmap)
return root
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.