blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
4789d3e5ea7dae714483f2f25aed18792e2bbfd0 | Lyra2108/AdventOfCode | /2018/Day9/MarbleMania.py | 1,413 | 3.5625 | 4 | from collections import defaultdict
class Marble:
def __init__(self, number):
self.number = number
self.previous = self
self.next = self
def add_next(self, number):
next_marble = Marble(number)
self.next.previous = next_marble
next_marble.next = self.next
self.next = next_marble
next_marble.previous = self
def remove(self):
self.previous.next = self.next
self.next.previous = self.previous
def marble_mania(player, last_marble):
current_marble = Marble(0)
points = defaultdict(lambda: 0)
for i in range(1, last_marble + 1):
if i % 23 != 0:
current_marble.next.add_next(i)
current_marble = current_marble.next.next
else:
pick = current_marble.previous.previous.previous.previous.previous.previous.previous
points[i % player] += i + pick.number
current_marble = pick.next
pick.remove()
return max(points.values())
if __name__ == '__main__':
assert 32 == marble_mania(9, 25)
assert 8317 == marble_mania(10, 1618)
assert 146373 == marble_mania(13, 7999)
assert 2764 == marble_mania(17, 1104)
assert 54718 == marble_mania(21, 6111)
assert 37305 == marble_mania(30, 5807)
print("Heighscore: %d" % marble_mania(410, 72059))
print("Heighscore: %d" % marble_mania(410, 72059*100))
|
8c440e1b948f841260b3befc74c8a9130e5e392a | aalvaradof/X-Serv-Python-Multiplica | /calculadora.py | 735 | 3.796875 | 4 | #!/usr/bin/python3
import sys
from sys import argv
def help():
print('Usage: calculadora.py function op1 op2')
print('Possible functions: sumar restar multiplicar dividir')
N_ARGS = 4
if len(sys.argv) != N_ARGS:
sys.exit("Invalid number of arguments")
func = argv[1]
op1 = argv[2]
op2 = argv[3]
try:
op1 = float(op1)
op2 = float(op2)
except ValueError:
help()
sys.exit("Introduced not numeric arguments")
if func == 'sumar':
print(op1 + op2)
elif func == 'restar':
print(op1 - op2)
elif func == 'multiplicar':
print(op1 * op2)
elif func == 'dividir':
try:
print(op1 / op2)
except ZeroDivisionError:
print("Cannot divide by 0")
else:
sys.exit("Invalid operation")
|
5306872900fb437bba82f703dc3a39fcfe2d2fc6 | anuj-chourasiya/Data-Sructure-in-C | /Trie.py | 1,373 | 3.875 | 4 |
from collections import defaultdict
class TrieNode:
def __init__(self,data):
self.data=data
self.children=defaultdict(lambda: None)
self.freq=0
self.isTerminal=False
def __str__(self):
return "hey "+(self.data)
class Trie:
def __init__(self,data):
self.root=self.getNode(data)
def getNode(self,data):
return TrieNode(data)
def insert(self,word):
pointer=self.root
for char in word:
if not pointer.children[char]:
pointer.children[char]=TrieNode(char)
pointer=pointer.children[char]
pointer.freq+=1
pointer.isTerminal = True
def firstOne(self,word):
ans=""
pointer=self.root
for char in word:
if pointer.freq>1 or pointer.freq==0:
ans+=char
pointer=pointer.children[char]
elif pointer.freq==1 :
return ans
if pointer.freq==1:
return ans
return -1
def uniqueSmallestPrefix(words):
root=Trie(0)
ans=[]
for word in words:
root.insert(word)
for word in words:
ans.append(root.firstOne(word))
return ans
inp=["don","duck","donhaihum","dont","anuj","aman"]
ans=uniqueSmallestPrefix(inp)
print(inp)
print(ans)
|
ac539d583de0ec8897fcd603203f30db94bf7eb9 | sachin3496/PythonCode | /batch10_dec_2018/tic_tac_toe.py | 4,070 | 3.5625 | 4 | from itertools import permutations
import sys
import random
import os
import time
def win(data):
win_comb = [ (1,2,3), (1,4,7), (1,5,9), (2,5,8), (3,6,9), (3,5,7),(4,5,6), (7,8,9) ]
player_comb = list(permutations(sorted(data),3))
for comb in win_comb:
if comb in player_comb :
return True
else :
return False
def print_board(msg):
clr_scr()
print(msg)
print("\n\nYour Current Board is : \n")
for var in board :
print("\t\t\t","-"*19)
print("\t\t\t","| | | |")
print("\t\t\t",f"| {var[0]} | {var[1]} | {var[2]} |")
print("\t\t\t","| | | |")
print("\t\t\t","-"*19)
print("\n\n")
def choice(player):
possible_choices = [ '1','2','3','4','5','6','7','8','9' ]
print("\n\nLeft Positions : ",*total_pos)
ch = input(f"\n\n{player} pos : ")
if ch in possible_choices :
ch = int(ch)
if ch in covered_pos :
print_board("")
print("\n\nThat Position is Already Choosen Please Select Another Position \n\n")
return choice(player)
else :
covered_pos.append(ch)
total_pos.remove(ch)
return ch
else :
print_board("")
print("\n\nInvalid Choice please Select only 1-9 positions \nTry Again\n\n")
return choice(player)
def play_game(p_list):
c = 1
ch1 = choice(p_list[1][0])
p_list[1][2].append(ch1)
pos_ch1 = pos.get(ch1)
board[pos_ch1[0]][pos_ch1[1]] = p_list[1][1]
print_board(f'\n\nAfter move {c} the board is ')
if win(p_list[1][2]) :
print(f"\n\nPlayer {p_list[0][0]} has won the Game\n\n")
return True
c = c + 1
k = 1
while k <= 4 :
ch1 = choice(p_list[0][0])
p_list[0][2].append(ch1)
pos_ch1 = pos.get(ch1)
board[pos_ch1[0]][pos_ch1[1]] = p_list[0][1]
print_board(f'\n\nAfter move {c} the board is ')
if win(p_list[0][2]) :
print(f"\n\nPlayer {p_list[0][0]} has won the Game\n\n")
break
c = c + 1
ch1 = choice(p_list[1][0])
p_list[1][2].append(ch1)
pos_ch1 = pos.get(ch1)
board[pos_ch1[0]][pos_ch1[1]] = p_list[1][1]
print_board(f'\n\nAfter move {c} the board is ')
if win(p_list[1][2]) :
print(f"\n\nPlayer {p_list[1][0]} has won the Game\n\n")
break
c = c + 1
k = k + 1
else :
print(f"\n\nwoooo...Match is Tie Between {p_list[0][0]} and {p_list[1][0]}\n\n")
def clr_scr():
os.system('cls')
print('\n\n\n')
if __name__ == "__main__" :
player1 = input("\n\nEnter Player one name : ")
player2 = input("\n\nEnter player two name : ")
while True :
clr_scr()
print("\n\nWelcome to Tic Tac Toe Game\n\n")
pos = { 1:(0,0), 2:(0,1), 3:(0,2), 4:(1,0), 5:(1,1), 6:(1,2), 7:(2,0),8:(2,1),9:(2,2) }
board = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
print_board('\t\tHere are the key Positions to select your move')
input("\n\nPress Enter key to Continue Game ")
board = [ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' '] ]
print_board('\t\tafter initial Move the board is ')
time.sleep(2)
clr_scr()
print("\n\nSymbols --> X and 0 ")
print("\n\nChoosing The Symobls for each Player")
symbol = [ 'X', '0']
random.shuffle(symbol)
print(f'\n\n{player1} symbol is - {symbol[0]}')
print(f'\n\n{player2} symbol is - {symbol[1]}')
p_list = ( ( player1, symbol[0],[] ),( player2, symbol[1],[] ) )
total_pos = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
covered_pos = []
input("\nPress Any key to Start Game ".center(300))
print_board('Initial Status of Board')
play_game(p_list)
if input("\n\nDo want to play again : ") :
continue
else :
break
|
010a132e2ef0c05b75d9c72307d09ca94aa21732 | MeiJohnson/compmath | /newton.py | 1,395 | 3.609375 | 4 | import math
def f(arg):
return arg**3 - 2 * arg**2 + 3 * arg - 5
def df(arg):
return 3 * arg**2 - 4 * arg + 3
def ddf(arg):
return 6 * arg - 4
def newton():
a = 1
b = 2
e = 0.000001
cntA = 0
cntB = 0
x = a
xi = x-f(x)/df(x)
cntA += 1
print("a =", a, "b =", b, "eps =", eps, "x0 =", x)
while abs(xi - x) > e:
x = xi
xi = x - f(x)/df(x)
cntA += 1
print("Answer A", round(xi, 6),"Count of cycles", cntA)
x = b
xi = x - f(x)/df(x)
cntB += 1
while abs(xi - x) > e:
x = xi
xi = x - f(x)/df(x)
cntB += 1
print("Answer B", round(xi, 6),"Count of cycles", cntB)
def f_ind(arg):
return arg * math.log10(arg+1) - 1
def df_ind(arg):
return (arg+(arg+1)*math.log(arg+1))/((arg+1)*math.log(10))
def ddf_ind(arg):
return (arg+2)/((arg+1)*(arg+1)*math.log(10))
def ind_newton():
a = 0
b = 10
e = 0.000001
cntB = 0
x = b
xi = x - f_ind(x)/df_ind(x)
cntB += 1
print("a =", a, "b =", b, "eps =", eps, "x0 =", x)
while abs(xi - x) > e:
x = xi
xi = x - f_ind(x)/df_ind(x)
cntB += 1
print("Answer B", round(xi, 6),"Count of cycles", cntB)
def main():
print("x^3-2*x^2+3*x-5=0")
newton()
print("x*lg(x+1)=1")
ind_newton()
if __name__ == "__main__":
main()
|
53db74810935731d80a071d178185dbe4f7cdd31 | SurajPatil314/Leetcode_Fundamental | /LinkedList/reverseLinkedList.py | 651 | 3.90625 | 4 | """
Reverse a singly linked list.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
temp = []
temp5 = head
while (head != None):
temp.append(head.val)
head = head.next
i = 0
print(len(temp))
if len(temp) == 0:
return None
temp8 = temp5
while (len(temp) > 0):
print("qq")
temp8.next = ListNode(temp.pop())
temp8 = temp8.next
return temp5.next
|
1312a85c36066029066f2b3d9753b278bc4c4ee3 | SurajPatil314/Leetcode_Fundamental | /LinkedList/checkPalndromeLinkedList.py | 936 | 3.796875 | 4 | """
Given a singly linked list, determine if it is a palindrome.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
temp2 = head3
temp = []
i = 0
while (temp2 != None):
temp.append(temp2.val)
temp2 = temp2.next
print(temp)
if len(temp) < 2:
return True
r = q = int(len(temp) / 2)
if len(temp) % 2 == 1:
while (q > 0):
if (temp[q - 1] != temp[r + 1]):
return False
q = q - 1
r = r + 1
else:
print(q)
while (q > 0):
if (temp[q - 1] != temp[r]):
return False
q = q - 1
r = r + 1
return True |
7bc5e5d8883fef3affe01b8dcfc80ce1845f46a8 | connorjclark/learn-code | /code/roll.py | 373 | 3.75 | 4 | import random
import sys
def roll(min, max):
return random.randint(min, max)
def play_round():
result = roll(1, 6)
print("You got " + str(result))
if result == 6:
print("Nice!")
if result == 1:
print("not good...")
play = True
while play:
play_round()
answer = input("Roll again? y/n: ")
if (answer != "y"):
play = False
print("Bye!")
|
3f4fe3c9790c8839f9d3c32116fa12d1194e0933 | baschte83/os-synchronisation | /LibrarySynchronization.py | 4,776 | 4.0625 | 4 | from sys import argv
from time import sleep
import threading
# semaphore objects
# lock objects for book1 copies
semBook1 = threading.BoundedSemaphore(3)
# lock objects for book2 copies
semBook2 = threading.BoundedSemaphore(2)
# lock objects for book3 copies
semBook3 = threading.BoundedSemaphore(2)
# lock objects for global counter how many times 3 books were lend
counterSem = threading.BoundedSemaphore()
# lock objects for global counter how many times each student lend 3 books
counterListSem = threading.BoundedSemaphore()
# lock objects for global boolean whether a student has all three books now or not
hasAllBooksListSem = threading.BoundedSemaphore()
# function to lend a copy of each book
def lend_the_books():
# definition of several global variables
global waiting_time
global counter_list
global counter
global hasAllBooksList
global output_interval
# while loop to acquire and release all 3 books
while True:
# acquiring of all three books
semBook1.acquire()
semBook2.acquire()
semBook3.acquire()
# entering "True" in list hasAllBooksList because this student process
# has a copy of all three books
hasAllBooksListSem.acquire()
hasAllBooksList[int(threading.currentThread().getName()) - 1] = True
hasAllBooksListSem.release()
# this student process has now to "read" its three books
# for waiting_time seconds
sleep(float(waiting_time))
# several outputs
# increase the counter variable which counts, how often three books
# were lent over all student processes
counterSem.acquire()
counter += 1
# increase the counter in list counter_list which stores how often
# this special student process has lent all three books
counterListSem.acquire()
counter_list[int(threading.currentThread().getName()) - 1] += 1
# "if" handles how often we print our outputs to the console.
# If output_interval is 1, every time all three books were lent this output
# is printed to the console. If output_interval = 100, every 100 loans
# this output is printed to the console.
if counter % output_interval == 0:
# for loop prints how often every single student process has lent all three books
for i in range(int(amountStudents)):
print("Student " + str(i + 1) + " hat " + str(counter_list[i]) + " Mal alle drei Buecher bekommen!\r")
print("")
# for loop prints, which student processes have all three books at the moment
for j in range(int(amountStudents)):
if hasAllBooksList[j]:
print("Student " + str(j + 1) + " hat aktuell alle drei Buecher.\r")
print("")
counterListSem.release()
counterSem.release()
# releasing of all three books
semBook1.release()
semBook2.release()
semBook3.release()
# entering "False" in list hasAllBooksList because this student process
# has no copy of any of the three books
hasAllBooksListSem.acquire()
hasAllBooksList[int(threading.currentThread().getName()) - 1] = False
hasAllBooksListSem.release()
# main function
def main():
# list to start and collect a thread for every student
students = []
# for loop creates the required amount of student processes,
# appends the current created student process in our list students
# of student processes, initializes the corresponding loan counter
# of this current created student process in list counter_list, sets the
# corresponding boolean in list hasAllBooksList of this current
# created student process to false (because it has not all three books
# at the moment) and starts the current created student process.
for i in range(int(amountStudents)):
t = threading.Thread(target=lend_the_books, name=str(i + 1))
students.append(t)
counter_list.append(0)
hasAllBooksList.append(False)
t.start()
# for loop joins all student processes
for student in students:
student.join()
# reads number of students from console input (first argument)
amountStudents = argv[1]
# time a student has to "read" when he/she has all three books (second argument)
waiting_time = argv[2]
# time a student has to "read" when he/she has all three books (second argument)
output_interval = 20
# counter for how many times 3 books were lent
counter = 0
# list how many times each student lend 3 books
counter_list = []
# list of boolean whether a student has all three books now or not
hasAllBooksList = []
# call of main function
main()
|
4718c3808d9323e5e39f1c76fa77b0ad5c175ed9 | DivyaraniPhondekar/PythonCode | /date and time.py | 425 | 3.515625 | 4 | import time;
import calendar;
ticks=time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
print (time.localtime())
localtime = time.asctime( time.localtime())
print ("Local current time :", localtime)
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)
print ("time.altzone : ", time.altzone)
t = time.localtime()
print ("asctime : ",time.asctime(t)) |
412efbd9c79764a161482cb43adcea5b50d0228d | DivyaraniPhondekar/PythonCode | /list.py | 538 | 3.875 | 4 | squares = []
for x in range(1, 11):
squares.append(x**2)
for x in squares:
print x
list1 = ['physics', 'chemistry', 'maths']
print max(list1) # checks ASCII value
list1.append('history')
print list1
print list1.count('maths')
print list1.index('maths')
list1.insert(2,'computer science')
print list1
list1.pop()
print list1
list1.pop(1)
print list1
list2=['vishal','divya','swati','aniket','amogh']
list2.remove('amogh')
print list2
list2.reverse()
print list2
list2.sort()
print list2 |
b245f8a691c067e69b89212cd9bb2fff8ee50128 | curiousTauseef/cryptography-codes | /diffiehellman.py | 1,943 | 3.578125 | 4 | import random
import math
def rabinMiller(num):
# Returns True if num is a prime number.
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for trials in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1: # this test does not apply if v is 1.
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v ** 2) % num
return True
def isPrime(num):
if (num<2):
return False
lowPrimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59];
if num in lowPrimes:
return True
for prime in lowPrimes:
if (num%prime==0):
return False
return rabinMiller(num)
def generate_random_prime():
while True:
num=random.getrandbits(16)
if isPrime(num):
return num
def choose_primitive_root(p):
while True:
alpha=random.randrange(2,p-2)
visited={}
#print("alpha ",alpha)
for i in range(1,p):
#print(i)
val=pow(alpha,i,p)
if val not in visited:
visited[val]=1
else:
break
if len(visited)==p-1:
return alpha
# Diffie Hellman Setup
p=generate_random_prime()
print("Modulus: ",p)
alpha=choose_primitive_root(p)
print("Primitive root: ",alpha)
# Diffie Hellman Key exchange
# Alice's parameters
a=random.randrange(2,p-2) # Private key of Alice
A=pow(alpha,a,p) # Public key of Alice
# Bob's parameters
b=random.randrange(2,p-2) # Private key of Alice
B=pow(alpha,b,p) # Public key of Alice
# Session key
k1=pow(B,a,p) # Computed by Alice
k2=pow(A,b,p) # Computed by Bob
if k1==k2:
print("Shared session key is: ",k1)
else:
print("Some error in Diffie Hellman algo")
|
aebe705c785b68173e4eb3ba196dd27297f6348f | Zhangchuchu1234/MH8811-G1902372H | /06/H1.py | 405 | 3.765625 | 4 | from passwordGenerator import genPassword
try:
password_length = int(input("Please input the password length (larger or equal to 4): "))
except:
print("Input error!")
exit()
if password_length < 4:
print("Input length should be larger or equal to 4! ")
exit()
password = genPassword(password_length)
print("A random password of length {0} is {1}".format(password_length, password)) |
a1ea84b418022f06070c6155f758f9d980b519bb | moisescantero/keepcoding_bc5_reto_binario_entero | /bin_int_tests.py | 1,129 | 3.796875 | 4 | """módulo para hacer tests a módulo bin_int_module.py"""
import unittest#importar para test de pruebas
import bin_int_module#para comprobar funcionalidad
class bin_int_test(unittest.TestCase):
def test_bin_int(self):
self.assertEqual(bin_int_module.convert_bit_int("001"), 1)
self.assertEqual(bin_int_module.convert_bit_int("110"), 6)
self.assertEqual(bin_int_module.convert_bit_int("211"), "Error de formato")
self.assertEqual(bin_int_module.convert_bit_int("kkk"), "Error de formato")
self.assertEqual(bin_int_module.convert_bit_int("011001110"), 206)
self.assertEqual(bin_int_module.convert_bit_int("101110"), 46)
self.assertEqual(bin_int_module.convert_bit_int("11111110000011010001100111111000111"), 34098171847)
self.assertEqual(bin_int_module.convert_bit_int("00k10"), "Error de formato")
self.assertEqual(bin_int_module.convert_bit_int("k0k1k"), "Error de formato")
if __name__ == "__main__":#esto se pone para que al llamar en la consola python bin_int_tests.py ejecute y compruebe los errores de arriba
unittest.main() |
f76c1e50db88f9f61b22f0a655faf0ff1ed817f7 | ryanhgunn/learning | /unique.py | 382 | 4.21875 | 4 | # A script to determine if characters in a given string are unique.
import sys
string = input("Input a string here: ")
for i in range(0, len(string)):
for j in range(i + 1, len(string)):
if string[i] == string[j]:
print("The characters in the given string are not unique.")
sys.exit(0)
print("The characters in the given string are unique.")
|
1146076cdd44cc42fe31f4b7ae3d4e36c670ffa9 | liramirez/setp01 | /Lab N°1/fibonacci.py | 832 | 4.0625 | 4 |
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Nombre : Lizzie Ramirez
#Fecha : 28-Abril-2013
#Actividad : 3 - Fibonacci Lab N°1
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Declaración de funciones
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
def fibo(n):
if(n==0):
return 0
else:
if (n==1):
return 1
else:
return (fibo (n-1) + fibo (n-2))
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Declaración de funcion principal
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
def main():
num=input("Ingrese el numero del termino de la serie fibonacci que desea mostrar : ")
a=fibo(int(num))
print("El termino ",num," de la serie fibonacci es ",a)
return 0
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Identificador del main
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
if __name__ == '__main__':
main()
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
|
44e5468f266e9019b04d4b7e91812dbe87cc5a96 | AlexFSmirnov/Tanks | /py/maze_gen.py | 2,174 | 3.6875 | 4 | from random import randint
class Cell:
def __init__(self, state, right=0, bottom=0, color=0):
self.st = state
self.right = right
self.bottom = bottom
def copyline(prevline):
newline = []
for pc in prevline:
newcell = Cell(pc.st, pc.right, pc.bottom)
newline.append(newcell)
return newline
def genline(prevline, w, last = 0):
line = copyline(prevline)
if last: #generating last line
for i in range(len(line) - 1):
line[i].bottom = 1
line[i].right = 0
line[i + 1].bottom = 1
return line[::]
used = set()
for cell in line: # Preparing the line for the next generation
cell.right = 0
if cell.bottom:
cell.st = 0
used.add(cell.st)
cell.bottom = 0
if 0 in used: used.remove(0)
for cell in line:
if not cell.st:
cell.st = max(used) + 1
used.add(cell.st)
for i in range(len(line)):
#generating RIGHT border
if i < len(line) - 1:
if randint(0, 1):
if line[i].st != line[i + 1].st:
line[i].right = 1
elif line[i].st == line[i + 1].st:
line[i].right = 1
else:
line[i + 1].st = line[i].st
else:
line[i].right = 1
#generating BOTTOM border
if randint(0, 1):
cnt = 0
for j in line:
if j.st == line[i].st and j.bottom == 0:
cnt += 1
if cnt > 1:
line[i].bottom = True
return copyline(line)
def maze_gen(w, h):
prevline = [Cell(i + 11) for i in range(w)]
maze = [[Cell(-1, 1, 1, 0) for i in range(w + 2)]]
for i in range(h):
if i == h - 1:
line = genline(prevline, w, 1)
else:
line = genline(prevline, w)
newline = [Cell(-1, 1, 1, 0)] + line + [Cell(-1, 1, 1, 0)]
maze.append(newline)
prevline = copyline(line)
maze.append([Cell(-1, 1, 1, 0) for i in range(w + 2)])
return maze |
d279398b290a9f0320bacaa23864b3be614100c3 | AndrewGreen96/Python | /math.py | 1,217 | 4.28125 | 4 | # 4.3 Counting to twenty
# Use a for loop to print the numbers from 1 to 20.
for number in range(1,21):
print(number)
# 4.4 One million
# Make a list from 1 to 1,000,000 and use a for loop to print it
big_list = list(range(1,1000001))
print(big_list)
# 4.5 Summing to one million
# Create a list from one to one million, use min() and max() to check that it starts at 1 and ends at 1000000 and then sum all of the elements from the list together.
onemillion = list(range(1,1000001))
print(min(onemillion))
print(max(onemillion))
print(sum(onemillion))
# 4.6 Odd numbers
# Make a list of the odd numbers from 1 to 20 and use a for loop to print each number.
odd_numbers = list(range(1,21,2))
for odd in odd_numbers:
print(odd)
print('\n')
# 4.7 Threes
# Make a list of the multiples of 3 from 3 to 30 and then print it.
threes =list(range(3,31,3))
for number in threes:
print(number)
# 4.8 Cubes
# Make a list of the first 10 cubes.
cubes = list(range(1,11))
for cube in cubes:
print(cube**3)
# 4.9 Cube comprehension
# Use a list comprehension to generate a list of the first 10 cubes.
cubes =[cube**3 for cube in range(1,11)]
|
bc890f0f40a7e9c916628d491e473b5ecfa9bb9b | JanaranjaniPalaniswamy/Safety-Monitoring-in-Restaurants-based-on-IoT | /Source_Code/Restaurant_Environment/simulatedtempiot.py | 1,492 | 3.734375 | 4 | from random import random
import numpy as np
class TemperatureSensor:
sensor_type = "temperature"
unit="celsius"
instance_id="283h62gsj"
#initialisation
def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature):
self.average_temperature = average_temperature
self.temperature_variation = temperature_variation
self.min_temperature = min_temperature
self.max_temperature= max_temperature
self.value = 0.0 #initialise current temp value
#sensing
def sense(self):
#self.value = self.value + self.simple_random()
self.value = self.complex_random() + self.noise()
return self.value
#noise
def noise(self):
self.noise_value = np.random.normal(0,1)
return self.noise_value
#helper function for generating values with min temp as its base
def simple_random(self):
value = self.min_temperature + (random() * (self.max_temperature - self.min_temperature)) #so that it is in the range
return value
def complex_random(self):
value = self.average_temperature * (1 + (self.temperature_variation/100) * (1 * random() -1))
value = max(value,self.min_temperature)
value = min(value,self.max_temperature)
return value
#creating instance of sensor
ts = TemperatureSensor(25,10,16,35)
|
00ad5d687e667948ad3a0fa1c785dcce1454c33f | JanaranjaniPalaniswamy/Safety-Monitoring-in-Restaurants-based-on-IoT | /Source_Code/Restaurant_Environment/simulatedweightiot.py | 1,384 | 3.578125 | 4 | from random import random
import numpy as np
class WeightSensor:
sensor_type = "weight"
unit="kg"
instance_id="285h62gsj"
#initialisation
def __init__(self, average_weight, weight_variation, min_weight, max_weight):
self.average_weight = average_weight
self.weight_variation = weight_variation
self.min_weight = min_weight
self.max_weight= max_weight
self.value = 0.0 #initialise current temp value
#sensing
def sense(self):
#self.value = self.value + self.simple_random()
self.value = self.complex_random() + self.noise()
return self.value
#noise
def noise(self):
self.noise_value = np.random.normal(0,0.5)
return self.noise_value
#helper function for generating values with min temp as its base
def simple_random(self):
value = self.min_weight + (random() * (self.max_weight - self.min_weight)) #so that it is in the range
return value
def complex_random(self):
value = self.average_weight * (1 + (self.weight_variation/100) * (1 * random() -1))
value = max(value,self.min_weight)
value = min(value,self.max_weight)
return value
#creating instance of sensor
ws = WeightSensor(25,30,15.3,29.5)
|
0fac9b063f054fbd85c04825690db77f865fcd27 | NayanJain09/TASK-2 | /class.py | 2,686 | 3.734375 | 4 | class Player(object):
def __init__(self, name, symbol, initial_score=0):
self.name= name
self.symbol= symbol
self.score= initial_score
def won_match(self):
self.score+= 100
def lost_match(self):
self.score-= 50
def show_score(self):
print('Player {}: {} points'.format(self.name, self.score))
class PlayingField(object):
def __init__(self):
self.field= [
[None, None, None],
[None, None, None],
[None, None, None]
]
def show_field(self):
for row in self.field:
for player in row:
print('_' if player is None else player.symbol,end=' ')
print()
def set_player(self, x, y, player):
if self.field[y][x] is not None:
return False
self.field[y][x]= player
return True
def full_board(self):
for row in self.field:
for col in self.field:
if col is '_':
return False
else:
return True
def check_won(self, x, y, player):
if self.field[0][x] == player.symbol and self.field[1][x] == player.symbol and self.field[2][x] == player.symbol:
return True
elif self.field[y][0] == player.symbol and self.field[y][1] == player.symbol and self.field[y][2] == player.symbol:
return True
elif self.field[0][0] == player.symbol and self.field[1][1] == player.symbol and self.field[2][2] == player.symbol:
return True
elif self.field[0][2] == player.symbol and self.field[1][1] == player.symbol and self.field[2][0] == player.symbol:
return True
else:
return False
name_1= input('Name of Player 1: ')
name_2= input('Name of Player 2: ')
players= [
Player(name_1, 'X'),
Player(name_2, 'O')
]
field= PlayingField()
while True:
for player in players:
print(player.symbol)
y= int(input('Player {} choose your row: '.format(player.name))) - 1
x= int(input('Player {} choose your column: '.format(player.name))) - 1
if not field.set_player(x, y, player):
print('That field is already occupied.')
else :
field.show_field()
for player in players:
print('{}: {}'.format(player.name, player.score))
if field.check_won(x,y,player):
print('Player {} won the game.'.format(player.name))
exit(0)
|
823815fa2fcabe0bae5f0c341935f3d5d0a84c4f | DigantaBiswas/python-codes | /working_with_lists.py | 277 | 3.953125 | 4 | cat_names = []
while True:
print('Enter the name of cat '+str(len(cat_names)+1)+'or enter nothing to stop')
name = input()
if name =='':
break
cat_names= cat_names+[name]
print('the cat names are:')
for name in cat_names:
print(''+name)
|
84bc960c4519feff5a5f96d991f563f12d57f8a0 | GopiReddy590/python_code | /task1.py | 128 | 3.625 | 4 | n='abbabbaabab'
for i in range(1,len(n)):
for j in range(0,i):
a=n[i:j]
if a==a[::-1]:
print(a)
|
6317d6a640f443b471f457f053cc1a7daf58e468 | RadSebastian/AdventOfCode2018 | /day02/part_1.py | 822 | 3.8125 | 4 |
def result(string):
count_twos = 0
count_threes = 0
dict = {}
for word in string:
dict[word] = 0
for key in dict:
for _word in string:
if key == _word:
dict[key] += 1
for _key in dict:
if dict[_key] == 2:
count_twos = 1
elif dict[_key] == 3:
count_threes = 1
return count_twos, count_threes, dict
if __name__ == "__main__":
INPUT = 'input.txt'
strings = [str(line.rstrip('\n')) for line in open(INPUT)]
count_twos_ = 0
count_threes_ = 0
for string in strings:
count_twos, count_threes, dict = result(string)
count_twos_ += count_twos
count_threes_ += count_threes
print(count_twos_, count_threes_)
print("Checksum:", count_twos_ * count_threes_)
|
c57bf5de10396fb91422064e3a68639c048ee4da | dreamson80/Python_learning | /loop_function.py | 149 | 3.890625 | 4 | def hi():
print('hi')
def loop(f, n): # f repeats n times
if n <= 0:
return
else:
f()
loop(f, n-1)
loop(hi , 5)
|
ea9628aae7659d2c942568ad4f6bfca3c32a8cf9 | Harrywekesa/Classes | /classstudents.py | 747 | 4.03125 | 4 | class Student: #defining class
'Common base class for all students'
student_count = 0 #class variable accessible to all instances of the class
def __init__(self, name, id): # class constructor
self.name = name
self.id = id
Student.student_count =+ 1
def printStudentData(self): #Other class methods declared as normal functions
print('Name : ', self.name, 'Id : ', self.id)
s = Student("Harrison wekesa", 2034)
d = Student('Nathan Lomin', 2042)
e = Student("Brian Kimutai", 2220)
s.printStudentData() #Accessing class attributes using the dot operator
d.printStudentData() #Accessing class attributes using the dot operator
e.printStudentData()
print("Total students : ", Student.student_count)
|
f600c5a54d0e24daac47a3c576c10e54c97a75e3 | PaulLiang1/CC150 | /binary_search/searchinsert/search_insert_2.py | 647 | 3.953125 | 4 | class Solution:
"""
@param A : a list of integers
@param target : an integer to be inserted
@return : an integer
"""
def searchInsert(self, A, target):
# boundary case
if A is None or target is None:
return None
if len(A) == 0:
return 0
low = 0
high = len(A) - 1
while low <= high:
# prevent overflow
mid = low + (high - low) / 2
if A[mid] == target:
return mid
elif A[mid] > target:
high = mid - 1
else:
low = mid + 1
return low
|
d01bc0fe676657ad68c0b3fdd3c3f5d13a7e8a36 | PaulLiang1/CC150 | /linklist/partition_list.py | 1,275 | 3.953125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@param x: an integer
@return: a ListNode
"""
def partition(self, head, x):
if head is None or head.next is None:
return head
before = after = None
before_ptr = after_ptr = None
ptr = head
while ptr is not None:
if ptr.val < x:
if before is None:
before_ptr = ptr
before = ptr
else:
before_ptr.next = ptr
before_ptr = ptr
else:
if after is None:
after_ptr = ptr
after = ptr
else:
after_ptr.next = ptr
after_ptr = ptr
ptr = ptr.next
if before is None:
after_ptr.next = None
return after
elif after is None:
before_ptr.next = None
return before
else:
before_ptr.next = after
after_ptr.next = None
return before
|
0832f4bc298fe913b4cd09bfb1f976173e74f751 | PaulLiang1/CC150 | /linklist/remoev_nth_node_from_list.py | 925 | 3.765625 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@param n: An integer.
@return: The head of linked list.
"""
def removeNthFromEnd(self, head, n):
prev_ptr = ptr = n_ptr = head
for i in xrange(n):
n_ptr = n_ptr.next
while n_ptr is not None:
n_ptr = n_ptr.next
prev_ptr = ptr
ptr = ptr.next
# remove head:
if head == ptr:
if ptr.next is None:
return None
else:
head = ptr.next
return head
# remove last nd
elif ptr.next is None:
prev_ptr.next = None
# remove nd in middle
else:
prev_ptr.next = ptr.next
return head
|
3a6afb8dd2b80a53e0b1375c0d9212d486bcc62a | PaulLiang1/CC150 | /linklist/sort_link_list_merge_sort.py | 1,353 | 3.953125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the sorted linked list,
using constant space complexity.
"""
def sortList(self, head):
if head is None or head.next is None:
return head
mid = self.findmid(head)
right = self.sortList(mid.next)
mid.next = None
left = self.sortList(head)
return self.merge(left, right)
def findmid(self, node):
slow_ptr = fast_ptr = node
while fast_ptr.next is not None and fast_ptr.next.next is not None:
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next
return slow_ptr
def merge(self, list1, list2):
dummy = ListNode(0)
ptr = dummy
while list1 and list2:
if list1.val < list2.val:
ptr.next = list1
ptr = list1
list1 = list1.next
else:
ptr.next = list2
ptr = list2
list2 = list2.next
if list1:
ptr.next = list1
if list2:
ptr.next = list2
return dummy.next
|
7eb9f91582d5d33fd2d8d4a9cc604075b63bd44f | PaulLiang1/CC150 | /binary_tree/complete_binary_tree_iter.py | 1,085 | 3.78125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
from collections import deque
class Solution:
"""
@param root, the root of binary tree.
@return true if it is a complete binary tree, or false.
"""
def isComplete(self, root):
if root is None:
return True
queue = deque()
queue.append(root)
result = list()
# Do BFS
while len(queue) > 0:
node = queue.popleft()
if node is None:
result.append('#')
continue
result.append(node.val)
queue.append(node.left)
queue.append(node.right)
if '#' not in result:
return True
non_hash_bang_found = False
for i in xrange(len(result) - 1, -1, -1):
if '#' == result[i] and non_hash_bang_found is True:
return False
if '#' != result[i]:
non_hash_bang_found = True
return True
|
6533ce18f884504f827c1bd6e96d9658d7a6d795 | PaulLiang1/CC150 | /binary_tree/binary_tree_level_order_traversal.py | 890 | 3.703125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
from collections import deque
class Solution:
"""
@param root: The root of binary tree.
@return: Level order in a list of lists of integers
"""
def levelOrder(self, root):
result = list()
if root is None:
return result
queue = deque()
queue.append(root)
while len(queue) > 0:
sub_result = list()
for i in xrange(len(queue)):
node = queue.popleft()
sub_result.append(node.val)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
result.append(sub_result)
return result
|
39e68074ff349b3c0b678957c5858ab9a7987833 | PaulLiang1/CC150 | /array/sort_colors.py | 632 | 3.71875 | 4 | class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
if nums is None or len(nums) == 0:
return nums
zero_idx = 0
two_idx = len(nums) - 1
i = 0
while i <= two_idx:
if nums[i] == 0:
nums[zero_idx], nums[i] = nums[i], nums[zero_idx]
zero_idx += 1
i += 1
elif nums[i] == 1:
i += 1
elif nums[i] == 2:
nums[two_idx], nums[i] = nums[i], nums[two_idx]
two_idx -= 1
|
36d89924222e0e22a0c1b77dd71a77102a64c7d9 | kiwanter/Python-Workspace | /work5/5-2.py | 375 | 3.5 | 4 | f=open('log.txt','w')
f.close()
def outer(func):
def inner(*args):
f=open('log.txt','a')
f.write('start %s(%s)'%(func.__name__,args))
f.write('\n')
f.close()
return func(*args)
return inner
@outer
def fun1(i):
print(i+1)
return i
@outer
def fun2(n,s):
for i in range(n):
print(s)
fun1(5)
fun2(3,'hello')
|
198d10d5bfedd6d8de05492324b991c7d5172f0a | kiwanter/Python-Workspace | /work1/1-1.py | 430 | 3.84375 | 4 | odd=[]
even=[]
prime=[]
user1=[]
for i in range(0,50):
if(i%2==0):
even.append(i)
if(i%3)==0:
user1.append(i)
if(i%2!=0):
odd.append(i)
isprime=1
for j in range(2,i):
if(i%j==0):
isprime=0
if(i>=2 and isprime==1):
prime.append(i)
print("偶数:",even)
print("奇数:",odd)
print("质数:",prime)
print("同时被二三整除:",user1)
|
033707f7e7982db2fc97a110263d385005f6223e | kiwanter/Python-Workspace | /work6/6-1.py | 1,057 | 4.09375 | 4 | #一、定义一个狗类,里面有一个 列表成员变量(列表的元素是字典), 分别记录了 3种颜色的狗的颜色, 数量,和价格;实现狗的买卖交易方法; 打印输出经过2-3次买卖方法后,剩下的各类狗的数量;
class dog():
__data=[]
def __init__(self,r:int,g:int,b:int):
self.__data.append({'color':'red','number':r,'price':30})
self.__data.append({'color':'green','number':g,'price':20})
self.__data.append({'color':'blue','number':b,'price':40})
def p(self):
for t in self.__data:
print('%s dog price %d now has %d' %(t['color'],t['price'],t['number']))
def buy(self,c:str,n:int):
for t in self.__data:
if t['color']==c:
t['number']+=n
print('buy %s dog %d' %(c,n))
def sell(self,c:str,n:int):
for t in self.__data:
if t['color']==c:
t['number']-=n
print('sell %s dog %d' %(c,n))
a=dog(2,3,4)
a.p()
a.buy('red',3)
a.p()
a.sell('blue',2)
a.p() |
fd9dad0af1812ba52f121ceb27cdac565a1441df | zilinwujian/sgFoodImg | /fileHandle.py | 1,119 | 3.734375 | 4 | # #coding:utf-8
import os
# def fileRead(filePath):
# fileList = list()
# with open(filePath,"r") as f:
#
# # for line in f.readline():
# # line = line.strip() # 去掉每行头尾空白
# # print line
# # if not len(line) or line.startswith('#'): # 判断是否是空行或注释行
# # continue # 是的话,跳过不处理
# # fileList.append(line) # 保存
# return fileList
# 读取文件
def fileRead(filePath):
f = open(filePath, 'r') # 以读方式打开文件
result = list()
for line in f.readlines(): # 依次读取每行
line = line.strip() # 去掉每行头尾空白
result.append(line) # 保存
f.close()
return result
# 写入文件
def fileWrite(filePath,contents):
f =open(filePath,'a+')
f.write(contents)
f.close()
return
# 创建目录
def makeDir(fileDir):
if not os.path.exists(fileDir):
# print(fileDir, " not exist")
os.makedirs(fileDir)
# print("make directory successfully")
else:
print(fileDir, "exist") |
fb62ce8b5b142244e6ad9e8ac4a0ea62bec28689 | OleKabigon/test1 | /Nested loop.py | 124 | 4.09375 | 4 | for x in range(4): # This is the outer loop
for y in range(3): # This is the inner loop
print(f"{x}, {y}")
|
43e3cb0d6e43924b778e04ac8e6aa2234bba0a7b | kishoreganth-Accenture/Training | /python assessment 3/rationalMultiplication2.py | 249 | 4.03125 | 4 | import math
t = int(input("enter the number of rrational numbers needed to multiply :"))
product = 1
num = 1
den = 1
for i in range(t):
a = int(input())
b = int(input())
product= product * a/b
print(product.as_integer_ratio()) |
7676428ccc068cb340ac724f2a4a7df6c288b250 | kishoreganth-Accenture/Training | /python assessment 3/cartesianProduct7.py | 115 | 3.5 | 4 |
A = [1, 2]
B = [3, 4]
for i in set(A):
for j in set(B):
print("(",i,",",j,")",end = "")
|
37aa1112ee4933613e016e886a874f31b3c76685 | PrasTAMU/SmartStats | /weatherUtil.py | 1,472 | 3.84375 | 4 | import requests
import config
#Uses the OpenWeatherMap API to get weather information at the location provided by the car
WEATHER_KEY=config.openweathermapCONST['apikey']#'741365596cedfc98045a26775a2f947d'
#gets generic weather information of the area
def get_weather(lat=30.6123149, lon=-96.3434963):
url = "https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}".format(str(lat), str(lon), WEATHER_KEY)
r = requests.get(url)
return r.json()
#isolates the temperature from the list and returns it to the main file
def weather(lat=30.6123149, lon=-96.3434963):
weather = get_weather(lat, lon)
temperature = weather['main']['temp']
temperature = temperature - 273.15
return str(temperature)
#creative descriptions of how the weather feels
def temperature_description(temperature="25"):
temp = float(temperature)
if temp < -30:
return ", perfect weather for penguins."
elif temp < -15:
return ", you might want stay inside."
elif temp < 0:
return ", you should wear a few layers."
elif temp < 10:
return ", sure is chilly."
elif temp < 20:
return ", sweater weather!"
elif temp < 30:
return ", the weather looks great!"
elif temp < 40:
return ", ice cream weather!"
elif temp < 45:
return " stay inside and stay hydrated."
else:
return ", the A/C bill is going to be high."
|
4f0ed2eb6105138360c8b2c165cfe5550c797fcb | NielsRoe/ProgHw | /Huiswerk/28.09 Control Structures/1. If statements.py | 213 | 3.765625 | 4 | score = float(input("Geef je score: "))
if score > 15 or score == 15:
print("Gefeliciteerd!")
print("Met een score van %d ben je geslaagd!" % (score))
else:
print("Helaas, je score is te laag.") |
4eb84d42d875ac7d4d69ca9fb3682b799b71ea50 | YuvalLevy1/ImageProcessing | /src/slider.py | 2,576 | 3.515625 | 4 | import math
import pygame
SLIDER_HEIGHT = 5
VALUE_SPACE = 50
class Circle:
def __init__(self, x, y, radius, color):
self.x = x
self.y = y
self.radius = radius
self.color = color
class Slider:
def __init__(self, coordinates, min_value, max_value, length, text):
self.held = False
self.__x = coordinates[0]
self.__y = coordinates[1]
self.__max_x = self.__x + length
self.min = min_value
self.max = max_value
self.__length = length
self.rectangle = pygame.Rect(self.__x, self.__y, length, SLIDER_HEIGHT)
self.__circle = Circle(self.__x + int(length / 2), self.__y + 2, SLIDER_HEIGHT, (127, 127, 127))
font = pygame.font.SysFont('Corbel', 20)
self.text = text
self.rendered_text = font.render(text, True, (0, 0, 0))
"""
moves the circle according to borders
"""
def move_circle(self, x):
if not self.held:
return
if self.between_borders(x):
self.__circle.x = x
return
self.__circle.x = self.__closest_to(x)
"""
returns the closest point to x from border
"""
def __closest_to(self, x):
if math.fabs(x - self.__x) > math.fabs(x - self.__max_x):
return self.__max_x
return self.__x
"""
returns true if param x is between the boarders of the slider.
"""
def between_borders(self, x):
return self.__max_x >= x >= self.__x
def get_value(self):
if self.__circle.x == self.__x:
return self.min
if self.__circle.x == self.__max_x:
return self.max
return int((self.__circle.x - self.__x) * (self.max / self.__length))
def get_circle_x_by_value(self, value):
return (value * self.__length + self.__x * self.max) / self.max
def is_mouse_on_circle(self, mouse_pos):
return math.dist(mouse_pos, self.get_circle_coordinates()) <= self.__circle.radius
def get_circle_coordinates(self):
return self.__circle.x, self.__circle.y
def get_size(self):
return self.rectangle.width + self.rendered_text.get_rect().width + (
self.__x - self.get_value_coordinates()[0]) + VALUE_SPACE
def get_circle_r(self):
return self.__circle.radius
def get_circle_color(self):
return self.__circle.color
def get_text_coordinates(self):
return self.__max_x + 3, self.__y - 8
def get_value_coordinates(self):
return self.__x - VALUE_SPACE, self.__y - 8
|
f003dd889cdce228f66dbad8f66955c9c32563c0 | csgray/IPND_lesson_3 | /media.py | 1,388 | 4.625 | 5 | # Lesson 3.4: Make Classes
# Mini-Project: Movies Website
# In this file, you will define the class Movie. You could do this
# directly in entertainment_center.py but many developers keep their
# class definitions separate from the rest of their code. This also
# gives you practice importing Python files.
# https://www.udacity.com/course/viewer#!/c-nd000/l-4185678656/m-1013629057
# class: a blueprint for objects that can include data and methods
# instance: multiple objects based on a class
# constructor: the __init__ inside the class to create the object
# self: Python common practice for referring back to the object
# instance methods: functions within a class that refers to itself
import webbrowser
class Movie():
"""This class provides a way to store movie related information."""
def __init__(self, movie_title, rating, duration, release_date, movie_storyline, poster_image, trailer_youtube):
# Initializes instance of class Movie
self.title = movie_title
self.rating = rating
self.duration = duration
self.release_date = release_date
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
# Opens a browser window with the movie trailer from YouTube
webbrowser.open(self.trailer_youtube_url)
|
967a8757c9139a9b7614956677620f3697443938 | HenkT28/GMIT | /my-first-program-new.py | 339 | 3.984375 | 4 | # Henk Tjalsma, 03-02-2019
# Calculate the factorial of a number.
# start wil be the start number, so we need to keep track of that.
# ans is what the answer will eventually become. It started as 1.
# i stands for iterate, something repetively.
start = 10
ans = 1
i = 1
while i <= start:
ans = ans * i
i = i + 1
print(ans) |
d2ea6ef4b341d5071a0adb05dd72d4f9995b677e | ncmarian/prediction | /archive/formatter.py | 4,918 | 3.578125 | 4 | #Owen Chapman
#first stab at text parsing
import string
#Premiership
#Championship
#opening files.
def getFiles (read, write):
"""
read: string of filename to be read from.
write: string name of file to be written to.
returns: tuple of files (read,write)
"""
r=open(read)
w=open(write,'w')
return (r,w)
def getPremierTeams(r,leaguename):
"""
finds the team names of all of the teams participating in the premier league of
a given year.
r: file object to be read from
return: list of strings. all of the teams' names.
"""
start=0
teams=[]
for line in r:
line=line.strip()
if start==0:
if line==leaguename:
start=1
elif start==1:
if line=="Round 1":
start=2
else:
if line=="Round 2":
break
elif line=='' or line[0]=='[' or line[-1]==']':
continue
else:
wordlist=line.split(' ')
firstname=""
scoreindex=0
for i in range(len(wordlist)):
word=wordlist[i]
if word=='':
continue
elif word[0] in string.digits:
scoreindex=i
break
else:
firstname+=(word+' ')
firstname=firstname.strip()
#print firstname
teams.append(firstname)
secondname=""
for i in range(scoreindex+1,len(wordlist)):
word=wordlist[i]
if word=='':
continue
else:
secondname+=(word+ ' ')
secondname=secondname.strip()
#print secondname
teams.append(secondname)
return teams
#09-10. for testing purposes.
globalteams=['Chelsea','Manchester U','Arsenal','Tottenham','Manchester C','Aston Villa',
'Liverpool','Everton','Birmingham','Blackburn','Stoke','Fulham','Sunderland',
'Bolton','Wolverhampton','Wigan','West Ham','Burnley','Hull','Portsmouth']
def parse (r,w,pteams,cteams):
"""
r: file object to be read from
w: file object to be written to
returns void
"""
count = 0
regseas=0
for line in r:
d=parseline(line,pteams+cteams)
if d!=None:
(t1,s,t2)=d
tag='c'
if t1 in pteams and t2 in pteams:
regseas+=1
tag='p'
#print t1+'_'+s+'_'+t2+'_'+tag
w.write(t1+'_'+s+'_'+t2+'_'+tag+'\n')
count +=1
print regseas, count
def parseline(line,teamlist):
"""
line: string line to be parsed
teamlist: list of strings: valid team names. Should be created prior to calling
this function. All teams in a given league.
return: void if not a valid score
(string team, string score, string team) if valid score.
"""
line=line.strip()
wordlist=line.split(" ")
firstname=""
scoreindex=0
for i in range(len(wordlist)):
word=wordlist[i]
if word=='':
continue
elif word[0] in string.digits:
scoreindex=i
break
else:
firstname+=(word+' ')
firstname=firstname.strip()
#print firstname
score=(wordlist[scoreindex]).strip()
if (len(score)<3) or (score[0] not in string.digits) or (score[-1] not in string.digits) or (score[1] != '-'):
return None
if firstname not in teamlist:
return None
secondname=""
for i in range(scoreindex+1,len(wordlist)):
word=wordlist[i]
if word=='':
continue
elif word[0]=='[':
break
else:
secondname+=(word+ ' ')
secondname=secondname.strip()
#print secondname
if secondname not in teamlist:
return None
return (firstname,wordlist[scoreindex],secondname)
def getFilePrefix(yr1):
if yr1<10:
tdy='0'
else:
tdy=''
tdy+=str(yr1)
if yr1<9:
tdyp1='0'
else:
tdyp1=''
tdyp1+=str(yr1+1)
return (tdy+'-'+tdyp1)
def writeTeams(year):
prefix=getFilePrefix(year)
r=open(prefix+" scores.txt")
w=open(prefix+" teams.txt",'w')
teams=getPremierTeams(r,'Premiership')
for team in teams:
print team
w.write(team+'\n')
r.close()
w.close()
return teams
def run(year):
pteams=writeTeams(year)
prefix=getFilePrefix(year)
fname1=prefix+' scores.txt'
fname2=prefix+' scores formatted.txt'
r=open(fname1)
cteams=getPremierTeams(r,'Championship')
print cteams
r.close()
(r,w)=getFiles(fname1,fname2)
parse(r,w,pteams,cteams)
r.close()
w.close()
|
16415d6886a2bc38110cdb9df667adb99a78b638 | Mounik007/Map-Reduce | /mounik_muralidhara_squared_two_1.py | 1,823 | 3.53125 | 4 | import MapReduce
import sys
import re
"""
Matrix 5*5 Multiplication Example in the Simple Python MapReduce Framework using two phase
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
class MapValueObject(object):
"""__init__() functions as class constructor"""
def __init__(self, mapSet=None, mapRowOrColumn = None, mapCellValue = None):
self.mapSet = mapSet
self.mapRowOrColumn = mapRowOrColumn
self.mapCellValue = mapCellValue
def mapper(record):
elements = record
mapValueObjA = MapValueObject()
mapValueObjA.mapSet = "A"
mapValueObjA.mapRowOrColumn = elements[0]
mapValueObjA.mapCellValue = elements[2]
mr.emit_intermediate(elements[1], mapValueObjA)
mapValueObjB = MapValueObject()
mapValueObjB.mapSet = "B"
mapValueObjB.mapRowOrColumn = elements[1]
mapValueObjB.mapCellValue = elements[2]
mr.emit_intermediate(elements[0], mapValueObjB)
def reducer(key, list_of_values):
listA = []
listB = []
for index in range(len(list_of_values)):
if(list_of_values[index].mapSet == "A"):
listA.append(list_of_values[index])
else:
listB.append(list_of_values[index])
for indexA in range(len(listA)):
for indexB in range(len(listB)):
keyValueLst = []
keyValueLst.append(listA[indexA].mapRowOrColumn)
keyValueLst.append(listB[indexB].mapRowOrColumn)
keyValueLst.append((listA[indexA].mapCellValue) * (listB[indexB].mapCellValue))
mr.emit(keyValueLst)
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
140675932ae15b2421f6ca7a1f7cbf6babab74f6 | Ludwig-Graef/webserver | /webserver_v3/WebServer.py | 1,154 | 3.671875 | 4 |
import sys
import argparse
import www
if __name__ == "__main__":
if sys.version_info[0] is not 3:
print("ERROR: Please use Python version 3 !! (Your version: %s)"
% (sys.version))
exit(1)
def type_port(x):
x = int(x)
if x < 1 or x > 65535:
raise argparse.ArgumentTypeError(
"Port number has to be greater than 1 and less than 65535.")
return x
description = ("Serves a local directory on your computer via the HTTP protocol."
"Use the www/serve.py file to implement your changes.")
parser = argparse.ArgumentParser(description=description)
parser.add_argument("-a",
"--address",
help="The address to listen on. (Default: '127.0.0.1')",
default="127.0.0.1")
parser.add_argument("-p",
"--port",
help="The port to listen on. (Default: 8080)",
type=type_port,
default=8080)
args = parser.parse_args()
www.serve(address=args.address, port=args.port)
|
f3a0ae3922cf341c118cb36ca0fdd6ca2d9ea521 | lucasgameiroborges/Python-lista-1---CES22 | /item10.py | 133 | 3.59375 | 4 | def sum(A, B):
(x, y) = A
(z, w) = B
return (x + z, y + w)
X = (1, 2)
Y = (3, 4)
print("{0}".format(sum(X, Y))) |
d3abb379287051f91e29c3bc69fc07df400b5573 | MathAdventurer/Python-Algorithms-and-Data-Structures | /Codes/chapter_1/chapter_1_solution.py | 2,116 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: Wang,Xudong 220041020 SDS time:2020/11/25
class Fraction:
def gcd(m: int, n: int):
if n != 0 and m != 0:
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
else:
return None
def __init__(self,top,bottom):
common = Fraction.gcd(top, bottom)
self.num = top//common
self.den = bottom//common
def show(self):
print(self.num,"/",self.den)
print(self.num,"/",self.den)
def __str__(self):
return str(self.num) + "/" + str(self.den)
# 定义加法 \为续行符
# def __add__(self, otherfraction):
# newnum = self.num * otherfraction.den + \
# self.den * otherfraction.num
# newden = self.den * otherfraction.den
# return Fraction(newnum,newden)
# 化简分数的方法 greatest common divisor,GCD
# 欧几里得算法 化简分数 不用loop用判断写不出来
def __add__(self,otherfraction):
newnum = self.num * otherfraction.den + \
self.den * otherfraction.num
newden = self.den * otherfraction.den
common = Fraction.gcd(newnum,newden) #如果函数定义在class内部,调用的时候需要用class.method,定义在外部可以直接调用gcd
return Fraction(newnum//common,newden//common) #只取了余数
# 浅相等与真相等
# 浅相等:同一个对象的引用(根据引用来判断)才为真,在当前实现中,分子和分母相同的两个不同的对象是不相等的。
# 深相等:根据值来判断相等,而不是根据引用
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = self.den * other.num
return firstnum == secondnum
def __le__(self, other):
firstnum = self.num * other.den
secondnum = self.den * other.num
return firstnum <= secondnum
if __name__ == "__main__":
f1 = Fraction(6,8)
f1.show()
print(f1)
|
4af35eb512097893fbb7cd211b0bb5cbdc60d5fb | camiladlsa/Recursividad | /FactorialTR.py | 445 | 3.984375 | 4 | n = int(input("\nIngrese un entero positivo para tomar el factorial: "))
def factorial(n):
if not isinstance(n, int):
print("Error: el valor debe ser un entero\n")
elif n < 0:
print("\nError: el factorial no existe para n < 0.\n")
else:
return factorial_process(n, 1);
def factorial_process(n, accm):
if n == 0:
return accm
else:
return factorial_process(n - 1, n * accm)
print("\nFactorial:",factorial(n),"\n") |
8dd4b348fd8210b3ca0c49a097bb52b97fefab2c | williamabreu/esp8266-micropython | /thermistor.py | 999 | 3.53125 | 4 | import machine, math
def get_temp(_pin):
# Inputs ADC Value from Thermistor and outputs temperature in Celsius
raw_ADC = machine.ADC(_pin).read()
# Assuming a 10k Thermistor. Calculation is actually: resistance = (1024/ADC)
resistance=((10240000/raw_ADC) - 10000)
# *****************************************************************
# * Utilizes the Steinhart-Hart Thermistor Equation: *
# * temperature in Kelvin = 1 / {A + B[ln(R)] + C[ln(R)]^3} *
# * where A = 0.001129148, B = 0.000234125 and C = 8.76741E-08 *
# *****************************************************************
temp = math.log(resistance)
temp = 1 / (0.001129148 + (0.000234125 * temp) + (0.0000000876741 * temp * temp * temp))
temp = temp - 273.15; # Convert Kelvin to Celsius
# Uncomment this line for the function to return Fahrenheit instead.
# temp = (temp * 9.0)/ 5.0 + 32.0 # Convert to Fahrenheit
return temp # Return the temperature |
faab5b174ee26be0d7355a29476d7d4af0d96418 | rmmo14/pyforloopbasic2 | /for_loop_basic_2.py | 3,023 | 3.890625 | 4 | # 1. Big size
# def biggie(mylist):
# empty = []
# for x in range (0,len(mylist)):
# if mylist[x] > 0:
# empty.append('big')
# else:
# empty.append(mylist[x])
# print(empty)
# return empty
# holder = biggie([-1, 2, 3, -5])
# 2. count positives
# def counting(my_list):
# count = 0
# empty = []
# for x in range (0,len(my_list)):
# if my_list[x] > 0:
# count += 1
# my_list[len(my_list) - 1] = count
# print (my_list)
# return my_list
# holder = counting([-1, 2, -3, 9, -3, -4])
# 3. sum total
# def sumtotal(mylist):
# sum = 0
# for x in range (0, len(mylist)):
# sum += mylist[x]
# print (sum)
# return sum
# hold = sumtotal([1,2,5,6])
# 4. average
# def average(my_list):
# sum = 0
# for x in range (0,len(my_list)):
# sum += my_list[x]
# avg = sum / len(my_list)
# print(avg)
# return avg
# holder = average([2,3,5,6,4])
# 5. length
# def length(mylist):
# holder = len(mylist)
# print(holder)
# return holder
# hold = length([2,3,4,5,6,7])
# 6. minimum
# def min(my_list):
# if my_list == []:
# print("False")
# return False
# else:
# min = my_list[0]
# for x in range (0,len(my_list)):
# if my_list[x] < min:
# min = my_list[x]
# print(min)
# return min
# holder = min([1,2,3,-1])
# 7. maximum
# def max(mylist):
# if mylist == []:
# print("False")
# return False
# else:
# max = mylist[0]
# for x in range (0, len(mylist)):
# if mylist[x] > max:
# max = mylist[x]
# print(max)
# return max
# hold = max([])
# 8. ulti analysis
# def ult(my_list):
# if my_list == []:
# print("False")
# return False
# else:
# dicto = {}
# min = my_list[0]
# max = my_list[0]
# sum = 0
# for x in range (0,len(my_list)):
# sum += my_list[x]
# if my_list[x] > max:
# max = my_list[x]
# elif my_list[x] < min:
# min = my_list[x]
# avg = sum / len(my_list)
# dicto['min'] = min
# dicto['max'] = max
# dicto['avg'] = avg
# dicto['length'] = len(my_list)
# print(dicto)
# return dicto
# holder = ult([2,3,4,5,6,4])
# potato = ult([-1,-1,-2,-1,0])
# 9. reverse list
def revlist(mylist):
length = len(mylist) - 1
for x in range (int(len(mylist)/2)):
temp = mylist[length - x]
mylist[length - x] = mylist[x]
mylist[x] = temp
print(mylist)
return mylist
# def reverse_list(nums_list):
# list_len = len(nums_list)
# for idx in range(int(list_len/2)):
# temp = nums_list[list_len-1-idx]
# nums_list[list_len-1-idx] = nums_list[idx]
# nums_list[idx] = temp
# print(nums_list)
# return nums_list
print(revlist([3, 1, 8, 10, -5, 6])) |
9f3dd5176c949bf0cf35fd32d81900aca0665e64 | mglowacz/algorithms | /ch4/quickSort.py | 422 | 3.953125 | 4 | from random import randint
def quickSort(arr) :
if (len(arr) < 2) : return arr
pivot = randint(0, len(arr))
less = [val for idx, val in enumerate(arr) if val <= arr[pivot] and idx != pivot]
greater = [val for idx, val in enumerate(arr) if val > arr[pivot] and idx != pivot]
return quickSort(less) + [arr[pivot]] + quickSort(greater)
arr = [56, 21, 45, 2, 14, 86, 33, 12, 8]
print(arr)
print(quickSort(arr))
|
2d451bac8c45fbacd81c9074a9261463d67fbf52 | mglowacz/algorithms | /ch4/binarySearch.py | 741 | 3.84375 | 4 | def binarySearch(arr, item) :
if arr == [] : return -1
if len(arr) == 1 : return 0 if item == arr[0] else -1
mid = len(arr) // 2
if arr[mid] == item : return mid
sublist = arr[:mid] if arr[mid] > item else arr[mid + 1:]
subindex = 0 if arr[mid] > item else mid + 1
bs = binarySearch(sublist, item)
return -1 if bs == -1 else subindex + bs
arr = [1, 3, 4, 6, 7, 9, 12, 13, 18]
print(arr)
print("Found (1) at {}".format(binarySearch(arr, 1)))
print("Found (3) at {}".format(binarySearch(arr, 3)))
print("Found (7) at {}".format(binarySearch(arr, 7)))
print("Found (12) at {}".format(binarySearch(arr, 12)))
print("Found (18) at {}".format(binarySearch(arr, 18)))
print("Found (11) at {}".format(binarySearch(arr, 11)))
|
8e52b22c8ed94bac68be42c51785e6333690d415 | SirBman/Prac5 | /listWarmUp.py | 305 | 3.90625 | 4 | """List Warm Up"""
numbers = [3, 1, 4, 1, 5, 9, 2]
print (numbers[0], numbers[-7], numbers[3], numbers[:-1], numbers[3:4], 5 in numbers, 7 in numbers, "3" in numbers, numbers + [6, 5, 3])
numbers [0] = "ten"
print(numbers[0])
numbers[-1] = 1
print(numbers[-1])
print(numbers[2:])
print(9 in numbers) |
bcab1361c0719abacf15a91b0ae627330749501e | rottenFetus/Algorithms-4-everyone | /Data Structures/Binary Search Tree/Python/BinarySearchTree.py | 4,827 | 4.28125 | 4 | from TreeNode import *
class BinarySearchTree:
def __init__(self, root):
"""
This constructor checks if the root is a TreeNode and if it is not
it creates a new one with the data being the given root.
"""
if not isinstance(root, TreeNode):
root = TreeNode(root)
self.root = root
def insertNewNode(self, node, root=None):
def _insertNewNode(root, node):
"""
'node' is the node that is to be inserted in the tree.
This function takes a node and a tree node and inserts it in that tree.
it checks if the current node (the root) is None and if so it just
returns 'node', if not it repeats the process but this time for the
left subtree if node.data < root.data else it repeats it for the right
subtree
"""
if (root == None):
return node
elif (node.data < root.data):
root.leftChild = _insertNewNode(root.leftChild, node)
return root
else:
root.rightChild = _insertNewNode(root.rightChild, node)
return root
# If the root is None this means that the tree has no nodes (no root)
if (root == None):
root = self.root
# If the input is not a TreeNode, Make it a TreeNode :)
if not isinstance(node, TreeNode):
node = TreeNode(node)
# Call the helper method
self.root = _insertNewNode(root, node)
def preOrderTraversal(self, root=None):
"""
This function traverses the tree in a way such it prints the root of the
current tree first, repeats the process for the left subtree then the right one
"""
def _preOrderTraversal(root):
if (root == None):
return
print(root.data)
_preOrderTraversal(root.leftChild)
_preOrderTraversal(root.rightChild)
# Initialize the root to pass it the helper method
if (root == None):
root = self.root
# Call the helper method
_preOrderTraversal(root)
def inOrderTraversal(self, root=None):
"""
Traverse the tree in a way such that it does not print a node unless it
had printed every other node that was to the left of it. After printing
that node it goes ot the right subtree and does the same
"""
def _inOrderTraversal(root):
if (root == None):
return
_inOrderTraversal(root.leftChild)
print(root.data)
_inOrderTraversal(root.rightChild)
if (root == None):
root = self.root
_inOrderTraversal(root)
def postOrderTraversal(self, root=None):
"""
Traverses the tree in a way such that it does not print a node unless it
had printed every other node to its right and to its left
"""
def _postOrderTraversal(root):
if (root == None):
return
_postOrderTraversal(root.leftChild)
_postOrderTraversal(root.rightChild)
print(root.data)
if (root == None):
root = self.root
_postOrderTraversal(root)
def getHeight(self, root=None):
"""
Gets the height of the tree where the tree that consists of only one node
(the root of the tree) has a height of zero.
we mean by the height of the tree the longest branch (subtree) it has.
The idea is simple, the height of any tree = the maximum between the height
of the left and right subtree + 1.
If a None value is reached then it has a length of -1, this means that the
leaf that is before it has a height of zero
"""
def _getHeight(root):
if (root == None):
return -1
leftHeight = _getHeight(root.leftChild)
rightHeight = _getHeight(root.rightChild)
return 1 + max(leftHeight, rightHeight)
if (root == None):
root = self.root
return _getHeight(root)
root = 5
bst = BinarySearchTree(root)
bst.insertNewNode(TreeNode(4))
bst.insertNewNode(TreeNode(8))
bst.insertNewNode(TreeNode(10))
bst.insertNewNode(TreeNode(1))
bst.insertNewNode(TreeNode('e'))
bst.insertNewNode(TreeNode(11))
bst.insertNewNode(TreeNode(9))
bst.insertNewNode(TreeNode('A'))
bst.insertNewNode(TreeNode('x'))
print("The height of the tree: " + str(bst.getHeight()))
print("-----------------------------")
print("In order traversal")
bst.inOrderTraversal()
print("------------------")
print("pre order traversal")
bst.preOrderTraversal()
print("------------------")
print("post order traversal")
bst.postOrderTraversal()
|
4a86095a7680c8066a0ef6e8c6cb54b0e121b08c | rottenFetus/Algorithms-4-everyone | /Algorithms/Searching Algorithms/Binary Search/Python/BinarySearch.py | 620 | 3.75 | 4 | class BinarySearch():
def search(self, haystack, needle):
middle = 0
lower_bound = 0
higher_bound = len(haystack)
while (lower_bound <= higher_bound):
middle = lower_bound + (higher_bound - lower_bound) / 2
if (haystack[middle] == needle):
return middle
elif (haystack[middle] < needle):
lower_bound = middle + 1
elif (haystack[middle] > needle):
higher_bound = middle - 1
return -1
bs = BinarySearch()
haystack = [2, 3, 5, 7, 11, 13, 17, 19]
print( bs.search(haystack, 1) )
|
a6abf1f12cc09aeb393630d5c59219e9ae0c479b | chill133/BMI-calculator- | /BMI.py | 310 | 4.25 | 4 | height = input("What is your height?")
weight = input("What is your weight?")
BMI = 703 * (int(weight))/(int(height)**2)
print("Your BMI " + str(BMI))
if (BMI <= 18):
print("You are underweight")
elif (BMI >= 18) and (BMI <= 26):
print("You are normal weight")
else:
print("You are overweight")
|
bb17f8db4c2707099517d4cf4c748135b5fe5a31 | MarvelICY/LeetCode | /Solutions/multiply_strings.py | 1,247 | 3.921875 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Multiply Strings] in LeetCode.
Created on: Nov 27, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param num1, a string
# @param num2, a string
# @return a string
# @ICY: big number multiply
def multiply(self, num1, num2):
num1 = num1[::-1]
num2 = num2[::-1]
tmp = [0 for i in range(len(num1)+len(num2))]
result = []
for i in range(len(num1)):
for j in range(len(num2)):
tmp[i+j] += int(num1[i]) * int(num2[j])
for i in range(len(tmp)):
digit = tmp[i] % 10
carry = tmp[i] / 10
if i < len(tmp) - 1:
tmp[i+1] += carry
result.append(str(digit))
result = result[::-1]
while result[0] == '0' and len(result) > 1:
del result[0]
result = ''.join(result)
return result
#----------------------------SELF TEST----------------------------#
def main():
num1 = '188'
num2 = '24'
solution = Solution()
print solution.multiply(num1,num2)
pass
if __name__ == '__main__':
main() |
9f62f466d3d580c12d4c2c93dc9cfd3d8ac93924 | MarvelICY/LeetCode | /Solutions/validate_binary_search_tree.py | 1,007 | 3.84375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Validate Binary Search Tree] in LeetCode.
Created on: Nov 12, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
return self.ValidBST(root, -2147483648, 2147483647)
def ValidBST(self, root, min, max): #update the value of min and max recursively
if root == None:
return True
if root.val <= min or root.val >= max:
return False
return self.ValidBST(root.left, min, root.val) and self.ValidBST(root.right, root.val, max)
#----------------------------SELF TEST----------------------------#
def main():
pass
if __name__ == '__main__':
main() |
c21f43947cb50c668b37bb9eee7624154a6e0653 | MarvelICY/LeetCode | /Solutions/unique_path.py | 1,515 | 3.734375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Unique Paths II] in LeetCode.
Created on: Nov 18, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param obstacleGrid, a list of lists of integers
# @return an integer
def uniquePathsWithObstacles(self, obstacleGrid):
if obstacleGrid == [] or obstacleGrid[0][0] == 1:
return 0
dp = obstacleGrid[:]
dp[0][0] = 1
row_max = len(obstacleGrid)
col_max = len(obstacleGrid[0])
for i in range(1, row_max):
if obstacleGrid[i][0] == 1:
dp[i][0] = 0
else:
dp[i][0] = dp[i-1][0]
for i in range(1, col_max):
if obstacleGrid[0][i] == 1:
dp[0][i] = 0
else:
dp[0][i] = dp[0][i-1]
for row in range(1, row_max):
for col in range(1, col_max):
if obstacleGrid[row][col] == 1:
dp[row][col] = 0
else:
dp[row][col] = dp[row-1][col] + dp[row][col-1]
return dp[row_max-1][col_max-1]
#----------------------------SELF TEST----------------------------#
def main():
grid = [
[0,0,0],
[0,1,0],
[0,0,0]
]
solution = Solution()
print solution.uniquePathsWithObstacles(grid)
pass
if __name__ == '__main__':
main() |
399f740052feeccdebd601c1bda14a24e04f64ed | MarvelICY/LeetCode | /Solutions/next_permutation.py | 1,261 | 3.609375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Next Permutation] in LeetCode.
Created on: Nov 20, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param num, a list of integer
# @return a list of integer
# @ICY: reprint
def nextPermutation(self, num):
if len(num) <= 1: return num
partition = -1
for i in range(len(num)-2, -1, -1):
if num[i] < num[i+1]:
partition = i
break
if partition == -1:
num.reverse()
return num
else:
for i in range(len(num)-1, partition, -1):
if num[i] > num[partition]:
num[i],num[partition] = num[partition],num[i]
break
left = partition+1; right = len(num)-1
while left < right:
num[left],num[right] = num[right],num[left]
left+=1; right-=1
return num
#----------------------------SELF TEST----------------------------#
def main():
num = [1,2,4,3]
num = [2,1,4,3]
solution = Solution()
print solution.nextPermutation(num)
pass
if __name__ == '__main__':
main() |
e5b13a2f77a66c8d33fea1c19bccc02d04e972a4 | MarvelICY/LeetCode | /Solutions/longest_valid_parentheses.py | 1,142 | 3.78125 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Longest Valid Parentheses] in LeetCode.
Created on: Nov 27, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param s, a string
# @return an integer
# @ICY: reprint,stack,O(n)
def longestValidParentheses(self, s):
result = 0
start_index = -1
stack = []
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
elif stack == []:
start_index = i #denote the beginning position
else:
stack.pop()
if stack == []:
result = max(result, i - start_index)
else:
result = max(result, i - stack[len(stack)-1])
return result
#----------------------------SELF TEST----------------------------#
def main():
test_string = '()()))())()))('
test_string = ')()'
solution = Solution()
print solution.longestValidParentheses(test_string)
pass
if __name__ == '__main__':
main() |
2419795a51efcdbe1d5ce3a3a2045f807dc00f5c | MarvelICY/LeetCode | /Solutions/sum_root_to_leaf_numbers.py | 978 | 3.734375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Sum Root to Leaf Numbers] in LeetCode.
Created on: Nov 12, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def sumNumbers(self, root):
return add_path(root, 0)
def add_path(self, root, path_sum):
if root == None:
return 0
path_sum = path_sum * 10 + root.val
if root.left == None and root.right == None:
return path_sum
return self.add_path(root.left, path_sum) + self.add_path(root.right, path_sum)
#----------------------------SELF TEST----------------------------#
def main():
pass
if __name__ == '__main__':
main() |
6ed224ce0268e3ccfb8a2ea8e361b4435e28cbb5 | MarvelICY/LeetCode | /Solutions/edit_distance.py | 1,138 | 3.703125 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Edit Distance] in LeetCode.
Created on: Nov 20, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @return an integer
# @ICY: dp
def minDistance(self, word1, word2):
row_max = len(word1) + 1
col_max = len(word2) + 1
dp = [[0 for i in range(col_max)] for j in range(row_max)]
for row in range(row_max):
dp[row][0] = row
for col in range(col_max):
dp[0][col] = col
#print dp
for row in range(1,row_max):
for col in range(1,col_max):
dp[row][col] = min(min(dp[row-1][col]+1, dp[row][col-1]+1),
dp[row-1][col-1] + (0 if word1[row-1] == word2[col-1] else 1))
return dp[row_max-1][col_max-1]
#----------------------------SELF TEST----------------------------#
def main():
word1 = 'abcd'
word2 = 'cba'
solution = Solution()
print solution.minDistance(word1,word2)
pass
if __name__ == '__main__':
main() |
5570392d12ebeada71dc57c0d7dc812012579dba | MarvelICY/LeetCode | /Solutions/length_of_last_word.py | 900 | 3.8125 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Length of Last Word] in LeetCode.
Created on: Nov 13, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
#remove space in the tail of the string
for i in range(len(s)-1,-1,-1):
if s[i] != ' ':
s = s[:i+1]
break
list = s.split(' ')
print list
return len(list[len(list)-1])
#----------------------------SELF TEST----------------------------#
def main():
test_string = 'leed code'
test_string = 'le asd wefsda'
test_string = 'a '
solution = Solution()
print solution.lengthOfLastWord(test_string)
pass
if __name__ == '__main__':
main() |
8904731c0bd6c47eebe2dd98d3c0296f6bdd3d99 | MarvelICY/LeetCode | /Solutions/binary_tree_level_order_traversal.py | 1,332 | 3.859375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Binary Tree Level Order Traversal] in LeetCode.
Created on: Nov 13, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
# dsf
def levelOrder(self, root):
if root == None:
return []
self.result = []
self.traversal(root,0)
return self.result
def traversal(self,root,level):
if root:
if level >= len(self.result):
self.result.append([])
self.result[level].append(root.val)
self.traversal(root.left, level+1)
self.traversal(root.right, level+1)
#----------------------------SELF TEST----------------------------#
def main():
root = TreeNode(1)
a = TreeNode(2)
b = TreeNode(3)
c = TreeNode(4)
d = TreeNode(5)
e = TreeNode(6)
root.left = a
root.right = b
a.left = c
c.left = e
a.right = d
solution = Solution()
print solution.levelOrder(root)
pass
if __name__ == '__main__':
main() |
79acb839e91a261e3bf2974608c3fa527efe1387 | MarvelICY/LeetCode | /Solutions/spiral_matrix_2.py | 1,641 | 3.890625 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Spiral Matrix II] in LeetCode.
Created on: Nov 18, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
if n == 0:
return []
result = [[0 for i in range(n)] for j in range(n)]
num = 1
#four boundaries
up = 0
bottom = len(result) - 1
left = 0
right = len(result[0]) - 1
# right:0, down:1, left:2, up:3
direct = 0
while up <= bottom and left <= right:
if direct == 0:
for i in range(left, right+1):
result[up][i] = num
num += 1
up += 1
if direct == 1:
for i in range(up, bottom+1):
result[i][right] = num
num += 1
right -= 1
if direct == 2:
for i in range(right, left-1, -1):
result[bottom][i] = num
num += 1
bottom -= 1
if direct == 3:
for i in range(bottom, up-1, -1):
result[i][left] = num
num += 1
left += 1
direct = (direct + 1) % 4 #loop
return result
#----------------------------SELF TEST----------------------------#
def main():
n = 3
solution = Solution()
print solution.generateMatrix(n)
pass
if __name__ == '__main__':
main() |
e75ff35b0086a8ef4a610ed3a737d756e3efc6c5 | MarvelICY/LeetCode | /Solutions/string_to_integer.py | 2,079 | 3.84375 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Srting to Integer] in LeetCode.
Created on: Nov 10, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @return an integer
# hints: space sign and overflow
# take care when : no-digit appears, space appears, multi signs appear
def atoi(self, str):
if str == '':
return 0
INT_MAX = 2147483647 #2^31
INT_MIN = -2147483648
sum = 0
sign = 1
sign_num = 0 #bug of leetcode
exist = 0
for letter in str:
if letter == ' ' and exist == 0:
continue
if letter == '-':
if sign_num > 0:
return 0
else:
sign = -1
sign_num = 1
exist = 1
elif letter == '+':
if sign_num > 0:
return 0
else:
sign = 1
sign_num = 1
exist = 1
elif letter in '0123456789':
digit = int(letter)
if sum <= INT_MAX / 10:
sum = sum * 10
else:
if sign == 1:
return INT_MAX
else:
return INT_MIN
if sum <= INT_MAX - digit:
sum = sum + digit
else:
if sign == 1:
return INT_MAX
else:
return INT_MIN
exist = 1
else:
return sign * sum
return sign * sum
#----------------------------SELF TEST----------------------------#
def main():
test_string = ' -65769863'
test_string = ' -0012a42'
solution = Solution()
print solution.atoi(test_string)
pass
if __name__ == '__main__':
main() |
1103ddc9f5b00fad29a428a1c962a7f1fc52b53e | rbpdqdat/osmProject | /phones.py | 1,181 | 3.6875 | 4 | import re
import phonenumbers
#convert alphabet phone characters to actual phone numbers
#
missphone = '+19999999999'
def phone_letter_tonum(alphaphone):
char_numbers = [('abc',2), ('def',3), ('ghi',4), ('jkl',5), ('mno',6), ('pqrs',7), ('tuv',8), ('wxyz',9)]
char_num_map = {c:v for k,v in char_numbers for c in k}
return("".join(str(char_num_map.get(v,v)) for v in alphaphone.lower()))
def is_phone(elem):
return (elem.attrib['k'] == "phone")
def audit_phone_number(phone):
#found some columns had 2 phone numbers
phone = phone.split(";")[0]
phone = re.sub("^\++0+1?","+1",phone)
#some phone numbers were purposely words
# such as '1-888-AMC-4FUN' for business
#the phone number needed to be converted to properly work
if re.search("[A-Za-z]",phone):
phone = phone_letter_tonum(phone)
if (re.search('^[\+1]',phone) == None):
phone = missphone
#additional substitution to make sure the
#country code was in the phone number
phone = re.sub("^1+","+1",phone)
z = phonenumbers.parse(phone, "US")
phone = phonenumbers.format_number(z, phonenumbers.PhoneNumberFormat.NATIONAL)
return phone
|
2e0b65f9be804d132dd15c781ce5bca69d3c7ff4 | niketanmoon/Data-Science | /Data Preprocessing/Day6-Final Data Preprocessing Template/final.py | 1,678 | 3.96875 | 4 | #No need to do missing data, categorical data, Feature Scaling
#Feature Scaling is implemented by some of the algorithms, but in some cases you need to do feature scaling
#This is the final template of the data preprocessing that you will be needed to do each and every time
#Step 1 importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Step2 Reading the dataset from the file
dataset = pd.read_csv('Data.csv') #Give the path to the exact folder
#Step3 Listing the dataset as X and Y
X = dataset.iloc[:,:-1].values
Y = dataset.iloc[:,3].values
#Transformation of the missing data
#First importing the library
# from sklearn.preprocessing import Imputer
# #Creating the object
# imputer = Imputer(missing_values='NaN', strategy = 'mean', axis= 0)
# imputer = imputer.fit(X[:,1:3])
# X[:,1:3] = imputer.transform(X[:,1:3])
#Categorical data encoding
#First importing the library
# from sklearn.preprocessing import LabelEncoder,OneHotEncoder
# #Encoding of X dataset
# labelencoder_X = LabelEncoder()
# X[:,0] = labelencoder_X.fit_transform(X[:,0])
# #Now doing the dummy encoding
# onehotencoder = OneHotEncoder(catgorical_features = [0])
# X = onehotencoder.fit_transform(X).toarray()
# #Encoding of the Y dataset
# labelencoder_Y = LabelEncoder()
# Y = labelencoder_Y.fit_transform(Y)
#Splitting the dataset
from sklearn.cross_validation import train_test_split
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size = 0.2, random_state = 0)
#Feature Scaling
# from sklearn.preprocessing import StandardScaler
# sc_X = StandardScaler()
# X_train = sc_X.fit_transform(X_train)
# X_test = sc_X.transform(X_test)
|
02092a3692fc1dca4d02a0aededb730650683d54 | cindykhris/temperature_convertor | /tem_conv.py | 1,593 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Authors: Cindy Pino
Date: 3/26/2020
Description: Kelvin, Celsius, Farenheight Temperature Convertor"""
import sys
def tempConvertor():
while True:
inp1 = (input("Temperature one? (c = celsius, f = fahrenheit, k = kelvin) "))
if inp1 == "c" or inp1 == "f" or inp1 == "k":
break
while True:
inp2 = input("Temperature two? (c = celsius, f = fahrenheit, k = kelvin) ")
if inp1 != inp2 and inp2 == "c" or inp1 != inp2 and inp2 == "f" or inp1 != inp2 and inp2 == "k":
break
while True:
inp3 = int(input(("What's your temperature " )))
if (inp3) <= 1000:
break
if inp1 == "c" and inp2 == "f":
c1 = float(inp3) * 9/5 + 32
print(c1)
elif inp1 == "c" and inp2 == "k":
c2 = float(inp3) + 273.15
print(c2)
elif inp1 == "f" and inp2 == "c":
f1 = (float(inp3) - 32 ) * 5/9
print(f1)
elif inp1 == "f" and inp2 == "k":
f2 = (((float(inp3) - 32) * 5/9 ) + 273.15 )
print(f2)
elif inp1 == "k" and inp2 == "c":
k1 = (float(inp3) - 273.15)
print(k1)
else:
k2 = (((float(inp3) - 273.15) * 9/5 )+ 32)
print(k2)
def again():
while True:
inp4 = (str(input(" Do you want to try again? yes/no. "))).lower()
if inp4 == "yes":
tempConvertor()
if inp4 == "no":
sys.exit()
while True:
if inp4 != "yes" or inp4 != "no":
break
(str(tempConvertor()))
(again())
|
73367dc10875863ceac9026f5292a5e4dccb6a21 | paulan94/Intermediate-Python-Tutorials | /listcomp_generators.py | 887 | 3.828125 | 4 |
##xyz = [i for i in range(5000000)] #list takes longer because its stored into memory
##print 'done'
##xyz = (i for i in range(5000000)) #generator doesnt store as list or into memory
##print 'done' #this is almost instant after list is created
input_list = [5,6,2,10,15,20,5,2,1,3]
def div_by_five(num):
return num % 5 == 0
xyz = (i for i in input_list if div_by_five(i)) #return #s that are div by 5
for i in xyz:
print i
##[print(i) for i in xyz] python 3 only
xyz = [i for i in input_list if div_by_five(i)] #cool
##print xyz
#these were never in memory, would run out of memory with lists
#lists take a lot of memory, generators might run out of time
##xyz = ( ( (i,ii) for ii in range(50000000))for i in range(5))
##for i in xyz:
## for ii in i:
## print ii
#python 3 this would work
##xyz = (print(i) for i in range(5))
##for i in xyz:
## i
|
55ef5cc09c7bdabe692af9783837faf6f5cfbc31 | paulan94/Intermediate-Python-Tutorials | /argparse_cli.py | 900 | 3.765625 | 4 | import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--x', type=float,default=1.0,
help='What is the first number?')
parser.add_argument('--y', type=float,default=1.0,
help='What is the second number?')
parser.add_argument('--operation', type=str,default='add',
help='What operation? (add,sub,mul,div)')
args = parser.parse_args()
sys.stdout.write(str(calc(args))) #print works sometimes but stdout better
def calc(args):
if args.operation == 'add':
return args.x+args.y
elif args.operation == 'sub':
return args.x-args.y
elif args.operation == 'mul':
return args.x*args.y
elif args.operation == 'div':
return args.x/args.y
##operation = calc(7,3,'div')
##print operation
if __name__ == '__main__':
main()
|
839de1b8a63762d56ab6c3d9f17a825bce6f410a | mucel/python-1 | /eksperiment.py | 749 | 3.625 | 4 | saraksts = ['a']
vardnica = {'black': 'melns', 'white': 'balts'}
vardnica['blue'] = 'zils'
print(vardnica['black'])
personaA = {
'vards' : 'Mara',
'dzimums':'s',
'gads': 2002
}
personaB = {
'vards': 'Linda',
'dzimums': 's',
'gads': 1999
}
cilveki = [personaA, personaB]
while True:
task = input("Please enter TODO task: ")
status = input("Was the task complited yet? (yes/no)")
print("Your task is: " + task)
if status == "yes"
todo_dict[task] = True
else:
todo_dict[task] = False
new = input("Would you like to enter new task? (yes/no)")
if new == "no"
break
print("All tasks: %s" % todo_dict)
print("Emd")
with open('piemers.html', '+w')as file
print ()
|
8ce4fb9950dc61d3b59664aee815d5b0cb8dca3f | bkwong1990/PygamePrimerFishBomb | /score_helper.py | 1,990 | 3.734375 | 4 | import json
ENEMY_SCORES = {
"missile": 1000,
"tank": 10000,
"laser": 100000
}
SCORE_PER_LIVING_TANK = 10
SCORE_COUNT = 5
NAME_CHAR_LIMIT = 10
score_file_name = "scores.json"
# Defaults to an empty list
scores = []
'''
Loads scores from a JSON file
'''
def load_scores():
global scores
try:
with open(score_file_name, "r") as json_file:
scores = json.load(json_file)
print("Successfully read from " + score_file_name)
except:
print("Couldn't read " + score_file_name)
'''
Saves scores to a JSON file
'''
def save_scores():
try:
with open(score_file_name, "w") as json_file:
# use optional args to prettify the JSON text
json.dump(scores, json_file, indent=2, separators=(", ", " : "))
print("Successfully wrote to " + score_file_name)
except:
print("Couldn't save " + score_file_name)
'''
Checks if the given score is high enough to be added. Will be added anyways if
there aren't enough scores.
Parameters:
new_score: the score to be tested
'''
def is_score_high_enough(new_score):
if len(scores) < SCORE_COUNT:
return True
else:
lowest_score = min( [ entry["score"] for entry in scores ] )
if new_score > lowest_score:
return True
return False
'''
Adds a new score and removes old scores if necessary
Parameters:
name: the name of the scorer
score: the score
'''
def add_score(name, new_score):
global scores
# Prevent overly long names from being used
if len(name) > NAME_CHAR_LIMIT:
name = name[:NAME_CHAR_LIMIT]
scores.append({
"name": name,
"score": new_score
})
def sort_fun(entry):
return entry["score"]
#It'd be more efficient to insert, but there aren't many scores to work with.
scores.sort(key = sort_fun,reverse = True)
#If necessary, cut out the lowest score
if len(scores) > SCORE_COUNT:
scores = scores[0:SCORE_COUNT]
|
e2bed78a5631d38dfdbbffe383bb5f09cac17e9e | bkwong1990/PygamePrimerFishBomb | /my_events.py | 1,090 | 3.5 | 4 | import pygame
ADDMISSILE = pygame.USEREVENT + 1
ADDCLOUD = pygame.USEREVENT + 2
ADDTANK = pygame.USEREVENT + 3
ADDLASER = pygame.USEREVENT + 4
MAKESOUND = pygame.USEREVENT + 5
ADDEXPLOSION = pygame.USEREVENT + 6
RELOADBOMB = pygame.USEREVENT + 7
SCOREBONUS = pygame.USEREVENT + 8
TANKDEATH = pygame.USEREVENT + 9
NEXTSESSION = pygame.USEREVENT + 10
'''
A function to simplify the process of posting an explosion event
Parameters:
rect: the rectangle needed to determine the explosion's size and position
'''
def post_explosion(rect):
explosion_event = pygame.event.Event(ADDEXPLOSION, rect = rect)
pygame.event.post(explosion_event)
'''
A function to simplify the process of posting a score bonus event
Parameters:
enemy_name: the name of the destroyed enemy, which is used to look up their score value
center: the center of the text showing the score bonus
'''
def post_score_bonus(enemy_name, center):
score_bonus_event = pygame.event.Event(SCOREBONUS, enemy_name = enemy_name, center = center)
pygame.event.post(score_bonus_event)
|
6070edc3bdc5fd7757edb7632903a78a56c12d06 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeDecisao - PythonBrasil/exec14.py | 542 | 3.609375 | 4 | def conceito(med):
if med >= 9:
idx = 0
elif med >= 7.5 and med < 9:
idx = 1
elif med >= 6 and med < 7.5:
idx = 2
elif med >= 4 and med < 6:
idx = 3
else:
idx = 4
con = ['A', 'B', 'C', 'D', 'E']
return con[idx]
n1, n2 = int(input('Insira a nota 1: ')), int(input('Insira a nota 2: '))
media = (n1+n2)/2
conc = conceito(media)
print('A media geral é: ', media)
print('O conceito é ', conc)
if conceito(media) in 'ABC':
print('Aprovado')
else:
print('Reprovado')
|
b5a78563e656e4617132516dd50a6ca328f29c25 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeDecisao - PythonBrasil/exec16.py | 709 | 3.796875 | 4 | import math
def calculaDelta(a, b, c):
delt = math.pow(b, 2) - 4*a*c
if delt >= 0:
print('O valor de delta é:', delt)
print(' X`:', calculaValorX1(delt, a, b))
print(' X``:', calculaValorX2(delt, a, b))
else:
print('Não há raizes para a equação.')
def calculaValorX1(delt, a, b):
x1 = ((-1*b) + math.sqrt(delt))/(2*a)
return x1
def calculaValorX2(delt, a, b):
x2 = ((-1*b) - math.sqrt(delt))/(2*a)
return x2
a = int(input('Indique um valor para a: '))
b = int(input('Indique um valor para b: '))
c = int(input('Indique um valor para c: '))
if a != 0:
calculaDelta(a, b, c)
else:
print('Não é uma equação de segundo grau.') |
525d2a568cba6cfa8a127e781f53e09b56cff1bb | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec36.py | 206 | 3.9375 | 4 | num = int(input('Digite um numero: '))
inicio = int(input('Digite o inicio: '))
fim = int(input('Digite o final: '))
for i in range(inicio,(fim+1)):
res = num * i
print('%d X %d = %d'%(num, i, res)) |
90a33d10723fa9f4cac04339dca95e9ebde4d0bb | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec41.py | 512 | 3.71875 | 4 | cont = 0
valorParcela = 0
parcela = 1
valorDivida = float(input('Insira o valor da divida: '))
print('\nValor da Dívida | Valor dos Juros | Quantidade de Parcelas | Valor da Parcela')
for i in [0,10,15,20,25]:
dividaTotal = valorDivida
valorJuros = valorDivida*(i/100)
dividaTotal += valorJuros
valorParcela = dividaTotal/parcela
print('R$ %5.2f %d %d R$ %5.2f'%(dividaTotal,valorJuros,cont, valorParcela))
cont += 3
parcela = cont
|
e742c028b56006a536127f23b6697000620b2923 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec22.py | 325 | 3.984375 | 4 | num = int(input('Digite um numero: '))
cont = 1
divisor = []
primo = 0
while cont <= num:
if num % cont == 0:
primo += 1
divisor.append(cont)
cont += 1
if primo == 1:
print(num, 'é primo, pois é divisivel apenas por', divisor)
else:
print(num, 'não é primo pois é divisivel por', divisor) |
c1d8a5f4962f68ac43d139ab714655917c5c4068 | flaviojussie/Exercicios_Python-Inciante- | /ExerciciosListas - PythonBrasil/exer05.py | 361 | 3.734375 | 4 | vetor = []
impares = []
pares = []
for i in range(20):
vetor.append(int(input('Digite o %d número: '%(i+1))))
for i in vetor:
if i % 2 == 0:
pares.append(i)
else:
impares.append(i)
print('O vetor é formado pelos numeros:',vetor)
print('Os numeros pares do vetor são: ', pares)
print('Os numeros impares do vetor são: ', impares) |
588f92fcd4309b777bf0f75be9a4bd6e9b99f8c4 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeDecisao - PythonBrasil/exec05.py | 272 | 3.828125 | 4 | n1, n2 = int(input('Nota 1: ')), int(input('Nota 2: '))
media = (n1 + n2)/2
if media >= 7:
print('Aluno nota,', media, 'Aprovado')
elif media == 10:
print('Aluno nota,', media ,'Aprovado com distinção')
elif media < 7:
print('Aluno Repovado, nota:', media)
|
2a3f669de150632c4a096455723c8a44d32dc43c | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec44.py | 1,062 | 3.84375 | 4 | sair = 's'
print('''Complete seu voto.
1 - para votar em Fulano
2 - para votar em Cicrano
3 - para votar em Beltrano
4 - para votar em Zezinho
5 - para nulo
6 - para branco''')
fulano = 0
cicrano = 0
beltrano = 0
zezinho = 0
nulo = 0
branco = 0
totalEleitores = 0
while sair == 's':
voto = int(input('Digite seu voto: '))
sair = input('Deseja continuar votando (S/N): ')
if voto == 1:
fulano += 1
elif voto == 2:
cicrano += 1
elif voto == 3:
beltrano += 1
elif voto == 4:
zezinho += 1
elif voto == 5:
nulo += 1
elif voto == 6:
branco += 1
totalEleitores += 1
perNulos = (nulo*100)/totalEleitores
perBranco = (branco*100)/totalEleitores
print('Fulano %d votos.'%fulano)
print('Cicrano %d votos.'%cicrano)
print('Beltrano %d votos'%beltrano)
print('Zezinho %d votos'%zezinho)
print('A soma dos votos nulos %d'%nulo)
print('A soma dos votos em branco %d\n'%branco)
print('O percentual de votos nulos é %5.1f'%perNulos)
print('O percentual de votos brancos é %5.1f'%perBranco)
|
93a61b2e40b4d8f0662b8e856d50d4648ac20ee6 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec42.py | 605 | 3.796875 | 4 | numVezes = int(input('Quantos numeros você que inserir: '))
intervalo1 = 0
intervalo2 = 0
intervalo3 = 0
intervalo4 = 0
for i in range(numVezes):
num = int(input('Digite o %d numero: '%(i+1)))
if num >= 0 and num <= 25:
intervalo1 += 1
elif num >=26 and num <= 50:
intervalo2 += 1
elif num >= 51 and num <= 75:
intervalo3 += 1
elif num >= 76 and num <= 100:
intervalo4 += 1
print('\n%d no intervalo [0-25]'%intervalo1)
print('%d no intervalo [26-50]'%intervalo2)
print('%d no intervalo [51-75]'%intervalo3)
print('%d no intervalo [76-100]'%intervalo4) |
209f266a0c58dac79b4ad6cd2d585a798c4ce3f7 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeDecisao - PythonBrasil/exec19.py | 850 | 3.515625 | 4 | def grafiaExtensso(num, quant):
c = 'centena'
d = 'dezena'
u = 'unidade'
compl = ''
if num == 0:
return compl
elif num == 1:
if quant == 100:
compl = ','
return str(num)+' '+ c + compl
elif quant == 10:
compl = ' e'
return str(num)+' '+ d + compl
else:
return str(num)+' '+ u
elif num >= 2:
if quant == 100:
compl = ','
return str(num)+' '+ c +'s' + compl
elif quant == 10:
compl = ' e'
return str(num)+' '+ d +'s' + compl
else:
return str(num)+' '+ u +'s'
num = int(input('Insira um numero menor que 1000: '))
cent = num//100
deze = (num%100)//10
unid = num%10
print(grafiaExtensso(cent,100), grafiaExtensso(deze,10), grafiaExtensso(unid,1))
|
2cc8395ee00da81c09d43db8800ecd08f1045542 | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec26.py | 706 | 3.78125 | 4 | eleitores = int(input('Insira o numero de eleitores: '))
print('''\nPara votar em fulano - 1
Para votar em cicrano - 2
Para votar em beltrano - 3
Para votar em branco - 4\n''')
cont = 0
fulano = 0
cicrano = 0
beltrano = 0
branco = 0
nulos = 0
candidatos = ['Fulano','Cicrano','Beltrano']
while cont < eleitores:
voto = int(input('Digite seu voto: '))
if voto == 1:
fulano += 1
elif voto == 2:
cicrano += 1
elif voto == 3:
beltrano += 1
elif voto == 4:
branco += 1
else:
nulos += 1
cont += 1
print('''\n\nRelação dos votos:
FULANO - %d
CICRANO - %d
BELTRANO - %d
BRANCO - %d
NULOS - %d'''%(fulano, cicrano, beltrano, branco, nulos))
|
09ebe4d259f873fbc9a53fe8710e30081ec29d2e | SachinMCReddy/810homework | /HW02(SSW-810).py | 3,147 | 3.71875 | 4 | ''' python program that includes class fractions , plus , minus, times,
divide ,equal to perform tasks on calculator'''
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
if self.denominator <=0 :
raise ValueError("This is not possible to divide by zero ")
def __str__(self): # display fraction
return str(self.numerator) + "/" + str(self.denominator)
def plus(self, a): # For addition
num = (self.numerator * a.denominator) + (self.denominator * a.numerator)
den = (self.denominator * a.denominator)
return Fraction(float(num), float(den))
def minus(self, a): # For subtraction
num = (self.numerator * a.denominator) - (self.denominator * a.numerator)
den = (self.denominator * a.denominator)
return Fraction(float(num), float(den))
def times(self, a): # For multiplication
num = (self.numerator * a.denominator)
den = (self.denominator * a.denominator)
return Fraction(float(num), float(den))
def divide(self, a): # For division
num = (self.numerator * a.denominator)
den = (self.denominator * a.denominator)
return Fraction(float(num), float(den))
def equal(self, a): # For equal
if (self.numerator * a.denominator) == (self.denominator * a.numerator):
return True
else:
return False
def get_number(prompt): #input passed
while True:
inpt = input(prompt)
try:
return float(inpt)
except ValueError:
print("Error: Please try again")
def test(): #test function to demonstrate few functions
f12 = Fraction(1, 2)
f44 = Fraction(4, 4)
f34 = Fraction(3, 4)
f33 = Fraction(3, 3)
print(f12, '+', f12, '=', f12.plus(f12), '[4/4]')
print(f44, '-', f12, '=', f44.minus(f12), '[4/8]')
print(f12, '*', f34, '=', f12.times(f34), '[4/8]')
print(f34, '/', f12, '=', f34.divide(f12), '[6/8]')
print(f33, '=', f33, f33.equal(f33), '[TRUE]')
def main():
print("welcome to the fraction calculator")
nm1 = get_number("Fraction one numerator")
dn1 = get_number("Fraction one denominator")
operation = ["+", "-", "*", "/", "="]
opp = input("operation (+, -, *, /, =)")
if opp not in operation:
print("invalid operator")
return
nm2 = get_number("Fraction two numerator")
dn2 = get_number("Fraction two denominator")
f1 = Fraction(nm1, dn1)
f2 = Fraction(nm2, dn2)
#checking if the user input is the same as functions in the list printed[+, -, *, /]
if opp == "+":
print(f1, "+", f2, "=", f1.plus(f2))
elif opp == "-":
print(f1, "-", f2, "=", f1.minus(f2))
elif opp == "*":
print(f1, "*", f2, "=", f1.times(f2))
elif opp == "/":
print(f1, "/", f2, "=", f1.divide(f2))
elif opp == "=":
print(f1, "=", f2, f1.equal(f2))
if __name__ == "__main__":
test()
main()
|
e8e71c47bd34a628562c9dfcd351bcd336a99d70 | endar-firmansyah/belajar_python | /oddevennumber.py | 334 | 4.375 | 4 | # Python program to check if the input number is odd or even.
# A number is even if division by given 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number
# div = 79
div = int(input("Input a number: "))
if (div % 2) == 0:
print("{0} is even Number".format(div))
else:
print("{0} is Odd Number".format(div))
|
b928d3b1b8bfac3efa68e1bccaa9347c16482bd8 | JianHui1208/Code_File | /Python/Lists.py | 291 | 4.15625 | 4 | thislist = ["a", "b","c"]
print(thislist)
thislist = ["a", "b", "c"]
print(thislist[1])
# same the array start for 0
thislist = ["a", "b", "c"]
print(thislist[-1])
# -1 is same like the last itme
# -2 is second last itme
thislist = ["a", "b", "c", "d", "e", "f", "g"]
print(thislist[2:5]) |
48de21f792a50fa63d62e5656c123a20a551acd1 | acado1986/cs50 | /pset6_2016/crack.py | 2,617 | 3.96875 | 4 | import crypt
import argparse
import itertools
import time
def main():
# running time mesurements
start_time = time.time()
# path to default dictionary in Ubuntu distros
default_dictionary = '/usr/share/dict/american-english'
# ensure correct usage of the program
parser= argparse.ArgumentParser()
parser.add_argument("dictionary", default=default_dictionary, nargs="?", help="path to different dictionary, else default")
parser.add_argument("chiphertext",help="encrypted text to decipher")
args = parser.parse_args()
# store supplied dictionary or default
dictionary = args.dictionary
# store encrypted text
encrypted_text= args.chiphertext
# decrypt using a dictionary
def decryptDictionary(encrypted_text, dictionary):
''' The function reads dictionary in a text format, arranged one
word by line, encrypts the word and compares it to the encrypted text'''
salt = encrypted_text[:2]
with open(dictionary, 'r') as dictionary:
for word in dictionary:
# pset6 specificacion only password only 4 letters long
if len(word) < 5:
if encrypted_text == crypt.crypt(word.rstrip('\n'), salt):
return word.rstrip('\n')
else:
return None
# decrypt using brute force
def decryptBruteForce(encrypted_text, wordLength):
''' The function generates a permutation of letters to form words,
of wordLength length, encrypts the word and compares it to the encrypted text'''
salt = encrypted_text[:2]
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
for word in (itertools.product(chars, repeat=wordLength)):
if encrypted_text == crypt.crypt(''.join(word), salt):
return ''.join(word)
else:
return None
# find the password first in dictionary, if unsuccesfull use brute force
dict_passwd = decryptDictionary(encrypted_text, dictionary)
if dict_passwd == None:
# password max lenght only 4 letters
for i in range(5):
brute_passwd = decryptBruteForce(encrypted_text, i)
if brute_passwd is not None:
break
print('{}'.format(dict_passwd if dict_passwd is not None else brute_passwd))
# print running time
end_time = time.time()
print("--- %s seconds ---" % (end_time - start_time))
if __name__ == '__main__':
main() |
0ce3f5ef67b779ef85eade0c4457a38a50dc9c44 | wecchi/univesp_com110 | /Sem2-Strings.py | 404 | 3.921875 | 4 | # Videoaula 7 - Strings
nome = input('Digite o seu nome completo: ')
nome2 = input('Qual o nome da sua mãe? ')
nome = nome.strip()
nome2 = nome2.strip()
print('é Marcelo? ', 'Marcelo' in nome)
print('Seu nome e de sua mãe são diferentes? ', nome != nome2)
print('Seu nome vem depois da sua mãe? ', nome > nome2)
print('Quantidade de letras do seu nome: ', len(nome))
print(nome.upper())
|
5d175c14c2438c669efe9fd451e0c88ace14ce7b | wecchi/univesp_com110 | /contar_letras.py | 288 | 3.890625 | 4 | def countLetter(textAsCount, l):
x = textAsCount.count(l)
return x
frase = input('digite uma frase qualquer ')
letra = input('que letra deseja contar? ')
print('\n','''Encontramos %d letras "%s"s no seu texto "%s"'''%(countLetter(frase, letra), letra, frase[:8] + '...'))
|
7a539c585cf9adca8dc788fea5295f99a65b5e92 | wecchi/univesp_com110 | /Sem2-Texto22.py | 1,217 | 4.15625 | 4 | '''
Texto de apoio - Python3 – Conceitos e aplicações – uma abordagem didática (Ler: seções 2.3, 2.4 e 4.1) | Sérgio Luiz Banin
Problema Prático 2.2
Traduza os comandos a seguir para expressões Booleanas em Python e avalie-as:
(a)A soma de 2 e 2 é menor que 4.
(b)O valor de 7 // 3 é igual a 1 + 1.
(c)A soma de 3 ao quadrado e 4 ao quadrado é igual a 25.
(d)A soma de 2, 4 e 6 é maior que 12.
(e)1387 é divisível por 19.
(f)31 é par. (Dica: o que o resto lhe diz quando você divide por 2?)
(g)O preço mais baixo dentre R$ 34,99, R$ 29,95 e R$ 31,50 é menor que R$ 30,00.*
'''
a = (2 + 2) < 4
b = (7 // 3) == (1 + 1)
c = (3 ** 2 + 4 ** 2) == 25
d = (2 + 4 + 6 ) > 12
e = 1387 % 19 == 0
f = 31 % 2 == 0
g = min(34.99, 29.95, 31,50) < 30
print('(a)A soma de 2 e 2 é menor que 4.', a)
print('(b)O valor de 7 // 3 é igual a 1 + 1.', b)
print('(c)A soma de 3 ao quadrado e 4 ao quadrado é igual a 25.', c)
print('(d)A soma de 2, 4 e 6 é maior que 12.', d)
print('(e)1387 é divisível por 19.', e)
print('(f)31 é par. (Dica: o que o resto lhe diz quando você divide por 2?)', f)
print('(g)O preço mais baixo dentre R$ 34,99, R$ 29,95 e R$ 31,50 é menor que R$ 30,00.', g)
|
2681542783b3751bd885d3f5d829d6bf2ccde4be | code-wiki/Data-Structure | /Array/(Manacher's Algoritm)Longest Palindromic Substring.py | 1,046 | 4.125 | 4 | # Hi, here's your problem today. This problem was asked by Twitter:
# A palindrome is a sequence of characters that reads the same backwards and forwards.
# Given a string, s, find the longest palindromic substring in s.
# Example:
# Input: "banana"
# Output: "anana"
# Input: "million"
# Output: "illi"
# class Solution:
# def longestPalindrome(self, s):
# # Fill this in.
# # Test program
# s = "tracecars"
# print(str(Solution().longestPalindrome(s)))
# # racecar
class Solution:
def checkPalindrome(str):
# reversing a string in python to get the reversed string
# This is extended slice syntax.
# It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1,
# it reverses a string.
reversedString = str[::-1]
if (str == reversedString):
return true
else:
return false
def longestPalindrome(str):
while (index > str.length):
while ():
pass
|
e466c0aab2dbbe4e0a661609f0f7421ab23dc967 | xpessoles/Cycle_01_DecouverteSII | /Chaine_Fonctionnelle/02_Fonction_Traiter/TP_Traiter_Pyhon_Arduino/Librairie py2duino v4/py2duino.py | 22,737 | 3.53125 | 4 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: py2duino
# Purpose: Programming arduino from python commands
#
# Author: David Violeau, Alain Caignot
#
# Created: 01/01/2014
# Modified : 01/03/2016 D. Violeau
# Copyright: (c) Demosciences UPSTI
# Licence: GPL
#-------------------------------------------------------------------------------
import serial
import sys
import time
import struct
import traceback
class Servo():
"""
Classe Servo pour piloter un ou deux servomoteurs
Les servomoteurs doivent etre definis sur les broches 9 et 10 obligatoirement.
Il suffit ensuite de definir les numeros des servomoteurs 1 ou 2
servo=Servo(monarduino,1) # avec monarduino la carte definie
Pour demander au servomoteur de tourner de x degre (de 0 à 180), taper servo.write(x)
"""
def __init__(self,parent,number):
self.number=number
self.parent=parent
if number!=1 and number!=2:
print("Les servomoteurs doivent etre branches sur les pin digitaux 9 ou 10, taper Servo(monarduino,1 ou 2)")
self.parent.close()
else:
self.attach()
print("attach ok")
def attach(self):
mess="Sa"+str(self.number)
self.parent.ser.write(bytes(mess,"ascii"))
def dettach(self):
mess="Sd"+str(self.number)
self.parent.ser.write(bytes(mess,"ascii"))
print("detach ok")
def write(self,value):
if value<0 :
value=0
elif value>180:
value=180
mess="Sw"+str(self.number)+chr(value)
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
class PulseIn():
"""
Classe PulseIn pour connaitre le temps écoulé entre l'émission et la réception d'un signal de durée donnée
Vous devez spécifier la carte arduino et le pin digital du trigger (émetteur) puis du pin digital récepteur (echo)
pulse=DigitalOutput(macarte,6,5) (pin trigger 6, pin echo 5)
Pour lancer une lecture, taper puilse.read(duree) où duree est la durée en milliseconde entre le passage à l'état haut puis bas du trigger. La grandeur renvoyée est en microsecondes.
Si aucune duree n'est renseignée, une valeur de 20 ms est adoptée par défaut. La durée maximale est de 255 ms.
"""
def __init__(self,parent,pin_trigger,pin_echo):
self.trigger=pin_trigger
self.echo=pin_echo
self.parent=parent
self.init()
self.duree=20
def init(self):
self.parent.pinMode(self.trigger,"OUTPUT")
self.parent.pinMode(self.echo,"INPUT")
def read(self,duree=20):
if duree>255:
duree=20
if duree <=0:
duree=20
self.duree=duree
val=self.parent.pulseIn(self.duree,self.trigger,self.echo)
return val
class DigitalOutput():
"""
Classe DigitalOutput pour mettre à l'état haut ou bas une sortie digitale
Vous devez spécifier la carte arduino et le pin digital de sortie souhaité
led=DigitalOutput(macarte,9)
Pour mettre à l'état haut taper : led.high(), pour l'état bas : led.low()
"""
def __init__(self,parent,pin):
self.pin=pin
self.parent=parent
self.init()
def init(self):
self.parent.pinMode(self.pin,"OUTPUT")
def high(self):
self.parent.digitalWrite(self.pin,1)
def low(self):
self.parent.digitalWrite(self.pin,0)
class DigitalInput():
"""
Classe DigitalInput pour lire la donnée binaire d'un pin digital
Vous devez spécifier la carte arduino et le pin digital d'entré souhaité
push=DigitalInput(macarte,9)
Pour lire la valeur, tapez : push.read(). La valeur obtenue est 0 ou 1 (état haut)
La fonction push.upfront() (ou downfront) permet de renvoyer 1 ou 0 sur front montant ou descendant de l'entrée
La fonction push.pulse() renvoie la durée (en microsecondes) écoulée entre deux passages au niveau haut de l'entrée
"""
def __init__(self,parent,pin):
self.pin=pin
self.parent=parent
self.previous_value=0
self.value=0
self.duree=0
self.init()
def init(self):
self.parent.pinMode(self.pin,"INPUT")
self.value=self.parent.digitalRead(self.pin)
self.previous_value=self.value
def read(self):
return self.parent.digitalRead(self.pin)
def upfront(self):
self.value=self.parent.digitalRead(self.pin)
val=0
if ((self.value!=self.previous_value) & (self.value==1)):
val=1
else :
val=0
self.previous_value=self.value
return val
def downfront(self):
self.value=self.parent.digitalRead(self.pin)
val=0
if ((self.value!=self.previous_value) & (self.value==0)):
val=1
else :
val=0
self.previous_value=self.value
return val
def pulse(self):
print("pulse In ")
self.duree=self.parent.pulseIn(self.pin)
return self.duree
class AnalogInput():
"""
Classe AnalogInput pour lire les données issues d'une voie analogique
Vous devez spécifier la carte arduino et le pin analogique d'entrée souhaitée
analog=AnalogInput(macarte,0)
Pour lire la valeur analogique : analog.read(). La valeur renvoyée est comprise entre 0 et 1023
"""
def __init__(self,parent,pin):
self.pin=pin
self.parent=parent
self.value=0
def read(self):
self.value=self.parent.analogRead(self.pin)
return self.value
class AnalogOutput():
"""
Classe AnalogOutput pour envoyer une grandeur analogique variant de 0 à 5 V
ce qui correspond de 0 à 255 \n
Vous devez spécifier la carte arduino et le pin Analogique (pwm ~) de sortie souhaité
led=AnalogOutput(macarte,9)
Utiliser la commande led.write(200)
"""
def __init__(self,parent,pin):
self.pin=pin
self.parent=parent
self.value=0
def write(self,val):
if val>255 :
val=255
elif val<0:
val=0
self.parent.analogWrite(self.pin,val)
class DCmotor():
"""
Classe DCmotor pour le pilotage des moteurs a courant continu
Les parametres de definition d'une instance de la classe sont :\n
- la carte arduino selectionnee\n
- le numero du moteur de 1 a 4\n
- le pin du PWM1\n
- le pin de sens ou de PWM2\n
- le type de pilotage : 0 (type L293 avce 2 PWM) ou 1 (type L298 avec un PWM et une direction)\n
Ex : monmoteur=DCmotor(arduino1,1,3,5,0) (moteur 1 pilotage de type L293 avec les PWM des pins 3 et 5\n
Pour faire tourner le moteur a une vitesse donne, taper : monmoteur.write(x) avec x compris entre -255 et 255)
"""
def __init__(self,parent,number,pin_pwm,pin_dir,mode):
self.pin1=pin_pwm
self.pin2=pin_dir
self.mode=mode
self.number=number
self.parent=parent
if mode!=0 and mode!=1:
print("Choisir un mode egal a 0 pour un pilotage par 2 PWM ou 1 pour un pilotage par un PWM et un pin de sens")
elif number!=1 and number!=2 and number!=3 and number!=4:
print("Choisir un numero de moteur de 1 a 4")
else :
try:
mess="C"+str(self.number)+chr(48+self.pin1)+chr(48+self.pin2)+str(self.mode)
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
tic=time.time()
toread=self.parent.ser.inWaiting()
value=""
while(toread < 2 and time.time()-tic < 1): # attente retour Arduino
toread=self.parent.ser.inWaiting();
value=self.parent.ser.read(toread);
if value==b"OK":
print("Moteur "+str(self.number)+" correctement connecté")
else:
print("Problème de déclaration et connection au moteur")
self.parent.close()
return
except:
print("Problème de déclaration et connection au moteur")
self.parent.close()
def write(self,value):
value=int(value)
if value<-255:
value=-255
elif value>255:
value=255
if value<0:
direction=0
else:
direction=1
mess="M"+str(self.number)+chr(48+direction)+chr(abs(round(value)))
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
class Stepper():
"""
Classe Stepper pour le pilotage d'un moteur pas à pas accouplé à un driver nécessitant la donnée d'une direction et d'un signal pulsé
Les parametres de definition d'une instance de la classe sont :\n
- la carte arduino selectionnee\n
- un numero de 1 à 4 pour activer de 1 à 4 moteurs pas à pas\n
- le numéro du pin donnant le signal pulsé (STEP)\n
- le numéro du pin donnant la direction (DIR)\n
Ex : monstepper=Stepper(arduino1,1,10,11) (moteur 1 sur les pins STEP 10, DIR 11
Pour faire tourner le moteur d'un nombre de pas donné, taper : monmoteur.move(nb_steps, dt)
avec nb_steps le nombre de pas ou demi-pas (ou autre en fonction du mode) qui peut etre positif ou négatif (ce qui définit le sens de déplacement), dt le temps laissé entre chaque pas en millisecondes (de 0.05 à 15). Attention, le choix du pas de temps est fonction de la dynamique souhaitée et donc du réglage de l'intensité de consigne sur le driver du moteur.
Il est peut etre nécessaire de définir des sorties digitales ENABLE, pour autoriser ou non le moteur pas à pas à bouger et des sorties digitales MS1, MS2, MS3 pour définir le mode de pas à pas (pas complet, demi-pas, ou autre...)
"""
def __init__(self,parent,number,pin_pwm,pin_dir):
self.pin_pwm=pin_pwm
self.pin_dir=pin_dir
self.parent=parent
self.number=number
self.nb_steps=0
self.dt=0
self.launched=0
self.tic=0
try:
mess="Pa"+chr(48+self.number)+chr(48+self.pin_pwm)+chr(48+self.pin_dir)
print(mess)
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
tic=time.time()
toread=self.parent.ser.inWaiting()
value=""
while(toread < 2 and time.time()-tic < 1): # attente retour Arduino
toread=self.parent.ser.inWaiting();
value=self.parent.ser.read(toread);
if value==b"OK":
print("Moteur pas a pas correctement connecté")
else:
print("Problème de déclaration et connection au moteur pas a pas")
self.parent.close()
return
except:
print("Problème de déclaration et connection au moteur pas a pas")
self.parent.close()
def move(self,nb_steps,dt):
self.dt=dt
dt=dt/2
self.nb_steps=nb_steps
if dt>15:
dt=15
if dt<0.05:
dt=0.05
dt=int(dt*1000)
value=int(nb_steps)
if value >=0:
direction=1
else:
direction=0
value=abs(value)
if value>=2**32:
value=2**32-1
messb=bytes("Pm"+chr(48+self.number)+chr(48+direction),"ISO-8859-1")+struct.pack('L',value)+struct.pack('i',dt)
self.parent.ser.write(messb)
tic=time.time()
toread=self.parent.ser.inWaiting()
value=""
while(toread < 2 and time.time()-tic < 1): # attente retour Arduino
toread=self.parent.ser.inWaiting()
value=self.parent.ser.read(toread)
if value!=b'OK':
self.stop()
self.launched=1
self.tic=time.time()
def stop(self):
mess="Ps"+chr(48+self.number)
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
self.launched=0
def isMoving(self):
mess="Pi"+chr(48+self.number)
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
tic=time.time()
toread=self.parent.ser.inWaiting()
value=""
while(toread < 1 and time.time()-tic < 1): # attente retour Arduino
toread=self.parent.ser.inWaiting()
value=self.parent.ser.read(toread)
if value!=b'1' and value!=b'0':
return 0
else:
return int(value)
def isMoving2(self):
#print(time.time()-self.tic)
if time.time()-self.tic>abs(self.nb_steps*self.dt/1000)+0.01:
self.launched=0
return self.launched
class Encoder():
"""
Classe Encoder pour la lecture d'interruption sur des encodeurs 2 voies
Les parametres de definition d'une instance de la classe sont :\n
- la carte arduino selectionnee\n
- le pin de l'entrée digitale de la voie A (avec interruption)\n
- le pin de l'entrée digitale de la voie B (avec ou sans interruption)\n
- le type de lecture : 1 pour front montant de la voie A (et sens donné par la voie B), 2 pour fronts montants et descendants de la voie A seule, 4 pour fronts montants et descendants des deux voies
codeur=Encoder(macarte,2,3,1)
pour lire le nombre de tops, taper codeur.read(). La valeur obtenue peut etre positive ou négative (codée sur 4 octets)
Pour remettre à 0 la valeur lue, codeur.reset()
"""
def __init__(self,parent,pinA,pinB,mode):
self.parent=parent
self.pinA=pinA
self.pinB=pinB
self.mode=mode
self.corresp=[-1,-1,0,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,4,3,2]
try:
if self.corresp[self.pinA]==-1 or self.corresp[self.pinB]==-1:
print("Les pins utilisés pour l'encodeur doivent accepter les interruptions. Choisir les pins 2,3 (UNO, MEGA) ou 18 à 21 (MEGA)")
self.parent.close()
except:
print("Les pins utilisés pour l'encodeur doivent accepter les interruptions. Choisir les pins 2,3 (UNO, MEGA) ou 18 à 21 (MEGA)")
self.parent.close()
if mode!=1 and mode!=2 and mode !=4:
print(["Choisir un mode pour le codeur egal a : ",
"1 : front montant de la voie A, ",
"2 : front montant et descendants de la voie A,",
"4 : fronts montants et descendants des voies A et B"])
self.parent.close()
else :
if mode==4:
mess="Ea"+chr(self.corresp[self.pinA])+chr(self.corresp[self.pinB])+str(mode)
else:
mess="Ea"+chr(self.corresp[self.pinA])+chr(self.pinB)+str(mode)
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
def reset(self):
mess="Ez"+chr(self.corresp[self.pinA])
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
def read(self):
mess="Ep"+chr(self.corresp[self.pinA])
self.parent.ser.write(bytes(mess,"ISO-8859-1"))
toread=self.parent.ser.inWaiting()
tic=time.time()
while(toread < 4 and time.time()-tic < 1): # attente retour Arduino
toread=self.parent.ser.inWaiting();
value=self.parent.ser.read(toread);
value=struct.unpack('l',value)
return value[0]
class Arduino():
"""
Classe Arduino pour definition d'une carte arduino. Ne fonctionne qu'en python 3.X
Il faut charger le programme toolbox_arduino_vX.ino dans la carte Arduino pour pouvoir utiliser cette classe.
Les parametres de definition d'une instance de la classe sont :\n
- le port de communication (numero sous Windows, chemin sous linux /dev/xxx )\n
Le taux de transfert peut être passé en argument mais il faut modifier celui du fichier ino pour qu'il corresponde. Par défaut il est à 115200
La connection à la carte est faite automatiquement à la déclaration\n
Taper macarte=Arduino(8) pour se connecter automatiquement à la carte sur le port 8\n
Taper macarte.close() pour fermer la connexion\n
Il faudra alors toujours passer en argument l'objet macarte pour toute déclaration de pins arduino (DigitalOutput, DigitalInput, DCmotor, Stepper, Servo, AnalogInput, AnalogOutput, Encoder)
"""
def __init__(self,com,baudrate=115200):
self.ser = serial.Serial()
self.com=com #define com port
self.baudrate=baudrate #define com debit
self.digitalPins=[] #list of defined digital pins
self.analogPins=[] #list of defined analog pins
self.interrupts=[] #list of defined interrupt
self.steppers=[] #list of defined pins for stepper
self.connect()
def ask(self):
mess="B"
self.ser.write(bytes(mess,"ISO-8859-1"))
toread=self.ser.inWaiting();
#tic=time.time()
#while(toread < 2 and time.time()-tic < 2): # attente retour Arduino
# toread=self.ser.inWaiting();
value=0
if toread!=0:
value=self.ser.read(toread)
print(value)
def connect(self):
self.ser.baudrate=self.baudrate #definition du debit
import os
if os.name == "posix":
self.ser.port=self.com
else:
if int(serial.VERSION.split('.')[0])>=3:
self.ser.port="COM"+str(self.com)
else:
self.ser.port=self.com-1
connect = 0
try:
self.ser.open(); #open port4
time.sleep(2); #wait for stabilisation
self.ser.write(b"R3"); #send R3 to ask for arduino program
tic = time.time();
toread=self.ser.inWaiting();
while(toread < 2 and time.time()-tic < 2): # attente retour Arduino
toread=self.ser.inWaiting();
value=self.ser.read(toread)
if value == b"v4":
print("Connexion ok avec l'arduino")
connect=1
finally:
if connect==0:
print("Connexion impossible avec l'arduino. Verifier que le com est le bon et que le programme toolbox_arduino_v4.ino est bien chargé dans l'arduino")
return 0
else:
return 1
def close(self):
self.ser.close()
def pinMode(self,pin,type):
mode='x'
if type=='OUTPUT':
mode='1'
elif type=='INPUT':
mode='0'
else:
print("Attention le type OUTPUT ou INPUT du pin n'est pas bien renseigne")
if mode != 'x':
mess="Da"+chr(pin+48)+mode
#self.ser.write(bytes(mess,"ascii"))
self.ser.write(bytes(mess,"ISO-8859-1"))
self.digitalPins.append(pin)
def digitalwrite(self,pin,value):
self.digitalWrite(self,pin,value)
def digitalWrite(self,pin,value):
try:
self.digitalPins.index(pin)
data='x'
if value=="HIGH":
data='1'
elif value=="LOW":
data='0'
elif value==1 or value==0:
data=str(value)
else:
print("Valeur incorrecte pour un pin digital")
if data !='x':
mess="Dw"+chr(pin+48)+data
#self.ser.write(bytes(mess,"ascii"))
self.ser.write(bytes(mess,"ISO-8859-1"))
except:
print("Erreur de transmission ou bien le pin digital n'a pas ete bien assigne au prealable avec arduino.pinMode")
self.close()
traceback.print_exc(file=sys.stdout)
def analogwrite(self,pin,value):
self.analogWrite(self,pin,value)
def analogWrite(self,pin,value):
try:
if abs(value)>255:
code_sent="W"+chr(pin+48)+chr(255);
else:
code_sent="W"+chr(pin+48)+chr(abs(round(value)))
self.ser.write(bytes(code_sent,"ISO-8859-1"))
except:
print("Erreur de transmission")
self.close()
#traceback.print_exc(file=sys.stdout)
def digitalread(self,pin):
return self.digitalRead(self,pin)
def digitalRead(self,pin):
try:
self.digitalPins.index(pin)
mess="Dr"+chr(pin+48)
#self.ser.write(bytes(mess,"ascii"))
self.ser.write(bytes(mess,"ISO-8859-1"))
tic=time.time()
toread=self.ser.inWaiting();
while(toread < 1 and time.time()-tic < 1): # attente retour Arduino
toread=self.ser.inWaiting();
value=self.ser.read(toread)
return int(value)
except:
print("Erreur de transmission ou bien le pin digital n'a pas ete bien assigne au prealable avec arduino.pinMode")
self.close()
#traceback.print_exc(file=sys.stdout)
def pulseIn(self,duree,trigger,echo):
try:
self.digitalPins.index(trigger)
self.digitalPins.index(echo)
mess="Dp"+chr(trigger+48)+chr(echo+48)+chr(abs(round(duree)))
#self.ser.write(bytes(mess,"ascii"))
self.ser.write(bytes(mess,"ISO-8859-1"))
toread=self.ser.inWaiting()
tic=time.time()
while(toread < 4 and time.time()-tic < 1): # attente retour Arduino
toread=self.ser.inWaiting()
value=self.ser.read(toread)
value=struct.unpack('l',value)
return value[0]
except:
print("Erreur de transmission")
self.close()
#traceback.print_exc(file=sys.stdout)
def analogread(self,pin):
return self.analogRead(self,pin)
def analogRead(self,pin):
try:
mess="A"+chr(pin+48)
#self.ser.write(bytes(mess,"ascii"))
self.ser.write(bytes(mess,"ISO-8859-1"))
toread=self.ser.inWaiting()
tic=time.time()
while(toread < 2 and time.time()-tic < 1): # attente retour Arduino
toread=self.ser.inWaiting();
value=self.ser.read(toread);
value=struct.unpack('h',value)
return value[0]
except:
print("Erreur de transmission")
self.close()
#traceback.print_exc(file=sys.stdout)
def Servo(self,pin):
return Servo(self,pin)
|
09c24a1dce6f40409993005a582dafc018ce3d3e | adykumar/Leeter | /python/206_reverse-linked-list.py | 1,281 | 3.890625 | 4 | """
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
"""
class Node(object):
def __init__(self, x):
self.val= x
self.next= None
class Solution(object):
def createLL(self, lis):
if len(lis)<1:
return None
head= Node(lis[0])
p= head
for each in lis[1:]:
temp= Node(each)
p.next= temp
p= p.next
return head
def printLL(self, head):
while head!= None:
print head.val,
head= head.next
print
def reverseLL(self, head):
if head==None or head.next==None:
return head
left= head
right= head.next
while right.next!= None:
temp= right
right= right.next
temp.next= left
left= temp
right.next= left
head.next= None
return right
if __name__=="__main__":
testcases= [ [1,2,3,4], [1], [], [2,1,34,7] ]
obj= Solution()
for test in testcases:
print "-----------\n",test
print "Orig LL => ",
orig= obj.createLL(test)
obj.printLL(orig)
print "Reversed => ",
rev= obj.reverseLL(orig)
obj.printLL(rev)
|
f503e91072d0dd6c7402e8ae662b6139feed05e0 | adykumar/Leeter | /python/104_maximum-depth-of-binary-tree.py | 1,449 | 4.125 | 4 | """
WORKING....
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
"""
import Queue as queue
class TreeNode(object):
def __init__(self,x):
self.val= x
self.left= None
self.right= None
class Solution(object):
def createTree(self, treelist):
root= TreeNode(treelist[0])
q= queue.Queue(maxsize= len(treelist))
q.put(root)
i = 1
while True:
if i>= len(treelist): break
node= q.get()
if treelist[i] != "null":
node.left= TreeNode(treelist[i])
q.put(node.left)
i+=1
if i>= len(treelist): break
if treelist[i] != "null":
node.right= TreeNode(treelist[i])
q.put(node.right)
i+=1
return root
def maxDepth(self, root):
if root==None: return 0
return max( self.maxDepth(root.left)+1, self.maxDepth(root.right)+1 )
if __name__=="__main__":
testcases= [[3,9,20,"null","null",15,7, 1, 1, 3], [1], [1,"null", 3]]
obj= Solution()
for test in testcases:
root= obj.createTree(test)
print test, " -> ", obj.maxDepth(root)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.