blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
e727b0f0a0416ba695b263ab9109342a894b1156 | a123aaa/python_know | /Python知识清单/字符串(str)对齐.py | 1,213 | 4.03125 | 4 | arr='hello,Python'
print(arr.center(20,'*')) #****hello,Python****
print(arr.ljust(20,'*')) #hello,Python********
print(arr.ljust(10)) #hello,Python
print(arr.ljust(20)) #hello,Python 空格
print(arr.rjust(20,'*')) #********hello,Python
print(arr.rjust(10)) #hello,Python
print(arr.rjust(20)) # hello,Python
print(arr.zfill(20)) #00000000hello,Python
print(arr.zfill(10)) #hello,Python
#print(-9806,zfill(10)) #0000009806
#字符串名 .center(站位大小,'标志符') 居中对齐,用'标志符'补齐空位
#字符串名 .center(站位大小) 居中对齐,用'空格'补齐空位
#字符串名 .ljust(站位大小,'标志符') 左对齐,用'标志符'补齐空位
#字符串名 .ljust(站位大小) 左对齐,用'空格'补齐空位
#字符串名 .rjust(站位大小,'标志符') 右对齐,用'标志符'补齐空位
#字符串名 .rjust(站位大小) 右对齐,用'空格'补齐空位
#字符串名 .zfill(站位大小) 右对齐,用0补齐空位
|
ab86ec527e8bf779159c384224dbe656f11a4345 | nandha-batzzy/Python-Projects-and-Learning | /Code forces Simple probs/ep9_Petya and Strings.py | 216 | 4.0625 | 4 | strn1 = input("Enter the first string: ").lower()
strn2 = input("Enter the second string: ").lower()
if strn1 > strn2:
print(1)
elif strn1 < strn2:
print(-1)
elif strn1 == strn2:
print(0)
|
67fd064339b61f06bff67050d28021f1bd69b567 | TvylorMvde/Numeric_Matrix_Processor | /Numeric Matrix Processor/task/processor/processor.py | 5,492 | 3.8125 | 4 | import numpy as np
class Matrix:
def __init__(self, row, column):
self.row = row
self.column = column
self.matrix = []
def create_matrix(self):
for i in range(self.row):
numbers = list(map(float, input().split()))
self.matrix.append(numbers)
@staticmethod
def matrix_addition(matrix1, matrix2):
if matrix1.row == matrix2.row and matrix1.column == matrix2.column:
result = [[matrix1.matrix[i][j] + matrix2.matrix[i][j] for j in range(len(matrix1.matrix[0]))] for i in
range(len(matrix1.matrix))]
for i in result:
i = " ".join(map(str, i))
print(i)
else:
print("The operation cannot be performed")
def multiply_by_const(self, x):
result = []
for i in self.matrix:
result = [[x * self.matrix[i][j] for j in range(len(self.matrix[0]))] for i in range(len(self.matrix))]
for i in result:
i = " ".join(map(str, i))
print(i)
@staticmethod
def multiplication(matrix1, matrix2):
result = [[0 for col in range(len(matrix2.matrix[0]))] for row in range(len(matrix1.matrix))]
if matrix1.column == matrix2.row:
for i in range(len(matrix1.matrix)):
for j in range(len(matrix2.matrix[0])):
for k in range(len(matrix2.matrix)):
result[i][j] += matrix1.matrix[i][k] * matrix2.matrix[k][j]
for i in result:
i = " ".join(map(str, i))
print(i)
else:
print("The operation cannot be performed")
def transpose(self, x):
if x == 1:
result = [[self.matrix[j][i] for j in range(len(self.matrix))]
for i in range(len(self.matrix[0]))]
for i in result:
i = " ".join(map(str, i))
print(i)
if x == 2:
result = [[self.matrix[j][i] for j in reversed(range(len(self.matrix)))]
for i in reversed(range(len(self.matrix[0])))]
for i in result:
i = " ".join(map(str, i))
print(i)
if x == 3:
for i in range(len(self.matrix)):
self.matrix[i].reverse()
for i in self.matrix:
i = " ".join(map(str, i))
print(i)
if x == 4:
j = 0
new_matrix = []
for i in reversed(range(len(self.matrix))):
new_matrix.append(self.matrix[i])
j += 1
for i in new_matrix:
i = " ".join(map(str, i))
print(i)
def calculate_determinant(self):
a = np.array(self.matrix)
print(np.linalg.det(a))
def inverse_matrix(self):
a = np.array(self.matrix)
if np.linalg.det(a) != 0:
print('The result is: ')
for i in np.linalg.inv(a):
i = " ".join(map(str, i))
print(i)
else:
print('This matrix doesn\'t have an inverse.')
def menu():
print("""1. Add matrices
2. Multiply matrix by a constant
3. Multiply matrices
4. Transpose matrix
5. Calculate a determinant
6. Inverse matrix
0. Exit""")
def menu_transpose():
print("""1. Main diagonal
2. Side diagonal
3. Vertical line
4. Horizontal line""")
while True:
print()
menu()
choice = int(input('Your choice: '))
if choice == 1:
n1, m1 = map(int, input('Enter size of first matrix: ').split())
A = Matrix(n1, m1)
print('Enter first matrix: ')
A.create_matrix()
n2, m2 = map(int, input('Enter size of second matrix: ').split())
B = Matrix(n2, m2)
print('Enter second matrix: ')
B.create_matrix()
print('The result is: ')
Matrix.matrix_addition(A, B)
if choice == 2:
n1, m1 = map(int, input('Enter size of matrix: ').split())
A = Matrix(n1, m1)
print('Enter matrix: ')
A.create_matrix()
constant = float(input('Enter constant: '))
print('The result is: ')
A.multiply_by_const(constant)
if choice == 3:
n1, m1 = map(int, input('Enter size of first matrix: ').split())
A = Matrix(n1, m1)
print('Enter first matrix: ')
A.create_matrix()
n2, m2 = map(int, input('Enter size of second matrix: ').split())
B = Matrix(n2, m2)
print('Enter second matrix: ')
B.create_matrix()
print('The result is: ')
Matrix.multiplication(A, B)
if choice == 4:
menu_transpose()
transpose_choice = int(input('Your choice: '))
n1, m1 = map(int, input('Enter matrix size: ').split())
A = Matrix(n1, m1)
print('Enter matrix: ')
A.create_matrix()
print('The result is: ')
A.transpose(transpose_choice)
if choice == 5:
n1, m1 = map(int, input('Enter matrix size: ').split())
A = Matrix(n1, m1)
print('Enter matrix: ')
A.create_matrix()
print('The result is: ')
A.calculate_determinant()
if choice == 6:
n1, m1 = map(int, input('Enter matrix size: ').split())
A = Matrix(n1, m1)
print('Enter matrix: ')
A.create_matrix()
A.inverse_matrix()
if choice == 0:
break
|
f83f048f2e826feb6f7b68d77983e1d4777b739b | rds504/AoC-2020 | /solutions/day2.py | 731 | 3.71875 | 4 | import re
from tools.general import load_input_list
input_data = load_input_list("day2.txt")
pattern = re.compile("^([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)$")
valid_p1, valid_p2 = 0, 0
for i in input_data:
m = pattern.match(i)
if m:
lower = int(m.group(1))
upper = int(m.group(2))
char = m.group(3)
password = m.group(4)
# Part 1
if lower <= password.count(char) <= upper:
valid_p1 += 1
# Part 2
if char == password[lower - 1]:
if char != password[upper - 1]:
valid_p2 += 1
elif char == password[upper - 1]:
valid_p2 += 1
print(f"Part 1 => {valid_p1}")
print(f"Part 2 => {valid_p2}")
|
59968a36318f933642a56ac1b633113c24ad5da1 | Kimuda/Phillip_Python | /while_loops/14_compiled_while.py | 630 | 4.03125 | 4 | phrase1=input("enter a phrase ")
phrase2=input("enter a phrase ")
letter=input("enter a letter ")
phraselength1=len(phrase1)
phraselength2=len(phrase2)
counter1=0
counter2=0
while phraselength1>=0:
if phrase1[phraselength1-1]==letter:
counter1=counter1+1
phraselength1=phraselength1-1
#print(counter1)
while phraselength2>=0:
if phrase2[phraselength2-1]==letter:
counter2=counter2+1
phraselength2=phraselength2-1
#print(counter2)
if counter1>counter2:
print("letter",letter, "occured most in the phrase--", phrase1)
else:
print("letter",letter, "occured most in the phrase--", phrase2)
|
5d483761d4900248b6c1894feea768f7508c49d2 | ryanloughlin25/interview-practice | /interview_cake/making_change/ryan/making_change.py | 1,503 | 3.75 | 4 | from itertools import islice
from collections import defaultdict
"""
bother, I've implemented a function to return the set of
combinations that sum to the amount. It should have just
been a function to return the number of combinations.
"""
def making_change(amount, denominations):
result = []
for index, denomination in enumerate(denominations):
if amount == denomination:
result.append([denomination])
elif denomination < amount:
subproblems = making_change(
amount - denomination,
denominations[index:],
# islice(denominations, index, None),
)
for subproblem in subproblems:
result.append([denomination] + subproblem)
return result
def making_change_subproblem(amount, denomination, subresults):
result = []
for subresult in subresults:
result.append(subresult + [denomination])
if amount == denomination:
result.append([denomination])
return result
def making_change(amount, denominations):
results = defaultdict(list)
for denomination in denominations:
for sub_amount in range(denomination, amount + 1):
subresults = making_change_subproblem(
sub_amount,
denomination,
results[sub_amount - denomination],
)
for subresult in subresults:
results[sub_amount].append(subresult)
return results[amount]
|
e8ad205ed7bfac59827e24fd0bf65000025d4275 | DanSGraham/code | /Other/Python/StockMarketProgram/timeConverter.py | 2,162 | 3.96875 | 4 | #A program to convert time to EST
#By Daniel Graham
import convertTimeToSeconds
import time
January = 31
February = 28
March = 31
April = 30
May = 31
June = 30
July = 31
August = 31
September = 30
October = 31
November = 30
December = 31
months_list = [January, February, March, April, May, June, July, August, September, October, November, December]
months_string = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
days_of_week = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
#ISSUE WITH TIME CONVERSION. CHECK EACH SITE FOR BUGS.
def converter(time_string):
if time_string[-3:] == 'EST' or time_string[-3:] == 'EDT':
return time_string
else:
time_in_seconds = convertTimeToSeconds.convert_to_seconds(time_string[-12:-4])
if time_string[-3:] == 'GMT' or time_string[-3:] == 'UTC':
new_time = time_in_seconds - 5*3600
if new_time < 0:
day_of_week = days_of_week[days_of_week.index(time_string[0:3])-1]
day_of_month = int(time_string[5:7]) - 1
if day_of_month <= 0:
month = months_string[months_string.index(time_string[8:11]) - 1]
if month == 'Dec':
year = int(time_string[12:16]) - 1
else:
year = int(time_string[12:16])
day_of_month = months_list[months_string.index(month)]
else:
year = int(time_string[12:16])
month = time_string[8:11]
new_time = 24*3600 + new_time
EST_time = convertTimeToSeconds.convert_to_regtime(new_time)
else:
day_of_week = time_string[0:3]
day_of_month = int(time_string[5:7])
month = time_string[8:11]
year = int(time_string[12:16])
EST_time = convertTimeToSeconds.convert_to_regtime(new_time)
return day_of_week + ', ' + str(day_of_month) + ' ' + month + ' ' + str(year) + ' ' + EST_time + ' ' + 'EST'
|
f552921c9f25d358ca20fe905858ae66815092ed | lichkingwulaa/Codewars | /5 kyu/5_kyu_Directions_Reduction.py | 876 | 3.75 | 4 | """
https://www.codewars.com/kata/directions-reduction/solutions/python
"""
def dirReduc(arr):
i = 0
while True:
if i + 1 - len(arr) >= 0:
return arr
if sorted([arr[i],arr[i+1]]) in [['NORTH', 'SOUTH'] , ['EAST', 'WEST']]:
del arr[i]
del arr[i]
i = 0
else:
i += 1
a = dirReduc(['EAST', 'NORTH', 'SOUTH', 'WEST', 'WEST'])
print(a)
# 大佬鼠的迷惑方法
def dirReduc1(arr):
dir1 = " ".join(arr)
dir2 = dir1.replace("NORTH SOUTH",'').replace("SOUTH NORTH",'').replace("EAST WEST",'').replace("WEST EAST",'')
dir3 = dir2.split()
return dirReduc(dir3) if len(dir3) < len(arr) else dir3
def dirReduc2(arr):
while True:
dir1 = " ".join(arr)
dir2 = dir1.replace("NORTH SOUTH",'').replace("SOUTH NORTH",'').replace("EAST WEST",'').replace("WEST EAST",'')
dir3 = dir2.split()
if len(dir3) >= len(arr):
break
arr = dir3[:]
return dir3 |
903bce7d48f37f2341831c18b58e23c9dfedc02c | chc1129/introducing-python3 | /chap10/timeCtrl.py | 638 | 3.90625 | 4 | import time
now = time.time()
print(now)
print(time.ctime(now))
print(time.localtime(now))
print(time.gmtime(now))
tm = time.localtime(now)
print(time.mktime(tm))
now = time.time()
print(time.ctime(now))
fmt = "It's %A, %B %d, %Y, local time%I:%M:%S%p"
t = time.localtime()
print(t)
print(time.strftime(fmt, t))
from datetime import date
some_day = date(2014, 7, 4)
print(some_day.strftime(fmt))
from datetime import time
some_time = time(10, 35)
print(some_time.strftime(fmt))
import time
fmt = "%Y-%m-%d"
#print(time.strptime("2012 01 29", fmt))
print(time.strptime("2012-01-29", fmt))
#print(time.strptime("2012-13-29", fmt))
|
e8c39a3ad8896eeb5a26b1c2c471974c6a0b7d7c | Chevtastic/CS110 | /input01.py | 369 | 3.90625 | 4 | import random
colorlist = ['orange', 'red', 'blue', 'yellow', 'turqoise', 'black', 'white', 'green']
print("Hello there!")
name = input("What is your name? ")
print("Nice to meet you",name,"!")
color = input("Here's a question for you...What is your favorite color? ")
print(name, "your favorite color is", color)
print("My favorite color is", random.choice(colorlist)) |
355e2e0b88d685bcd0ba0462f2b51c342e6784f2 | R281295/Proyectos | /Python/Ahorcado/Ahorcado.py | 1,827 | 3.890625 | 4 | def pedirPalabra():
return input("Escribe tu palabra: ")
def toAsteriscos(frase):
asteriscos = ""
for i in range(len(frase)):
if frase[i] == " ":
asteriscos += " "
else:
asteriscos += "*"
return asteriscos
def pedirLetra():
try:
return input("Elige una letra: ")[0]
except:
return ""
def pintarMuneco(errores):
switcher = {
1: "_____\n| O\n|\n|\n|\n",
2: "_____\n| O\n| |\n|\n|\n",
3: "_____\n| O\n| /|\n|\n|\n",
4: "_____\n| O\n| /|\\\n|\n|\n",
5: "_____\n| O\n| /|\\\n| |\n|\n",
6: "_____\n| O\n| /|\\\n| |\n| /\n",
7: "_____\n| O\n| /|\\\n| |\n| / \\\n"
}
print(switcher[errores])
def desvelarLetras(frase, letra, asteriscos):
newAsteriscos = ""
global errores
if asteriscos.count("*") == 0:
errores = maximoErroresPermitidos+1
if frase.count(letra) == 0:
errores += 1
print(f"Tienes {errores}/{maximoErroresPermitidos} fallos")
pintarMuneco(errores)
for i in range(len(frase)):
if frase[i] == letra:
newAsteriscos += letra
else:
newAsteriscos += asteriscos[i]
return newAsteriscos
maximoErroresPermitidos = 7
errores = 0
frase = pedirPalabra()
asteriscos = toAsteriscos(frase)
print(asteriscos)
letrasDichas = ""
while(errores < maximoErroresPermitidos and asteriscos.count("*") > 0):
letra = pedirLetra()
if(letrasDichas.count(letra) == 0):
letrasDichas += letra
asteriscos = desvelarLetras(frase, letra, asteriscos)
else:
print("Ya has dicho esa letra")
print(asteriscos+"\n")
if(errores == maximoErroresPermitidos):
print(f"Has perdido... la palabra era: {frase}")
else:
print("Enhorabuena! Has ganado!!")
|
c33ae19dd1c6a6c7a425e948698b2df0409e9429 | Mahrjose/BRACU-CSE110 | /Assignment 01/Problem 10.py | 130 | 3.828125 | 4 | user_input = int(input())
if not (user_input % 2 == 0) or not (user_input % 5 == 0):
print(user_input)
else:
print("No")
|
433c430e15872d4f248021879c98f2891b04f493 | llathrop/udacity-classprojects | /udacity-cs373/kalmanFilter.py | 1,160 | 3.609375 | 4 | #!/bin/python
from mystatslib import *
from math import *
import random
import itertools
# Write a program that will iteratively update and
# predict based on the location measurements
# and inferred motions shown below.
#Kalman Filter:- Measurement update step
def kalmanUpdate(mean1, var1, mean2, var2):
new_mean = (var2 * mean1 + var1 * mean2) / (var1 + var2)
new_var = 1/(1/var1 + 1/var2)
return [new_mean, new_var]
#Kalman Filter:- movement update step
def kalmanPredict(mean1, var1, mean2, var2):
new_mean = mean1 + mean2
new_var = var1 + var2
return [new_mean, new_var]
#1 Dimension Kalman Filter
def Kalman(measurements,motion,measurement_sig,motion_sig,mu,sig):
for i in range(len(motion)):
mu,sig=kalmanUpdate(mu,sig,measurements[i],measurement_sig)
print 'update: ', mu,sig
mu,sig=kalmanPredict(mu,sig,motion[i],motion_sig)
print 'predict: ', mu,sig
return[mu,sig]
measurements = [5., 6., 7., 9., 10.]
motion = [1., 1., 2., 1., 1.]
measurement_sig = 4.
motion_sig = 2.
mu = 10.
sig = 1000.
print Kalman(measurements,motion,measurement_sig,motion_sig,mu,sig)
|
5f3705794701b138224f8af95ab96506aedcba4f | kelmory06/FR-2017-10-10--201554422---201554041- | /Cliente-Servidor-protocolo-HTTP.py | 4,760 | 3.515625 | 4 | # FR-2017-10-10--201554422---201554041-
Cliente en el protocolo HTTP
#!/usr/bin/python
# Complete el codigo, en la seccion que dice COMPLETE de acuerdo al enunciado
# dado en este enlace https://goo.gl/1uQqiB, item 'socket-http-client'
#
import socket
import sys
try: # esta estructura permite capturar comportamientos anomalos
# COMPLETE (1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg: # si es del tipo socket.error
print "Failed to create socket. Error code: " + str(msg[0]) + ", error message: " + msg[1]
sys.exit()
print "Socket created"
host = "www.google.com"
# defina una variable port y almacene alli el numero 80
# COMPLETE (2)
port=80
try:
# COMPLETE (3)
remote_ip = socket.gethostbyname(remote_port)
except socket.gaierror:
print "Hostname could not be resolved. Exiting"
sys.exit()
# COMPLETE (4)
print "IP of %s: %s" + host + "es" + remote_ip
# COMPLETE (5)
endpoint = (remote_ip , port)
# COMPLETE (6)
s.connect(endpoint)
print "Socket connected to " + host + " on ip " + remote_ip
# Datos a enviarse
message = "GET / HTTP/1.1\r\n\r\n"
try:
# COMPLETE (7)
s.sendall(message('utf-8'))
except socket.error:
print "Send failed"
sys.exit()
print "Message send successfullly"
# Recibiendo datos
# COMPLETE (8)
s.recvfrom(reply)
print reply
s.close()
Servidor en el protocolo HTTP
#!/usr/bin/env python3
import argparse
import sys
import itertools
import socket
from socket import socket as Socket
# A simple web server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Issues:
# Ignores CRLF requirement
# Header must be < 1024 bytes
# ...
# probabaly loads more
def main():
# Command line arguments. Use a port > 1024 by default so that we can run
# without sudo, for use as a real server you need to use port 80.
parser = argparse.ArgumentParser()
parser.add_argument('--port', '-p', default=2080, type=int,
help='Port to use')
args = parser.parse_args()
# Create the server socket (to handle tcp requests using ipv4), make sure
# it is always closed by using with statement.
#with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
# COMPLETE (1)
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# The socket stays connected even after this script ends. So in order
# to allow the immediate reuse of the socket (so that we can kill and
# re-run the server while debugging) we set the following option. This
# is potentially dangerous in real code: in rare cases you may get junk
# data arriving at the socket.
ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# COMPLETE (2)
endpoint = ('' , args.port)
# COMPLETE (3)
ss.bind(endpoint)
ss.listen(5)
print("server ready")
while True:
cs = ss.accept()[0]
request = cs.recv(1024).decode('ascii')
print (request)
reply = http_handle(request)
cs.send(reply.encode('ascii'))
print("\n\nReceived request")
print("======================")
print(request.rstrip())
print("======================")
print("\n\nReplied with")
print("======================")
print(reply.rstrip())
print("======================")
return 0
def http_handle(request_string):
"""Given a http requst return a response
Both request and response are unicode strings with platform standard
line endings.
"""
assert not isinstance(request_string, bytes)
# Fill in the code to handle the http request here. You will probably want
# to write additional functions to parse the http request into a nicer data
# structure (eg a dict), and to easily create http responses.
# COMPLETE (4)
request = HTTPRequest(request_version)
print request.request_version
print request.path
if (request.path[0] == "/")
#
# Esta el archivo que se pide?
#
with open(request.path[1:]) as myfile:
data = mylife.read()
headers = "HTTP/1.1 200
# esta funcion DEBE RETORNAR UNA CADENA que contenga el recurso (archivo)
# que se consulta desde un navegador e.g. http://localhost:2080/index.html
# En el ejemplo anterior se esta solicitando por el archivo 'index.html'
# Referencias que pueden ser de utilidad
# - https://www.acmesystems.it/python_http, muestra como enviar otros
# archivos ademas del HTML
# - https://goo.gl/i7hJYP, muestra como construir un mensaje de respuesta
# correcto en HTTP
if __name__ == "__main__":
sys.exit(main())
|
2273e97e1b7e653abb73412a11ec00bf86da130a | psymen145/LeetCodeSolutions | /965.univalued-binary-tree.py | 1,075 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
# bfs -> queue
if not root:
return True
t_val = root.val
q = [root]
while q:
node = q.pop(0)
if node:
q.append(node.left)
q.append(node.right)
if t_val != node.val:
return False
return True
def _isUnivalTree(self, root: TreeNode) -> bool:
# dfs -> recursion
if not root:
return True
if root.right and root.right.val != root.val:
return False
if root.left and root.left.val != root.val:
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
|
91a5f389132a5453fc7a6a2696a521c39ca92adf | CodyDeepPlay/LeetCodePractice | /Q345_ReverseVowels.py | 2,649 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 10 23:13:41 2021
@author: mingmingzhang
345. Reverse Vowels of a String
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.
Example 1:
Input: s = "hello"
Output: "holle"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
"""
class Solution:
'''
Solution 1,
find the vowels first, and reserve them
'''
def reverseVowels(self, s: str) -> str:
vowels = ["a", "e","i", "o", "u", "A", "E","I", "O", "U", ]
# find any possible vowels
idx_list = []
for n in range(len(s)):
if s[n] in vowels: idx_list.append(n)
# no vowel or just 1 vowel found
if len(idx_list)==0 or len(idx_list)==1: return s
# two or more vowels are found
left=0; right=len(idx_list)-1;
while left<right:
temp_left = s[idx_list[left]]
temp_right = s[idx_list[right]]
# replace the left found vowel
s = s[0:idx_list[left]] + temp_right + s[idx_list[left]+1:]
# replace the right found vowel
s = s[0:idx_list[right]] + temp_left + s[idx_list[right]+1:]
left +=1
right -=1
return s
'''
Solution 2,
One for loop starting from beginning,
if a vowel found, then starting from the end backwards to conduct next search
if found a vowel, then swap the previous finding.
Then continue this process
'''
def reverseVowels2(self, s: str) -> str:
if len(s)==1 or len(s)==0: return s
vowels = ["a","e","i","o", "u","A","E","I","O","U"]
right_end = len(s)-1
for l in range(right_end+1): # will include 0 to right_end, so plus 1 here to include right_end
# find vowel on the left side
if s[l] in vowels:
for r in range(right_end, l, -1):
# find vowel on the right side
if s[r] in vowels:
temp = s[l] # extract the left
s = s[0:l] + s[r] + s[l+1:] # put right into left
s = s[0:r] + temp + s[r+1:] # put left into right
right_end = r-1 # already found at vowel in right side, so next iteration will not include this one
break # finish one finding, will break the right side search
return s
|
b281fbd7a81dbfdab11ca5f23e7bfa72d0c956e6 | vincentchen1/learnpython | /Chapter 8/pets.py | 1,809 | 4.3125 | 4 | #positional arguments match each argument in the function call with a parameter in the function definition
#order matters in positional arguments
def describe_pet(animal_type, pet_name):
"""Display information about a pet"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('dog', 'luna')
describe_pet('chicken', 'max')
#a keyword argument is a name-value pair that you pass to a function
#they free you from having to worry about correctly ordering your arguments in the function call and they clarify the role of each value in the function call
def describe_pet(animal_type, pet_name):
"""Display information about a pet"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster', pet_name='harry')
#you can also set a default value
#with no animal_type specified, python knows to use the value 'dog' for this parameter
def describe_pet(pet_name, animal_type = 'dog'):
"""Display information about a pet"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')
#you could also just put the name of the dog since it is the only argument and matches up to the first parameter in the definition pet_name
#because no argument is provided for animal_type, it uses the default value 'dog'
describe_pet('willie')
#recap: these are equivalent functions
#to avoid errors, make sure there are function arguments for the parameter
# A dog named Willie.
describe_pet('willie')
describe_pet(pet_name='willie')
# A hamster named Harry.
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry') |
86cfee87cfa73ede55783fb2035ab6d288ce1efb | breezekiller789/LeetCode | /378_Kth_Smallest_Element_In_A_Sorted_Matrix.py | 764 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
# 用binary search,先把matrix每一個element取出來放在Array裡,然後Sort Array,
# 最後再用binary search就可以找到了。
matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]]
k = 5
# ==============Code Starts===============
Array = []
for i in matrix: # O(n^2)
Array.extend(i) # 先把matrix所有element都取出來
Array = sorted(Array) # Sort, O(n^2 * logn)
low = 0
high = len(Array)-1 # Binary Search, O(logn)
while low <= high:
mid = (low+high)/2
if mid+1 == k:
print Array[mid]
break
elif mid+1 > k:
high = mid - 1
elif mid+1 < k:
low = mid + 1
|
dcf92a5f08d2936029e6578b9163213b56a277ff | s-m-kashani98/loopFinder | /Finder.py | 688 | 3.84375 | 4 |
loop= []
def addToLoop(x):
if loop[0] == x:
return True
loop.append(x)
return False
def makeStep(a,pos):
temp = []
for i in a:
if pos[1] == i[0]:
temp.append(i)
return temp
def loopFinder(a,pos):
step = makeStep(a,pos)
for k in step:
x = addToLoop(k)
if(x):
return True
else:
if loopFinder(a,k):
return True
else:
loop.pop()
return False
def thereIsLoop(a):
flag = False
for i in a:
loop.append(i)
if loopFinder(a,i):
flag = True
break
loop.pop()
return flag
|
add5efba749583c0fbef0ac6b62091002d206211 | karankrw/Data-Structures-and-Algorithms | /Algorithms on Graphs/Week 1 - Decomposition 1/Reachability.py | 777 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 22:08:34 2020
@author: karanwaghela
"""
def reach(adj, x, y):
visited = [0] * len(adj)
return explore(adj, x, y, visited)
def explore(adj, x, y, visited):
if x == y:
return 1
visited[x] = 1
for i in range(len(adj[x])):
if (not visited[adj[x][i]]):
if (explore(adj, adj[x][i], y, visited)):
return 1
return 0
if __name__ == '__main__':
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for i in range(m):
a, b = map(int, input().split())
# adjacency list
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
x, y = map(int, input().split())
print(reach(adj, x-1, y-1)) |
5161fac9a2b584dd2525bf75dd51d2e3d02926b5 | oknashar/interview-preparation | /googlePY/OA/Maximum-Time.py | 1,498 | 3.828125 | 4 | '''
ref: https://leetcode.com/discuss/interview-question/396769/
You are given a string that represents time in the format hh:mm. Some of the digits are blank (represented by ?). Fill in ? such that the time represented by this string is the maximum possible. Maximum time: 23:59, minimum time: 00:00. You can assume that input string is always valid.
Example 1:
Input: "?4:5?"
Output: "14:59"
Example 2:
Input: "23:5?"
Output: "23:59"
Example 3:
Input: "2?:22"
Output: "23:22"
Example 4:
Input: "0?:??"
Output: "09:59"
Example 5:
Input: "??:??"
Output: "23:59"
'''
def sol(string):
finalStr = ''
maxRanges = {
0:(1 if string[1] != '?' and int(string[1]) > 3 else 2),
1: 9,
2:':',
3:5,
4:9}
for i in range(len(string)):
if i == 1 and string[i] == '?' and finalStr[0] == '2':
finalStr += '3'
else:
finalStr += str(maxRanges[i]) if string[i] == '?' else string[i]
return finalStr
print(sol("?4:5?"))
print(sol("23:5?"))
print(sol("2?:22"))
print(sol("1?:?2"))
print(sol("2?:?2"))
print(sol("??:??"))
print(sol("23:5?"))# 23:59
print(sol("2?:22"))# 23:22
print(sol("0?:??"))# 09:59
print(sol("1?:??"))# 19:59
print(sol("?4:??"))# 14:59
print(sol("?3:??"))# 23:59
print(sol("??:??"))# 23:59
print(sol("?4:5?"))#14:59
print(sol("?4:??"))#14:59
print(sol("?3:??"))#23:59
print(sol("23:5?"))#23:59
print(sol("2?:22"))#23:22
print(sol("0?:??"))#09:59
print(sol("1?:??"))#19:59
print(sol("?4:0?"))#14:09
print(sol("?9:4?"))
|
58e1a1395b0ef8642803d2bdaf45d6580c1dd5f2 | katerina-ash/Python_tasks | /Вычисления/Разность времени.py | 1,122 | 4.125 | 4 | # Задача «Разность времени»
# Условие
# Даны значения двух моментов времени, принадлежащих одним и тем же суткам:
# часы, минуты и секунды для каждого из моментов времени. Известно,
# что второй момент времени наступил не раньше первого. Определите,
# сколько секунд прошло между двумя моментами времени.
# Программа на вход получает три целых числа: часы, минуты, секунды,
# задающие первый момент времени и три целых числа, задающих
# второй момент времени.
# Выведите число секунд между этими моментами времени.
h1 = int( input() )
m1 = int( input() )
s1 = int( input() )
h2 = int( input() )
m2 = int( input() )
s2 = int( input() )
mom1 = h1*60*60+m1*60+s1
mom2 = h2*60*60+m2*60+s2
s3 = mom2-mom1
print(s3)
|
c917d9dc87548ceca8bfe1eda10ac9e45c006eda | ps-raghotham-rao/Learning-Python | /Python/linkedlist+bst.py | 1,026 | 4.15625 | 4 | # class Node:
# def __init__(self,key):
# self.left = None
# self.right = None
# self.value = key
# # A function to insert a new node with the given key value
# def insert(root,node):
# if root is None:
# root=node
# else:
# if root.value<node.value:
# if root.right is None:
# root.right=node
# else:
# insert(root.right,node)
# else:
# if root.left is None:
# root.left = node
# else:
# insert(root.left,node)
# # A function for inorder tree traversal
# def inorder(root):
# if root:
# inorder(root.left)
# print(root.value)
# inorder(root.right)
# root= Node(3)
# insert(root,Node(5))
# insert(root,Node(2))
# insert(root,Node(4))
# insert(root,Node(11))
# inorder(root)
def trav(f):
while f != None:
print(f.data)
f=f.next
class Node:
def __init__(self,data):
self.next=None
self.data = data
f=c=Node(1)
while True:
data=input("Enter data ")
if data == "-1":
break
c.next=Node(data)
c=c.next
trav(f) |
41aa6d30cc7aecfb5f547354731cd59b2b50ea7f | ec0629/python-recipes | /002-truthiness.py | 380 | 3.703125 | 4 | # Data Science from Scratch by Joel Grus
# all takes an iterable and returns True if all values are Truthy
print(all([True, 1, []])) # False since [] is Falsy
# any takes an iterable and returns True if any values are Truthy
print(any([False, [], 1]))
x = None
# always return a number
safe_x = x or 0
print(safe_x)
# alternative
safe_x = x if x is not None else 0
print(safe_x)
|
c6d6b199a9847579e7a6576828901157fcc7329c | anshu-pathak/python-basic | /Basic-Programs/add_two_num.py | 261 | 3.9375 | 4 | x = 10
y = 20
z = x + y
print(z)
# Performe the add operation on the bases of the user enter values.
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
print(sum) |
be485b7c3a1329d83141cdff21597f1db80c751f | c-eng/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 600 | 3.53125 | 4 | #!/usr/bin/python3
"""lists all cities from the database hbtn_0e_4_usa
"""
if __name__ == "__main__":
import MySQLdb
from sys import argv
db = MySQLdb.connect(user=argv[1], passwd=argv[2], host='localhost',
port=3306, db=argv[3])
cursor = db.cursor()
cursor.execute("SELECT cities.id, cities.name, states.name "
"FROM cities JOIN states ON cities.state_id = states.id "
"ORDER BY cities.id")
states = cursor.fetchall()
cursor.close()
db.close()
for state in states:
print("{}".format(state))
|
e6cf7abd7bf1b9cc74b32b4e5574c6c1c9921466 | daniel-reich/turbo-robot | /EWZqYT4QGMYotfQTu_20.py | 2,309 | 4.125 | 4 | """
Tap code is a way to communicate messages via a series of taps (or knocks) for
each letter in the message. Letters are arranged in a 5x5 _polybius square_ ,
with the letter "K" being moved to the space with "C".
1 2 3 4 5
1 A B C\K D E
2 F G H I J
3 L M N O P
4 Q R S T U
5 V W X Y Z
Each letter is translated by tapping out the _row_ and _column_ number that
the letter appears in, leaving a short pause in-between. If we use "." for
each tap, and a single space to denote the pause:
text = "break"
"B" = (1, 2) = ". .."
"R" = (4, 2) = ".... .."
"E" = (1, 5) = ". ....."
"A" = (1, 1) = ". ."
"K" = (1, 3) = ". ..."
Another space is added between the groups of taps for each letter to give the
final code:
"break" = ". .. .... .. . ..... . . . ..."
Write a function that returns the tap code if given a word, or returns the
translated word (in lower case) if given the tap code.
### Examples
tap_code("break") ➞ ". .. .... .. . ..... . . . ..."
tap_code(".... ... ... ..... . ..... ... ... .... ....") ➞ "spent"
### Notes
For more information on tap code, please see the resources section. The code
was widely used in WW2 as a way for prisoners to communicate.
"""
def tap_code(n):
if("." not in n):
a=[["a","b","ck","d","e"],["f","g","h","i","j"],["l","m","n","o","p"],["q","r","s","t","u"],["v","w","x","y","z"]]
ans=''
for i in n:
row=0
col=0
if(i=="c" or i=="k"):
row=0
col=2
else:
while(row<5):
check=0
col=0
while(col<5):
if(a[row][col]==i):
check=1
break
col+=1
if(check==1):
break
row+=1
row+=1
col+=1
aa="."*row+" "
bb="."*col+" "
ans+=(aa+bb)
return ans[0:len(ans)-1]
else:
a=[["a","b","c","d","e"],["f","g","h","i","j"],["l","m","n","o","p"],["q","r","s","t","u"],["v","w","x","y","z"]]
n=n.split(" ")
i=list()
j=list()
for x in range(0,len(n),2):
i.append(len(n[x])-1)
for x in range(1,len(n),2):
j.append(len(n[x])-1)
ans=''
for x in range(0,len(i)):
ans+=a[i[x]][j[x]]
return ans
|
7e5579cd4bf62a8c5b5dcaa52dd86b2dc6236b9a | satfail/Python | /02_Fundamento/loops2.py | 317 | 4.1875 | 4 | coches = ["ok","ok","ok","ok","ok","ok","ok"]
for estado in coches:
if estado == "error":
print("Se paro la linea de producción")
break
print(estado)
else:
print("Todos los coches estan bien")
#En python podemos poner un else a un loop y si no encuentra
#un break da la salida del else! |
a563186d64ba9f92dc3f52dca156b90545e0f61b | dondon17/algorithm | /BOJ/2630.py | 556 | 3.546875 | 4 | import sys
myinput = sys.stdin.readline
n = int(myinput())
tree = [list(map(int, myinput().split())) for _ in range(n)]
cnt = [0, 0]
def quadTree(y, x, n):
base = tree[y][x]
flag = True
for row in range(y, y+n):
for col in range(x, x+n):
if tree[row][col] != base:
quadTree(y, x, n//2)
quadTree(y+n//2, x, n//2)
quadTree(y, x+n//2, n//2)
quadTree(y+n//2, x+n//2, n//2)
return
cnt[base] += 1
quadTree(0, 0, n)
for e in cnt:
print(e)
|
ebb812faa546ab844dbad77ab347e0e52f551396 | mragankyadav/LeetCode_Solved | /sudokuSolver.py | 1,615 | 3.75 | 4 | class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
for i in range(len(board)):
board[i]=list(board[i])
self.solver(board)
def solver(self,board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]==".":
for k in range(1,10):
if self.checkrow(str(k),i,j,board)==False and self.checkcol(str(k),i,j,board)==False and self.checksq(str(k),i,j,board)==False:
board[i][j]=str(k)
ans=self.solver(board)
if ans==True:
return True
else:
board[i][j]='.'
return False
return True
def checkrow(self,val,i,j,board):
for k in range(len(board[0])):
if val ==board[i][k]:
return True
return False
def checkcol(self,val,i,j,board):
for k in range(len(board)):
if val ==board[k][j]:
return True
return False
def checksq(self,val,i,j,board):
srow=i/3
scol=j/3
srow*=3
scol*=3
for m in range(srow,srow+3):
for n in range(scol,scol+3):
if board[m][n]==val:
return True
return False |
694f64f6e0046a30f881fe86258d44c2988bcea3 | dgurjar/monopoly_ai_simulator | /monopoly_ai_sim/auction.py | 1,545 | 3.640625 | 4 | from monopoly_ai_sim.board import RentIdx
from random import shuffle
class MonopolyAuctionItem:
def __init__(self, name, item=None):
self.name = name
self.item = item
class MonopolyAuction:
def __init__(self, auction_item, players):
self.auction_item = auction_item
# You aren't allowed to auction an item with houses on it
# Make sure that the item doesn't have any
if auction_item.name == "BoardPosition":
if self.auction_item.rent_idx >= RentIdx.HOUSE_1:
raise ValueError("Auction created for a property with houses, \
only properties without any buildings are allowed to be auctioned")
self.last_offer = 0
self.current_winner = None
self.players = players[:] # Create a copy of the players in the game
# Randomly create a play order
def get_auction_winner(self):
shuffle(self.players) # Choose a random auction order each time!
offer_updated = True
while offer_updated:
offer_updated = False
for player in self.players:
offer = player.handle_auction_turn(self)
# Register the offer if it is better than the previous offer,
# and if the player can afford to pay it!
if self.last_offer < offer < player.get_asset_value():
offer_updated = True
self.current_winner = player
self.last_offer = offer
return self.current_winner
|
ef5547c1185c34cfdb497e814c3fb2b1a6963b9b | alankrit03/LeetCode_Solutions | /82. Remove Duplicates from Sorted List II.py | 995 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
curr = None
while head:
if head.next:
if head.val == head.next.val:
curr = head.val
if curr == head.val:
head = head.next
else:
break
if not head:
return
ptr = head.next
ptr1 = head
curr = None
while ptr:
if ptr.next:
if ptr.val == ptr.next.val:
curr = ptr.val
if curr == ptr.val:
ptr = ptr.next
else:
ptr1.next = ptr
ptr1 = ptr1.next
ptr = ptr.next
ptr1.next = ptr
return head
|
7decbc49788a3161cfb56fcc61a62a63bf84ec93 | samwasden/data_python | /data_presenter.py | 1,622 | 3.609375 | 4 | import plotly.graph_objects as go
file = open("CupcakeInvoices.csv")
cupcakes = []
invoice_totals = []
all_invoices = 0
#variables I created to store data to be used for data visualization
choc = []
van = []
straw = []
#Parsing through the csv file and saving the data I need
for line in file:
print(line)
currentLine = line.split(",")
cupcakes.append(currentLine[2])
total = float(currentLine[3])*float(currentLine[4])
invoice_totals.append(total)
all_invoices += total
file.close()
#Printouts of the multiple arrays I created from the csv file.
print()
for i in range(len(cupcakes)):
if cupcakes[i] == "Chocolate":
choc.append(round(invoice_totals[i],2))
elif cupcakes[i] == "Vanilla":
van.append(round(invoice_totals[i],2))
elif cupcakes[i] == "Strawberry":
straw.append(round(invoice_totals[i],2))
print(cupcakes[i])
print()
#Formatting for the data display. Unsure where the extra digits are coming from in certain prints so I formatted to 2 decimal points
for invoice in invoice_totals:
print(round(invoice,2))
print()
print(round(all_invoices,2))
#below is in largely code that I found in the plotly documentation for displaying data in a browser.
large_rockwell_template = dict(
layout=go.Layout(title_font=dict(family="Rockwell", size=24))
)
fig = go.Figure(data=go.Bar(y=[round(sum(choc),2), round(sum(van),2), round(sum(straw),2)],x=["Chocolate", "Vanilla", "Strawberry"]))
fig.update_layout(yaxis_tickformat = '$')
fig.update_layout(title="Best-Selling Cupcakes", template=large_rockwell_template)
fig.show() |
7a2140c8a43584de078213b6c40ac3c922796bb9 | atsushinee/leetcode | /leetcode/496. 下一个更大元素 I.py | 2,252 | 4 | 4 | """
给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
示例 1:
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
示例 2:
输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于num1中的数字2,第二个数组中的下一个较大数字是3。
对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。
注意:
nums1和nums2中所有元素是唯一的。
nums1和nums2 的数组大小都不超过1000。
"""
from typing import List
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stack = []
d = {}
ans = []
for n in nums2:
while len(stack) != 0 and stack[-1] < n:
d[stack.pop()] = n
stack.append(n)
nums1_len = len(nums1)
for i in range(nums1_len):
ans.append(d.get(nums1[i], -1))
return ans
def nextGreaterElement1(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans = []
nums1_len = len(nums1)
nums2_len = len(nums2)
for i in range(nums1_len):
m = -1
for j in range(nums2_len):
if nums2[j] == nums1[i] and j != nums2_len - 1:
k = j + 1
while k < nums2_len:
if nums2[k] > nums1[i]:
m = nums2[k]
break
k += 1
ans.append(m)
return ans
if __name__ == '__main__':
nums1 = [4, 1, 2]
nums2 = [1, 3, 4, 2]
print(Solution().nextGreaterElement(nums1, nums2))
|
7219d65cbe2124e2e937a33aaaa722fa4e4ebc2e | ThomasZumsteg/project-euler | /problem_0133.py | 1,005 | 3.515625 | 4 | #!/usr/bin/python
"""http://projecteuler.net/problem=133"""
from time import time
from itertools import count
from common import prime_generator
from sys import stdout
def main():
big_num = 100000
prime_sum = 2 + 3 + 5
for p in prime_generator(block=100100):
if p <= 5: continue
if p >= big_num: break
stdout.write("%d\r" %(p))
stdout.flush()
if not match(p):
prime_sum += p
print "Sum of all primes with property is %d" %(prime_sum)
def has_other_factors(n, factors):
for f in factors:
while n % f == 0:
n /= f
return n != 1
def match(n):
return not has_other_factors(A(n), (2, 5))
def has_match_old(n):
seen = set()
for i in count(1):
rem = pow(10, 10**i, 9*n)
if rem == 1: return True
elif rem in seen: return False
#print rem
seen.add(rem)
#if i > 20: break
def A(n):
rep = 1
for i in count(1):
rep %= n
if rep == 0:
return i
rep = rep * 10 +1
if __name__ == "__main__":
start = time()
main()
print "That took %f seconds" %(time() - start) |
b1b5100e358850d7cbbb8f94bccc46c67a67ec7f | PerryP1/AdvanceDataAnalyticsBootcamp | /EmployeePay.py | 330 | 3.6875 | 4 | import sys
print('Name is :', sys.argv[1])
print('Pay Rate :', sys.argv[2])
print('Hours :', sys.argv[3])
name = sys.argv[1]
payrate = int(sys.argv[2])
hours = int (sys.argv[3])
if hours <= 40:
pay = payrate *hours
else:
othours = hours - 40
pay = 40 * payrate + othours * 1.5 * payrate
print ("Pay is ", pay)
|
746f78352cb843912d13f9705c3eae17bbd708d6 | olaborde/-Google-IT-Automation-with-Python | /Using Python To Interact With OS/coursera/week3/Basic Regular Expressions/wildcards.py | 1,172 | 4.5625 | 5 | import re
'''
Character classes are written inside square brackets and let us list the characters we want to match inside of those brackets
'''
print(re.search(r"[Pp]ython", "Python"))
print(re.search(r"[a-z]way", "The end of the highway"))
print(re.search(r"[a-z]way", "What a way to go"))
print(re.search(r"cloud[a-zA-Z0-9]", "cloudy"))
print(re.search(r"cloud[a-zA-Z0-9]", "cloud9"))
'''
Sometimes we may want to match any characters that aren't in a group. To do that, we use a circumflex inside the square brackets.
'''
print(re.search(r"[^a-zA-Z]", "This is a sentence with spaces."))
print(re.search(r"[^a-zA-Z ]", "This is a sentence with spaces."))
# print(re.search(r"[^a-zA-Z \.]", "This is a sentence with spaces."))
print(re.search(r"dog|cat", "I like cats"))
print(re.search(r"dog|cat", "I like dogs"))
print(re.findall(r"dog|cat", "I like both dogs and cats"))
# Repetition Qualifiers
print(re.search(r"Py.*n", "Pygmalion"))
print(re.search(r"Py[a-z]*n", "Python Programming"))
# The plus character matches one or more occurrences of the character that comes before it.
print(re.search(r"o+l+", "goldfish"))
print(re.search(r"o+l+", "woolly"))
|
f5d570b9404a5ddcf35749a9d7be20f8dd584105 | CircuitLaunch/CoLab-Reachy | /software/Motor_Control_Scripts/Step1_Camera_Rasp_pi_wKeyBoardInput.py | 1,483 | 3.59375 | 4 | '''
This is a code that runs on Rasp pi.
What it does: Allowing the user to input keyboard commands and communicate
them (say number 1 or 0) over I2C.
Rasp Pi controls the Arduino
'''
from picamera import PiCamera
from time import sleep
import sys
from smbus2 import SMBus
addr = 0x8 # bus address
bus = SMBus(1) # indicates /dev/ic2-1
numb = 1
camera = PiCamera()
print ("Enter 1 for ON or 0 for OFF")
while numb == 1:
ledstate = input(">>>> ")
if ledstate == "1":
camera.start_preview(alpha=200) # Add alpha parameter to make it slightly see through in ops - adjust to different resolution
sleep(5) # at least 2 seconds so that camera can sense lighting conditions
camera.capture('testimage_loop1.jpg') # change location and file name, if needed
camera.stop_preview()
bus.write_byte(addr, 0x1) # switch it on
elif ledstate == "0":
bus.write_byte(addr, 0x0) # switch it on
camera.start_preview(alpha=200) # Add alpha parameter to make it slightly see through in ops - adjust to different resolution
sleep(5) # at least 2 seconds so that camera can sense lighting conditions
camera.capture('testimage_loop2.jpg') # change location and file name, if needed
camera.stop_preview()
else:
numb = 0
sys.exit() # esc in case of issues, added to make sure no system hang
|
56963aaeb87c5b89e64a416d3b97d56cc572d7a5 | gauravsonawane01/Exercises | /Decorator_ex.py | 656 | 3.84375 | 4 | """
Write different methods for addition,substraction,division,multiplication of number.
Write decoratoe which will call above methods only id
1.Only 2 input values are allowed
2.Both inputs should be of type integer
3.Both input values are positive integer only
"""
def add(a,b):
print(a+b)
def substract(a,b):
print(a-b)
def div(a,b):
print(a/b)
def mul(a,b):
print(a*b)
def decorator(fnc):
def wrapper(a,b):
if(isinstance(a, int) and isinstance(b, int) and a>0 and b>0):
return fnc(a,b)
else:
return print("Enter int value")
return wrapper
add = decorator(add)
add(4,4)
mul(2,2)
|
40fd3314630da5c008da2d49e523cdb07aa13936 | candilek/Python-Projeler | /Atm_makinesi.py | 1,045 | 3.5625 | 4 | print("""*****************************
Atm Makinesine Hoşgeldiniz.
İşlemler;
1-Bakiye Sorgulama
2-Para Yatırma
3- Para Çekme
4-Havale
Programdan çıkmak için q'ya basın.
***************************************
""")
bakiye =1000
while True:
işlem= input("işlemi seçiniz: ")
if (işlem == "q"):
print( "Yine Bekleriz.:)" )
break
elif(işlem== "1"):
print("Bakiyeniz: {} tl'dir.".format(bakiye))
elif(işlem == "2"):
miktar=int(input("yatırılacak para miktarını giriniz: "))
bakiye +=miktar
elif(işlem== "3"):
miktar=int(input("para miktarını giriniz: "))
if(bakiye - miktar <0):
print("Böyle bir miktar çekemessiniz.")
continue
bakiye -= miktar
elif(işlem=="4"):
havale=int(input("Havale edilecek miktarı girin: "))
bakiye-=havale
print("bakiyeniz: {} tl'dir".format((bakiye)))
else:
print("geçersiz işlem")
|
9d570c03fd375880356ba9a630a368b81a74b72f | spettigrew/cs-module-practice1 | /formatted_strings.py | 323 | 4.0625 | 4 | """
1. Assign three different types of data to the three variables "a", "b", and "c".
2. Use a format string to inject the data from your three variables into the string.
"""
# Modify the code below to meet the requirements above.
a = "Colette's Birthday!"
b = 6
c = 9.30
print("Yay! It's %s Age: %d. Date: %.2f." % (a, b, c)) |
d6d67130cb8f1a33eeb73d7ddcfe6db371ae90cf | SparksFlyMe/python_learning | /forDemo.py | 1,096 | 4.09375 | 4 | # author: KaiZhang
# date: 2021/8/3 22:16
for letter in 'Python': # 第一个实例
print("当前字母: %s" % letter)
pass
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print('当前水果: %s' % fruit)
pass
# 通过序列索引迭代
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print('当前水果 : %s' % fruits[index])
pass
# 循环使用 else 语句
"""for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。"""
for i in range(5):
if i > 3:
print(i)
else:
print('hello world') # for循环正常执行完了,所以会打印
for i in range(5):
if i > 3:
print(i)
break
else:
print('hello world') # for循环被提前终止了,所以不会打印hello world
pass
# 如果在循环中不需要使用到自定义变量,可将自定义变量写为“_”下划线
for _ in range(5):
print("haha")
|
3d1bdc750f809164a722d54ead0d0173b3801611 | jagadeeshwithu/Data-Structures-and-Algos-Python | /BubbleSort.py | 450 | 4.15625 | 4 | """
Bubble Sort implementation
Time complexity: O(n2)
Space complexity: O(1)
"""
def BubbleSort(inputlist):
n = len(inputlist)
if n <= 1:
return inputlist
for i in range(n):
for j in range(1, n):
if inputlist[j-1] > inputlist[j]:
inputlist[j-1], inputlist[j] = inputlist[j], inputlist[j-1]
return inputlist
if __name__ == "__main__":
print(BubbleSort([1, 3, 8, 5, 6, 4])) |
9c82f9823a05c17571af59c16f64f8cc6e6002ea | xavierwwj/socket_test | /non_daemon_thread.py | 1,758 | 4.09375 | 4 | """
- For non-daemon threads, the program will wait till these threads are done at the end of the program before exiting
- Specifically, at the end of the program, there will be a call .join() for the non-daemon alive threads.
- This is a blocking call that awaits completion of the thread.
- If you look at the source for Python threading, you’ll see that threading._shutdown() walks through all of the
running threads and calls .join() on every one that does not have the daemon flag set.
- Experiment:
- thread1.start(), thread2.start(), end prog
- thread1.start(), thread1.join(). thread2.start() end prog
- Compare the two, at the end of the program, join will be called implicitly, so we omit the necessary ones
- Result:
- Case 1 -> concurrency
- Case 2 -> One after another
"""
import threading
import time
def test_func(thread_no):
print("thread_no: " + str(thread_no))
time.sleep(2)
# Setting time.sleep will block the thread. This means that the processor will go ahead with the other thread first
# Removing this will result in the thread reaching completion first.
print("thread_no " + str(thread_no) + " completed")
thread1 = threading.Thread(target = test_func, args = (1,))
thread2 = threading.Thread(target = test_func, args = (2,))
print("Experiment 1 Start")
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Experiment 1 Complete")
thread3 = threading.Thread(target = test_func, args = (3,))
thread4 = threading.Thread(target = test_func, args = (4,))
time.sleep(5)
print("Experiment 2 Start")
thread3.start()
thread3.join()
thread4.start()
thread4.join() # Here we explicitly wait for thread to end then print afterwards
print("Experiment 2 Complete")
|
bf5e303b370032a71b6f4c3f5432241c16460d47 | andyundso/python-exercises | /P05/1_3_Vangsted_Fixed.py | 2,319 | 3.84375 | 4 | ##############################
# P05 - 1.3 Battleship
##############################
# Import
import random
import copy
import sys
##############################
# Definitionen
def spielbrett_neu():
'''
Neues Spielbrett erzeugen
'''
global board
row = [" O"] * 10
for a in range(15):
board.append(row[:])
def spielbrett_verdeckt():
'''
Schiff auf verdecktem Spielbrett einzeichnen
'''
global board_verdeckt
zeile_verdeckt = random.randint(0, 9)
spalte_verdeckt = random.randint(0, 14)
print(zeile_verdeckt)
print(spalte_verdeckt)
print(board_verdeckt)
board_verdeckt[spalte_verdeckt][zeile_verdeckt] = " S"
def spielbrett_ausgabe(spielbrett):
'''
Print Funktion für das Spielbrett
'''
for ab in range(0, 15):
print(''.join(spielbrett[ab]))
def spielbrett_pruefen(column, row):
'''
Überprüft Spielbrett und fügt Zeichen auf Spielbrett
'''
global board_verdeckt
global board
if " S" == board_verdeckt[column - 1][row - 1]:
board[column - 1][row - 1] = " S"
return True
else:
board[column - 1][row - 1] = " X"
return False
##############################
# Spiel
board = list()
spielbrett_neu()
board_verdeckt = copy.deepcopy(board)
spielbrett_verdeckt()
spielbrett_ausgabe(board)
for a in range(0, 11):
print("Sie haben noch " + str(10 - a) + " Versuche übrig.")
b = int(input("Zeile eingeben: ")) - 1
c = int(input("Spalte eingeben: ")) - 1
if 0 <= b <= 14 and 0 <= c <= 9:
d = spielbrett_pruefen(b, c)
if d:
print('''Herzlichen Glückwunsch,
Sie haben das Schiff versenkt.
''')
spielbrett_ausgabe(board)
z = input("Drücken Sie Enter um das Spiel zu beenden.")
sys.exit()
if not (d):
print('''Sie haben das Schiff nicht getroffen.
Probieren Sie es noch einmal.''')
spielbrett_ausgabe(board)
z = input("Drücken Sie Enter zum Fortfahren des Spiels.")
else:
print('''Bitte geben Sie einen Punkt innerhalb des Speilfelds an.
''')
spielbrett_ausgabe(board)
z = input("Drücken Sie Enter zum Fortfahren des Spiels.")
|
22e3bfadd94fbdb53aab71f716e03af21ce226e1 | InternalHell/Algorithms-Python | /selection_sort.py | 343 | 3.90625 | 4 | from random import *
def selection_sort(list):
for i in range(len(list)-1):
for j in range(i+1, len(list)):
if list[j] < list[i]:
list[i], list[j] = list[j], list[i]
return list
list = [randint(1, 1000) for i in range(10)]
print(f'Your start list: {list}\nSorting list: {selection_sort(list)}')
|
f1e19a700c57d73801ceb8bab0dec548836ae4ba | fuyangchang/Practice_Programming | /LearnPythonHardWay/ex40.py | 848 | 3.78125 | 4 | # -*- coding: utf-8 -*-
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
print type(self)
def sing_me_a_song(self):
for line in self.lyrics:
print line
def sing_me_twice(self):
for line in self.lyrics:
print line
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday",
"Since I don\'t want to be sued",
"I'll stop here."])
bulls_on_parade = Song(["With bags full of shells",
"they gathered around the family."])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
oh_happy_day = Song(["Oh!",
"Happy",
"day!"])
oh_happy_day.sing_me_a_song()
print type(oh_happy_day)
oh_happy_day.sing_me_twice()
newLyrics = ["1", "2", "3"]
number_song = Song(newLyrics)
number_song.sing_me_a_song()
|
8e3c631b68e8816b5c0b96e25db2be44d10d3239 | usman-tahir/rubyeuler | /add_first_n_odd_int.py | 275 | 4.15625 | 4 | #!/usr/bin/env python
# add first n odd integers
def add_odd_integers(n):
def _add_odd_int(n,counter,next,acc):
if counter == n:
return acc
else:
return _add_odd_int(n,counter+1,next+2,acc+next)
return _add_odd_int(n,0,1,0)
print add_odd_integers(9) |
18d749524baf7679be685eeb4db1e2d997bc2eaf | shodhak/bio-playground | /utils/partsort.py | 4,025 | 3.71875 | 4 | #!/bin/env python
"""
partial sort of a file. Useful when some columns are known to be sorted, but
within a group defined by those column, some other columns are out of order.
e.g., if you have a bed file and you know it's already sorted by (or even
just grouped by) chromosome, you can sort by start, stop within the
chromosome without reading the entire bed-file into memory. The syntax for
that would be::
%(prog)s -g 0 -s 1n,2n my.bed > my.sorted.bed
where the 'n' suffix indicates that it's a number. The default is to
sort as a string.
"""
import argparse
from toolshed import reader, header as get_header
from itertools import groupby, chain
from operator import itemgetter
import sys
def partsort(afile, group_cols, sort_cols, sort_convertors, header=False):
"""
the converted columns are appended to the end of the row.
then after the sort, these are removed.
this removes problems with floating point reprs.
"""
the_first_line = get_header(afile)
row_len = len(the_first_line)
n_extra = len(sort_convertors)
# maintain order of the sort cols, but use the appended columns for the
# numeric ones.
actual_sort_cols = []
n_extra = 0
# since we append floats to the end *and* want to maintain the
# requested sort order, we create the `actual_sort_cols`
for c in sort_cols:
if not c in sort_convertors:
actual_sort_cols.append(c)
else:
idx = row_len + n_extra
actual_sort_cols.append(idx)
n_extra += 1
# if it was stdin, then we read one line to get the header length.
lines = reader(afile, header=header) if afile != "-" \
else chain([the_first_line], reader(afile, header))
# groupby the correct columns
for keyed, group in groupby(lines, lambda toks:
[toks[i] for i in group_cols]):
# then generate the rows with the converted columns appended.
def gen_converted_group():
for toks in group:
# add the converted columns onto the end.
yield toks + [fn(toks[col_idx]) for col_idx, fn in sort_convertors.items()]
# then iterator over the sorted cols.
for toks in sorted(gen_converted_group(), key=itemgetter(*actual_sort_cols)):
# strip the extra columns.
yield toks[:row_len]
def read_sort_spec(spec):
toks = [x.strip() for x in spec.split(",")]
col_idxs = map(int, (x.rstrip("n") for x in toks))
col_convertors = dict([(i, float) for i, x in enumerate(toks) \
if x[-1] == "n"])
return col_idxs, col_convertors
def main():
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("-g", dest="g", help="these 0-based column numbers define a"
" group and must already be sorted. Once these change, the group "
" ends and is sorted by the columns defined in option `-s`")
p.add_argument("-s", dest="s", help="these 0-based column numbers define"
"the columns to sort on. if the column to be sorted is numeric "
"(float or int) add a 'n'. e.g. -s 3n indicates that the 4th "
"column should be converted to a number before sorting")
p.add_argument('file', help='file to process', default="-")
args = p.parse_args()
if (args.g is None or args.s is None):
sys.exit(not p.print_help())
group_cols, group_convertors = read_sort_spec(args.g)
sort_cols, sort_convertors = read_sort_spec(args.s)
# group_convertors not used.
for toks in partsort(args.file, group_cols, sort_cols, sort_convertors, header=False):
print "\t".join(toks)
if __name__ == "__main__":
import doctest
if doctest.testmod(optionflags=doctest.ELLIPSIS |\
doctest.NORMALIZE_WHITESPACE).failed == 0:
main()
|
91c4442cea28cfd49f8c86552d1148b8fa75aa12 | raphamoral/Exercicicios_PythonBrazil_Mackenzie_PYTHONPRO | /Funções PythonBrasil/PythonBrasil Exercicio1duvida de def.py | 219 | 3.90625 | 4 | numero = int(input("Digite um numero"))
def imprimir_triangulo_de_numeros():
lista = [numero]
lista2 = lista * numero
for r in lista2:
listafinal = [r] * r
return(listafinal)
r += 1
|
7a3e8b9f62d89e21e01e6295ceff478fd52c706c | Sandbox4KidsTM/Python_Basics | /Supplemental_Material/PythonProjects/5. STRINGS/SEQUENCES & STRINGS.py | 189 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 5 07:04:31 2017
@author: Sandbox999
"""
filelist=list(range(2000,2020,2))
print(filelist)
for item in filelist:
print(item) |
7a5f3f0bdcfa000aa2e14af12e738bb5d5d02834 | Uthaeus/w3_python | /33.py | 379 | 4.28125 | 4 | # Write a Python program to sum of three given integers. However, if two values are equal sum will be zero.
def sum_of_three(a, b, c):
if a == b or a == c or b == c:
result = 0
else:
result = a + b + c
return result
print(sum_of_three(1, 2, 3))
print(sum_of_three(1, 2, 2))
print(sum_of_three(1, 1, 2))
print(sum_of_three(1, 2, 1))
print(sum_of_three(3, 3, 3)) |
8ac4e83aeac45db150cecd711c54a8633cf5282f | tracymeng2000/PyMaze | /grid.py | 2,356 | 3.59375 | 4 | from cell import Cell
from direction import Direction
from random import randint
class Grid:
def __init__(self, rows, cols):
self._rows = rows
self._cols = cols
self._grid = self.prepare_grid()
self.configure_cells()
@property
def rows(self):
return self._rows
@property
def cols(self):
return self._cols
@property
def __len__(self):
return self._rows * self._cols
def __getitem__(self, pos):
row, col = pos
if(row in range(0, self.rows) and col in range(0, self.cols)):
return self._grid[row][col]
else:
return None
def __iter__(self):
self.cur_row = 0
return self
def __next__(self):
if(self.cur_row < self.rows):
result = self._grid[self.cur_row]
self.cur_row += 1
return result
else:
raise StopIteration
def prepare_grid(self):
return [[Cell(row, col) for col in range(self._cols)]
for row in range(self._rows)]
def configure_cells(self):
for row, grid_row in enumerate(self._grid):
for col, cell in enumerate(grid_row):
cell.add_neighbor(Direction.north, self[row - 1, col])
cell.add_neighbor(Direction.south, self[row + 1, col])
cell.add_neighbor(Direction.west, self[row, col - 1])
cell.add_neighbor(Direction.east, self[row, col + 1])
def random_cell(self):
row = randint(0, self._rows - 1)
col = randint(0, self._cols - 1)
return self[row, col]
def __str__(self):
output = '+' + '---+' * self._cols + '\n'
for row in self._grid:
top = '|'
bottom = '+'
for cell in row:
if(cell is not None):
body = " " * 3
east_boundary = ' ' if (cell.linked(cell.east)) else '|'
top += body + east_boundary
south_boundary = ' ' * 3 if (cell.linked(cell.south)) else '-' * 3
corner = '+'
bottom += south_boundary + corner
output += top + '\n'
output += bottom + '\n'
return output
def __repr__(self):
return str(self)
|
43371076b595a042813d8545da4b24ba4a51556d | sfwarnock/python_programming | /chapter2/convert_exercises_2.4.py | 469 | 4.4375 | 4 | # convert.py
# A program to convert Celsius temps to Fahrenheit
#
# Pseudocode: Input the temperature in degrees Celsius (call it c)
# Calculate fahrenheit as (9/5) c + 32
# Print a table of Celsius temps and Fehrenhrit equivalents every 10 degrees from 0C to 100C.
def main():
c = -10
for temp in range(11):
c = c + 10
f = 9/5 * c + 32
print ("When it is",c,"degrees celsius, it is",f,"degrees fharenheit.")
main() |
e8bb981dcca99c926f98224830667e3572ebd716 | Ilijaxyz/pythonPath | /rockpaperscissors.py | 1,745 | 4.03125 | 4 | from random import choice
def endGame():
machine_choice = None
print("Play again? Y/N")
is_playing = input()
if is_playing and is_playing.lower().startswith("y"):
machine_choice = choice(["rock", "paper", "scissors"])
playGame(machine_choice)
else:
print("Thanks for playing, see you soon")
return machine_choice
def playGame(machine_choice):
player_choice = input("Plase enter your choice: ").lower()
if player_choice == machine_choice:
print(f"\nMachine played {machine_choice.upper()}")
print("DRAW!")
machine_choice = endGame()
if player_choice not in choices:
print("something went wrong")
machine_choice = endGame()
if machine_choice == "scissors":
print(f"\nMachine played {machine_choice.upper()}")
if player_choice == "rock":
print("YOU WIN!")
endGame()
elif player_choice == "paper":
print("YOU LOST!")
endGame()
if machine_choice == "rock":
print(f"\nMachine played {machine_choice.upper()}")
if player_choice == "paper":
print("YOU WON!")
endGame()
elif player_choice == "scissors":
print("YOU LOST!")
endGame()
if machine_choice == "paper":
print(f"\nMachine played {machine_choice.upper()}")
if player_choice == "rock":
print("YOU LOST!")
endGame()
elif player_choice == "scissors":
print("YOU WON!")
endGame()
choices = ["rock", "paper", "scissors"]
machine_choice = choice(["rock", "paper", "scissors"])
print("Welcome to ROCK, PAPER, SCISSORS VS the MACHINE!")
playGame(machine_choice)
|
3ebd80807b603749c5075e41c6974bf238831b70 | kaysiz/kenorb | /scripts/python/Quartz/mouse.py | 2,863 | 3.515625 | 4 | #!/usr/bin/python
# Script simulating mouse events in macOS.
# See: https://stackoverflow.com/q/281133/55075
import sys
from AppKit import NSEvent
import Quartz
class Mouse():
down = [Quartz.kCGEventLeftMouseDown, Quartz.kCGEventRightMouseDown, Quartz.kCGEventOtherMouseDown]
up = [Quartz.kCGEventLeftMouseUp, Quartz.kCGEventRightMouseUp, Quartz.kCGEventOtherMouseUp]
[LEFT, RIGHT, OTHER] = [0, 1, 2]
def position(self):
point = Quartz.CGEventGetLocation( Quartz.CGEventCreate(None) )
return point.x, point.y
def location(self):
loc = NSEvent.mouseLocation()
return loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y
def move_to(self, x, y):
moveEvent = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, Quartz.CGPointMake(x, y), 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, moveEvent)
def press(self, x, y, button=LEFT):
event = Quartz.CGEventCreateMouseEvent(None, Mouse.down[button], Quartz.CGPointMake(x, y), 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
def release(self, x, y, button=LEFT):
event = Quartz.CGEventCreateMouseEvent(None, Mouse.up[button], Quartz.CGPointMake(x, y), 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
def click(self, button=1):
x, y = self.position()
self.press(x, y, button)
self.release(x, y, button)
def click_pos(self, x, y, button=LEFT):
self.move_to(x, y)
self.click(button)
# Send click even to the app via its PID.
def click_via_pid(self, pid, x, y, button=LEFT):
pressEvent = Quartz.CGEventCreateMouseEvent(None, Mouse.down[button], Quartz.CGPointMake(x, y), 0)
releaseEvent = Quartz.CGEventCreateMouseEvent(None, Mouse.up[button], Quartz.CGPointMake(x, y), 0)
Quartz.CGEventPostToPid(pid, pressEvent)
Quartz.CGEventPostToPid(pid, releaseEvent)
def to_relative(self, x, y):
curr_pos = Quartz.CGEventGetLocation( Quartz.CGEventCreate(None) )
x += current_position.x;
y += current_position.y;
return [x, y]
def move_rel(self, x, y):
[x, y] = to_relative(x, y)
moveEvent = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, Quartz.CGPointMake(x, y), 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, moveEvent)
# DEMO
if __name__ == '__main__':
mouse = Mouse()
if sys.platform == "darwin":
print("Current mouse position: %d:%d" % mouse.position())
print("Moving to 100:100...");
#mouse.move_to(100, 100)
print("Clicking 200:200 position using the right mouse button...");
#mouse.click_pos(200, 200, mouse.RIGHT)
mouse.click_pos(100, 100)
mouse.click_via_pid(99725, 100, 100)
elif sys.platform == "win32":
print("Error: Platform not supported!")
|
6820cd52316dc5bca7f89c75c7e7a1a6972981dd | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv12.py | 1,154 | 4.09375 | 4 | # 12. Uma fruteira está vendendo frutas com a seguinte tabela de
# # preços:
# # Até 5 Kg Acima de 5 Kg
# # Morango R$ 2,50 por Kg R$ 2,20 por Kg
# # Maçã R$ 1,80 por Kg R$ 1,50 por Kg
# # Se o cliente comprar mais de 8 Kg em frutas ou o valor total da
# # compra ultrapassar R$ 25,00, receberá ainda um desconto de 10%
# # sobre este total. Escreva um algoritmo para ler a quantidade (em
# # Kg) de morangos e a quantidade (em Kg) de maças adquiridas e
# # escreva o valor a ser pago pelo cliente.
list = {"morango":[2.50,2.20], "maca": [1.80, 1.50]}
morango = float(input("qunatidade em kg de morando: "))
maca = float(input("qunatidade em kg de maça: "))
if morango <= 5:
valor_morando = list["morango"][0]
else:
valor_morando = list["morango"][1]
if maca <=5:
valor_maca = list["maca"][0]
else:
valor_maca = list["maca"][1]
total_kg = morango + maca
total_valor = (morango * valor_morando) + (maca * valor_maca)
if total_kg > 8 or total_valor > 25:
desconto = total_valor * 0.10
print("valor da total da compra com desconto: ",( total_valor -desconto))
else:
print("valor total da compra: ", total_valor) |
f25948c52fa6aef295232b8b7fa4ec49352cf245 | jeffsouza01/PycharmProjects | /Ex027 - PrimeiroUltimoNome.py | 453 | 4.03125 | 4 | '''
Exercício Python 027: Faça um programa que leia o nome completo de uma pessoa,
mostrando em seguida o primeiro e o último nome separadamente.
'''
nomec = str(input('Digite seu nome completo: ')).strip()
print(f'Muito prazer em te conhecer, {nomec}!')
nomeDividido = nomec.split()
primeiroNome = nomeDividido[0]
ultimoNome = nomeDividido[len(nomeDividido) - 1]
print(f'Seu primeiro nome: {primeiroNome}\n'
f'Seu ultimo nome: {ultimoNome}')
|
ec6b9a741e1d3876d203aa89375ef03c6c1fc9ef | felipmarqs/exerciciospythonbrasil | /exercicios de tuplas_listas_dicionários/vogais.py | 389 | 4.125 | 4 | #Crie um programa que tenha uma tupla com várias palavras(não usar acentos). DEpois disso, você deve mostrar para cada palavra quais sao as suas vogais
tupla = ('feijao','arroz','salada','batata','banana','brocolis','amora')
for p in tupla:
print(f"\n Na paralavra {p.upper()} temos ",end='')
for letra in p:
if letra.lower() in 'aeiou':
print(letra,end=' ') |
93c4a0bb5627e5715dca951272209f4e66829645 | asenal/loop2hash | /loop2hash.py | 1,700 | 3.796875 | 4 | #!/usr/bin/env python
#-*- coding=utf-8
import sys,re
import pprint
#-------- a naive config parser
def loop2hash(file,sep=None): # set config in param-list to enable config update.
'''
Loop a config file, split each line into key & value.
Usage: python $0 data/example.config
A config file is merely a plain text file with a key ~ value pair in each line.
In our situation, a config file follows guidelines below:
1. Text after '#' mark is regarded as annotation, empty lines will be ignored.
2. Field separator is either '\s+' or '=', choose and choose only one within a file,specify the corresponding one in loop2hash(file,sep=XX)
3. Wrap string with quotes: '0755-625384' or 'Shenzhen-08732'. leave digital value as it is.
4. Nested Python data structure 'tuple' & 'dictionary' is 'evaled' inside config parser,but don't use '=' as separator inside a dictionary.
5. Non-ascii key is supported but not recommended.
'''
config = {}
lines = open(file,'r').readlines()
for line in lines:
# ignore with annotations & empty lines
if re.search(r"(^\s*#)|(^\s$)",line):
continue
line = re.sub("#.*?$","",line)
# split line into key~value
key,value = line.strip().split(sep,1)
key = key.strip()
value = value.strip()
# if value is nested structure,evaluate it into Python tuple or dictionary
if '(' or '[' or '{' in value:
config[key] = eval(value)
# if value is simple string,read value as it is, '(,[,{' is abondoned
else:
config[key] = value
return config
if __name__=='__main__':
config_file = sys.argv[1]
print "===Now I'll read config from a plain text: %s." % config_file
GLOBAL_CONFIG = loop2hash(config_file)
pprint.pprint (GLOBAL_CONFIG)
|
b2e4a5f95eaba181c8ab655615ee5c4c4e5d6234 | jwoojun/CodingTest | /src/main/python/algo_expert/Implementation/문제선정하기.py | 400 | 3.515625 | 4 | def main():
num = int(input())
array = list(map(int, input().split()))
array.sort()
answer, nb = [], 0
while (nb<len(array)):
if len(answer) == 0:
answer.append(array[nb])
elif array[nb] > answer[-1]:
answer.append(array[nb])
nb += 1
if len(answer) == 3:
return "YES"
return "NO"
# 출처 : 구름에듀 |
b0f04cd84bce02f40f3e5a9e41aca5098915b136 | 555Russich/geekbrains1 | /venv/3rdless.py | 3,556 | 4.03125 | 4 | # Функции и работа с файлами
# max(1, 2, 3)
# print(max('zz', 'aaa', key=len))
# print(round(1.98754, 3)) # 3 знака после запятой
for index, char in enumerate('qwerty', start=3):
print(index, char)
# def say_hello(name): # создаем функцию, которую можем вызывать в последствии
# print('Hello', name)
# say_hello('Ivan')
# def average(numbers):
# count = len(numbers) # сколько всего значений в листе
# all_sum = sum(numbers) # считаем сумму значений
# # print(all_sum / count)
# answer = all_sum / count
# return answer
#
# average_number = average([1, 2, 3, 4, 5, 6, 7, 8 ,9])
# print(average_number)
# def print(text): # называем функцию существующей функией и она перестает работать
# pass
# print('bla')
# x = 100
# def test(x):
# # global x
# x += 1
# return x
# x = test(x)
# print(x)
# def my_func(name, surname='Guest'): # сперва обязательный аргумент. необяз можно не выводить
# print(name, surname)
# my_func('Ivan')
# def func(name, *args): # n кол-во аргументов в args. !!!
# print(name) # !!! *abc не работает, только *args выдает только tuple(картеж)
# print(args)
# func('Ivan', 10, 20, 30, 40, 50, 60, 70, 80, 90)
# def func(name, age, surname):
# print(name, surname, age)
# func(surname='Ivanov', age=99, name='Ivan')
# def func(name, **kwargs): # !!! usefull
# print(name, kwargs)
# func('Ivan', surname='Popin', age=50, flat=160)
# def func(**kwargs): # !!! usefull
# print(kwargs)
# func(name='Ivan', surname='Popin', age=50, flat=160)
names = ['Ivan', 'Oleg', 'Sosed']
ages = (35, 45, 80)
#
for name, age in zip(names, ages):
print(name,'-', age)
# print(list(zip(names, ages)))
# print(dict(zip(names, ages)))
# print(pow(10, 2)) # pow возводит x в степень y
# def my_pow(x):
# return x ** 2
#
#
# data = [-2, -10, 6, 19]
# result = []
#
#
# # for num in data:
# # result.append(my_pow(num))
# # print(result)
#
# # result_1 = tuple(map(my_pow, data)) # скобки у функции не ставить, иначе она сразу вызовется. можно list не tuple
# # print(result_1)
#
# def my_filter(x):
# return x > 0
#
#
# result_2 = list(filter(my_filter, data)) # в отличие от map возвращает либо тру либо фолс
# print(result_2)
# data = [-2, -10, 6, 19]
# result = list(map(lambda x: x ** 2, data))
# print(result)
# result = list(filter(lambda x: x > 0, data))
# print(result)
# РАБОТА С ФАЙЛАМИ
# file = open('1') # r(ead) - читает файл, но можно и без него
# for line in file:
# # print(line, end='')
# print(line.strip())
# file = open('2.txt', 'w')
# file.write('1000')
# file.close()
# w(rite) - создает файл и удаляет все прошлые данные в нем...
# a(ppend) - добавить в конец (дозапись)
# a+ и w+ редкие, дозапись и чтение/создание
# file = open('2.txt', 'a+', encoding='utf-8')
# file.write('\na\n')
# file.seek(0)
# print(file.readlines())
# file.close()
# with open('2.txt') as f: #автоматически закрывает файл после qwe
# for line in f:
# print(line.strip())
#
# print('qwe') |
92911484dcd4c512d2b9849fd3a92bf52e41063e | chriskang97/CS_412 | /HW_3/HW_3.py | 4,607 | 3.609375 | 4 | import fileinput
import operator
import collections
## Step 1: Reading Information from File
counter = 0
support = 0
unique_item = []
indiv_trans = []
miscellaneous = ['\n', ' ']
for line in fileinput.input('input.txt'):
### Determine Min Support
if counter == 0 :
support = int(line)
### Transaction Extraction
else :
indiv_trans.append('')
### Get all of unique items/transactions
for item in line :
if item not in unique_item and item not in miscellaneous :
unique_item.append(item)
if item not in miscellaneous :
indiv_trans[counter-1] += item
counter += 1
pass
## Step 2: Scan for Support - Determine Items that has Min Support - Find Union of 1 Element More - Repeat
tracker_dict = {}
item_max = 2
for i in range( len(indiv_trans) + 1) :
tracker_dict[i] = []
while unique_item != [] :
remain_item = []
### 1) Get the item to check: i.e A,B,AB,BC, etc
for item in unique_item :
item_count = 0
### 2) Obtain the corresponding transactions: i.e ABC, BCD, BC, etc
for trans in indiv_trans :
letter_count = 0
### 3) Detect if letter is in transaction: i.e if item is AB, check if A is in ... and B is in ...
for letter in item :
letter_count += trans.count(letter)
### 4) Check if item exists in transaction
if letter_count >= len(item) :
item_count += 1
### 5) Check if Item Count is greater or equal than support
if item_count >= support :
tracker_dict[item_count].append(item)
remain_item.append(item)
### 6) Create a new set of items based on satisfactory support items
unique_item = []
length = len(remain_item)
for i in remain_item[0:length-1] :
### 7) Obtain unique set of letters -> Sort them alphabetically -> See if its within item_max and not existing already
for j in remain_item[1:length] :
unique_trans = set(i+j)
unique_trans = sorted(unique_trans)
test_union = ''.join(unique_trans)
if len(test_union) == item_max and test_union not in unique_item :
unique_item.append( test_union )
item_max += 1
### Step 3: Print out Frequent Item List
max_support = len(indiv_trans)
for i in range(max_support + 1) :
key = max_support - i
total_item = tracker_dict[key]
if total_item != [] :
sorted_list = sorted( total_item )
for item in sorted_list :
print("%d: %s" %(key, " ".join(item) ) )
print()
### Step 4: Print out Closed Item List
closed_item = []
pot_maximal_item = []
### 1) Go through the Dictionary
for i in range(max_support + 1) :
key = max_support - i
total_item = tracker_dict[key]
if total_item != [] :
if len(total_item) == 1 :
closed_item.append("%d: %s" %(key, " ".join(tracker_dict[key]) ) )
pot_maximal_item.append( (key, tracker_dict[key][0]) )
else :
sorted_list = sorted( total_item )
check_item = list(sorted_list[0])
num_common = len(sorted_list)
for j in range(1, num_common ) :
test_subset = [ letter for letter in check_item if letter in sorted_list[j] ]
### Check for 2 Conditions: If length matched, that means we found a subset
if len(test_subset) == len(check_item) :
check_item = sorted_list[j]
elif test_subset == [] or j == num_common - 1:
closed_item.append("%d: %s" %(key, " ".join(check_item) ) )
pot_maximal_item.append( (key, check_item) )
check_item = sorted_list[j]
for item in closed_item :
print(item)
print()
### Step 5: Print out Maximal Item List
maximal_item = []
pot_max = len(pot_maximal_item)
#print(pot_maximal_item)
for i in range(pot_max ) :
detect = 0
item_check = pot_maximal_item[i][1]
#print( pot_maximal_item[i] )
for j in range(i+1, pot_max) :
test_subset = [ letter for letter in item_check if letter in pot_maximal_item[j][1] ]
if len(test_subset) >= len(item_check):
detect = 1
break ;
if not detect :
maximal_item.append("%d: %s" %(pot_maximal_item[i][0], " ".join(item_check) ) )
for item in maximal_item :
print(item)
# for item in maximal_item :
# print(item)
#print(closed_item)
# print(tracker_dict)
# print(satisfied_closed)
|
698d08620beb3524016d50e70abcf27353978e81 | alikhalilli/Algorithms | /.z/Sorting/SelectionSort.py | 579 | 4.09375 | 4 | """
@github: github.com/alikhalilli
Time Complexity: O(n^2)
Space Complexity: O(1)
"""
def swap(arr, i1, i2):
temp = arr[i2]
arr[i2] = arr[i1]
arr[i1] = temp
def selectionSort(arr, asc=False):
n = len(arr)
for i in range(n):
best_index = i
for j in range(i, n):
if asc:
if arr[j] < arr[i]:
best_index = j
else:
if arr[j] > arr[i]:
best_index = j
swap(arr, i, best_index)
return arr
arr = [9, 8, 10, 5]
print(selectionSort(arr))
|
447f470d5d2babb1c3dd0c8d0ebbfe987556086f | nana-agyeman1/Global-code-py-2k19 | /global.py | 461 | 4.125 | 4 | #converting 32deg to radians
import math
import datetime
#degree = 32
#radian = degree*(math.pi/180)
#print(radian)
# Calculating surface area and Volume of a sphere
#radian = float(input('Radius of sphere: '))
#surface_area = 4 * math.pi * radian **2
#volume = (4/3) * (math.pi * radian **3)
#print("Surface Area is: ", surface_area)
#print("Volumeis: ", volume)
now = datetime.datetime.now()
print ("Current time : ")
print (now.strftime("%H:%M:%S"))
|
497ecd45f4d18e84ac5fd2c07e609abc898af6d7 | jossy254-git/OOP2_PROJECTS | /functions.py | 505 | 3.640625 | 4 | def courses(*args):
for subject in args:
print(subject)
courses("big data","CCNA", "OOP2")
#keyword arguements
def courses(**kwargs):
for key,value in kwargs.items():
print("{}:{}".format(key, value))
#overriding arguements
def kenya(county = "mombasa"):
print("i am from " + county)
kenya()
kenya("Nairobi")
kenya("kiambu")
kenya("kisumu")
#passing a list as an arguement
def my_function(food):
for x in food:
print(x)
fruits = ["apple","banana", "cherry"]
my_function(fruits)
|
c750bd682dd5579ce9520204b6c646e5afb207b1 | jekuszynski/bch5884jek | /assignments/python_scripts/.ipynb_checkpoints/convert_F_to_K-checkpoint.py | 256 | 3.8125 | 4 | #!/usr/bin/env python3
#https://github.com/jekuszynski/bch5884jek/tree/master/assignments
# -*- coding: utf-8 -*-
print("What is the temperature in \u2109 ?:")
t = input()
c = round(((int(t)-32)*(5/9))+273.15,3)
print("The temperature in K is: " + str(c)) |
c8e3fb1cecc1bb30e70def3aa24c8d9ca8f86fbb | alex-code4okc/advent_of_code_2019 | /Day_1/day_1_solution.py | 608 | 3.703125 | 4 | import math
def fuel_requirement_by_mass(mass):
calculation = math.floor((mass/3))-2
return calculation
def recursive_fuel_requirement_by_mass(mass):
fuel = int(math.floor((mass/3)))-2
print(fuel)
if(fuel>=0):
return fuel+recursive_fuel_requirement_by_mass(fuel)
else:
return 0
total = 0
with open('day_1_input.txt','rt',encoding='utf-8') as file:
for item in file.readlines():
total += recursive_fuel_requirement_by_mass(int(item))
print(total)
with open('day_1_solved_p2.txt','wt',encoding='utf-8') as solution:
solution.write(str(total))
|
a73ae83e0703d946a73c7fc2ecf3910f0bc30dd4 | priyankamadhwal/Python-Practice | /hackerrank/Collections.OrderedDict().py | 322 | 3.6875 | 4 | from collections import OrderedDict
N = int(input())
allItems = OrderedDict()
for _ in range(N):
curr = input().split()
item, price = " ".join(curr[:len(curr)-1]), int(curr[len(curr)-1])
if item in allItems : allItems[item] += price
else: allItems[item] = price
for x in allItems:
print(x,allItems[x])
|
84c82087e2610b961f9350b69cad523ff3f3e67a | lovroselic/Coursera | /Capstone/Week2/UniversalString.py | 1,258 | 3.734375 | 4 | #python3
'''
this problem is quite similar to problem 2. use 3 mers as example.
000=0, 001=1 ..., 111=7. to build graph, simply connect number to number*2%8 and number*2%8+1.
for example vertex 6 (110) is conect to 6*2%8=4 (100) and 6*2%8+1=5 (101).
after this the problem is exactly this sample as problem two. when print out, just print number%2.
'''
#https://www.geeksforgeeks.org/de-bruijn-sequence-set-1/
DEBUG = True
def Euler(ADJ):
currentpath = [0]
cycle = []
while len(currentpath) > 0:
vertex = currentpath[-1]
if ADJ[vertex]:
nextVertex = ADJ[vertex].pop()
currentpath.append(nextVertex)
else:
cycle.append(currentpath.pop())
result = [cycle[i] for i in range(len(cycle)-1, 0, -1)]
return result
# =============================================================================
# # Main
# =============================================================================
N = int(input())
#N = 4
nodes = 2 ** (N-1)
ADJ = [[] for _ in range(nodes)]
for n in range(nodes):
i = (n * 2) % nodes
ADJ[n].append(i)
ADJ[n].append(i+1)
result = Euler(ADJ)
#string =[i % 2 for i in result]
print("".join(map(str, [i % 2 for i in result]))) |
cd4345f971a9b54a0a77089f1b770a2a24d31e72 | HaroldCCS/python | /python/platzi/1_Basico/adivina_el_numero.py | 459 | 3.765625 | 4 | import random
def run():
adivina = random.randint(1, 100)
encontrado = True
preguntar = 0
print('Ingresa un numero mayor a 0: ')
while adivina == preguntar:
if adivina > preguntar:
preguntar = int(input('Ingresa un numero mayor: '))
else:
preguntar = int(input('Ingresa un numero menor: '))
print('Excelente, Encontraste el numero!! es ' + str(adivina))
if __name__ == '__main__':
run() |
13491d5c79907a2585d010970b3692e459c4dc3a | iisdd/Courses | /python_fishc/20.0.py | 498 | 3.96875 | 4 | '''
0. 请用已学过的知识编写程序,统计下边这个长字符串中各个字符出现的次数
并找到小甲鱼送给大家的一句话。
(由于我们还没有学习到文件读取方法,大家下载后拷贝过去即可)
请下载字符串文件: string1.zip (55.49 KB, 下载次数: 23394)
'''
str1 = ''
with open ('string1.txt') as s:
for each in s:
str1 += each
for each in str1:
if each.isalpha():
print(each , end ='')
|
0853bc577366ae4f7c69aed6b906cb4b19ae2749 | nimerritt/programming_practice | /chp4/depths.py | 765 | 4.15625 | 4 | """
Question 4.3 from Cracking the Coding Interview 6th Edition
List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth 0, you'll have 0 linked lists).
"""
import trees
def depths(root, depth_lists, depth):
# invariant 1: depth_lists contains at least 'depth' elements
# base case
if not root:
return depth_lists
# enforce inv. 1
if len(depth_lists) <= depth:
depth_lists.append([])
depth_lists[depth].append(root.label)
depths(root.left, depth_lists, depth + 1)
depths(root.right, depth_lists, depth + 1)
return depth_lists
t = trees.treeify(list(range(10)))
lists = []
depths(t, lists, 0)
print(lists)
|
f5626b39e4d5dd6240a455e9c80ba76838d183b2 | borntoburnyo/AlgorithmInPython | /medium/1663_smallest_string_with_a_given_numeric_value.py | 1,039 | 3.5 | 4 | from collections import deque
class Solution:
def getSmallestString(self, n, k):
i = 0
# Need a deque container, since we need to construct the string from end backward
dek = deque()
while i < n:
if k - 26 > n - i - 1: # If K is larger than 26, the remaining can at least fill in the rest place in the string with 'a'
dek.appendleft(26)
k -= 26
else: # If not, put the largest possible character at the end
dek.appendleft(k - (n - i - 1))
k = n - i - 1
# Remember to increse the loop index
i += 1
# Convert the values in the deque to characters and form a string
return "".join([chr(96+x) for x in dek])
def v2(self, n, k):
res = [1]*n # Pre-populate 'a' in every position
k -= n
for i in range(n-1, -1, -1):
temp = min(k, 25)
res[i] += temp
k -= temp
return "".join([chr(96 + x) for x in res])
|
0137e9bd89943a006c58e3a57a293ff8b739c499 | polyglotm/coding-dojo | /coding-challange/leetcode/easy/~2021-10-08/1725-number-of-rectangles-that-can-form-the-largest-square/1725-number-of-rectangles-that-can-form-the-largest-square.py | 928 | 3.96875 | 4 | """
1725-number-of-rectangles-that-can-form-the-largest-square
leetcode/easy/1725. Number Of Rectangles That Can Form The Largest Square
URL: https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/
"""
from typing import List
class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
max_value = 0
count = 0
for rectangle in rectangles:
min_value = min(rectangle)
if min_value > max_value:
max_value = min_value
count = 1
elif min_value == max_value:
count += 1
return count
def test():
rectangles = [[5, 8], [3, 9], [5, 12], [16, 5]]
output = 3
assert Solution().countGoodRectangles(rectangles) == output
rectangles = [[2, 3], [3, 7], [4, 3], [3, 7]]
output = 3
assert Solution().countGoodRectangles(rectangles) == output
|
896dc4631cc3002ba5d8852fda4b3548c981248a | Valentin-Rault/tic-tac-toe | /tic-pygame/main.py | 1,168 | 3.59375 | 4 | import pygame
from tic_tac_toe.constants import WIDTH, HEIGHT, SQUARE_SIZE, SQUARE_PADDING, \
BOARD_PADDING_TOP, BOARD_PADDING_LEFT, RED
from tic_tac_toe.game import Game
from minimax.algorithm import minimax
FPS = 60
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Tic Tac Toe')
def get_row_col_from_mouse(x, y):
row = (y - BOARD_PADDING_TOP) // (SQUARE_SIZE + SQUARE_PADDING)
col = (x - BOARD_PADDING_LEFT) // (SQUARE_SIZE + SQUARE_PADDING)
return row, col
def main():
clock = pygame.time.Clock()
game = Game(WIN)
while game.is_active:
clock.tick(FPS)
if game.turn == RED:
_, new_board = minimax(game.get_board(), 3, False)
game.ai_move(new_board)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game.is_active = False
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
row, col = get_row_col_from_mouse(x, y)
game.is_active = game.play(row, col)
game.update()
pygame.quit()
main()
|
4d9f2846696cc7fe51568b1fcf02fab86e6bd5d7 | pilihaotian/pythonlearning | /leehao/learn120.py | 245 | 3.78125 | 4 | # 测试
def test1(x):
x = x + x # add return new
print(x)
def test2(x):
x += x # iadd return self
print(x)
a1 = [100]
test1(a1) # [100, 100]
print(a1) # [100]
a2 = [100]
test2(a2) # [100, 100]
print(a2) # [100, 100]
|
f6074927e190d596658ae5ce00253a84ef620dea | Pereirics/Exercicios_Curso_Python | /ex045.py | 1,336 | 3.859375 | 4 | import random
print('Bem-vindo ao jogo do "Pedra, Papel e Tesoura"!')
user = str(input('Escolha qual você quer jogar: ')).strip().lower()
cpu = random.choice(['pedra','papel','tesoura'])
if user == 'papel' and cpu == 'papel':
print(f'O CPU escolheu {cpu}!')
print('É um EMPATE!')
elif user == 'papel' and cpu == 'pedra':
print(f'O CPU escolheu {cpu}!')
print('O Utilizador venceu! Parabéns!')
elif user == 'papel' and cpu == 'tesoura':
print(f'O CPU escolheu {cpu}!')
print('O CPU venceu! Mais sorte para a próxima ;D')
elif user == 'pedra' and cpu == 'pedra':
print(f'O CPU escolheu {cpu}!')
print('É um EMPATE!')
elif user == 'pedra' and cpu == 'tesoura':
print(f'O CPU escolheu {cpu}!')
print('O Utilizador venceu! Parabéns!')
elif user == 'pedra' and cpu == 'papel':
print(f'O CPU escolheu {cpu}!')
print('O CPU venceu! Mais sorte para a próxima ;D')
elif user == 'tesoura' and cpu == 'tesoura':
print(f'O CPU escolheu {cpu}!')
print('É um EMPATE!')
elif user == 'tesoura' and cpu == 'papel':
print(f'O CPU escolheu {cpu}!')
print('O Utilizador venceu! Parabéns!')
elif user == 'tesoura' and cpu == 'pedra':
print(f'O CPU escolheu {cpu}!')
print('O CPU venceu! Mais sorte para a próxima ;D')
else:
print('Escolha inválida! Siga as regras ;)') |
22baea23fcb40cf4c07a08b094cd970229d4b4a5 | rpereira91/AI | /N_Queens/nqueens_heuristic.py | 6,394 | 3.828125 | 4 | #Name: Ralph Pereira
#Desc: A huristic search that uses two different 2-D array's, one to store the queens and one to store the values.
# The values are calculated after each move of the queen, the queens are initally placed randomly.
# Each move is is done by the row, a loop itrates through the array and adds up all the conflicts, and moves to the
# least conflicting piece
import random
import copy
#creates a board
def CreateBoard(n):
return [[0 for i in range(n)]for j in range (n)]
#prints out the board
def PrintBoard(board):
for y in range (0, len(board)):
print(board[y])
#checks if the numbers passed are within the scope of the board
def checkInRange(i, j):
return i >= 0 and j >= 0 and i < BoardSize and j < BoardSize
#logic behind checking the row col and diagonal, this is done very sloppy but it works!
def CalcAll(cost, board):
for i in range(0, len(board)):
for j in range(0, len(board)):
if board[i][j] == 1:
for k in range(1, len(board)):
if checkInRange(i + k, j):
cost[i+k][j] += 1
if board[i+k][j] == 1:
break
else:
break
for k in range(1, len(board)):
if checkInRange(i - k, j):
cost[i - k][j] += 1
if board[i - k][j] == 1:
break
else:
break
for k in range(1, len(board)):
if checkInRange(i, j + k):
cost[i][j + k] += 1
if board[i][j + k] == 1:
break
else:
break
for k in range(1, len(board)):
if checkInRange(i, j - k):
cost[i][j - k] += 1
if board[i][j - k] == 1:
break
else:
break
for k in range(1, len(board)):
if checkInRange(i + k, j+k):
cost[i+k][j+k] += 1
if board[i+k][j+k] == 1:
break
else:
break
for k in range(1, len(board)):
if checkInRange(i - k, j-k):
cost[i - k][j-k] += 1
if board[i - k][j-k] == 1:
break
else:
break
for k in range(1, len(board)):
if checkInRange(i-k, j + k):
cost[i-k][j + k] += 1
if board[i-k][j + k] == 1:
break
else:
break
for k in range(1, len(board)):
if checkInRange(i+k, j - k):
cost[i+k][j - k] += 1
if board[i+k][j - k] == 1:
break
else:
break
#basic runner method, creates the board, populates it, prints it, runs hill climber to solve
#then prints the board again
def SolveQueens():
board = CreateBoard(BoardSize)
cost = CreateBoard(BoardSize)
PopulateBoard(board,cost)
CalcAll(cost, board)
print("Before")
PrintBoard(board)
print(HillClimb(board, cost))
print("SOLVING...\n After")
PrintBoard(board)
#sudo-randomly place the queens on the board, it places the pieces on the spot with the least number of conflicts in order to make it easier
# for the hill climb
def PopulateBoard(board, cost):
random.seed(rs)
for x in range (0, len(board)):
cost = CreateBoard(BoardSize)
CalcAll(cost, board)
indices = [i for i, c in enumerate(cost[x]) if c == min(cost[x])]
board[x][indices[random.randint(0,len(indices)-1)]] = 1
#Checks to see if the board is complete, if all the queens have an attack value of zero the board is done
def IsComplete(board, cost):
for x in range(BoardSize):
for y in range(BoardSize):
if board[x][y] == 1 and cost[x][y] != 0:
return False
return True
#main logic behind the hill climber
def HillClimb(board, cost):
#tracker to see if the board has run too many times
mSum = numboards= 0
#while the board is not complete
while not IsComplete(board, cost):
#run through the rows of the board
for x in range(BoardSize):
#current index of the queen in the row
queenIndex = board[x].index(1)
#if there is more than one smallest digit it will store them in all in an array
#this is done so that it doesn't just pick the first smallest all the time
indices = [i for i, c in enumerate(cost[x]) if c == min(cost[x] )]
#if the queen's spot is bigger than the smallest spot it will put the queen down on that spot
if cost[x][queenIndex] > cost[x][indices[0]]:
board[x][queenIndex] = 0
minValue = indices[random.randint(0,len(indices)-1)]
board[x][minValue] = 1
queenIndex = x
cost = CreateBoard(BoardSize)
CalcAll(cost, board)
#if the hill climb has tried to solve the board more than the boardsize cube it will move a random piece
#this is to kick it out of a potental valley
if mSum >= (BoardSize**3):
mSum = 0
spot = random.randint(0, BoardSize-1)
for i in range(BoardSize):
if board[spot][i] == 1:
if checkInRange(spot, i+1):
board[spot][i] = 0
board[spot][i+1] = 1
else:
board[spot][i] = 0
board[spot][i-1] = 1
mSum += 1
numboards += 1
return numboards
BoardSize = int(input('Please input the number of queens: '))
rs = int(input('Please input the seed: '))
SolveQueens() |
f606afb3b70cd6ff98b9b0c18e2f1c31f8345e90 | MiroVatov/Python-SoftUni | /Python Advanced 2021/TUPLES AND SETS/Exercises 03. Periodic Table.py | 286 | 3.703125 | 4 | num = int(input())
unique_elements = set()
for _ in range(num):
element = input().split()
if len(element) > 1:
for el in element:
unique_elements.add(el)
else:
unique_elements.add(''.join(element))
print('\n'.join(unique_elements)) |
d636049961df1094866c0c350510a18c3d12623d | ankovachev/SoftUni | /PythonADV/01_lists_as_stacks_and_queues__lab/10_cups_and_bottles.py | 1,314 | 3.65625 | 4 | import sys
from collections import deque
from io import StringIO
input1 = """4 2 10 5
3 15 15 11 6
"""
input2 = """1 5 28 1 4
3 18 1 9 30 4 5
"""
input3 = """10 20 30 40 50
20 11
"""
sys.stdin = StringIO(input1)
cups = deque()
bottles = deque()
cups_input = input().split()
bottles_input = input().split()
is_filled_all_cups = False
[cups.append(int(each)) for each in cups_input]
[bottles.append(int(each)) for each in bottles_input]
current_wasted_water = 0
cuppernt_rest_water = 0
while True:
current_bottle = bottles.pop()
current_cup = cups[0]
if current_bottle >= current_cup:
cups.popleft() # You can fill the cup
current_wasted_water += current_bottle - current_cup
else:
current_rest_water = current_bottle - current_cup # You can't fill the cup
if not cups:
is_filled_all_cups = True
print(f"Bottles: {len(bottles_input)}")
break
if not bottles:
print(f"Cups: {len(cups_input)}")
break
# Converting all numbers to strings and print it
if is_filled_all_cups:
[str(each) for each in bottles]
# print(f"Bottles: {' '.join(bottles)}") # Print all bottles split by space.
else:
[str(each) for each in cups]
# print(f"Cups: {' '.join(cups)}") # Print all cups split by space.
# That's all, folks!
|
9eaaced9444abb393e1ccc3b1cfbb5eb45859ec0 | manemarron/mate-computacional | /alumnos/manemarron/proyecto/Robot-Simulation/modules/utils.py | 704 | 3.640625 | 4 | # -*- coding: utf8 -*-
import numpy as np
def rk4(f, y, t, dt):
"""
Integrates an ordinary differential equation using the order 4 Runge-Kutta method
:param f: function
Function to be integrated
:param y: array
Array containing previous state
:param t: float
Number representing current value of time
:param dt: float
Represents the time step for the integration
:return: array
Array containing the next state
"""
k1 = f(y, t)
k2 = f(y + 0.5 * k1 * dt, t + 0.5 * dt)
k3 = f(y + 0.5 * k2 * dt, t + 0.5 * dt)
k4 = f(y + k3 * dt, t + dt)
res = y + float(1) / 6 * dt * (k1 + 2 * k2 + 2 * k3 + k4)
return res
|
fc5e70fb3365ff653e01036da0681f7853d56078 | deepikaasharma/removing-items-from-a-list | /main.py | 456 | 4.125 | 4 | """Use .remove() to remove an item from a list"""
# fruit_list = ['apple', 'pear', 'peach', 'mango', 'pear']
# fruit_list.remove('pear')
# print(fruit_list)
"""Use del to remove index of an element"""
num_list = list(range(0, 9))
# remove the last element in the list
del num_list[-1]
print(num_list)
# remove the fifth element in the list
del num_list[4]
print(num_list)
# remove a range of elements from a list
del num_list[2:4]
print(num_list) |
bc5a8de9ccf420d055ddb5a1c4bd4875e73ffcf6 | ppli2015/leetcode | /1 Two Sum.py | 1,269 | 3.6875 | 4 | # -*-coding:cp936-*-
__author__ = 'lpp'
# 使用哈希表
# 避免同一个数字 3+3=6
# 可以扫描一次就完成
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
if (target - nums[i]) in nums and nums.index(target - nums[i]) != i:
return [i, nums.index(target - nums[i])]
def twoSum2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ht = {}
for i in range(len(nums)):
ht[nums[i]] = i
for i in range(len(nums)):
comp = target - nums[i]
if ht.has_key(comp) and ht[comp] != i:
return [i, ht[comp]]
def twoSum3(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ht = {}
for i in range(len(nums)):
comp = target - nums[i]
if ht.has_key(comp):
return [ht[comp], i]
ht[nums[i]] = i
nums = [3, 2, 4]
target = 6
test = Solution()
indices = test.twoSum3(nums, target)
print indices
|
5b96fc21f893b2a29ddf084bd877b3d07711bdce | nasserso/materias | /MC102/lista susy/lab04.py | 988 | 3.84375 | 4 | '''
O programa recebe 4 valores que representam pesos e tenta
encontrar equilíbrio em uma balança com os mesmos.
O programa mostra "sim" caso o equilíbrio possa ser feito,
e "nao" caso contrário.
'''
#Verifica todas as permutações de pesos
def temPermutacaoValida(peso):
permutacaoEhValida = False
for permutacao in range(4):
if(peso[0] == peso[1] + peso[2] + peso[3]):
permutacaoEhValida = True
elif(peso[0] + peso[1] == peso[2] + peso[3]):
permutacaoEhValida = True
elif(peso[0] + peso[3] == peso[2] + peso[1]):
permutacaoEhValida = True
elif(peso[0] + peso[1] + peso[2] == peso[3]):
permutacaoEhValida = True
#Permuta peso
primeiroPeso = peso[0]
peso[0] = peso[permutacao]
peso[permutacao] = primeiroPeso
return permutacaoEhValida
#Lê pesos
p1 = int(input())
p2 = int(input())
p3 = int(input())
p4 = int(input())
peso = [p1,p2,p3,p4]
if(permutacaoEhValida(peso)):
print("sim")
else:
print("nao")
|
db861c6ded96b69a69b2a232cd574d9f4bde58b7 | Akagi201/learning-python | /cmd/argparse2.py | 187 | 3.65625 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number", type=int)
args = parser.parse_args()
print(args.square ** 2)
|
703bef5d5d5ac9b9eff50fdcfef3b247c0a2b6c1 | rkandekar/python | /DurgaSir/sa_filter.py | 157 | 3.5625 | 4 | l=[1,2,3,4]
def funDouble(x):
if(x%2==0):
return x
l2=list(filter(funDouble,l))
print(l2)
l3=list(filter(lambda x:x%2==0,l))
print(l3)
|
633afccd23dde6ef6071dab950e57d15141dda59 | yl29/pe | /q0001.py | 226 | 3.703125 | 4 | from time import *
def p1(num):
sum = 0
for i in range(1,num):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
start = clock()
print p1(1000)
print clock() - start, "seconds"
#print p1(1000)
|
68e0493c293a4e40cdd976662c85c229f0ea13d4 | q13245632/CodeWars | /Reverse polish notation calculator.py | 1,716 | 3.859375 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-23
def calc(expr):
if not expr:return 0
lst = expr.split(" ")
stack = []
for i in lst:
if i.isdigit():
stack.append(int(i))
if "." in i:
stack.append(float(i))
if i == "+":
a = stack[-1]
b = stack[-2]
c = a + b
stack = stack[:-2] + [c]
if i == "-":
a = stack[-1]
b = stack[-2]
c = b - a
stack = stack[:-2] + [c]
if i == "*":
a = stack[-1]
b = stack[-2]
c = b * a
stack = stack[:-2] + [c]
if i == "/":
a = stack[-1]
b = stack[-2]
c = b / a
stack = stack[:-2] + [c]
return stack[-1] if stack[-1] else 0
import operator
def calc(expr):
OPERATORS = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
stack = [0]
for token in expr.split(" "):
if token in OPERATORS:
op2, op1 = stack.pop(), stack.pop()
stack.append(OPERATORS[token](op1, op2))
elif token:
stack.append(float(token))
return stack.pop()
# Test.assert_equals(calc(""), 0, "Should work with empty string")
# Test.assert_equals(calc("1 2 3"), 3, "Should parse numbers")
# Test.assert_equals(calc("1 2 3.5"), 3.5, "Should parse float numbers")
# Test.assert_equals(calc("1 3 +"), 4, "Should support addition")
# Test.assert_equals(calc("1 3 *"), 3, "Should support multiplication")
# Test.assert_equals(calc("1 3 -"), -2, "Should support subtraction")
# Test.assert_equals(calc("4 2 /"), 2, "Should support division") |
2d4d888fa7a6a4c32722bc79ca180496d1c983ee | jzendejas/Random-Wiki-Article-Browser | /test_loop.pyw | 124 | 3.78125 | 4 | #!/usr/bin/env python3
ask = 'n'
while ask == 'n':
print("looping")
ask = input("y/n").lower()
print("exited loop")
|
4d52cc9953e13fa75a2b2fe2b62c02143100aba3 | lrw3716740/study | /dailyTest/day07List.py | 107 | 3.53125 | 4 | l=[1,2,3,4,5]
#print max(l)
#print min(l)
del(l[1])
print l
l.insert(2,23)
print l
l.sort()
print l |
51dc0b4396bb3eab965a4daa17edb46cc03542df | fatihsencer/algohack21 | /soru2/2.py | 527 | 3.5 | 4 | op_file = open('toplamlar.txt','w')
def digits(nb1):
total = 0
while nb1 > 0:
total += nb1 % 10
nb1 = int(nb1 / 10)
return total
with open('sayilar.txt','r') as file:
line = file.readline()
while line:
number = digits(int(line.strip()))
op_file.write(str(number))
while len(str(number)) > 1:
number = digits(number)
op_file.write(" " + str(number))
op_file.write("\n")
line = file.readline() |
eab1c8b55e235eb2b04fe664335a0796d6a43a55 | sowmya8900/Python-Practice | /Class_vs_Instance.py | 903 | 3.796875 | 4 | class Person:
def __init__(self,age):
# checking if the age is negative or positive
if (age < 0):
self.age = 0
print("Age is not valid, setting age to 0.")
else:
self.age = age
def amIOld(self):
# Printing the statement depending upon the age
# Printing the statement depending upon the age after 3 years
if (self.age < 13):
print("You are young.")
elif (self.age >= 13 and self.age < 18):
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person
self.age = self.age + 1
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
|
c01a2be57546c095fa91ce7f288fb4e86a4a87fa | abdulwahid211/Project-Euler-in-Python | /SolutionForProblem_1.py | 335 | 4.21875 | 4 | #
# Multiples of 3 and 5
# Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
num = 1000
sum = 0
for x in range(0, num):
if x%3==0 or x%5==0:
sum = sum +x
print(sum)
|
d4441a0180cf145c0f7bb72a6487aa4979fc81e2 | Sujankhyaju/IW_pythonAssignment3 | /data structure and algorithm problem/2.py | 344 | 4.03125 | 4 | # Insertion Sort
def insertion(lst):
for i in range(1,len(lst)):
currentvalue = lst[i]
index = i
while index > 0 and lst[index-1]>currentvalue:
lst[index] =lst[index-1]
index -= 1
lst[index]= currentvalue
lst = [2,9,6,1,0,5,7,3]
insertion(lst)
print(lst)
|
a041eb1326889239a561de365e0873f223f31961 | andrewStich/Facebook-Interview-Python | /solution.py | 10,269 | 4.09375 | 4 | import pandas as pd
# Thank you for interviewing! This should take approximately 1 hour of your time; you may use up to 3 if necessary.
#Feel free to call ********** for 15 minutes of help. Please pay attention to code quality, use 'Pythonic' coding style when possible, and comment like you normally would. Use any documentation that you need.
# Do not modify below this line
employee_db = {'name':['Steve Wozniak', 'Morgan Stanley', 'Steve Jobs', 'Bill Gates', 'Steve Ballmer', 'Warren Buffett', "Intern McIntern"], 'reports_to': ['Steve Jobs', 'Bill Gates', 'Steve Jobs', 'Steve Jobs', 'Bill Gates', 'Steve Jobs', 'Warren Buffett'], 'seniority':[30, 45, 24, 28, 20, 13, 9], 'type': ["hourly","hourly","full_time","full_time","full_time","full_time", "full_time"]}
salary_db = {'name':[ 'Bill Gates', 'Steve Ballmer', 'Warren Buffett', "Intern McIntern", 'Steve Wozniak', 'Morgan Stanley', 'Steve Jobs'], 'salary':[1, 0.5, 1, 0.1, 0.25, 0.33, 1.5]}
employee_df = pd.DataFrame(employee_db)
salary_df = pd.DataFrame(salary_db)
print(employee_df)
print(salary_df)
# Do not modify above this line
# Step 1:
# Using the dataframes 'employee_df' and 'salary_df', create a new dataframe 'fulltime_df' that contains salary, seniority, type, and reports_to columns. Filter this dataframe to contain only employees that are full time and have been with the company longer than 1 year. Use this filtered dataframe in the rest of this exercise.
# "salary" is in units of millions
# "seniority" is in units of months
# Expected answer:
# name reports_to seniority type salary
#1 Steve Jobs Steve Jobs 24 full_time 1.50
#2 Bill Gates Steve Jobs 28 full_time 1.00
#3 Steve Ballmer Bill Gates 20 full_time 0.50
#4 Warren Buffett Steve Jobs 13 full_time 1.00
fulltime_df = pd.merge(employee_df, salary_df, on='name').where(employee_df['type'] == 'full_time').where(employee_df['seniority'] > 12).dropna()
# nice :D
pass
# Step 2a:
# Complete this Employee class definition. This class should implement a tree. This is not a binary tree; please support many employees per manager.
# Example:
#
# Steve Jobs (salary 1.5M$)
# / \
# Bill Gates (salary 1M) Warren Buffett (salary 1M)
# /
# Steve Ballmer (salary 0.5M)
#
# get_expenses() must return the salary of the current employee, plus salaries of all reports, recursively.
#
# Example: billGatesInstance.get_expenses()
# > 1.5M
# You may add or modify any methods and class variables inside this class, but all your work must be done entirely within class Employee().
#create dictionary to map employees to their children, rather than to their parent
children_dict = {}
for index, row in fulltime_df.iterrows():
# if the supervisor isn't in the dict yet
if row['reports_to'] not in children_dict:
# if this item is the CEO, we don't want to include it's name in its children
if row['name'] not in row['reports_to']:
children_dict[row['reports_to']] = [(row['name'])]
# supervisor is already in the dict, so we append its list instead of overwriting/creating a new one
else:
children_dict[row['reports_to']].append(row['name'])
# if the current employee supervises isn't in the dict yet, add them with an empty list
if row['name'] not in children_dict:
children_dict[row['name']] = []
class Employee(object):
#a list of tuples
EXPENSES = []
def __init__(self, name, children_dict, fulltime_df):
#name/key of employee object
self.name = name
#name of the company CEO
self.ceo = fulltime_df.loc[fulltime_df['name'] == fulltime_df['reports_to']].iloc[0]['name']
#list of children filled with employee objects
self.children = self.get_children(children_dict[self.name], children_dict, fulltime_df)
#data
self.seniority = fulltime_df.where(fulltime_df['name'] == self.name).dropna().iloc[0]['seniority']
self.salary = fulltime_df.where(fulltime_df['name'] == self.name).dropna().iloc[0]['salary']
self._type = fulltime_df.where(fulltime_df['name'] == self.name).dropna().iloc[0]['type']
#print(str(self.name)+' '+str(self.seniority)+' '+str(self.salary)+' '+str(self._type))
pass
def get_children(self, children, children_dict, fulltime_df):
#method for finding this employees children using the children_dict created in main
temp = []
# base case: The employee has no children -> return an empty list
if(children == []):
return []
else:
# for each name in the children list, create a new employee and append it to the temp list. Then return the temp list (a list of employee objects)
for i in children:
temp.append(Employee(i, children_dict, fulltime_df))
return temp
pass
def get_expenses(self, sum=0):
#method for recursively getting the expenses of this employee and all its children. stores this data in EXPENSES (local dict)
#uses print expenses to print out a table of the EXPENSES dict
if(self.children == []):
#print(self.name + str(self.salary))
#if no children, add this employees salary to the table and return self.salary for calculation of parent expenses
self.add_expenses(self.salary)
return self.salary
else:
#if children exist, call this function on each child, storing their expenses in sum
for i in self.children:
sum += i.get_expenses(sum)
#print(self.name + str(sum))
#once all children expenses have been added to sum, add self.salary to sum and add that value to EXPENSES table
#call the print_exp_table function to print the EXPENSES dict as a pd.DF
#then return self.salary + sum for calculation of parent expenses
self.add_expenses(sum + self.salary)
self.print_exp_table()
return sum + self.salary
pass
def add_expenses(self, exp):
#method to add employees and their expenses to the EXPENSES list
#step 3 solution
#self.EXPENSES.insert(0, (self.name, exp) )
#step 5 solution
self.EXPENSES.insert(0, (self.name, exp, self.seniority) )
pass
def print_exp_table(self):
#method to print EXPENSES dict as a DF table
#we only want to print out the CEO's table (unordered) as this contains data for the whole company, rather than all sub-tree tables.
##################################
# Step 3 Solution
#if(self.name == self.ceo):
# print("\nRecursive Step-3 Solution:")
# print(pd.DataFrame(self.EXPENSES, columns=['Employee', 'Expenses']))
# pass
##################################
##################################
# Step 5 Solution
if(self.name == self.ceo):
print("\nRecursive Step-5 Solution:")
print(pd.DataFrame(self.EXPENSES, columns=['Employee', 'Expenses', 'Seniority']))
pass
##################################
# Step 2b: Create the company tree from the fulltime_df dataframe. The 'company' variable must be set to the root of the tree (the CEO Steve Jobs). If you're feeling confident, attempt this solution recursively (pass the entire fulltime_df dataframe to the class constructor or a class method).
#determine the CEO of the company, which is the employee who reports to themselves
ceo = fulltime_df.loc[fulltime_df['name'] == fulltime_df['reports_to']]
#create the company tree, passing in the CEO name to be the root. children_dict is passed to help recursively build the tree
company = Employee(ceo.iloc[0]['name'], children_dict, fulltime_df)
# Step 3: Print the expenses for every employee as a table. Ex:
# Employee | Expenses
# Steve Jobs | 4.0
# Bill Gates | 1.5
# Steve Balmer | 0.5
# Warren Buffett | 1.0
company.get_expenses()
# Step 5: Modify the class to report the seniority of each employee. Modify the class in Step 2a to print this in a table that looks like this:
# Expected: Salary Seniority
# Steve Jobs | 4.0 | 24
# Bill Gates | 1.5 | 28
# Steve Balmer | 0.5 | 20
# Warren Buffett | 1.0 | 13
pass
# Step 4: Implement the get_expenses_iterative() method
# This method does the exact same thing as your previous solution, but you must implement it within just this function below. All your work must be within the function. You may not modify the function arguments. Do not use the recursive get_expenses() method in this solution.
def get_expenses_iterative(employee):
#method to iteratively traverse the tree and determine the expense for each employee
#expenses_dict to keep track of the running count for each node, since I can't alter the Employee class to include this variable
expenses_dict = {}
#stacks to help traverse the tree iteratively
stack1 = []
stack2 = []
#initialize stack1 to contain the root
stack1.append(employee)
#use stack1 to comb through the tree, adding nodes in order of visit to stack 2
while stack1:
visit = stack1.pop()
#initialize employee's expenses to their own salary
expenses_dict[visit.name] = visit.salary
stack2.append(visit)
for child in visit.children:
stack1.append(child)
while stack2:
visit = stack2.pop()
# if visiting node has children, add childrens expenses to visiting nodes expenses
# if no children, nothing happense as we already initialized their expenses in the first while loop
if(len(visit.children) > 0):
for child in visit.children:
expenses_dict[visit.name] += expenses_dict[child.name]
#convert expenses_dict to a pretty Pandas DF and print it
print("\nIterative Solution:")
print(pd.DataFrame(expenses_dict.items(), columns=['Employee', 'Expenses']))
pass
# Step 6: Test it
# Expected:
# Steve Jobs | 4.0
# Bill Gates | 1.5
# Steve Balmer | 0.5
# Warren Buffett | 1.0
get_expenses_iterative(company)
# Have a great day!
|
2aa556b46db3f7aca4065431d91ccdb460cd1127 | CodeDeemons/Python-Tkinter-Gui-Project | /Email_Sender/main.py | 4,074 | 3.84375 | 4 | from tkinter import *
import smtplib
from tkinter import messagebox
# making tkinter window
root = Tk()
root.geometry('500x500')
root.title('Email Sender @_python.py_')
root.resizable(False, False)
root.config(bg="#fff")
# variable for Entry box
Email = StringVar()
Password = StringVar()
To = StringVar()
Subject = StringVar()
# In this we make layout for sing in mail id
def emaillogin():
f = Frame(root, height=480, width=500, bg='#FFF')
Label(f, text="Sign in", font=("Helvetica", 30, "bold"), bg='#FFF', fg="#2F9DFF").place(x=180, y=120)
Label(f, text='to continue to Email', font=("Helvetica", 12, "bold"), fg='#666A6C', bg='#FFF').place(x=170, y=170)
Label(f, text='Email', font=("Helvetica", 12, "bold"), fg='#4C4A49', bg='#FFF').place(x=140, y=210)
email = Entry(f, textvariable=Email, font=('calibre',10,'normal'), width=30, bg="#E2E2E2")
email.place(x=140, y=230)
Label(f, text='Password', font=("Helvetica", 12, "bold"), fg='#4C4A49', bg='#FFF').place(x=140, y=280)
password = Entry(f, textvariable=Password, font=('calibre',10,'normal'), width=30, bg="#E2E2E2", show="*")
password.place(x=140, y=300)
Button(f, text='NEXT',font=("Helvetica", 10, "bold"), bg='#2F9DFF',
fg="#FFF", command=mail_verification).place(x=300,y=330)
Label(f, text='Note:',font=("Helvetica", 10, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=400)
Label(f, text='1. If Mail Id is not working use different one.',font=("Helvetica", 8, "bold"),
fg='#4C4A49', bg='#FFF').place(x=20, y=420)
Label(f, text='2. Please remove also email authentication for testing this application.',font=("Helvetica", 8, "bold"),
fg='#4C4A49', bg='#FFF').place(x=20, y=440)
Label(f, text=' otherwise use fake/temporary Mail Id.',font=("Helvetica", 8, "bold"),
fg='#4C4A49', bg='#FFF').place(x=20, y=460)
f.place(x=0, y=0)
# here we make send mail layout like from, to, subject and text box
def mail_compose():
global body
f = Frame(root, height=480, width=500, bg='#FFF')
Label(f, text='New Message', font=("Helvetica", 12, "bold"), fg='#fff', bg='#666A6C').place(x=20, y=20)
Label(f, text='From', font=("Helvetica", 12, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=60)
Label(f, text=f"<{Email.get()}>", font=("Helvetica", 12, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=80)
Label(f, text='To', font=("Helvetica", 12), fg='#4C4A49', bg='#FFF').place(x=20, y=130)
to = Entry(f, textvariable=To, font=('calibre',10,'normal'), width=50, bg="#E2E2E2")
to.place(x=20, y=150)
Label(f, text='Subject', font=("Helvetica", 12), fg='#4C4A49', bg='#FFF').place(x=20, y=170)
subject = Entry(f, textvariable=Subject, font=('calibre',10,'normal'), width=50, bg="#E2E2E2")
subject.place(x=20, y=190)
Label(f, text='Body', font=("Helvetica", 12), fg='#4C4A49', bg='#FFF').place(x=20, y=210)
body = Text(f, font=('calibre',10,'normal'), width=50, bg="#E2E2E2", height=12)
body.place(x=20, y=230)
Button(f, text='Send',font=("Helvetica", 10, "bold"), bg='#2F9DFF', fg="#FFF", command=mail_sending).place(x=20,y=440)
f.place(x=0, y=0)
# here 1st we verify mail after that we call to
# mail_compose fun otherwise it's show error
def mail_verification():
global server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
try:
server.login(Email.get(), Password.get())
mail_compose()
except Exception:
messagebox.showerror('Sign in Error!', 'Please check your email id and password\notherwise use different mail id')
# after verfication we send mail from this function
def mail_sending():
subject = Subject.get()
body_text = body.get("1.0", "end-1c")
msg = f"Subject : {subject} \n\n {body_text}"
server.sendmail(
Email.get(), To.get(), msg )
messagebox.showinfo("Success!", 'mail has been send')
if __name__ == '__main__':
emaillogin()
root.mainloop()
|
060d869ff8c8ff2f96f12ed144303918e087346a | AkashMullick/IntroToCompSci | /SquareRootNewtonRhapson.py | 206 | 3.9375 | 4 | epsilon = 0.01
y = int(input("Square root of: "))
guess = y/2.0
while abs(guess**2 - y) >= epsilon:
guess -= (((guess**2) - y)/(2*guess))
print("The square root of " + str(y) + " is about " + str(guess))
|
09977f7bb06342d557f788306cd560a102fb5849 | aswinvk28/titanic-survival-exploration | /predictions.py | 1,136 | 3.5625 | 4 | import os
import sys
import csv
def import_csv(file_path):
file = open(file_path, 'r')
csvreader = csv.reader(file, delimiter=',')
prediction_data = PredictionData()
for line in csvreader:
prediction_data.append(line)
return prediction_data
def predictions_0(data):
""" Model with no features. Always predicts a passenger did not survive. """
predictions = []
for _, passenger in data.iterrows():
# Predict the survival of 'passenger'
predictions.append(0)
# Return our predictions
return pd.Series(predictions)
# Make the predictions
data = import_csv('titanic_data.csv')
predictions = predictions_0(data)
def predictions_1(data):
""" Model with one feature:
- Predict a passenger survived if they are female. """
predictions = []
for _, passenger in data.iterrows():
# Remove the 'pass' statement below
# and write your prediction conditions here
pass
# Return our predictions
return pd.Series(predictions)
# Make the predictions
predictions = predictions_1(data) |
111f6cb7cda1796488bffea3f9ada5ff3d9fcaeb | obernardovieira/learn-testing | /PythonTest/calculator.py | 628 | 3.65625 | 4 | class Calculator(object):
def __init__(self):
self.history = []
def sum(self, x, y):
result = x + y
self.history += [[x, '+', y]]
return result
def sub(self, x, y):
result = x - y
self.history += [[x, '-', y]]
return result
def mul(self, x, y):
result = x * y
self.history += [[x, '*', y]]
return result
def div(self, x, y):
result = x / y
self.history += [[x, '/', y]]
return result
def get_history(self):
return self.history
def clear_history(self):
self.history = [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.