blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
92e0aa3c1962fdb1ae4eed83d9544230abab919f | ryanSoftwareEngineer/algorithms | /graphs and trees/230_kth_smallest_element_in_a_bst.py | 1,205 | 3.671875 | 4 | '''
Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
'''
# do an in order traversal
# when you reach a node that is none..
# you flag k to start counting down
# when k is 0 you set the answer to that node
# you could set the flag in the class object instead of passing it through the recursive function. it would be a bit easier to read
# so def __init__:
# self.k = None
# self.ans = None
# self.flag = False
#
class Solution:
def kthSmallest(self, root, k):
return self.in_order(root, k, False, None)[2]
def in_order(self, node, k, end, ans):
if ans:
return end, k, ans
if node is None:
end = True
return end, k, ans
end, k, ans = self.in_order(node.left, k, end, ans)
end, k, ans = self.visit(node, k, end, ans)
end, k, ans = self.in_order(node.right, k, end, ans)
return end, k, ans
def visit(self, node, k, end, ans):
if ans:
return end, k, ans
k-=1
if k == 0:
ans = node.val
return end, k, ans
|
30e81797e4d0067d6be86efa63b5d4a595e34459 | ryanSoftwareEngineer/algorithms | /arrays and matrices/121_best_time_to_buy_and_sell_stock.py | 912 | 3.96875 | 4 | '''
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
'''
class Solution:
def maxProfit(self, prices):
# keep track of lowest and highest
# if new low is found set new_low to that and new_highest to 0
# if new_highest - new_low > previous, then update
low = high = prices[0]
summ = 0
for val in prices:
if val < low:
low = high = val
if val > high:
high = val
summ = max(summ, high-low)
print(summ)
return summ
input = [7,1,5,3,6,4]
a = Solution()
a.maxProfit(input)
# output: 5 |
09c6d467d2570b88286da1373664cf74c8f41b53 | ryanSoftwareEngineer/algorithms | /recursion and dynamic programming/substrings_of_size_k.py | 1,305 | 3.859375 | 4 | '''Find all unique substrings containing distinct characters of length k given a string s containing
only lowercase alphabet characters.
Input: s = xabxcd, k = 4
Output: ["abxc", "bxcd"]
Explanation:
The substrings are xabx, abxc, and bxcd. However x repeats in the xabx, so it is not a valid substring of a distinct characters.
'''
# create a hash table
# iterate through string s storing chars in hash table and keeping track of start and end
# if char is in hash table, iterate start until it gets to equal char and move one more
# pop all chars as you go
# then move end until end index - start index == k and continue
def find_subs(s, k):
if len(s)< k:
return
book = {}
start= end = 0
result = set()
while end < len(s):
value = s[end]
if value in book:
print(value,book, start, end, book[value]+1)
while start < book[value]:
book.pop(s[start])
start+=1
book[value]= end
start+=1
else:
book[value] = end
if end-start ==k-1:
sub = s[start:end+1]
if sub not in result:
result.add(sub)
book.pop(s[start])
start+=1
end += 1
return result
s = "aabcdbcd"; k = 3
find_subs(s,k) |
1baa47ebd1d4d7c129f20ffab0f3965ef2ef1296 | ryanSoftwareEngineer/algorithms | /recursion and dynamic programming/1335_min_difficulty_of_schedule.py | 2,096 | 4.0625 | 4 | '''
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i-th job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days.
The difficulty of a day is the maximum difficulty of a job done in that day.
Given an array of integers jobDifficulty and an integer d. The difficulty of the i-th job is jobDifficulty[i].
Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.
Example 1:
Input: jobDifficulty = [6,5,4,3,2,1], d = 2
Output: 7
Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7
Example 2:
Input: jobDifficulty = [7,1,7,1,7,1], d = 3
Output: 15
'''
# attempt one: memoization and recursion
# we're trying to find all possible combinations of the different ways we can partition an array
# if d =2 we want to cut the array in two parts
# [6][5,4,3,2,1]
# [6,5][4,3,2,1]
# [6,5,4][3,2,1]
# [6,5,4,3][2,1]
# [6,5,4,3,2][1]
# so we create a recursive call for [6],[5,4,3,2,1] we test the score for this partition
# then we increment index by one and try [6,5], [4,3,2,1] and test the score again
# so on and so forth.
class Solution:
def minDifficulty(self, jobs: List[int], d: int) -> int:
if d > len(jobs): return -1
def helper(jobs, index, d, cache):
if (index, d) in cache:
return cache[(index, d)]
if d == 1:
cache[(index, 1)] = max(jobs[index:])
return cache[(index, 1)]
answer = float(inf)
maxsofar = 0
for i in range(index, len(jobs) - (d - 1)):
maxsofar = max(jobs[index:i + 1])
a = helper(jobs, i + 1, d - 1, cache)
answer = min(answer, maxsofar + a)
cache[(index, d)] = answer
return answer
return helper(jobs, 0, d, {})
|
d4091ef007d1c4c4790b0706e7778c0b0ff62dc3 | ryanSoftwareEngineer/algorithms | /graphs and trees/shopping_patterns.py | 3,359 | 3.875 | 4 | '''
Your team is trying to understand customer shopping patterns and offer items that are regularly bought together to new customers. Each item that has been bought together can be represented as an undirected graph where edges join often bundled products. A group of n products is uniquely numbered from 1 of product_nodes. A trio is defined as a group of three related products that all connected by an edge. Trios are scored by counting the number of related products outside of the trio, this is referred as a product sum.
Given product relation data, determine the minimum product sum for all trios of related products in the group. If no such trio exists, return -1.
Example
products_nodes = 6
products_edges = 6
products_from = [1,2,2,3,4,5]
products_to = [2,4,5,5,5,6]
Product Related Products
1 2
2 1, 4, 5
3 5
4 2, 5
5 2, 3, 4, 6
6 5
A graph of n = 6 products where the only trio of related products is (2, 4, 5).
The product scores based on the graph above are:
Product Outside Products Which Products Are Outside
2 1 1
4 0
5 2 3, 6
In the diagram above, the total product score is 1 + 0 + 2 = 3 for the trio (2, 4, 5).
'''
# fast first attempt. I remove any leaf nodes from the graph and did a dfs
# that only travels 3 nodes deep looking for 3 node circles to find triple sets
# i probably did not need to remove leaf nodes first but i thought it would reduce the dfs calls by eliminating
# nodes that can't possibly be in the trio
#
# it was implied that the product id's ranged from 0 to product_nodes-1 but it didn't specify this so I accomplished
# the task without utilizing product_nodes and product_edges data. With this data we could cut
# hash tables in exchange for array's where index = id
def getMinScore(product_nodes, product_edges, products_from, products_to):
# store products to in set if
trios = {}
book = {}
for i, b in enumerate(products_from):
a = products_to[i]
if b in book:
book[b].append(a)
else:
book[b] = [a]
if a in book:
book[a].append(b)
else:
book[a] = [b]
nonleaves = set()
for i in book:
if len(book[i]) >1:
nonleaves.add(i)
for c in book:
if c in nonleaves:
path, ans = get_trio(c, book, set())
if ans is True:
if tuple(path) not in trios:
trios[tuple(path)] = path
mini = 2**31
for key in trios:
score = 0
for j in key:
for val in book[j]:
print(j, val, key, nonleaves, score)
if val not in nonleaves:
score+= 1
mini = min(score, mini)
return mini
def get_trio(node, book, visited):
if node not in book or len(book[node])<2:
return visited, None
if len(visited) > 3:
return visited, False
if node in visited:
return visited, True
visited.add(node)
ans = None
for i in book[node]:
if len(book[i]) >1:
visited, ans = get_trio(i, book, visited)
if ans is False:
visited.remove(i)
if ans is None:
ans = False
return visited, ans
products_nodes = 6
products_edges = 6
products_from = [1,2,2,3,4,5]
products_to = [2,4,5,5,5,6]
getMinScore(products_nodes, products_edges, products_from, products_to) |
57cd15146c5a663a0ccaa74d2187dce5c5dc6962 | PabloLSalatic/Python-100-Days | /Days/Day 2/Q6.py | 498 | 4.1875 | 4 | print('------ Q 6 ------')
# ?Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
# ?Suppose the following input is supplied to the program:
# ?Hello world
# ?Practice makes perfect
# *Then, the output should be:
# *HELLO WORLD
# *PRACTICE MAKES PERFECT
lines = []
while True:
line = input('linea: ')
if line:
lines.append(line.upper())
else:
break
for line in lines:
print(line)
|
95747debbbceafd283d76860e01fca9bcc416be5 | jaalorsa517/gestion_mensajeria_API | /app/models/delivery.py | 1,038 | 3.5 | 4 | """Módulo que se encarga de gestionar los mensajeros"""
from csv import DictReader, DictWriter
from os import write
from os.path import join
from app import app
def get_deliveries():
with open(
join(app.root_path, "data", "delivery.csv"), newline=""
) as csv_file:
reader = DictReader(csv_file)
if reader:
return [delivery for delivery in reader]
else:
return []
def save_delivery(delivery,available):
deliveries = get_deliveries()
if deliveries:
for index,delivery_ in enumerate(deliveries):
if delivery == delivery_.get('delivery'):
deliveries[index]['available'] = available
break
with open(
join(app.root_path, "data", "delivery.csv"), "w", newline=""
) as csv_file:
writer = DictWriter(csv_file,['delivery','available'])
writer.writeheader()
writer.writerows(deliveries)
return True
else:
return False
|
c6a3d1beb068a85da6f35c73d2e5f61539d252c2 | javierfrjunior2/Python | /numero_de_pares.py | 246 | 3.796875 | 4 | def numero_de_pares():
pares=0
numero=input("Dime cualquier numero")
while numero>0:
if (numero%10)%2==0:
pares=pares+1
numero=numero/10
print "El numero tiene",pares,"pares"
numero_de_pares()
|
7902ec6be552b5e44af3e0c73335acd52c7cb3e7 | 44858/lists | /Bubble Sort.py | 609 | 4.28125 | 4 | #Lewis Travers
#09/01/2015
#Bubble Sort
unsorted_list = ["a", "d", "c", "e", "b", "f", "h", "g"]
def bubble_sort(unsorted_list):
list_sorted = False
length = len(unsorted_list) - 1
while not list_sorted:
list_sorted = True
for num in range(length):
if unsorted_list[num] > unsorted_list[num+1]:
list_sorted = False
unsorted_list[num], unsorted_list[num+1] = unsorted_list[num+1], unsorted_list[num]
return unsorted_list
#main program
sorted_list = bubble_sort(unsorted_list)
print(sorted_list)
|
10b8fb226ad47e75500e17eaff0197ed2d6eb447 | lbingle/Think-Python | /hexagon_pie.py | 185 | 3.5 | 4 | import turtle
import math
bob = turtle.Turtle()
print(bob)
l = 100
a = 120
b = 60
for i in range (6):
for i in range(3):
bob.fd(l)
bob.rt(a)
bob.rt(b)
|
7e317b88cd28f4c8c5f9a449564826a30cf138bc | lbingle/Think-Python | /Rose2.py | 549 | 4 | 4 | import turtle
import math
bob = turtle.Turtle()
print(bob)
def polyline(t, n, length, angle):
for i in range(n):
t.fd(length)
t.lt(angle)
def arc(t, angle, pedal):
radius = 200
arc_length = 2*math.pi*radius*angle/360
n = 50
step_length = arc_length/n
step_angle = angle/n
outer_angle = 180-angle
for i in range(10):
polyline(t, n, step_length, step_angle)
t.lt(outer_angle)
polyline(t, n, step_length, step_angle)
t.lt(angle)
def rose(t, pedal):
angel = 180/pedal
arc(t, angel, pedal)
rose(bob, 5)
turtle.mainloop()
|
e01e7aed7bdc3f3969c2d9ad640cdc5ffec72bb9 | anandnevase/bday-app | /bday-app/app.py | 4,957 | 3.5625 | 4 | from flask import Flask
from flask import request
from flask import jsonify
from flask import json
import datetime
import sqlite3
from flask import g
app = Flask(__name__)
#userlist={"userlist":[]}
@app.route('/hello', methods=['GET'])
def get_userlist():
if request.method == 'GET':
myuserlist = query_db('select * from user')
return jsonify({"userlist": myuserlist}),200
@app.route('/hello/<username>', methods=['GET','PUT'])
def hello_world(username):
if request.method == 'GET':
user_found = False
user = query_db('select * from user where username = ?',(username,), one=True)
if user is not None:
if user["username"] == username:
user_found = True
dob = datetime.datetime.strptime(user["dateOfBirth"], '%Y-%m-%d')
if check_dob_today(dob):
return display("Hello, %s! Happy Birthday!" %(user["username"]))
else:
days = calculate_dates(dob)
return display("Hello, %s! Your birthday is in %s day(s)" %(user["username"], days))
else:
if user_found == False:
return display("username %s not found" % (username)), 400
if request.method == 'PUT':
#check username contains only letters
if not username.isalpha():
return display("Username shoud contains only letters"), 400
request_data = json.loads(request.data)
if request_data!=None and request_data != {}:
dob = request_data.get('dateOfBirth')
if dob:
#check date format YYYY-MM-DD
if not validate_dob(dob):
return display("Incorrect data format, should be YYYY-MM-DD"), 400
#check dateofbirth is less then todays date
if datetime.datetime.strptime(dob, '%Y-%m-%d').date() >= datetime.date.today():
return display("Birth day should be less than equal to todays date: "+str(datetime.date.today())), 400
else:
return display("Request params are missing. Please pass dateOfBirth. E.g {'dateOfBirth': '1988-01-02'}"), 400
user = query_db('select * from user where username = ?',(username,), one=True)
print("PUT:: user:"+str(user))
if user is None:
query_db('insert into USER (username, dateOfBirth) values(?,?)',(username,dob,), insert_update=True)
return display('username successfully added!'), 204
else:
query_db('update USER set dateOfBirth=? where username=?',(dob,username,),insert_update=True)
return display('username successfully updated!'), 204
#userlist['userlist'].append({'username': username, "dateOfBirth":dob})
def display(msg):
return jsonify({"message":msg})
def validate_dob(date_text):
is_date_valid = True
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
is_date_valid = False
return is_date_valid
def check_dob_today(original_date):
now = datetime.datetime.now()
if now.day == original_date.day and now.month == original_date.month:
return True
return False
def calculate_dates(original_date):
now = datetime.datetime.now()
delta1 = datetime.datetime(now.year, original_date.month, original_date.day)
delta2 = datetime.datetime(now.year+1, original_date.month, original_date.day)
if original_date.month >= now.month and original_date.day >= now.day:
days = (delta1 - now).days + 1
else:
days = (delta2 - now).days
return days
DATABASE = './database/revolut.db'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('./db-schema/schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def query_db(query, args=(), one=False, insert_update=False):
con = get_db()
con.row_factory = dict_factory
cur = con.cursor()
cur = cur.execute(query, args)
if not insert_update:
rv = cur.fetchall()
cur.close()
result= (rv[0] if rv else None) if one else rv
#print("Type:"+str(type(result)))
return result
else:
con.commit()
cur.close()
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
if __name__ == '__main__':
try:
init_db()
except:
print("DB already Exists!!")
app.run(host='0.0.0.0', port=80,debug=True)
|
3ec3a1ef9d822dad32d77313b8026164841e743f | dlievre/python | /d01/all_in.py | 1,567 | 3.515625 | 4 |
def isState(param, states, capital_cities):
if param in states:
return getCapitalOfState(param, states, capital_cities)
def isCapital(param, states, capital_cities):
if param in capital_cities.values():
return getStateOfCapital(param, states, capital_cities)
def getStateOfCapital(param, states, capital_cities):
if param in capital_cities.values():
for key in capital_cities:
if capital_cities[key] == param:
for key2 in states:
if states[key2] == key:
return key2
def getCapitalOfState(param, states, capital_cities):
return capital_cities[states[param]]
def formatWord(param):
resulta = param.rstrip()
resultb = resulta.lstrip()
resultc = resultb.title()
return resultc
if __name__ == '__main__':
import sys
if len(sys.argv) == 2:
states = {
"Oregon" : "OR",
"Alabama" : "AL",
"New Jersey": "NJ",
"Colorado" : "CO"
}
capital_cities = {
"OR": "Salem",
"AL": "Montgomery",
"NJ": "Trenton",
"CO": "Denver"
}
newlist = sys.argv[1].split(',')
for paramBrut in newlist:
param = formatWord(paramBrut)
St = 0
Ca = 0
chkState = isState(param, states, capital_cities)
if chkState:
St = 1
print (getCapitalOfState(param, states, capital_cities), 'is the capital of', param)
chkCapital = isCapital(param, states, capital_cities)
if chkCapital:
Ca = 1
print (param, 'is the capital of', getStateOfCapital(param, states, capital_cities))
if Ca + St == 0 and len(param) >0:
print (paramBrut.rstrip().lstrip(),'is neither a capital city nor a state') |
cc65ccc6d616b280f9fbff06272db4a2359a57ac | milktea8285/Interview | /Trend-1.py | 984 | 4 | 4 | # 1. clock 15:10:10 - 15:15:15 find time with at most two integer
from datetime import datetime, timedelta
import time
# Determine if it has more than two numbers
def isTwoNum(S):
dic = {}
count = 0
if len(S) < 6:
dic[0] = 1
count += 1
for s in S:
if s not in dic.keys():
dic[s] = 1
count += 1
if count > 2:
return False
return True
# Datetime to deal with second plus, string to compare numbers counter
def solution(S, T):
S = datetime.strptime(S, "%H:%M:%S")
T = datetime.strptime(T, "%H:%M:%S")
result = 0
while True:
timeStr = str(S.hour) + str(S.minute) + str(S.second)
if isTwoNum(timeStr):
result += 1
print S.strftime("%H:%M:%S")
S += timedelta(seconds=1)
if S == T:
break
# print result
return result
# Test Case
solution ("15:15:15", "15:16:05") |
a0d8aa7501b9bd7ae8375f3841c03457ad8a481e | Aynazik/2021_starchenko_infa | /lab2/exs13.py | 674 | 3.796875 | 4 | import turtle as t
t.hideturtle()
def circle(k):
for _ in range(50):
t.forward(k)
t.left(36 / 5)
def halfcircle(k):
for _ in range(25):
t.forward(k)
t.right(36 / 5)
t.shape('turtle')
t.begin_fill()
circle(7)
t.color('yellow')
t.end_fill()
t.color('black')
t.penup()
t.goto(-15, 70)
t.pendown()
t.begin_fill()
circle(1)
t.color('blue')
t.end_fill()
t.color('black')
t.penup()
t.goto(25, 70)
t.pendown()
t.begin_fill()
circle(1)
t.color('blue')
t.end_fill()
t.color('black')
t.penup()
t.goto(5, 60)
t.right(90)
t.pendown()
t.width(5)
t.forward(15)
t.penup()
t.goto(30, 35)
t.pendown()
t.color('red')
halfcircle(3)
t.exitonclick()
|
6920bedb8cafbca14d58b7923f024394cb41bb07 | Aynazik/2021_starchenko_infa | /lab3/exs1.py | 147 | 3.59375 | 4 | import turtle as t
import random
t.speed(0)
t.shape('circle')
while True:
t.forward(25 * random.random())
t.right(360 * random.random())
|
fee4831ef102d440d800c1142a2420e843aa8808 | SebastiGarmen/checkout | /productosEmpleados.py | 971 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Persona:
nombre = ""
apellido = ""
edad = 0
nacionalidad = ""
sexo = ""
def __init__(self, nombre="NA", apellido="NA", edad="NA", nacionalidad="mexicano", sexo=""):
self.nombre = nombre
self.apellido = apellido
self.edad = edad
self.nacionalidad = nacionalidad
self.sexo = sexo
class Empleado(Persona):
salario= 0
antiguedad= 0
area= 0.0
class Directivo(Empleado): #aqui en lugar de persona pudiera ser (empleado) para aprovechar lo que se puso atras
numeroDeEstacionamiento= 0
numeroDeOficina= 0
semanasDeVacaciones= 0
diasEnCasaClub= 0
empleado1 = Empleado("Jorge", "Lopez", 38, "Mexicano", "M" )
print(empleado1.nombre)
print(empleado1.apellido)
print(empleado1.edad)
print(empleado1.nacionalidad)
print(empleado1.sexo)
print(empleado1.diasDeVacaciones)
print(empleado1.salarioSemanal)
print(empleado1.numeroDeCubiculo)
|
44c1cd0140dab1a369406292c8c7865f96e69e1c | HarryIsSecured/chattybot-python-hyperskill | /Problems/Healthy sleep/task.py | 196 | 3.53125 | 4 | a = int(input()) # Recommended
b = int(input()) # Over
h = int(input()) # Input
if h < a:
print('Deficiency')
else:
if h > b:
print('Excess')
else:
print('Normal')
|
3bb3f7cf5db3a34c6181fe369eddf4727579d2c9 | ivanjureta/new-concept-networks | /archive/v0/analysis/ilang_f_output_text.py | 615 | 3.96875 | 4 | # Functions to print to text files
# Print text to text file.
def print_to_txt(file_content, project_name, content_description, save_to_project_dir = False):
import os
from tabulate import tabulate
output_file_name = project_name + '_' + content_description + '.txt'
if save_to_project_dir == False:
with open(output_file_name, "w") as text_file:
print(tabulate(file_content, tablefmt="pipe"), file=text_file)
else:
os.chdir(project_name)
with open(output_file_name, "w") as text_file:
print(file_content, file=text_file)
os.chdir('..')
|
b0de2b2dcdf3e54d03182cfc106d976b90f0095c | danieljohnson107/EmpDat-Payroll | /payroll.py | 4,879 | 3.5 | 4 | from abc import ABC, abstractmethod
import os, os.path
PAY_LOGFILE = "paylog.txt"
employees = []
def load_employees():
"""Loads employee data into memory and creates an instance of the employee object for each entry"""
with open("employees.csv", "r") as emp_file:
first_line = True
for line in emp_file:
if first_line:
first_line = False
continue
tmp = line[:-1].split(",")
employees.append(Employee(tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5],tmp[6],int(tmp[7]),float(tmp[8]),float(tmp[9]),float(tmp[10])))
def process_timecards():
"""Processes time cards for hourly employees"""
with open("timecards.csv", "r") as time_file:
for line in time_file:
emp_time = line[:-1].split(",")
emp = find_employee_by_id(emp_time[0])
if isinstance(emp.classification, Hourly):
for hours in emp_time[1:]:
emp.classification.add_timecard(float(hours))
def process_receipts():
"""Processes reciepts for commissioned employees"""
with open("receipts.csv", "r") as receipts_file:
for line in receipts_file:
emp_receipts = line[:-1].split(",")
emp = find_employee_by_id(emp_receipts[0])
if isinstance(emp.classification, Commissioned):
for receipt in emp_receipts[1:]:
emp.classification.add_receipt(float(receipt))
def run_payroll():
"""Runs payroll for all employees"""
if os.path.exists(PAY_LOGFILE): # pay_log_file is a global variable holding ‘payroll.txt’
os.remove(PAY_LOGFILE)
for emp in employees: # employees is the global list of Employee objects
emp.issue_payment() # issue_payment calls a method in the classification
# object to compute the pay, which in turn invokes
# the pay method.
def find_employee_by_id(id):
for employee in employees:
if employee.emp_id == id:
return employee
class Employee():
"""Defines an Employee object
Required Params: emp_id, first_name, last_name, address, city, state, postal_code, classification, salary, commission, hourly
"""
def __init__(self, emp_id, first_name, last_name, address, city, state, postal_code, classification, salary, commission, hourly):
self.emp_id = emp_id
self.first_name = first_name
self.last_name = last_name
self.address = address
self.city = city
self.state = state
self.postal_code = postal_code
if classification == 1:
self.classification = Salaried(salary)
elif classification == 2:
self.classification = Commissioned(salary, commission)
else:
self.classification = Hourly(hourly)
def make_hourly(self, hourly_rate):
"""Sets the Employee classification to hourly"""
self.classification = Hourly(hourly_rate)
def make_salaried(self, salary):
"""Sets the Employee classification to salaried"""
self.classification = Salaried(salary)
def make_commissioned(self, salary, commission_rate):
"""Sets the Employee classification to commissioned"""
self.classification = Commissioned(salary, commission_rate)
def issue_payment(self):
"""Issues payment to employee"""
pay = self.classification.compute_pay()
if pay > 0:
with open(PAY_LOGFILE, "a") as paylog:
print("Mailing", f"{pay:.2f}", "to", self.first_name, self.last_name,
"at", self.address, self.city, self.state, self.postal_code, file=paylog)
class Classification(ABC):
@abstractmethod
def compute_pay(self):
pass
class Hourly(Classification):
"""Defines methods for hourly Employees"""
def __init__(self, hourly_rate):
self.hourly_rate = hourly_rate
self.timecard = []
def add_timecard(self, hours):
self.timecard.append(hours)
def compute_pay(self):
pay = round(sum(self.timecard)*self.hourly_rate, 2)
self.timecard.clear()
return pay
class Salaried(Classification):
"""Defines methods for salaried Employees"""
def __init__(self, salary):
self.salary = salary
def compute_pay(self):
return round(self.salary/24, 2)
class Commissioned(Salaried):
"""Defines methods for commissioned Employees"""
def __init__(self, salary, commission_rate):
super().__init__(salary)
self.commission_rate = commission_rate
self.receipts = []
def add_receipt(self, amount):
self.receipts.append(amount)
def compute_pay(self):
pay = round((sum(self.receipts)*self.commission_rate/100)+self.salary/24, 2)
self.receipts.clear()
return pay |
04f3fbda2d7553f9450a90d7b8d64b604e29fef2 | danieljohnson107/EmpDat-Payroll | /Checkpoints/Sprint Something/EnterNewEmployee.py | 10,012 | 3.875 | 4 | from tkinter import *
# from PIL import imageTk, Image
from UserData import *
from GuiValues import *
ud = UserData()
gv = GuiValues()
''' to use images yoy need to install pillow
install with "pip install pillow" on your python to use
ImageTk.PhotoImage(Image.open("imagename.png"))
put image in widget
then put on page
'''
''' everything is a widget
start with a self
widget
this shoudl be first every time you use tkinter'''
'''define the action the function will take'''
class EnterNewEmployee(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
# Object list
''' to create anyting you need to do two things
first create the item then put it in a location'''
fNameLabel = Label(self, text="First Name:")
lNameLabel = Label(self, text="Last Name:")
addressLabel = Label(self, text='Address:')
addressLineTwoLabel = Label(self, text='Address Line 2:')
cityLabel = Label(self, text='City:')
stateLabel = Label(self, text='State:')
zipCodeLabel = Label(self, text='Zip:')
phoneLabel = Label(self, text='Phone Number:')
classificationLabel = Label(self, text='Classification:')
empNumberLabel = Label(self, text='Employee Number:')
passwordLabel = Label(self, text='Password:')
departmentLabel = Label(self, text='Department:')
payRateLabel = Label(self, text='Pay Rate:')
payYTDLabel = Label(self, text='Pay YTD:')
securityAccessLabel = Label(self, text='Security Access:')
spacer = Label(self, text=" ")
# button
employeesButton = Button(self, text="Employee's",
width=gv.buttonWidth,
bg=gv.buttonColor,
height=gv.buttonHeight,
command=self.employees,
state=DISABLED)
timeCardsButton = Button(self, text='Timecardsards',
width=gv.buttonWidth,
height=gv.buttonHeight,
bg=gv.buttonColor,
command=self.timecards)
salesButton = Button(self, text=' Sales ',
width=gv.buttonWidth,
height=gv.buttonHeight,
command=self.sales,
bg=gv.buttonColor)
myProfileButton = Button(self, text='My Profile',
width=gv.buttonWidth,
height=gv.buttonHeight,
command=self.myProfile, bg=gv.buttonColor)
newEmployeeButton = Button(self, text='Enter New\nEmployee',
width=gv.buttonWidth,
height=gv.buttonHeight,
command=self.newEmployee,
bg=gv.buttonColor,
state=DISABLED)
findEmployeeButton = Button(self, text='Find Employee',
width=gv.buttonWidth,
height=gv.buttonHeight,
command=self.findEmployee,
bg=gv.buttonColor)
importEmployeeButton = Button(self, text='Import txt of\nnew Employees',
width=gv.buttonWidth,
height=gv.buttonHeight,
command=self.importEmployee,
bg=gv.buttonColor)
saveProfileButton = Button(self, text='Save',
width=gv.buttonWidth,
height=gv.buttonHeight,
command=self.saveChanges,
bg=gv.buttonColor)
payrollButton = Button(self, text="Payroll",
width=gv.buttonWidth,
height=gv.buttonHeight,
command=self.pay,
bg=gv.buttonColor)
# input box for client data input
# e.get() will retreive the input from the field
fNameInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
lNameInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
addressInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
addressTwoInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
cityInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
stateInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
zipInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
phoneInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
classInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
empNumInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
passwordInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
departmentInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
payRateInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
payYTDInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
securityInput = Entry(self, bg=gv.inputEditColor,
borderwidth=gv.inputBorderWidth)
# location of items on the screen
''' you can put things into specific locations,
but for now we will pack it in.
we will usually use a place system to define locations of
items on the interface.
everything is a place with ys up and down and
xs left to right.
consider this like a table with 0 - N on the locations
You can add these commands to the creation above as well
if you would like. ie spacer = Label(self
, text='').place(x=0,y=0)
'''
# set all locations on form
# buttons
employeesButton.place(x=0, y=0)
timeCardsButton.place(x=185, y=0)
salesButton.place(x=370, y=0)
payrollButton.place(x=555, y=0)
myProfileButton.place(x=740, y=0)
newEmployeeButton.place(x=0, y=40)
findEmployeeButton.place(x=0, y=80)
importEmployeeButton.place(x=0, y=120)
saveProfileButton.place(x=0, y=160)
# Labels
fNameLabel.place(x=200, y=40)
lNameLabel.place(x=200, y=65)
addressLabel.place(x=200, y=90)
addressLineTwoLabel.place(x=200, y=115)
cityLabel.place(x=200, y=140)
stateLabel.place(x=200, y=165)
zipCodeLabel.place(x=200, y=190)
phoneLabel.place(x=200, y=215)
classificationLabel.place(x=200, y=240)
empNumberLabel.place(x=200, y=265)
passwordLabel.place(x=200, y=290)
departmentLabel.place(x=200, y=315)
payRateLabel.place(x=200, y=340)
payYTDLabel.place(x=200, y=365)
securityAccessLabel.place(x=200, y=390)
# Inputs
fNameInput.place(x=340, y=40, width=gv.inputWidth,
height=gv.inputHeight)
lNameInput.place(x=340, y=65, width=gv.inputWidth,
height=gv.inputHeight)
addressInput.place(x=340, y=90, width=gv.inputWidth,
height=gv.inputHeight)
addressTwoInput.place(x=340, y=115, width=gv.inputWidth,
height=gv.inputHeight)
cityInput.place(x=340, y=140, width=gv.inputWidth,
height=gv.inputHeight)
stateInput.place(x=340, y=165, width=gv.inputWidth,
height=gv.inputHeight)
zipInput.place(x=340, y=190, width=gv.inputWidth,
height=gv.inputHeight)
phoneInput.place(x=340, y=215, width=gv.inputWidth,
height=gv.inputHeight)
classInput.place(x=340, y=240, width=gv.inputWidth,
height=gv.inputHeight)
empNumInput.place(x=340, y=265, width=gv.inputWidth,
height=gv.inputHeight)
passwordInput.place(x=340, y=290, width=gv.inputWidth,
height=gv.inputHeight)
departmentInput.place(x=340, y=315, width=gv.inputWidth,
height=gv.inputHeight)
payRateInput.place(x=340, y=340, width=gv.inputWidth,
height=gv.inputHeight)
payYTDInput.place(x=340, y=365, width=gv.inputWidth,
height=gv.inputHeight)
securityInput.place(x=340, y=390, width=gv.inputWidth,
height=gv.inputHeight)
def pay(self):
self.controller.show_frame("PayrollProcessing")
def employees(self):
self.controller.show_frame("FindEmployee")
def timecards(self):
pass
def sales(self):
pass
def myProfile(self):
self.controller.show_frame("MyProfile")
def newEmployee(self):
self.controller.show_frame("EnterNewEmployee")
def findEmployee(self):
self.controller.show_frame("FindEmployee")
def importEmployee(self):
pass
def saveChanges(self):
pass
|
77ef65d344b1306138c43cfd77ee29774126d632 | THEIOTIDIOT/data_structures_and_algorithms | /P1/huffman_coding_task_3.py | 2,855 | 3.5 | 4 | import sys
class Node:
def __init__(self, value):
self.value = value
self.char = None
self.left_child = None
self.right_child = None
self.left_code = None
self.right_code = None
def set_value(self, value):
self.value = value
def get_value(self):
return self.value
def set_char(self, char):
self.char = char
def get_char(self):
return self.char
def set_left_child(self, left):
self.left = left
def get_left_child(self):
return self.left_child
def set_right_child(self, right):
self.right = right
def get_right(self):
return self.right
def has_right_child(self):
return self.right is not None
def has_left_child(self):
return self.left is not None
def set_left_code(self, left_code):
self.left_code = left_code
def get_left_code(self):
return self.left_code
def set_right_code(self, right_code):
self.right_code = right_code
def get_right_code(self):
return self.right_code
def __repr__(self):
return repr((self.value, self.char))
class Tree:
def __init__(self):
self.root = None
def set_root(self, value):
self.root = Node(value)
def get_root(self):
return self.root
def char_freq_dict(data):
char_freq = {}
for char in data:
if char in char_freq:
char_freq[char] += 1
else:
char_freq[char] = 1
return char_freq
def huffman_encoding(data):
freq = ''
freq_tup = tuple()
char_freq_list = list()
char_freq_lo_hi_list = list()
char_set = set(data)
char_list = list(char_set)
#take a string and determine the relevant frequencies of the characters
char_dict = char_freq_dict(data)
#build and sort a list of tuples from lowest to highest frequencies
for item in char_list:
freq = char_dict[item]
new_node = Node(freq)
new_node.set_char(item)
char_freq_list.append(new_node)
#one way to generate a sorted list
#char_freq_lo_hi_list = min_heap_queue(char_freq_list)
char_freq_lo_hi_list = sorted(char_freq_list, key=lambda freq: cha)
#build a huffman tree by assigning a binary code to each letter, using
#shorter codes for the more frequent letters. (This is the heart of the
#huffman algorithm.)
#trim the Huffman Tree (remove the frequencies from the previously built
#tree)
return char_freq_lo_hi_list
def recursive_huffman_tree(char_freq_lo_hi_list):
#if char_freq_lo_hi_list == 1:
# return
pass
def min_heap_queue(char_freq_list):
#return sorted(char_freq_list, key=lambda freq: node.value)
pass
#def huffman_decoding(data,tree):
# pass
|
5e0280d79cfd8be76595523a7c329bd0c6735ad3 | THEIOTIDIOT/data_structures_and_algorithms | /P1/recursion_indexed_linear_time.py | 2,284 | 4.03125 | 4 | """
def sum_array_index(array, index):
# Base Cases
if len(array) - 1 == index:
return array[index]
return array[index] + sum_array_index(array, index + 1)
arr = [1, 2, 3, 4]
print(sum_array_index(arr, 0))
"""
"""
def recursion(listy, num):
if len(listy) == 0:
print('False')
return False
for item in listy:
if isinstance(item, list):
recursion(item, num)
else:
if num == item:
print('True')
return True
else:
continue
listy = [1,[1,2],[1,2,[1,88,3]]]
recursion(listy, 88)
"""
"""
def addDigits(num):
new_num = 0
num_str = str(num)
for n in num_str:
new_num += int(n)
if num < 10:
return num
return addDigits(new_num)
num = 38
print(addDigits(num))
"""
def permutations(string):
"""
:param: input string
Return - list of all permutations of the input string
TODO: complete this function to return a list of all permutations of the string
"""
return return_permutation(string, 0)
def return_permutation(string, index):
if index >= len(string):
return [""]
small_output = return_permutation(string, index + 1)
output = []
current_char = string[index]
for permutation in small_output:
for index in range(len(small_output[0]) + 1):
new_permutation = permutation[0:index] + current_char + permutation[index:]
output.append(new_permutation)
return output
def test_function(test_case):
string = test_case[0]
solution = test_case[1]
output = permutations(string)
output.sort()
solution.sort()
if output == solution:
print("Pass")
else:
print("Fail")
string = 'ab'
solution = ['ab', 'ba']
test_case = [string, solution]
test_function(test_case)
string = 'abc'
output = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']
test_case = [string, output]
test_function(test_case)
string = 'abcd'
output = ['abcd', 'bacd', 'bcad', 'bcda', 'acbd', 'cabd', 'cbad', 'cbda', 'acdb', 'cadb', 'cdab', 'cdba', 'abdc', 'badc', 'bdac', 'bdca', 'adbc', 'dabc', 'dbac', 'dbca', 'adcb', 'dacb', 'dcab', 'dcba']
test_case = [string, output]
test_function(test_case) |
1e40b7e83b0f6b42321108d478be47b6610fabe8 | terrywang15/optim_assignment | /knapsack/stupid_tree_search.py | 7,161 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
def parse_input(file_location):
with open(file_location, 'r') as input_data_file:
input_data = input_data_file.read()
Item = namedtuple("Item", ['index', 'value', 'weight'])
# parse the input
lines = input_data.split('\n')
firstLine = lines[0].split()
item_count = int(firstLine[0])
capacity = int(firstLine[1])
items = []
for i in range(1, item_count+1):
line = lines[i]
parts = line.split()
items.append(Item(i-1, int(parts[0]), int(parts[1])))
return items, capacity
class Node:
def __init__(self, depth, choice, val, weight):
"""
depth is how deep the node is in the tree structure
choices is either 1 (chosen) or 0 (not chosen)
"""
self.id = str(depth) + str(choice)
self.val = val
self.weight = weight
self.depth = depth
self.choice = choice
self.children = []
self.parent = []
self.path = []
def add_children(self, other_node):
self.children.append(other_node)
def add_parent(self, other_node):
self.parent.append(other_node)
def get_children(self):
return self.children
def get_parent_id(self):
if len(self.parent) == 0:
pass
else:
return [n.id for n in self.parent]
def get_path(self):
path = []
cur_node = self
while cur_node is not None:
path.insert(0, cur_node.id)
cur_node = cur_node.parent
return path
def populate_nodes(items):
yes_nodes = [Node(idx, 1, val, weight) for idx, val, weight in items]
no_nodes = [Node(idx, 0, val, weight) for idx, val, weight in items]
# root note denoted by -1-1
root_node = Node(-1, -1, 0, 0)
root_node.add_children(yes_nodes[0])
root_node.add_children(no_nodes[0])
all_nodes = [root_node]
# Nodes have to be sorted by their index
for idx, node in enumerate(yes_nodes):
if idx == 0:
node.add_parent(root_node)
else:
node.add_parent(yes_nodes[idx-1])
node.add_parent(no_nodes[idx-1])
if idx == len(yes_nodes)-1:
pass
else:
node.add_children(yes_nodes[idx+1])
node.add_children(no_nodes[idx+1])
all_nodes.append(node)
for idx, node in enumerate(no_nodes):
if idx == 0:
node.add_parent(root_node)
else:
node.add_parent(yes_nodes[idx-1])
node.add_parent(no_nodes[idx-1])
if idx == len(yes_nodes)-1:
pass
else:
node.add_children(yes_nodes[idx+1])
node.add_children(no_nodes[idx+1])
all_nodes.append(node)
return all_nodes
def find_node(all_nodes, depth, choice):
"""
find index of node given id
"""
idx = str(depth) + str(choice)
return all_nodes[[n.id for n in all_nodes].index(idx)]
def back_to_last_left(path):
"""
find where is the last step where choice is 1:
reverse the index of choices, grab index of first 1, add 1, add minus sign,
gives you index of the last 1
"""
return path[:-([n.choice for n in path][::-1].index(1))]
def calculate_score(path, max_weight):
"""
returns objective function given path
"""
# check if total weight > weight constraint
if sum([n.weight*n.choice for n in path]) > max_weight:
return -1000000
return sum([n.val*n.choice for n in path])
def traverse_tree_stupid(all_nodes, capacity=10):
"""
traverses the tree in a depth first search manner, exhaust all solutions,
and returns list of solutions
"""
# root has to be the first node
cur_node = all_nodes[0]
# visited = set([cur_node])
path = [cur_node]
solutions = []
# while not solved or len_solutions == 2**((len(all_nodes)-1)/2):
while True:
# if reached the deepest layer and is in the left branch,
# go up to the last step in path where the step's choice is 1,
# and go to the node with the same depth but choice 0
# print("currently at " + cur_node.id)
if path[-1].depth+1 == (len(all_nodes)-1)/2:
# currently at left branch, go to right branch
if path[-1].choice == 1:
# print("at bottom left")
solutions.append(([n.id for n in path], calculate_score(path, capacity)))
# remove last step in path
cur_node = find_node(all_nodes, path[-1].depth, 0)
path = path[:-1]
path.append(cur_node)
# print('going to the right')
elif path[-1].choice == 0:
# find where is the last step where choice is 1:
# reverse the index of choices,
# grab index of first 1, add 1, add minus sign,
# gives you index of the last 1
# print("at bottom right")
# make calculations
solutions.append(([n.id for n in path], calculate_score(path, capacity)))
# try skipping back to lowest depth where choice is 1
# If can't find it it means that you have to
# print("trying to go back up")
try:
path = back_to_last_left(path)
cur_node = find_node(all_nodes, path[-1].depth, 0)
path = path[:-1]
path.append(cur_node)
except:
# exhausted solutions if all nodes in the deepest layer are visited
break
else:
# Go one layer deeper to the left
cur_node = find_node(all_nodes, path[-1].depth+1, 1)
path.append(cur_node)
# print("going one layer deeper to " + cur_node.id)
# get the solution with the highest calculate_score
best_solution = sorted(solutions, key=lambda x: x[1], reverse=True)[0]
# return solutions
return best_solution
def write_output(best_solution):
"""
Parses best_solution's path and returns desired strings
"""
output_data = str(best_solution[1]) + ' ' + str(1) + '\n'
output_data += ' '.join([i[1] for i in best_solution[0] if int(i[1]) != -1])
return output_data
def solve_it(items, capacity):
# Modify this code to run your optimization algorithm
# populate nodes into searchable tree
all_nodes = populate_nodes(items)
# Traverse tree to find best solution
best_solution = traverse_tree_stupid(all_nodes, capacity=capacity)
# prepare the solution in the specified output format
return write_output(best_solution)
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
file_location = sys.argv[1].strip()
items, capacity = parse_input(file_location)
# solve the problem
print(solve_it(items, capacity))
else:
print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)')
|
8bdad239bf2f477aa074cc51f058db1d5f4c66ff | MikeMull10/spanishproject | /Post.py | 1,490 | 3.671875 | 4 | import pygame
from math import *
class Post:
def __init__(self, screen, x, y):
self.win = screen
self.x = x
self.y = y
self.dx = 0
self.dy = 0
self.radius = 16
self.gravity = .8
def tick(self):
self.x += self.dx
self.y += self.dy
self.dy += self.gravity
if self.x <= self.radius or self.x >= 1280 - self.radius:
self.dx = -self.dx
if self.y <= self.radius or self.y >= 720 - self.radius:
self.dy = -self.dy
def draw(self):
pygame.draw.circle(self.win, [0, 0, 0], (int(self.x), int(self.y)), self.radius)
def collide(self, ball):
cx, cy = 0, 0
distance = sqrt((self.x - ball.x) ** 2 + (self.y - ball.y) ** 2)
if distance <= 40:
dx = self.x - ball.x
dy = self.y - ball.y
if dx == 0:
return 0, 0
angle = atan(dy / dx)
if ball.dx > 10:
cx = cos(angle) * 25
else:
cx = cos(angle) * (15 + ball.dx)
if ball.dy > 10:
cy = sin(angle) * 25
else:
cy = sin(angle) * (15 + ball.dy)
if ball.x < self.x:
cx = -abs(cx)
elif ball.x > self.x:
cx = abs(cx)
if ball.y < self.y:
cy = -abs(cx)
elif ball.y > self.y:
cy = abs(cx)
return cx, cy
|
90b59d5607388d4f18382624219a9fcfd7c9cf17 | LorenzoY2J/py111 | /Tasks/d0_stairway.py | 675 | 4.3125 | 4 | from typing import Union, Sequence
from itertools import islice
def stairway_path(stairway: Sequence[Union[float, int]]) -> Union[float, int]:
"""
Calculate min cost of getting to the top of stairway if agent can go on next or through one step.
:param stairway: list of ints, where each int is a cost of appropriate step
:return: minimal cost of getting to the top
"""
prev_1, prev = stairway[0], stairway[1]
for cost in islice(stairway, 2, len(stairway)):
current = cost + min(prev_1, prev)
prev_1, prev = prev, current
return prev
if __name__ == '__main__':
stairway = [1, 3, 5, 1]
print(stairway_path(stairway))
|
15242cc4f007545a85c3d7f65039678617051231 | LorenzoY2J/py111 | /Tasks/b1_binary_search.py | 841 | 4.1875 | 4 | from typing import Sequence, Optional
def binary_search(elem: int, arr: Sequence) -> Optional[int]:
"""
Performs binary search of given element inside of array
:param elem: element to be found
:param arr: array where element is to be found
:return: Index of element if it's presented in the arr, None otherwise
"""
first = 0
last = len(arr) - 1
while first <= last:
mid = (last + first) // 2
if elem == arr[mid]:
break
elif elem < arr[mid]:
last = mid - 1
else:
first = mid + 1
else:
return None
while mid > 0 and arr[mid - 1] == elem:
mid -= 1
return mid
def main():
elem = 10
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(binary_search(elem, arr))
if __name__ == '__main__':
main()
|
7941328e4cb2d286fefd935541e2dab8afde61c0 | SACHSTech/ics2o1-livehack---2-Maximilian-Schwarzenberg | /problem2.py | 771 | 4.59375 | 5 | """
-------------------------------------------------------------------------------
Name: problem2.py
Purpose: To check if the inputted sides form a triangle.
Author: Schwarenberg.M
Created: 23/02/2021
------------------------------------------------------------------------------
"""
# Welcome message
print("Welcome to the Triangle Checker")
print("---")
# Input triangle sides
side1 = int(input("Enter the length of the first side: "))
side2 = int(input("Enter the length of the second side: "))
side3 = int(input("Enter the length of the third side: "))
print("---")
# processing and output of data
if side1 + side2 >= side3 or side1 + side3 >= side2 or side3 + side2 >= side1:
print("The figure is a triangle.")
else:
print("The figure is NOT a triangle.") |
88ad6f097eae9f8f1944d6d7ed0de2e8432bf5b7 | vandat0599/DecisionTree | /ID3_AI.py | 5,461 | 3.625 | 4 | import matplotlib.pyplot as plt
from sklearn import datasets
import pandas as pd
import numpy as np
import math
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
iris=datasets.load_iris()
X=iris.data
y=iris.target
#split dataset into training data and testing data
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.33, random_state=42)
def entropy(counts, n_samples):
"""
Parameters:
-----------
counts: shape (n_classes): list number of samples in each class
n_samples: number of data samples
-----------
return entropy
"""
#TODO
entropy = 0
for c in counts:
entropy += (c/n_samples)*math.log2((c/n_samples))
return -entropy
def entropy_of_one_division(division):
"""
Returns entropy of a divided group of data
Data may have multiple classes
"""
n_samples = len(division)
n_classes = set(division)
counts=[]
dict_classes = {}
#count samples in each class then store it to list counts
#TODO:
for d in division:
if d not in dict_classes.keys():
dict_classes[d] = 1
else:
dict_classes[d] += 1
counts = dict_classes.values()
return entropy(counts,n_samples),n_samples
def get_entropy(y_predict, y):
"""
Returns entropy of a split
y_predict is the split decision by cutoff, True/Fasle
"""
n = len(y)
entropy_true, n_true = entropy_of_one_division(y[y_predict]) # left hand side entropy
entropy_false, n_false = entropy_of_one_division(y[~y_predict]) # right hand side entropy
# overall entropy
#TODO s=?
s = (n_true/(n_true+n_false))*entropy_true + (n_false/(n_true+n_false))*entropy_false
return s
class DecisionTreeClassifier:
def __init__(self, tree=None, depth=0):
'''Parameters:
-----------------
tree: decision tree
depth: depth of decision tree after training'''
self.depth = depth
self.tree=tree
def fit(self, X, y, node={}, depth=0):
'''Parameter:
-----------------
X: training data
y: label of training data
------------------
return: node
node: each node represented by cutoff value and column index, value and children.
- cutoff value is thresold where you divide your attribute
- column index is your data attribute index
- value of node is mean value of label indexes,
if a node is leaf all data samples will have same label
Note that: we divide each attribute into 2 part => each node will have 2 children: left, right.
'''
#Stop conditions
#if all value of y are the same
if len(y) > 0 and np.all(y==y[0]):
return {'val':y[0]}
else:
col_idx, cutoff, entropy = self.find_best_split_of_all(X, y) # find one split given an information gain
y_left = y[X[:, col_idx] < cutoff]
y_right = y[X[:, col_idx] >= cutoff]
node = {'index_col':col_idx,
'cutoff':cutoff,
'val':np.mean(y)}
node['left'] = self.fit(X[X[:, col_idx] < cutoff], y_left, {}, depth+1)
node['right'] = self.fit(X[X[:, col_idx] >= cutoff], y_right, {}, depth+1)
self.depth += 1
self.tree = node
return node
def find_best_split_of_all(self, X, y):
col_idx = None
min_entropy = 1
cutoff = None
for i, col_data in enumerate(X.T):
entropy, cur_cutoff = self.find_best_split(col_data, y)
if entropy == 0: #best entropy
return i, cur_cutoff, entropy
elif entropy <= min_entropy:
min_entropy = entropy
col_idx = i
cutoff = cur_cutoff
return col_idx, cutoff, min_entropy
def find_best_split(self, col_data, y):
''' Parameters:
-------------
col_data: data samples in column'''
min_entropy = 10
#Loop through col_data find cutoff where entropy is minimum
cutoff = None
for value in set(col_data):
y_predict = col_data < value
my_entropy = get_entropy(y_predict, y)
#TODO
#min entropy=?, cutoff=?
if my_entropy < min_entropy:
min_entropy = my_entropy
cutoff = value
return min_entropy, cutoff
def predict(self, X):
tree = self.tree
pred = np.zeros(shape=len(X))
for i, c in enumerate(X):
pred[i] = self._predict(c)
return pred
def _predict(self, row):
cur_layer = self.tree
while cur_layer.get('cutoff'):
if row[cur_layer['index_col']] < cur_layer['cutoff']:
cur_layer = cur_layer['left']
else:
cur_layer = cur_layer['right']
else:
return cur_layer.get('val')
model = DecisionTreeClassifier()
tree = model.fit(X_train, y_train)
pred=model.predict(X_train)
print('Accuracy of your decision tree model on training data:', accuracy_score(y_train,pred))
pred=model.predict(X_test)
print('Accuracy of your decision tree model:', accuracy_score(y_test,pred))
|
098005bffaac2433081c9fde0decda640f2a5809 | lyfxgd/Test | /ground.py | 5,576 | 3.53125 | 4 | # # 斐波那契
# a = 0
# b = 1
# fbLength = 10
# for i in range(fbLength):
# print(a,end=' ')
# a, b = b , a + b
# ---------------------------
# # for loop
# aaa = [1,2,3,4,5,6,7,8,9,0]
# for i in range(len(aaa)):
# print(aaa[i],end=' ')
# print() #换个行
# for i in aaa:
# print(i,end=' ')
# --------------------------
# # 迭代器
# aaa = [1,2,3,4,5,6]
# aaaIter = iter(aaa)
# print(aaaIter)
# print(next(aaaIter))
# print(aaaIter)
# print(next(aaaIter))
# for i in aaaIter:
# print(i)
# print(aaaIter)
# print(next(aaaIter)) # StopIteration
# --------------------------
# # 斐波那契by生成器
# # 使用了yield的函数都是生成器,生成器返回一个迭代器。调用生成器函数时,会在yield处停止,保存现有状态,并且输出yield的值,直到再次使用next()调用迭代器
# import sys
# def fib(n: int):
# a, b, count = 0, 1, 0
# while count < n:
# yield a
# a, b = b, a + b
# count += 1
# f = fib(10)
# while True:
# try:
# print(next(f), end=' ')
# except StopIteration:
# sys.exit()
# -----------------------------
# #PEP8
# # parameter type return value type
# # | |
# def print_hello(name: str) -> str:
# # | |
# # variable_name space
# #inline comment
# """
# Greeting Function
# Parameters:
# name(str): The name of the person
# Returns:
# The cool message
# """
# print('hello, ' + name)
# print_hello('SGCC')
# print
# ----------------------------
# #lanmda
# def sorter(item:dict) -> any:
# return item['name']
# parameters = [
# {'name': 'Li', 'age': 28},
# {'name': 'Yifan', 'age': 15},
# {'name': 'Aba', 'age': 13},
# ]
# parameters.sort(key= lambda item: len(item['name']), reverse=True)
# print('reverse sort by name length:\n', parameters)
# parameters.sort(key= lambda item: len(item['name']))
# print('sort by name length:\n', parameters)
# parameters.sort(key= lambda item: item['age'])
# print('sort by age:\n', parameters)
# parameters.sort(key=sorter)
# print('sort by name:\n ', parameters)
# ----------------------------
# # Class
# # Pascel Casing(每个单词的首字母都要大写)
# # |
# class Presenter():
# def __init__(self, name):
# # Constructor
# print('In the Cons')
# self.name = name
# # 最佳实践:采用设置属性的方式,将字段命名为双下划线,避免对字段直接操作
# # 并且记住,一旦你创建了属性,那就要一直使用它,就算你知道__name对应的是name属性,也不要访问__name字段
# # @property修饰了name属性,其实质是一个与属性同名的getter方法,但是通过装饰器,可以通过访问字段一样的形式来使用该方法
# # @name.setter同样修饰了name带value参数的方法,一样可以通过设置字段一样的方式来使用该方法。
# @property
# def name(self):
# print('In the getter')
# return self.__name
# @name.setter
# def name(self, value):
# print('In the setter')
# self.__name = value
# def say_hello(self):
# # method
# print('Hello, ' + self.name)
# print('1.')
# presenter = Presenter('Li Yifan')
# print('2.')
# presenter.name = "Li Er fan"
# print('3.')
# presenter.say_hello()
# # Python中一切都是public,不存在私有。通过下划线来建议开发者。
# # _一个下划线表示“你必须确保你知道这是什么,你再使用它”
# # __两个下划线表示“无论如何,千万不要用”
# --------------------------------------
# # 继承
# class Person():
# def __init__(self, name):
# self.name = name
# def __str__(self):
# return self.name
# @property
# def name(self):
# return self.__name
# @name.setter
# def name(self, value):
# self.__name = value
# def say_hello(self):
# print('Hello, ', self.name)
# class Student(Person):
# def __init__(self, name, school):
# super().__init__(name)
# self.school = school
# def __str__(self):
# return super().__str__()
# @property
# def school(self):
# return self.__school
# @school.setter
# def school(self, value):
# self.__school = value
# def sing_school_song(self):
# print('Hi, ', self.school)
# def say_hello(self):
# super().say_hello()
# print('I\'m so tired')
# s = Student('Li Yifan', 'XJTU')
# s.say_hello()
# s.sing_school_song()
# print(f'Is this a student? {isinstance(s, Student)}')
# print(f'Is this a Person? {isinstance(s, Person)}')
# print(f'is student a person? {issubclass(Student, Person)}')
# print(s)
#--------------------------------------
#file system
from pathlib import Path
cwd = Path.cwd()
print(cwd)
new_file = Path.joinpath(cwd,'new_file.txt')
print(new_file)
print(f'Is this new file exists? {new_file.exists()}')
parent = cwd.parent
print(f'Is {parent} a dir? {parent.is_dir()}')
print(f'Is {parent} a file? {parent.is_file()}')
for child in parent.iterdir():
if child.is_dir():
print(child)
demo_file = cwd.joinpath(cwd, 'ground.py')
print(demo_file.name)
print(demo_file.suffix)
print(demo_file.parent.name)
print(demo_file.stat()) |
66b8b7e645ccd548eddf896153738f8e3d3974f5 | tgquintela/pySpatialTools | /pySpatialTools/utils/util_classes/Membership.py | 17,497 | 3.71875 | 4 |
"""
Membership
----------
Module which contains the classes and functions needed to define membership
object.
Membership object is a map between elements and collections to which they
belong. It is done to unify and simplify tasks.
"""
import numpy as np
import networkx as nx
from scipy.sparse import coo_matrix, issparse
class Membership:
"""Class representing a membership object in which maps every element
assigned by an index to a group or collection of elements.
Represent a mapping between elements and collections.
"""
def _initialization(self):
self._membership = []
self.n_elements = 0
self._unique = True
self._weighted = False
self.n_collections = 0
self._maxcollection_id = -1
def __init__(self, membership):
"""Constructor function.
Parameters
----------
membership: numpy.ndarray, list of lists or list of dicts
the membership information. If the assignation of each element to
a collection of elements is unique the membership can be
represented as a numpy array, else it will be represented as a list
of lists.
"""
self._initialization()
membership, out = format_membership(membership)
self._membership = membership
self._unique = out[1]
self._weighted = out[2]
self.collections_id = out[3]
self.n_elements = out[0]
self.n_collections = len(out[3])
def __getitem__(self, i):
"""Returns the collections to which belong the element i.
Parameters
----------
i: int
the element id we want to retrieve the collections to which it
belongs.
Returns
-------
collections: list
the collections list which belong to the element i.
"""
if i < 0 or i >= self.n_elements:
raise IndexError("Element ID out of range")
if issparse(self._membership):
try:
#irow = np.where(i == self.elements_id)[0][0]
irow = i
except:
raise IndexError("Collection ID out of range")
collections = np.zeros(self.n_elements).astype(bool)
collections[self._membership.getrow(irow).nonzero()[0]] = True
return collections
if self._unique:
collections = [self._membership[i]]
else:
if not self._weighted:
collections = self._membership[i]
else:
collections = self._membership[i].keys()
return collections
def __eq__(self, collection_id):
"""The equal function collection by collection.
Parameters
----------
collection_id: int
the collection code we want to obtain their linked elements.
Returns
-------
elements: list or np.ndarray
the elements associated to a collection given in the input.
"""
elements = self.getcollection(collection_id)
return elements
def __iter__(self):
"""Iterates over the elements and return element i, its collections to
which it belongs and the membership value.
Returns
-------
i: int
the element considered.
colls: int or list or np.ndarray
the collections associated to the value of the element `i`.
memb_vals: float
the membership value.
"""
if issparse(self._membership):
for i in xrange(self.n_elements):
yield i, [self[i]], np.array([1.])
elif self._unique:
for i in xrange(self.n_elements):
yield i, [self._membership[i]], np.array([1.])
else:
if not self._weighted:
for i in xrange(self.n_elements):
colls = self._membership[i]
memb_vals = np.ones(len(colls))
yield i, colls, memb_vals
else:
for i in xrange(self.n_elements):
colls = self._membership[i].keys()
memb_vals = np.array(self._membership[i].values())
yield i, colls, memb_vals
def __str__(self):
"""Return a representation of information about the data of this class.
Returns
-------
summary: str
the summary information of that class.
"""
summary = """Membership class with %s elements and %s collections,
in which there are %sweighted and %sunique relations between
elements and collections."""
wei = "" if self._weighted else "non-"
unique = "" if self._unique else "non-"
summary = summary % (self.n_elements, self.n_collections, wei, unique)
return summary
@property
def membership(self):
"""Returns the membership data.
Parameters
----------
_membership: list, dict or np.ndarray
the membership information.
"""
return self._membership
@property
def shape(self):
"""The size of the inputs and outputs.
Returns
-------
n_elements: int
the number of elements.
n_collections: int
the number of collections.
"""
return self.n_elements, self.n_collections
@property
def elements_id(self):
"""The element indices.
Returns
-------
elements_id: list
the elements codes.
"""
return list(range(self.shape[0]))
@property
def max_collection_id(self):
"""
Returns
-------
max_collection_id: int
the number of maximum code of the collections.
"""
try:
return np.max(self.collections_id)
except:
maxs_id = [np.max(e) for e in self._membership if e]
return np.max(maxs_id)
def getcollection(self, collection_id):
"""Returns the members of the specified collection.
Parameters
----------
collection_id: int
the collection id we want to retrieve its members.
Returns
-------
elements: boolean numpy.ndarray
the elements which belong to the collection_id.
"""
if collection_id < 0 or collection_id > self.max_collection_id:
raise IndexError("Collection ID out of range")
if issparse(self._membership):
try:
jcol = np.where(collection_id == self.collections_id)[0][0]
except:
raise IndexError("Collection ID out of range")
elements = np.zeros(self.n_elements).astype(bool)
elements[self._membership.getcol(jcol).nonzero()[0]] = True
return elements
if self._unique:
elements = self._membership == collection_id
else:
if not self._weighted:
elements = [collection_id in self._membership[i]
for i in xrange(self.n_elements)]
elements = np.array(elements).astype(bool)
else:
aux = [e.keys() for e in self._membership]
elements = [collection_id in aux[i]
for i in xrange(self.n_elements)]
elements = np.array(elements).astype(bool)
return elements
def to_network(self):
"""Return a networkx graph object.
Returns
-------
membership: nx.Graph
the network representation of the membership in a networkx package.
The network has to be a bipartite network.
"""
dict_relations = self.to_dict()
G = nx.from_dict_of_dicts(dict_relations)
return G
def to_dict(self):
"""Return a dictionary object.
Returns
-------
membership: dict
the membership representation in a dictionary form.
"""
element_lab = ["e %s" % str(e) for e in xrange(self.n_elements)]
d = {}
for i, collects_i, weighs in self:
if np.sum(collects_i) == 0:
collects_i = []
else:
collects_i = np.array(collects_i).ravel()
collects_i = list(np.where(collects_i)[0])
if self._weighted:
collects_i = ["c %s" % str(c_i) for c_i in collects_i]
weighs = [{'membership': w_i} for w_i in weighs]
d[element_lab[i]] = dict(zip(collects_i, weighs))
else:
collects_i = ["c %s" % str(c_i) for c_i in collects_i]
weighs = [{} for c_i in collects_i]
d[element_lab[i]] = dict(zip(collects_i, weighs))
return d
def to_sparse(self):
"""Return a sparse object.
Returns
-------
membership: scipy.sparse
the membership representation in a sparse matrix representation.
"""
au = self.n_elements, self._unique, self._weighted, self.collections_id
return to_sparse(self._membership, au)
def reverse_mapping(self):
"""Reverse the mapping of elements to collections to collections to
elements.
Returns
-------
reverse_membership: dict
the reverse mapping between collections and elements.
"""
reversed_ = {}
for coll_id in self.collections_id:
elements = self.getcollection(coll_id)
elements = list(np.where(elements)[0])
reversed_[coll_id] = elements
return reversed_
def format_membership(membership):
"""Format membership to fit it into the set discretizor standart.
Parameters
----------
membership: dict, np.ndarray, list, scipy.sparse or nx.Graph
the membership information.
Returns
-------
membership: dict, np.ndarray, list, scipy.sparse or nx.Graph
the membership information.
"""
tuple2 = False
# Pre compute
if type(membership) == tuple:
tuple2 = True
collections_id2 = membership[1]
membership = membership[0]
# Computing if array
if type(membership) == np.ndarray:
_membership = membership
n_elements = membership.shape[0]
_unique = True
_weighted = False
collections_id = np.unique(membership)
# Computing if list
elif type(membership) == list:
n_elements = len(membership)
# Possibilities
types = np.array([type(e) for e in membership])
op1 = np.any([t == list for t in types])
op2 = np.all([t == dict for t in types])
op30 = np.all([t == list for t in types])
op31 = np.all([t == np.ndarray for t in types])
op3 = op30 or op31
# Uniformation
if op1:
for i in xrange(len(membership)):
if type(membership[i]) != list:
membership[i] = [membership[i]]
# Computing if dicts
if op2:
_membership = membership
_unique = False
_weighted = True
n_elements = len(membership)
aux = [membership[i].keys() for i in xrange(n_elements)]
aux = np.hstack(aux)
collections_id = np.unique(aux)
# Computing if lists
elif op3:
if op31:
membership = [list(m) for m in membership]
length = np.array([len(e) for e in membership])
if np.all(length == 1):
membership = np.array(membership).ravel()
_membership = membership
n_elements = membership.shape[0]
_unique = True
_weighted = False
collections_id = np.unique(membership)
else:
_membership = membership
n_elements = len(membership)
_unique = False
_weighted = False
aux = np.hstack(membership)
collections_id = np.unique(aux)
elif issparse(membership):
_membership = membership
n_elements = membership.shape[0]
collections_id = np.arange(membership.shape[1])
_weighted = np.any(membership.data != 1)
_unique = np.all(membership.sum(1) == 1)
## Final imputing
if tuple2:
collections_id = collections_id2
## Transform to sparse
out = n_elements, _unique, _weighted, collections_id
# if not _unique:
# _membership, _ = to_sparse(_membership, out)
return _membership, out
def to_sparse(_membership, out):
"""Return a sparse matrix object.
Parameters
----------
membership: dict, np.ndarray, list, scipy.sparse or nx.Graph
the membership information.
out: str, optional ['network', 'sparse', 'membership', 'list', 'matrix']
the out format we want to output the membership.
Returns
-------
membership: dict, np.ndarray, list, scipy.sparse or nx.Graph
the membership information.
"""
n_elements, _unique, _weighted, collections_id = out
sh = n_elements, len(collections_id)
aux_map = dict(zip(collections_id, range(sh[1])))
if issparse(_membership):
return _membership, (range(n_elements), collections_id)
if _unique:
matrix = np.array([aux_map[e] for e in _membership])
matrix = matrix.astype(int)
matrix = coo_matrix((np.ones(sh[0]), (range(sh[0]), matrix)),
shape=sh)
elif not _weighted:
indices = []
for i in xrange(sh[0]):
for j in range(len(_membership[i])):
indices.append((i, aux_map[_membership[i][j]]))
indices = np.array(indices)[:, 0], np.array(indices)[:, 1]
matrix = coo_matrix((np.ones(len(indices[0])), indices), shape=sh)
elif _weighted:
indices, data = [], []
for i in xrange(sh[0]):
for j in _membership[i]:
indices.append((i, aux_map[j]))
data.append(_membership[i][j])
indices = np.array(indices)[:, 0], np.array(indices)[:, 1]
matrix = coo_matrix((np.array(data), indices), shape=sh)
return matrix, (range(n_elements), collections_id)
def formatrelationship(relationship, typeoutput):
pass
"""
typeoutput = 'network', 'sparse', 'membership', 'list', 'matrix'
"""
# def collections_id_computer():
# "Return the collections ID of the membership."
# # For each 3 cases
# if self._unique:
# collections_id = np.unique(self._membership)
# elif not self._unique and not self._weighted:
# collections_id = np.unique(np.hstack(self.membership)).astype(int)
# elif not self._unique and self._weighted:
# aux = [self._membership[e].keys() for e in self._membership]
# collections_id = np.unique(np.hstack(aux))
# return collections_id
#
# def to_sparse(self):
# "Return a sparse matrix object."
# sh = self._nelements, self._ncollections
# aux_map = dict(zip(self.collections_id, range(self._ncollections)))
# if self._unique:
# matrix = np.array([aux_map[e] for e in self._membership])
# matrix = matrix.astype(int)
# matrix = coo_matrix((np.ones(sh[0]), (range(sh[0], matrix))),
# shape=sh)
# elif not self._weighted:
# indices = []
# for i in xrange(sh[0]):
# for j in range(self._membership[i]):
# indices.append((i, aux_map[self._membership[i][j]]))
# matrix = coo_matrix((np.ones(sh[0]), indices), shape=sh)
#
# elif self._weighted:
# indices, data = [], []
# for i in xrange(sh[0]):
# for j in self._membership[i]:
# indices.append((i, aux_map[j]))
# data.append(self._membership[i][j])
# matrix = coo_matrix((np.array(data), indices), shape=sh)
# return matrix, (range(self._nelements), self.collections_id)
# def to_dict(self):
# DEPRECATED
#
# if issparse(self._membership):
# d = {}
# for i, collects_i, weighs in self:
# d[i] = {}
# yield i, [self._membership[i]], np.array([1.])
# for i in range(self.n_elements):
#
# if self._unique:
# d = {}
# for i in xrange(self.n_elements):
# d[element_lab[i]] = {"c %s" % str(self[i]): {}}
# elif not self._weighted:
# d = {}
# for i in xrange(self.n_elements):
# n_i = len(self._membership[i])
# aux_i = ["c %s" % str(self.membership[i][j])
# for j in range(n_i)]
# aux_i = dict(zip(aux_i, [{} for j in range(n_i)]))
# d[element_lab[i]] = {"c %s" % str(self._membership[i]): {}}
# elif self._weighted:
# d = {}
# for i in xrange(self.n_elements):
# k = self._membership[i].keys()
# v = self._membership[i].values()
# vs = [{'membership': v[j]} for j in range(len(k))]
# ks = ["c %s" % k[j] for j in range(len(k))]
# d["e %s" % i] = dict(zip(vs, ks))
# return d
|
89a48a124f396752291d053063f6126c8bbac45c | nigelaukland/project-euler | /euler_005.py | 835 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 22:55:22 2020
https://projecteuler.net/problem=5
@author: nigel
"""
# What is the smallest positive number that is evenly divisible by all of the
# numbers from 1 to 20?
# All integers less than or equal to ten can be ignored
# check each integer greater than 20
# loop up until you find the number!
dividend = 148842440
#dividend = 20
divisorSet = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
divisorSet = { 20, 19, 18, 17, 16, 15, 14, 13, 12, 11 }
#divisorSet = { 20 }
quotientSum = 0
solved = 0
while solved == 0:
for divisor in divisorSet:
quotientSum += dividend % divisor
if quotientSum > 0:
break
if quotientSum == 0:
print("The dividend is ", dividend)
solved = 1
dividend += 20
print(dividend)
quotientSum = 0
|
7feee7c365f92d707d7967c2b8ccb99323957a11 | nigelaukland/project-euler | /euler_002.py | 324 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 6 21:46:26 2020
https://projecteuler.net/problem=2
@author: nigel
"""
# create fibonnaci sequence
# sum all even elements
a, b = 0, 1
total = 0
while a < 4000000:
a, b = b, a + b
print("b = ", b)
if b % 2 == 0:
total += b
print("total = ", total) |
0679779b2fdd92c7f8d85170088ac46ebe1fe985 | astat17/PythonCourse | /hw_B3.py | 193 | 3.625 | 4 | first_dna, second_dna, mutation = input(''), input(''), 0
for i in range ( len (first_dna) ):
if first_dna[i] != second_dna[i]:
mutation += 1
print(mutation)
|
05dcc638c74e67fbc1248394e9f775cec5118c1e | pulakdas1999/DecisionTree | /Machine_learning_5_Decision_Tree.py | 4,746 | 3.765625 | 4 | training_data = [
['Green',3,'Mango'],
['Yellow',3,'Mango'],
['Red',1,'Grape'],
['Red',1,'Grape'],
['Yellow',3,'Lemon']
]
header = ['Color','Diameter','Label']
# Find the unique values for a column in dataset.
def unique_vals(rows,columns):
return set([rows[columns] for row in rows])
# Counts the number of each type of example in adataset.
def class_counts(rows):
counts = {}
for row in rows:
label = row[-1]
if label not in counts:
counts[label]=0
counts[label]+=1
return counts
# Test if a value is numeric.
def isnumeric(values):
return isinstance(values,int) or isinstance(values,float)
# A question is used to partition a dataset.
# This class just records a column number(e.g., 0 for colour) and a column value("Green").The match method is used to compare the
# feature value in an e.g. to the feature value stored in the question.
class Question:
def __init__(self,column,value):
self.column = column
self.value = value
def match(self,example):
# Compare the feature value in an e.g. to the feature value in in this question.
val = example[self.column]
if isnumeric(val):
return val >= self.value
else:
return val == self.value
def __repr__(self):
# This is just a helper method to print the question in a readable format.
condition = "=="
if isnumeric(self.value):
condition = ">="
return "Is %s %s %s?" % (header[self.column],condition,str(self.value))
# Partitions is a dataset.For each row in dataset check if it matches the question.If so add it to true_rows else to false_rows.
def partition(rows,question):
true_rows, false_rows = [], []
for row in rows:
if question.match(row):
true_rows.append(row)
else:
false_rows.append(row)
return true_rows,false_rows
def gini(rows):
counts = class_counts(rows)
impurity = 1
for lbl in counts:
prob_of_lbl = counts[lbl]/float(len(rows))
impurity -= prob_of_lbl**2
return impurity
def information_gain(left,right,current_uncertainty):
p = float(len(left))/(len(left)+len(right))
return current_uncertainty-p*gini(left)-(1-p)*gini(right)
def find_best_split(rows):
best_gain = 0
best_question = None
current_uncertainty = gini(rows)
n_features = len(rows[0])-1
for col in range(n_features):
values = set([row[col] for row in rows])
for val in values:
question = Question(col,val)
true_rows,false_rows=partition(rows,question)
if len(true_rows)==0 or len(false_rows)==0:
continue
gain = information_gain(true_rows,false_rows,current_uncertainty)
if gain >= best_gain:
best_gain,best_question = gain,question
return best_gain,best_question
class leaf:
def __init__(self,rows):
self.predictions = class_counts(rows)
class decision_Node:
def __init__(self,question,true_branch,false_branch):
self.question = question
self.true_branch = true_branch
self.false_branch = false_branch
def build_tree(rows):
gain,question = find_best_split(rows)
if gain==0:
return leaf(rows)
true_rows,false_rows = partition(rows,question)
true_branch = build_tree(true_rows)
false_branch = build_tree(false_rows)
return decision_Node(question,true_branch,false_branch)
def print_tree(node,spacing=""):
if isinstance(node,leaf):
print(spacing +"predict",node.predictions)
return
print(spacing+str(node.question))
print(spacing+'---> TRUE:')
print_tree(node.true_branch,spacing+" ")
print(spacing+'---> FALSE:')
print_tree(node.false_branch,spacing+" ")
def classify(row,node):
if isinstance(node,leaf):
return node.predictions
if node.question.match(row):
return classify(row,node.true_branch)
else:
return classify(row,node.false_branch)
def print_leaf(counts):
total = sum(counts.values())*1.0
probs = {}
for lbl in counts.keys():
probs[lbl]=str(int(counts[lbl]/total * 100))+"%"
return probs
if __name__=='__main__':
my_tree = build_tree(training_data)
print_tree(my_tree)
testing_data = [
['Green', 3, 'Mango'],
['Yellow', 4, 'Mango'],
['Red', 2, 'Grape'],
['Red', 1, 'Grape'],
['Yellow', 3, 'Lemon']
]
for row in testing_data:
print("Actual : %s. Predicted : %s"%(row[-1],print_leaf(classify(row,my_tree))))
|
12bc8c474358876720c5c6f6cb2adaedaebb9bac | adkulas/Project-Euler | /006_problem.py | 803 | 4.0625 | 4 | '''
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
'''
import numpy as np
def sum_of_squares(numbers):
a = np.array(numbers)**2
return np.sum(a)
def square_of_sum(numbers):
a = sum(numbers)
return a**2
if __name__ == '__main__':
num1 = list(range(1,11))
num2 = list(range(1,101))
print(square_of_sum(num1) - sum_of_squares(num1))
print(square_of_sum(num2) - sum_of_squares(num2)) |
c4bdec7d10a125cbbb4da1edfc4aca7004064d2e | sriniverve/Python_Learning | /venv/tests/decorators.py | 633 | 3.875 | 4 | '''
This is to demonstrate the usage of decorators
'''
import time
import math
#function decorators
def decorator_timer(func):
#print('came in to the decorator')
def timer_function(*args, **kwargs):
print('Inner function started')
begin_time = time.time()
print(begin_time)
func(*args, **kwargs)
time.sleep(1)
end_time = time.time()
print(end_time)
return (end_time - begin_time)
return timer_function
@decorator_timer
def factorial_find(number):
return math.factorial(number)
fac = factorial_find(500)
print(f'factorial of 500 is {fac}')
|
9b3495345e4f4ad9648dcca17a8288e62db1220e | sriniverve/Python_Learning | /venv/tests/conditions.py | 271 | 4.21875 | 4 | '''
This is to demonstrate the usage of conditional operators
'''
temperature = input('Enter the temperature:')
if int(temperature) > 30:
print('This is a hot day')
elif int(temperature) < 5:
print('This is a cold day')
else:
print('This is a pleasant day') |
1140a8dd58988892ecca96673ffe3d2c1bf44564 | sriniverve/Python_Learning | /venv/tests/guessing_number.py | 395 | 4.21875 | 4 | '''
This is an example program for gussing a number using while loop
'''
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess_number = int(input('Guess a number: '))
guess_count += 1
if guess_number == secret_number:
print('You guessed it right. You Win!!!')
break
else:
print('You are have exhausted your options. Sorry!!!')
|
a5c94db302c2c2fc7e394569f90372b9df42ecd9 | sriniverve/Python_Learning | /venv/tests/modules.py | 151 | 3.5 | 4 | from libs.utils import utils
list = [1, 5, 9, 3, 2, 8]
largest = utils()
largest_num_in_list = largest.find_max(list)
print(largest_num_in_list)
|
01b3319010f240b6ddfdd0b5ae3e07f201a9a046 | sriniverve/Python_Learning | /venv/tests/kg2lb_converter.py | 285 | 4.21875 | 4 | '''
This program is to take input in KGs & display the weight in pounds
'''
weight_kg = input('Enter your weight in Kilograms:') #prompt user input
weight_lb = 2.2 * float(weight_kg) #1 kg is 2.2 pounds
print('You weight is '+str(weight_lb)+' pounds')
|
2d7f003b6d1f2d148586e8ca3ac26a55a6869bc9 | vmmc2/Competitive-Programming | /Cracking The Code/Chapter 1 (Arrays and Strings)/1_6(string compression).py | 863 | 3.5 | 4 | def compress(s1: str) -> str:
s2 = ""
index = 0
tam = len(s1)
counter = 1
while index <= tam - 1:
if index > 0:
if index == tam - 1:
if s1[index] == s1[index - 1]:
counter += 1
s2 = s2 + s1[index] + str(counter)
else:
s2 = s2 + s1[index - 1] + str(counter)
s2 = s2 + s1[index] + '1'
break
if s1[index] == s1[index - 1]:
counter += 1
elif s1[index] != s1[index - 1]:
s2 = s2 + s1[index - 1] + str(counter)
counter = 1
index += 1
return s2
def main():
s1 = "abc"
compressed = compress(s1)
if len(compressed) >= len(s1):
print(s1)
else:
print(compressed)
main()
|
23d110cff79eb57616586da7f78c7ac6d4e7a957 | vmmc2/Competitive-Programming | /Sets.py | 1,369 | 4.4375 | 4 | #set is like a list but it removes repeated values
#1) Initializing: To create a set, we use the set function: set()
x = set([1,2,3,4,5])
z = {1,2,3}
#To create an empty set we use the following:
y = set()
#2) Adding a value to a set
x.add(3)
#The add function just works when we are inserting just 1 element into our set
#3) Adding more than one element to a set
x.update([34,45,56])
#To do this, we use the update function.
#We can also pass another set to the update function
y = {1,2,3}
a = {4,5,6}
y.update(a, [34,45,56])
#4) Removing a specific value from a set
#We can use two different functions to do this same action: remove() and discard()
a.remove(1) or a.discard(1)
#The problem with remove() is that if we are trying to remove a value that doesn`t exist in the set, we are going to get a key error.
#On the other hand, if we try to discard a value that doesn`t exist, then we don`t get any type of error. In other words, it works just fine.
So, ALWAYS use the discard() method.
s1 = {1,2,3}
s2 = {2,3,4}
s3 = {3,4,5}
#5) Intersection Method
s4 = s1.intersection(s2) # s4 = {2,3}
s4 = s1.intersection(s2, s3) # s4 = {3}
#6) Difference Method
s4 = s1.difference(s2) # s4 = {1}
s4 = s2.difference(s1) # s4 = {4}
#OBSERVATION: We can pass multiple sets as arguments to these different methods.
#7) Sym Difference
s4 = s1.symmetric_difference(s2)
|
720af938c7a753de2be6a73a89711de860527d92 | vmmc2/Competitive-Programming | /LeetCode/Top Interview Questions/Hard Collection/Array and Strings/Game of Life (Space - O(1)).py | 1,710 | 3.53125 | 4 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# This version will have a space-complexity of O(1) instead of O(m*n)
# Se uma celula que era viva (1) morrer, eu transformo ela em -1.
# Se uma celula que era morta (0) nascer, eu transformo ela em 2
m = len(board)
n = len(board[0])
dx = [-1,-1,-1,0,1,1, 1, 0]
dy = [-1, 0, 1,1,1,0,-1,-1]
for i in range(0, m):
for j in range(0, n):
neighbours = 0
for k in range(0, 8):
newx = i + dx[k]
newy = j + dy[k]
if newx >= 0 and newx < m and newy >= 0 and newy < n:
if board[newx][newy] == -1: # Tenho uma celula viva mas que na proxima geracao vai morrer.
neighbours += 1
elif board[newx][newy] == 1: # Celula viva.
neighbours += 1
if board[i][j] == 0:
if neighbours == 3:
board[i][j] = 2
elif board[i][j] == 1:
if neighbours < 2:
board[i][j] = -1
elif neighbours == 2 or neighbours == 3:
board[i][j] = 1
else:
board[i][j] = -1
for i in range(0, m):
for j in range(0, n):
if board[i][j] == -1:
board[i][j] = 0
elif board[i][j] == 2:
board[i][j] = 1
return
|
0594a4160131b1fb61465082360eef71b1e9704a | vmmc2/Competitive-Programming | /LeetCode/Top Interview Questions/Medium Collection/Arrays and Strings/Group Anagrams(MUCH BETTER).py | 621 | 3.734375 | 4 | from collections import defaultdict
# A funcao ord() de python3 retorna o codigo da tabela ASCII de um char.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = defaultdict(list) # dicionario que mapeia para listas..
for string in strs: # iterando sobre cada string
count = [0]*26 # meu vetor de frequencia. Garantido que temos apenas letras minusculas na strings
for c in string:
count[ord(c) - ord('a')] += 1 # fazendo a contagem no vetor de frequencia
ans[tuple(count)].append(string)
return ans.values()
|
52377e7a4daa4d849a168c07dcef1c0eae862ead | vmmc2/Competitive-Programming | /Codeforces/50A - Domino Piling.py | 228 | 3.671875 | 4 | dominoarea = 2
linha, coluna = input().split()
#convertendo de string para inteiro
linha = int(linha)
coluna = int(coluna)
#calculando a area do tabuleiro
area = linha*coluna
#resposta
dominos = area//dominoarea
print(dominos)
|
768ce4a45879ad23c94de8d37f33f7c8c50dca24 | AmangeldiK/lesson3 | /kall.py | 795 | 4.1875 | 4 | active = True
while active:
num1 = int(input('Enter first number: '))
oper = input('Enter operations: ')
num2 = int(input('Enter second number: '))
#dict_ = {'+': 'num1 + num2', '-': 'num1 - num2', '*': 'num1 * num2', '/': 'num1 / num2'}
if oper == '+':
print(num1+num2)
elif oper == '-':
print(num1-num2)
else:
if oper == '*':
print(num1*num2)
elif oper == '/':
try:
num1 / num2 == 0
except ZeroDivisionError:
print('Division by zero is forbidden!')
else:
print(num1/num2)
else:
print('Wrong operations')
continue_ = input('If you want continue click any button and Enter, if not click to Enter: ')
|
ed0fe74197a845a6cf4c59c9c106050bbe0bdd91 | erickfmm/ANMetaL | /src/anmetal/iterative_methods.py | 441 | 3.625 | 4 |
def euler_method(dy_times_dx_func, x_start, x_end, y0, n_steps):
h = float(x_end - x_start) / float(n_steps)
x = x_start
y = y0
for _ in range(n_steps):
y = y + h * dy_times_dx_func(x, y)
x = x + h
return y
def newton_method(func, derivative_func, x_start, n_iterations, m=1):
x = x_start
for _ in range(n_iterations):
x = x - m*(float(func(x)) / float(derivative_func(x)))
return x |
69795887c2cd00981551931827615e124d6fd14e | mharmanani/hangman-cli | /hangman.py | 3,731 | 4.1875 | 4 | """
hangman.py
Mohamed Harmanani, 2017
"""
import random
from HangmanWord import *
from HangingMan import *
import getpass
ROOT = '.lang/'
#modules for pick_language
LANGUAGES = { 0: 'english',
1: 'french',
2: 'spanish' }
MAX_LANG_INDEX = max(list(LANGUAGES.keys()))
MIN_LANG_INDEX = min(list(LANGUAGES.keys()))
#modules for pick_length
class InvalidLengthException(Exception):
pass
class InvalidNumberOfPlayersException(Exception):
pass
def pick_number_of_players():
"""
Prompts the user to choose how many players will play.
@rtype: int
"""
chosen = False
while not chosen:
try:
num = int(input("How many players would you like? (1/2) "))
except:
print("Please enter an integer.")
if num < 1 or num > 2:
print("Please pick 1 or 2 players.")
continue
chosen = True
return num
def pick_language():
"""
Prompts the user to choose the language he desires to play in.
@rtype: str
"""
NO_LANGUAGE_SELECTED = True
print("Welcome to Hangman")
print("Please select any of the following languages")
while NO_LANGUAGE_SELECTED:
lang_index = input("English (0)"
+ '\n' + "Français(1)"
+ '\n' + "Español (2)"
+ '\n' + "Enter the number of your desired language: ")
try:
lang_index = int(lang_index)
assert lang_index >= MIN_LANG_INDEX and lang_index <= MAX_LANG_INDEX
except:
print("An error has occurred, try again...")
continue
NO_LANGUAGE_SELECTED = False
lang = LANGUAGES[lang_index]
return lang
def get_word_list(fname):
"""
Uses the data from pick_language to generate a list of words in the
language selected by the user.
@param str fname: name of the file to read from
@rtype: list[str]
"""
fhand = open(fname)
words = fhand.readlines()
words = [word.strip() for word in words]
return words
def pick_length(word_lst, word_len):
"""
Initializes a randomly generated word of length word_len from word_lst.
@param list[str] word_lst: list of words
@param int word_len: length of the word to be selected
@rtype:
"""
def has_desired_size(word):
""" (str, int) -> bool
"""
return len(word) == word_len
if word_len <= 2:
raise InvalidLengthException
sized_lst = list(filter(has_desired_size, word_lst))
return sized_lst
def main():
print("--------------- Welcome to Hangman")
guessed = False
number_of_players = pick_number_of_players()
if number_of_players == 1:
lang = ROOT + pick_language() + '.txt'
word_lst = get_word_list(lang)
try:
word_len = int(input("Pick the length of your desired word (>2) : "))
sized_lst = pick_length(word_lst, word_len)
except ValueError:
print("You have not entered a valid number, we have selected the length at random.")
word_len = random.randint(1,10)
except InvalidLengthException:
print("Your word is too short, we have selected the length at random.")
word_len = random.randint(1,10)
sized_lst = pick_length(word_lst, word_len)
chosen_word = HangmanWord(random.choice(sized_lst))
elif number_of_players == 2:
print("Have one player choose the word, and the other guess:")
chosen_word = HangmanWord(getpass.getpass("Your word here: "))
print("Your word is " + str(chosen_word))
while not guessed:
letter = input("Take a guess (quit to end game): ")
try:
chosen_word.take_a_guess(letter)
except AssertionError:
print("You have chosen to quit the game...")
break
except deadPlayerException:
print("You have failed to complete the word",
''.join(chosen_word.visible))
print("You are dead...")
break
if chosen_word.visible == chosen_word.blurred:
print("You have successfully completed the word", str(chosen_word))
guessed = True
if __name__ == '__main__':
main()
|
b42889f94a49b620300eec99b9f9ff9b793c0867 | macgors/Prog-Class-tasks | /list1/3.py | 149 | 3.671875 | 4 | from numpy import dot
from math import sqrt
def cosine(a,b):
return dot(a,b) / (sqrt(dot(a,a))*sqrt(dot(b,b)))
print(cosine((1,1,1), (-1,1,1))) |
bbd1f925c4f75ce3df82a0c8f644c077739fb776 | macgors/Prog-Class-tasks | /list1/2.py | 160 | 3.5625 | 4 | import random
from typing import List
def mean(lst: List[int]) -> int:
return sum(lst) / len(lst)
print(mean([random.randint(10, 90) for _ in range(20)])) |
729cbbfce5e4444bb70f8a204c482a98d4207ab8 | TJBachorz/BJJ | /Data/create_work_dictionary.py | 4,306 | 3.59375 | 4 | from nltk.corpus import stopwords
sw = stopwords.words("english")
from Functions.functions import iterative_levenshtein as lev
from Functions.functions import get_key
#################### FUNCTION TO CREATE A DICTIONARY #########################
#
# I am creating a work-in-progress dictionary, where I find words similar
# to values in a selected dictionary (Dictionary directory)
#
# For example:
# 1. Existing dictionary:
#
# athletes_dictionary = {
# 'keenan cornelious':['keenan cornelious']
# }
#
# 2. Someone entered 'keenan kornelious' into the survey
#
# 3. Using Levenshtein distance I calulate the score: 1
#
# 4. If it's less than X (declared in the function) I am adding it to the
# appropriate key in the dictionary
#
# 5. If the values are too different from any existing value I can create a
# new key
#
# 6. I am running the algorithm until each value from the survey is assigned
#
##############################################################################
#
# out_path = where do you want the created file to be saved
#
# dictionary = an accepted previous dictionary (base)
#
# input_list = values to be found in the dictionary and checked with
# Levenshtein distance
#
##############################################################################
def create_work_dictionary(out_path, dictionary, input_list):
def leven_score(name, elem_list, min_ = 1):
min_sc = len(name)
closest = ""
for elem in elem_list:
score = lev(elem, name)
if score < min_sc:
min_sc = score
closest = elem
return [name,closest,min_sc] if len(name)>1 and len(closest)>1 else ''
# ------------------------------------------------------------------------
new_dictionary = dictionary.copy()
values_from_new_dict = [y for x in new_dictionary.values() for y in x]
list_to_check = list()
# ------------------------------------------------------------------------
for element in input_list:
closest = leven_score(element, values_from_new_dict)
if len(closest) > 0:
if 0 < closest[2] < 4:
print("\n")
key = get_key(closest[1],new_dictionary)
print("key: {}".format(key))
if closest[0] not in new_dictionary[key]:
new_dictionary[key].append(closest[0])
print("'{}' ---> '{}' ---> '{}' ({})" \
.format(closest[0],closest[1],key,closest[2]))
# I want each key also in the values
if key not in new_dictionary[key]:
new_dictionary[key].append(key)
print('KEY itself was not in values. Added it')
elif 12 > closest[2] > 4:
if closest[0] not in list_to_check:
print("appended: '{}'".format(closest[0]))
list_to_check.append(closest[0])
elif closest[2] > 12:
new_dictionary[closest[0]] = [closest[0]]
print("'{}' - added to the dictionary".format(closest[0]))
# ------------------------------------------------------------------------
with open(out_path + "\dictionary_to_check.txt","w") as f:
f.write('dictionary = { \n')
for key, value in sorted(new_dictionary.items()):
f.write("\'{}\':{},\n".format(key,value))
f.write('}')
f.close()
print('{}_to_check.txt created!'.format(dictionary))
# ------------------------------------------------------------------------
list_to_check_final = []
for element in list_to_check:
list_to_check_final \
.append(' '.join([x for x in element.split(' ') if x not in sw ]))
with open(out_path + r"\list_to_check.txt","w") as f:
for row in sorted(list_to_check_final):
f.write("'{}',\n".format(row))
f.close()
return 'list_to_check.txt created!' |
356512f8a2f2e12aa231238a789ad4ff2be8401a | FaithS15-6/L1_Programmign-Assessment | /04fixing_rounds_v2.py | 3,155 | 4.09375 | 4 | import random
# Functions go here...
def intcheck(question):
while True:
response = input(question)
round_error = "Please type either <enter> or an " \
"integer that is more than 0\n"
# If infinite mode not chosen, check response
# Is an integer that is more than 0
if response != "":
try:
response = int(response)
# If response is too low, go back to start of loop
except ValueError:
print(round_error)
continue
return response
def yes_no(question):
valid = False
while not valid:
response = input(question).lower()
if response == "yes" or response == "y":
response = "yes"
return response
elif response == "no" or response == "n":
response = "no"
return response
else:
print("Please answer yes / no")
def instructions():
print()
print("**** How to play ****")
print()
print("In order to play this game...")
print()
return ""
# Main Routine goes here...
answered_before = yes_no("Have you played the game before? ")
if answered_before == "no":
instructions()
print()
# Checks number of question
question_answered = 0
question_wrong = 0
question_correct = 0
game_summary = []
chose_instructions = "please chose the highest"
# Ask user for number of question. <enter> for infinite mode
question =intcheck ("How many questions?:")
end_game ="no"
while end_game == "no":
# develop random numbers players choose from...
num_1 = random.randrange(1, 50)
num_2 = num_1 * 15
num_3 = num_2 + 4
num_4 = num_3 +2
num_5 = num_2 + 3
num_6 = num_5 +num_3
list1 = [num_1, num_2, num_3, num_4, num_5, num_6]
# shuffle numbers in list.
random.shuffle(list1)
print(list1)
print()
# ask user for answer and check that it is correct.
user_ans = intcheck("Choose the highest number from the list ")
correct_answer = max(list1)
if user_ans == correct_answer:
print ("Well done")
else:
print("Oops")
user_ans = intcheck("Choose the lowest number from the list")
correct_answer = min(list1)
if user_ans == correct_answer:
print ("Correct!!")
else:
print("Damn It")
# ways to win
# End Game if exit code is typed
if user_ans == "xxx":
break
elif question!= "" and question_answered >= question - 1:
break
# Number list,
correct = max(list1)
# Prints out correct answers (Highest and Lowest when player is done)
print ("Max value element :", max(list1))
print ("Min value element :", min(list1))
# loops while questions answered is more than questions requested
# Start of game play loop
question_answered +=1
# Rounds Heading
print()
if question =="":
heading = "Continues Mode :Question {}".format(question_answered)
else:
heading = "Question {} of Question {}".format(question_answered, question)
print(heading)
|
882064b6ad10fd35ea7a9d251f067d9f7eab3656 | patricknelli/SF_DAT_17_WORK | /code/04_more_pandas_lab.py | 3,987 | 3.625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
'''
Part 1: UFO
'''
ufo = pd.read_csv('https://raw.githubusercontent.com/sinanuozdemir/SF_DAT_17/master/data/ufo.csv') # can also read csvs directly from the web!
# 1. change the column names so that each name has no spaces
# and all lower case
ufo.columns = [x.replace(" ", "").lower() for x in ufo.columns]
ufo.head()
ufo.count(axis = 1)
# 2. Show a bar chart of all shapes reported
ufo['shapereported'].value_counts().plot(kind = 'bar')
# 3. Show a dataframe that only displays the reportings from Utah
ufo[ufo['state'] == 'UT']
# 4. Show a dataframe that only displays the reportings from Texas
ufo[ufo['state'] == 'TX']
# 5. Show a dataframe that only displays the reportings from Utah OR Texas
ufo[(ufo['state'] == 'TX') | (ufo['state'] == 'UT')]
# 6. Which shape is reported most often?
ufo['shapereported'].value_counts().idxmax()
# 7. Plot number of sightings per day in 2014 (days should be in order!)
ufo['Day'] = ufo['time'].apply(lambda x:int(x.split('/')[1]))
ufo['Month'] = ufo['time'].apply(lambda x:int(x.split('/')[0]))
ufo['Year'] = ufo['time'].apply(lambda x:int(x.split('/')[2][:4]))
ufo['MonthDay'] = ufo['Month'].map(str) + '/' + ufo['Day'].map(str)
ufo['MonthDay'][ufo['Year'] == 2014].value_counts().hist(bins=365)
'''
Part 2: IRIS
'''
iris = pd.read_csv('https://raw.githubusercontent.com/sinanuozdemir/SF_DAT_17/master/data/iris.csv') # can also read csvs directly from the web!
iris.head()
# 1. Show the mean petal length by flower species
iris['petal_length'].groupby(iris['species']).mean()
# 2. Show the mean sepal width by flower species
iris['sepal_width'].groupby(iris['species']).mean()
# 3. Use the groupby to show both #1 and #2 in one dataframe
iris[['petal_length','sepal_width']].groupby(iris['species']).mean()
# 4. Create a scatter plot plotting petal length against petal width
# Use the color_flowers function to
# apply this function to the species column to give us
# designated colors!
def color_flower(flower_name):
if flower_name == 'Iris-setosa':
return 'b'
elif flower_name == 'Iris-virginica':
return 'r'
else:
return 'g'
colors = iris.species.apply(color_flower)
colors
iris.plot(x='petal_length', y='petal_width', kind='scatter', c=colors)
# 5. Show flowers with sepal length over 5 and petal length under 1.5
iris[(iris['sepal_length'] > 5) & (iris['petal_length'] < 1.5)]
# 6. Show setosa flowers with petal width of exactly 0.2
iris[(iris['species'] == 'Iris-setosa') & (iris['petal_width'] == 0.2)]
# 7. Write a function to predict the species for each observation
def classify_iris(data):
if data[3] < .75:
return 'Iris-setosa'
elif data[2] < 5:
return 'Iris-versicolor'
else:
return 'Iris-virginica'
# example use:
# classify_iris([0,3,2.1,3.2]) == 'Iris-virginica'
# assume the order is the same as the dataframe, so:
# [sepal_length', 'sepal_width', 'petal_length', 'petal_width']
# make predictions and store as preds
preds = iris.drop('species', axis=1).apply(classify_iris, axis = 1)
preds
# test your function: compute accuracy of your prediction
(preds == iris['species']).sum() / float(iris.shape[0])
'''
Part 3: FIFA GOALS
'''
goals = pd.read_csv('https://raw.githubusercontent.com/sinanuozdemir/SF_DAT_17/master/data/fifa_goals.csv')
# removing '+' from minute and turning them into ints
goals.minute = goals.minute.apply(lambda x: int(x.replace('+','')))
goals.head()
# 1. Show goals scored in the first 5 minutes of a game
goals[goals.minute <= 5]
# 2. Show goals scored after the regulation 90 minutes is over
goals[goals.minute > 90]
# 3. Show the top scoring players
goals.player.value_counts(sort=True)
# 4. Show a histogram of minutes with 20 bins
goals.minute.hist(bins=20)
# 5. Show a histogram of the number of goals scored by players
goals.player.value_counts(sort=True).hist()
|
0b9ab5984a8213a6756575cf6d0fb88ca6302103 | rampac/ArtificialIntelligence | /SciKit_Learn/DecisionTree.py | 1,818 | 3.921875 | 4 | # A decision tree is one of most frequently and widely used supervised machine learning algorithms that can perform both regression and classification tasks.
#classification solution
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
dataset = pd.read_csv("D:/Datasets/bill_authentication.csv")
dataset.shape
dataset.head()
X = dataset.drop('Class', axis=1)
y = dataset['Class']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier()
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
#Regression soultion
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
dataset = pd.read_csv('D:\Datasets\petrol_consumption.csv')
dataset.describe()
X = dataset.drop('Petrol_Consumption', axis=1)
y = dataset['Petrol_Consumption']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor()
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)
df=pd.DataFrame({'Actual':y_test, 'Predicted':y_pred})
df
from sklearn import metrics
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))
print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred))
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
|
bea03d15b11574ed4b225fe22bc6e7d6ec37ed26 | brantheman60/BIPS-Robotics-Course-Labs | /lab2/lab2_student.py | 2,062 | 4.03125 | 4 | from lab2_questions import question_list
import random
round = 1 # current round number
completed = [] # list of the indices of completed questions
# TODO: Check that every question has exactly 6 elements,
# and the last element is either "A", "B", "C", or "D"
for question in question_list:
assert(???)
assert(???)
# TODO: Write an introduction to the quiz
print(???)
# TODO: Loop for 15 rounds
while(???):
# TODO: Pick a random index from 0 to (number of questions - 1)
q = ???
# TODO: keep finding an index that hasn't been put in completed yet
while(q in completed):
q = ???
# Add the index to the completed list
completed.append(q)
# TODO: Get the question, choices, and answer from question_list[q]
question = ???
choice1 = ???
choice2 = ???
choice3 = ???
choice4 = ???
answer = ???
# TODO: Print the round, question, and choices
print(???) # Round X
print(???) # Question
print(???) # A. X
print(???) # B. X
print(???) # C. X
print(???) # D. X
# TODO: Get player's inputted answer
a = ???
# TODO: If a isn't A, B, C, or D, tell them to try again
# and get their next inputted answer
while(??? and ??? and ??? and ???):
a = ???
# TODO: Check if the player's answer was correct
if ???:
print("Correct! The correct answer was "+answer)
else:
print("Incorrect! The correct answer was "+answer)
print("You lost at Round " + str(round))
exit()
# TODO: Increase the round number
round = ???
print()
# TODO: Congratulate the player for winning
print(???)
# CHALLENGE TODO: Rewrite the code (in a new Python file called
# lab2_challenge.py) so that instead of only needing to select 1 of
# 4 options, players need to type out the full answer. Be generous and
# let the player win if they use extra spaces or capitalize/don't
# capitalize their answers. Use a new list of questions (instead of
# the list in lab2_questions.py).
|
2d2d81bc949b136f791868c948c07fdaa4eccb45 | viclule/performance_script_machine_learning | /opmimization/particle_swarm.py | 5,978 | 3.859375 | 4 | # particle swarm optimizer
# based on the article:
# https://medium.com/analytics-vidhya/implementing-particle-swarm-optimization-pso-algorithm-in-python-9efc2eb179a6
import random
import numpy as np
class Particle():
"""
A particle of the swarm
"""
def __init__(self, dimensions):
"""
Init
:param self:
:param dimensions: number of dimensions for the particle
"""
self._initialize_position(dimensions)
self.pbest_position = self.position
self.pbest_value = float('inf')
self.velocity = np.zeros(dimensions)
def _initialize_position(self, dimensions):
"""
Initialize to a random position
:param self:
:param dimensions: number of dimensions to optimize
"""
self.position = np.zeros(dimensions)
for d in range(dimensions):
self.position[d] = (-1)**(bool(random.getrandbits(1))) * \
random.random()*50
def __str__(self):
print("I am at ", self.position, " meu pbest is ", self.pbest_position)
def move(self):
"""
Update the particle position
:param self:
"""
self.position = self.position + self.velocity
class Space():
"""
Space where the particles displace
"""
def __init__(self, function, dimensions, target, target_error, n_particles,
inertia=0.5, acc_coefficient_1=0.8, acc_coefficient_2=0.9):
"""
Init
:param self:
:param function: function to explore
:param dimensions: number of dimensions for the space
:param target: target value
:param target_error: acceptable error
:param n_particles: number of particles
:param inertia=0.5: inertial parameter
:param acc_coefficient_1=0.8: coefficient personal best value
:param acc_coefficient_2=0.9: coefficient social best value
"""
self.function = function
self.dimensions = dimensions
self.target = target
self.target_error = target_error
self.n_particles = n_particles
self.inertia = inertia
self.acc_coefficient_1 = acc_coefficient_1
self.acc_coefficient_2 = acc_coefficient_2
self.gbest_value = float('inf')
self._initialize_gbest_position()
self._generate_particles()
def _initialize_gbest_position(self):
self.gbest_position = np.zeros(self.dimensions)
for d in range(self.dimensions):
self.gbest_position[d] = random.random()*50
def print_particles(self):
for particle in self.particles:
particle.__str__()
def _generate_particles(self):
self.particles = \
[Particle(self.dimensions) for _ in range(self.n_particles)]
def _fitness(self, particle):
return self.function(particle.position)
def set_pbest(self):
for particle in self.particles:
fitness_cadidate = self._fitness(particle)
if(particle.pbest_value > fitness_cadidate):
particle.pbest_value = fitness_cadidate
particle.pbest_position = particle.position
def set_gbest(self):
for particle in self.particles:
best_fitness_cadidate = self._fitness(particle)
if(self.gbest_value > best_fitness_cadidate):
self.gbest_value = best_fitness_cadidate
self.gbest_position = particle.position
def move_particles(self):
for particle in self.particles:
new_velocity = (self.inertia*particle.velocity) + \
(self.acc_coefficient_1*random.random()) * \
(particle.pbest_position - particle.position) + \
(random.random()*self.acc_coefficient_2) * \
(self.gbest_position - particle.position)
particle.velocity = new_velocity
particle.move()
class ParticleSwarmOptimizer():
"""
A Particle Swarm Optimizer.
"""
def __init__(self, function, dimensions, target, target_error, n_particles,
inertia=0.5, acc_coefficient_1=0.8, acc_coefficient_2=0.9):
"""
Init
:param self:
:param function: function to explore
:param dimensions: number of dimensions to optimize
:param target: target value
:param target_error: acceptable error
:param n_particles: number of particles
:param inertia=0.5: inertial parameter
:param acc_coefficient_1=0.8: coefficient personal best value
:param acc_coefficient_2=0.9: coefficient social best value
"""
self.search_space = Space(function, dimensions, target,
target_error, n_particles)
self.inertia = inertia
self.acc_coefficient_1 = acc_coefficient_1
self.acc_coefficient_2 = acc_coefficient_2
def optimize(self, n_iterations, run_full_iterations=False,
print_opt=False):
"""
Run the optimizer
:param self:
:param n_iterations: number of iterations
:param print_opt=False: print the result
"""
iteration = 0
while(iteration < n_iterations):
self.search_space.set_pbest()
self.search_space.set_gbest()
if not run_full_iterations:
if(abs(self.search_space.gbest_value - \
self.search_space.target) <= \
self.search_space.target_error):
# finish the search
break
self.search_space.move_particles()
iteration += 1
if print_opt:
print("The best solution is: ", self.search_space.gbest_position,
" in n_iterations: ", iteration)
|
11ad8bdf32ed08e847fc5a8fa68a91783b473da9 | ilookforme102/bachelor_thesis | /Sentiment_Analysis.py | 2,342 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 12:59:00 2019
@author: macbook
"""
from textblob import TextBlob
import re
import string
def clean_data(tweet):
# Remove HTML special entities (e.g. &)
tweet = re.sub(r'\&\w*;', '', tweet)
# To lowercase
tweet = tweet.lower()
# using regex to clean the text by removing the link from text
tweet = re.sub('@[^\s]+','AT_USER',tweet)
# Remove Punctuation and split 's, 't, 've with a space for filter
tweet = re.sub(r'[' + string.punctuation.replace('@', '') + ']+', ' ', tweet)
# Remove words with 2 or fewer letters
tweet = re.sub(r'\b\w{1,2}\b', '', tweet)
# Remove whitespace (including new line characters)
tweet = re.sub(r'\s\s+', ' ', tweet)
# Remove single space remaining at the front of the tweet.
tweet = tweet.lstrip(' ')
#Remove additional white spaces
tweet = re.sub('[\s]+', ' ', tweet)
tweet = re.sub('[\n]+', ' ', tweet)
#Remove not alphanumeric symbols white spaces
tweet = re.sub(r'[^\w]', ' ', tweet)
#Replace #word with word
tweet = re.sub(r'#([^\s]+)', r'\1', tweet)
#Remove :( or :)
tweet = tweet.replace(':)','')
tweet = tweet.replace(':(','')
#trim
tweet = tweet.strip('\'"')
tweet = ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
return tweet
def sentiment_tweets(tweet):
model = TextBlob(clean_data(tweet))
if model.sentiment.polarity > 0:
return 1
elif model.sentiment.polarity == 0:
return 0
else:
return -1
data['Sentiment']= np.array([sentiment_tweets(tweet) for tweet in data['Tweets']])
display(data.head(10))
#anlysing the result of sentiment analysis:
pos_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['Sentiment'][index] > 0]
neu_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['Sentiment'][index] == 0]
neg_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['Sentiment'][index] < 0]
print("percentage of positive tweets: {}%".format(len(pos_tweets)*100/len(data['Tweets'])))
print("Percentage of neutral tweets: {}%".format(len(neu_tweets)*100/len(data['Tweets'])))
print("Percentage de negative tweets: {}%".format(len(neg_tweets)*100/len(data['Tweets'])))
#Topic modeling
|
99a0eb3222f6d9994f0e9295c5d1f3a5a7e8e6a0 | maleeham/Leetcode | /ValidPalindrome.py | 406 | 3.90625 | 4 | /*Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.*/
class Solution:
def isPalindrome(self, s):
translator = str.maketrans('', '', string.punctuation + ' ')
s = s.translate(translator)
s = s.lower()
return s == s[::-1]
s = "".join([c.lower() for c in s if c.isalnum()])
return s == s[::-1]
|
0aa44823b9d602567270221004e967033998b4a9 | mcphersonmd28/Fin5350-Assignments | /Assignments/Assignment1WordProblems/Assignment 1_Word Problem_Madyson McPherson.py | 2,197 | 4.09375 | 4 | print("Word Problem 1")
print("If a group of 5 students work on a project for 70 hours and they")
print("split the work evenly, how many hours does each student work?")
input("Press enter to find out.")
print("70 / 5 =", 70 // 5)
print("")
print("Word Problem 2")
print("If George orders 6 whole pizza cut into 12 slices each")
print("and he wants to eat pizza every day for the next 10 days")
print("how many slices of pizza should he eat per day?")
input("Press enter to find out.")
print("6 * 12 / 10 =", 6 * 12 / 10)
print("")
print("Word Problem 3")
print("Johnny wants to give his mother flowers for Mothers' Day.")
print("When he went to the flower shop, he saw that they had 200 flowers.")
print("Half of them were yellow and half of them were red.")
print("His mother likes red and yellow flowers the best.")
print("If Johnny wants to give his mother 20 flowers, how many of each color")
print("should he get?")
answer = input("Please input your answer here.")
print("answer")
if answer == "10":
print("Correct")
else:
print("Wrong")
input("Press enter to check your answer")
print("If one color is half of the total amount of flowers")
print("then each color needs to be half of the desired amount")
print("of 20. Therefore, Johnny needs 10 red flowers and 10 yellow flowers")
print("")
print("Word Problem 4")
print("Holly works for a catering company and she has to set out plates for")
print("a wedding reception. If there are 30 tables that seat 8 people each")
print("and Holly has 2 hours to set up, how many plates must she set every")
print("10 minutes?")
answer = input("Please input your answer here.")
print("answer")
if answer == "20":
print("Correct")
else:
print("Wrong")
input("Press enter to check your answer")
print("30 * 8 / 12 =", 30 * 8 / 12)
print("")
print("Word Problem 5")
print("Hank and Julia decide to make pasta to share with their neighbors.")
print("They decide to make 30 pounds of pasta. If half a pound of pasta can")
print("can fit into a Tupperware container, how many neighbors can Hank and")
print("Julia give pasta to if they give one container to each neighbor?")
input("Press enter to find out.")
print("30 * 2 =", 30 * 2)
|
11a14bcda4c59606d82520cd0c833e4d0e2f33c6 | alvaro3023/t10_Rojas.delacruz | /ROJAS_OLIVA/menu3.py | 430 | 3.765625 | 4 | # Menu de comandos
opc=0
max=3
while(opc!= max):
print("############### MENU ##############")
print("#1. agregar area triangulo")
print("#2. agregar area trapecio ")
print("#3. salir ")
#2. Eleccion de la opcion menu
opc=libreria.pedir_numero("Ingreso la opcion:", 1, 3)
#3. Mapeo de las opciones
if (opc==1):
opcionareatriangulo()
if (opc==2):
opcionareatrapecio()
#fin_menu
|
dab9dfc7cc08cb6adc931582928adea652e5bc0e | alvaro3023/t10_Rojas.delacruz | /ROJAS_OLIVA/menu1.py | 414 | 3.84375 | 4 | import libreria
# Menu de comandos
opc=0
max=3
while(opc!= max):
print("############### MENU ##############")
print("#1. pedir RUC ")
print("#2. Mostrar monto")
print("#3. Salir")
#2. Eleccion de la opcion menu
opc=libreria.pedir_numero("Ingreso la opcion:", 1, 3)
#3. Mapeo de las opciones
if (opc==1):
pedirRUC()
if (opc==2):
mostrarmonto()
#fin_while
|
c5d41a0ce9a8153202fd0acc7d05e9a60f1dcf37 | alvaro3023/t10_Rojas.delacruz | /DelaCruz/app4.py | 570 | 4.09375 | 4 | import libreria
opc=0
max=3
def agregar_uni():
input("Ingresar universidad: ")
def agregar_carrera():
input("Ingresar carrera profesional: ")
while (opc!=max):
print("########## MENU #############")
print("#1. Universidad #")
print("#2. Carrera profesion #")
print("#3. Salir #")
print("#############################")
opc=libreria.pedir_numero("Ingrese opcion:", 1,3)
# Mapeo de funciones
if(opc==1):
agregar_uni()
if(opc==2):
agregar_carrera()
print("Fin del programa")
|
109ab8774125f4f49defeda0c726533f62aeda66 | fisadev/zombsole | /players/randoman.py | 713 | 3.609375 | 4 | # coding: utf-8
import random
from things import Player
class RandoMan(Player):
"""A player that decides what to do with a dice."""
def next_step(self, things, t):
action = random.choice(('move', 'attack', 'heal'))
if action in ('attack', 'heal'):
self.status = action + 'ing'
target = random.choice(list(things.values()))
else:
self.status = u'moving'
target = list(self.position)
target[random.choice((0, 1))] += random.choice((-1, 1))
target = tuple(target)
return action, target
def create(rules, objectives=None):
return RandoMan('randoman', 'red', rules=rules, objectives=objectives)
|
230616616f10a6207b4a407b768afaabb846528a | SynthetiCode/EasyGames-Python | /guessGame.py | 744 | 4.125 | 4 | #This is a "Guess the number game"
import random
print('Hello. What is your nombre?')
nombre = input()
print('Well, ' + nombre + ', I am thining of a numero between Uno(1) y Veinte(20)')
secretNumber =random.randint(1,20)
#ask player 6 times
for guessesTaken in range(0, 6):
print ('Take a guess:' )
guess = int(input())
if guess < secretNumber:
print ('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break # <-- This condition is the correct guess!
if guess ==secretNumber:
print ('Good job, ' + nombre + '! You guessed my number in ' + str(guessesTaken+1)+ ' guesses!')
else:
print ('Nope, the number I was thinking of was: ' + str(secretNumber))
print ('Better luck next time')
|
e291518a1582a80bc20f25d383ad863a2d0219c1 | mdanassid2254/pythonTT | /constrector/5prog.py | 973 | 3.578125 | 4 | class Customer:
def setcustomerid(self,customerid):
self.__customerid=customerid
def getcustomerid(self):
return self.__customerid
def setcustomername(self,customername):
self.__customername=customername
def getcustomername(self):
return self.__customername
class regularcustomer(Customer):
def setdiscount(self,discount):
self.__discount=discount
def getdiscount(self):
return self.__discount
class pc(Customer):
def setmemcardtype(self,memcardtype):
self.__memcardtype=memcardtype
def getmemcardtype(self):
return self.__memcardtype
choice=1
list=[]
while(choice==1):
ch=input("Enter your choise:")
if(ch==1):
list.append(regularcustomer())
else:
list.append(pc())
list1=[]
for i in range (3):
list1.append(Customer())
list1[i].setcustomerid(int(input(("enter id"))))
for i in list1:
print(getopt)
|
fb038cc7201cd3302a5eeedf9fd86511d6ff2cf6 | mdanassid2254/pythonTT | /constrector/hashing.py | 422 | 4.65625 | 5 | # Python 3 code to demonstrate
# working of hash()
# initializing objects
int_val = 4
str_val = 'GeeksforGeeks'
flt_val = 24.56
# Printing the hash values.
# Notice Integer value doesn't change
# You'l have answer later in article.
print("The integer hash value is : " + str(hash(int_val)))
print("The string hash value is : " + str(hash(str_val)))
print("The float hash value is : " + str(hash(flt_val)))
|
dd80f057de9d0de521b37e1dea8fdbaf9ea5d6e6 | mdanassid2254/pythonTT | /constrector/superk_keyword.py | 425 | 3.578125 | 4 | class c1:
def __init__(self,a,b):
print(self)
self.a=a
self.b=b
def area(self):
print(self.a*self.b)
print(self)
class c2(c1):
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
print(self)
def vol(self):
print(self.a*self.b*self.c)
super(c2,self).__init__(self.a,self.b)
o=c2(3,3,3)
o.vol()
o.area() |
140ec062dcfd212169b33720ef0395ef46e24ff7 | mzakrze/tkom-interpreter | /tokens.py | 1,667 | 3.5625 | 4 | from enum import Enum
class TokenType(Enum):
INT = "int"
double = "double"
BOOLEAN = "boolean"
STRING = "string"
POSITION = "position"
MOVEABLE = "moveable"
DEF = "def"
WHILE = "while"
IF = "if"
ELSE = "else"
RETURN = "return"
NULL = "null"
VAR = "var"
TRUE = "true"
FALSE = "false"
ASTERISK = "*"
SLASH = "/"
PLUS = "+"
MINUS = "-"
MODUL = "%"
ADDEQ = "+="
SUBEQ = "-="
MULEQ = "*="
DIVEQ = "/="
EXCL_MARK = "!"
LEFT_BRACET = "{"
RIGHT_BRACET = "}"
LEFT_PARENTH = "("
RIGHT_PARENTH = ")"
LEFT_SQ_BRACKET = "["
RIGHT_SQ_BRACKET = "]"
SEMICOLON = ";"
COLON = ":"
COMMA = ","
DOT = "."
EQ = "="
EQEQ = "=="
LESS = "<"
GREATER = ">"
LESS_EQ = "<="
GREATER_EQ = ">="
AND = "&&"
OR = "||"
STRING_LITERAL = 1
NUM_LITERAL_INT = 2
NUM_LITERAL_DOUBLE = 3
IDENTIFIER = 4
FUNCTION_IDENTIFIER = 5
ILLEGAL_TOKEN = 6
@staticmethod
def printAll():
for member in TokenType.__members__:
print(member)
@staticmethod
def getMatchingElseNone(string):
for symbolic, member in TokenType.__members__.items():
if member is not None and member.value == string:
return member
return None
class Token:
def __init__(self, tokenType, value, pointer):
self.tokenType = tokenType
self.value = value
self.pointer = pointer # self.pointer points at last character of that token
def __str__(self):
return (str(self.pointer) + ":").ljust(5) + ("\"" + str(self.value) + "\"").ljust(30) + str(self.tokenType)[10:] |
4c6440cd45ecaeb0152d2c5bc017fdc56a33afc1 | AliMurtaza096/alilab2 | /ver.py | 54 | 3.5 | 4 | # Multiply
def mul(x,y):
return x*y
print(mul(5,3)) |
0e6b136b69f36b75e8088756712889eb45f1d24a | Kaden-A/GameDesign2021 | /VarAndStrings.py | 882 | 4.375 | 4 | #Kaden Alibhai 6/7/21
#We are learning how to work with strings
#While loop
#Different type of var
num1=19
num2=3.5
num3=0x2342FABCDEBDA
#How to know what type of date is a variable
print(type(num1))
print(type(num2))
print(type(num3))
phrase="Hello there!"
print(type(phrase))
#String functions
num=len(phrase)
print(phrase[3:7]) #from 3 to 6
print(phrase[6:]) #from index to the end
print(phrase*2) #print it twice
#concadentation --> joining strings
phrase = phrase + "Goodbye"
print(phrase)
print(phrase[2:num-1])
while "there" in phrase:
print("there" in phrase)
phrase="changed"
print(phrase)
# make 3 string variables print them individually
#"print s1+s2"
#print st2+st3
#print st1+st2+st3
phrase1="Lebron"
phrase2=">"
phrase3="MJ"
print(phrase1)
print(phrase2)
print(phrase3)
print(phrase1+phrase2)
print(phrase2+phrase3)
print(phrase1+ " ", phrase2+ " ",phrase3) |
7bfc308392fd4f8fd82ed0d2d5fb19ab1789bb8b | mdmss37/programmingQuiz | /mathPazzle/03_card_turn.py | 574 | 3.765625 | 4 | def create_cards_facingdown(n):
empty_dic = {}
for i in range(1,n):
empty_dic[i] = False
return empty_dic
cards_set = create_cards_facingdown(101)
def card_turn(start):
current = cards_set
while start < 101:
#print(start)
for i in range(start,101,start):
#print(current[i])
if current[i] == False:
current[i] = True
elif current[i] == True:
current[i] = False
#print(current[i])
start += 1
return current
turned_card = card_turn(2)
for card in turned_card:
if turned_card[card] == False:
print(card)
|
8523346cb241006bae4a9f3e69a3b0d22ee406b5 | mdmss37/programmingQuiz | /UdacityIntroToCS/mutateList.py | 475 | 3.875 | 4 | # Mutating lists. which of the following procedures
# leves the value passed in as the input unchanged?
def proc1(p):
p[0] = p[1]
def proc2(p):
p = p + [1]
def proc3(p):
q = p
p.append(3)
q.pop()
def proc4(p):
q = []
while p:
q.append(p.pop())
while q:
p.append(q.pop())
# Answer is 2, 3, 4
p = [1, 2, 3]
proc1(p)
print(p)
p = [1, 2, 3]
proc2(p)
print(p)
p = [1, 2, 3]
proc3(p)
print(p)
p = [1, 2, 3]
proc4(p)
print(p) |
449bc7be6a6278d204083ed27a63facbfe57a931 | 1049884729/projecteulerByPython | /Question12.py | 1,102 | 4.03125 | 4 | '''
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
n * (n + 1) / 2;
求第一个拥有超过500个因子的三角数?
'''
import math
print(int(math.sqrt(15)))
def divisors(integer):
'''
算法理由:如果一个数,能够整除某个数的平方根,那么肯定有一个比它大的数也能够整除;
所以只需检查interger的平方根以下的所有整数即可
比如数15,平方根整数是3,,所以只需要算1,2,3能否被15整除即可,能,则存在另一个被整除的,所以+2
:param integer:
:return:
'''
count = 0
divided = int(math.sqrt(integer))+1
for i in range(1, divided):
if integer % i is 0:
count += 2
return count
def getNumber(num):
'''
:param num: 因子数
:return:
'''
count=0
temp=1
index=1
while(count<num):
temp=int((index**2+index)/2)
count=divisors(temp)
if(count<num):
index+=1
print(temp)
getNumber(500)
|
2f1f2581f1237b8adce941c4b8a48d89dc177399 | Hehwang/Leetcode-Python | /code/082 Remove Duplicates from Sorted List II.py | 956 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
head2=head
### creat a dict record the frequency of values
### then we can know if we could drop this node in loop!
freqDict={}
while head2:
if head2.val in freqDict:
freqDict[head2.val]+=1
else:
freqDict[head2.val]=1
head2=head2.next
root=res=ListNode(head.val)
while head:
if freqDict[head.val]>1:
head=head.next
else:
res.next=ListNode(head.val)
res=res.next
head=head.next
return root.next |
9a799e2d2ba2c8973cf5af8a7d07e251f40ad36f | Hehwang/Leetcode-Python | /code/224 Basic Calculator.py | 1,162 | 3.546875 | 4 | class Solution:
# 定义一个函数计算括号里的式子
def helper(self,s):
length=len(s)
# 检查时候含有'--','+-'
s=''.join(s)
s=s.replace('--','+')
s=s.replace('+-','-')
s=[x for x in s if x!='#']
s=['+']+s[1:-1]+['+']
tmp=0
lastsign=0
for i in range(1,len(s)):
if i==1 and s[i]=='-':
lastsign=1
continue
if s[i]=='+' or s[i]=='-':
tmp+=int(''.join(s[lastsign:i]))
lastsign=i
return (list(str(tmp)),(length-len(list(str(tmp)))))
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
s='('+s+')'
s=[x for x in s if x!=' ']
stack=[]
i=0
while i<len(s):
if s[i]=='(':
stack.append(i)
i+=1
elif s[i]==')':
last=stack.pop()
tmp=self.helper(s[last:i+1])
s[last:i+1]=tmp[0]
i-=tmp[1]
else:
i+=1
return int(''.join(s)) |
296b5c3c6f16c368d547ad14c2f5e9b981825a3a | Hehwang/Leetcode-Python | /code/461 Hamming Distance.py | 288 | 3.59375 | 4 | class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
tmp=x^y
res=0
while tmp!=0:
if tmp%2!=0:
res+=1
tmp=tmp>>1
return res |
ea7b9f0cefeca1c88653ba86342bc82727cf8ff2 | Hehwang/Leetcode-Python | /code/504 Base 7.py | 411 | 3.5 | 4 | class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num==0:
return "0"
flag=True if num>0 else False
num=abs(num)
res=[]
while num:
res.append(str(num%7))
num=num//7
res.reverse()
return '-'+''.join(res) if not flag else ''.join(res)
|
f7aac03275b43a35f790d9698b94e76f93207e7d | abokareem/LuhnAlgorithm | /luhnalgo.py | 1,758 | 4.21875 | 4 | """
------------------------------------------
|Luhn Algorithm by Brian Oliver, 07/15/19 |
------------------------------------------
The Luhn Algorithm is commonly used to verify credit card numbers, IMEI numbers, etc...
Luhn makes it possible to check numbers (credit card, SIRET, etc.) via a control key (called checksum, it is a number
of the number which makes it possible to check the others). If a character is incorrect, then Luhn's algorithm will
detect the error.
Starting with the right-most digit, double every other digit to the left of it. Then all of the undoubled and doubled
digits together. If the total is a multiple of 10, then the number passes the Luhn Algorithm.
For Luhn to be true:
(double digits + undoubled digits) % 10 == 0
========================================================================================================================
"""
def luhn_algorithm_test(number):
digit_list = list(map(int, str(number)))
luhn_digits = []
total = 0
for digit in digit_list[-2::-2]:
double_digit = digit * 2
if double_digit >= 10:
double_digit = double_digit - 9
luhn_digits.append(double_digit)
digit_list.remove(digit)
total = sum(digit_list) + sum(luhn_digits)
if total % 10 == 0:
return "Luhn Algorithm Test Passed"
else:
return "Luhn Algorithm Test Failed"
def main():
while True:
try:
number = int(input("Please enter a number: "))
print(luhn_algorithm_test(number))
except ValueError:
print("Sorry, please input numbers only.")
continue
else:
break
if __name__ == '__main__':
main() |
f17e1ca5453a920e41097d3c045638edce0dc3fc | cramosCuc/Exercism_Python | /acronym/acronym.py | 149 | 3.953125 | 4 | import re
def abbreviate(palabras):
regex = "[A-Z]+['a-z]*|['a-z]+"
return ''.join(word[0].upper() for word in re.findall(regex, palabras))
|
1677fac97c69a1a4419e3352dab0cc1537600532 | cramosCuc/Exercism_Python | /pangram/pangram.py | 133 | 3.859375 | 4 | from string import ascii_lowercase
def is_pangram(oracion):
return all(char in oracion.lower() for char in ascii_lowercase)
|
35d1e795d933697b63f90dce0e9bd9e2074b184b | kadikraman/KadiCarAPI | /backend/database/convert_json_to_sql.py | 2,341 | 3.5 | 4 | '''
This will read in data from data.json and convert it into a dict
Then will create or rewrite populate_db.py with the insert statements
to insert all the data that was in the JSON file to the expenses table
'''
import json
import time
json_data = open('data.json')
# load the json data into a dictionary
data = json.load(json_data)
# the string which will be written into file
sql = ''
for expense in data:
sql += 'con.execute("""INSERT INTO expenses\n'
# expense_type always in dict
sql += '\t' + '(expense_type, \n \t'
# amount always in dict
sql += 'amount, \n \t'
# mileage is nullable
if('mileage' in expense):
sql += 'mileage, \n \t'
# litres is mullable
if('litres' in expense):
sql += 'litres, \n \t'
# comment is nullable
if('comment' in expense):
sql += 'comment, \n \t'
# expense_date always in dict
sql += 'expense_date) \n'
sql += 'VALUES \n'
# expense_type always in dict
sql += '\t' + '(\'' + expense['expense_type'] + '\', \n'
# amount always in dict
sql += '\t' + str(expense['cost']) + ', \n'
# mileage is nullable
if('mileage' in expense):
sql += '\t' + str(expense['mileage']) + ', \n'
# litres is nullable
if('litres' in expense):
sql += '\t' + str(expense['litres']) + ', \n'
# comment is nullable
if('comment' in expense):
sql += '\t' + '\'' + str(expense['comment']) + '\'' + ', \n'
# expense_date always in dict
sql += '\t' + '\'' + expense['expense_date'] + '\')""") \n \n'
# open the file (this creates the file if it didn't already exist)
file = open('populate_db.py', 'w')
file.close()
# open the file (this erases the contents if there was anything there previously)
file = open('populate_db.py', 'r+')
file.truncate()
# autogenerated file warning
file.write('\'\'\' \n' + 'This is an autogenerated file. \n')
file.write('This file was generated by convert_json_to_sql.py at ' + str(time.strftime("%c")) + '. \n')
file.write('Any edits will be overwritten. \n' + '\'\'\' \n \n')
# beginning statements
file.write('import sqlite3 \n \n')
file.write('con = sqlite3.connect(\'expenses.sqlite\') \n \n')
# write all the sql we constructed above
file.write(sql)
#end statement
file.write('con.commit()')
# close the file
file.close()
|
717156b49b0614af228351169b0bbc8081394293 | kaddynator/nqueens-npuzzle-localsearch | /scratch.py | 711 | 3.875 | 4 | def h_distinct_attacks(queen_state):
'''Groups attack pairs together if they share a common queen and returns the number of groups'''
def have_queen_in_common(queen_list_a, queen_list_b):
return len(set(queen_list_a + queen_list_b)) < len(queen_list_a) + len(queen_list_b)
attacking_pairs = queen_attacks(queen_state)
print(attacking_pairs)
explored = []
score = 0
while attacking_pairs:
current_pair = attacking_pairs.pop()
if not have_queen_in_common(current_pair, explored):
score += 1
explored += current_pair
print(score)
return score
def h(queen_state):
return num_queen_attacks(queen_state) / 6 |
027ab31cab21f5034a69b2002e2f67b4238033b9 | AlSavva/Python-basics-homework | /homework2-3.py | 1,138 | 3.984375 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна,
# лето, осень). Напишите решения через list и через dict.
month_list = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль",
"Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"]
seasons_dict = {
"Зима": (1, 2, 12),
"Весна": (3, 4, 5),
"Лето": (6, 7, 8),
"Осень": (9, 10, 11)
}
month_num = int(input("Введите порядковый номер месяца в году: "))
while 1 > month_num or month_num > 12:
month_num = int(input('Ошибка! В календаре 12 месяцев. '
'Попробуйте ещё раз:'))
for season in seasons_dict:
if month_num in seasons_dict.get(season):
my_season = (season)
print(f'Вы ввели {month_list[month_num - 1]}, это {my_season}')
|
a0d900a3e43322ab1e994aa82f74a5d759e8260a | AlSavva/Python-basics-homework | /homework3-4.py | 2,163 | 4.21875 | 4 | # Программа принимает действительное положительное число x и целое
# отрицательное число y. Необходимо выполнить возведение числа x в степень y.
# Задание необходимо реализовать в виде функции my_func(x, y). При
# решении задания необходимо обойтись без встроенной функции возведения числа
# в степень.
# Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в
# степень с помощью оператора **. Второй — более сложная реализация без
# оператора **, предусматривающая использование цикла.
def my_pow(x, y):
"""Function implementing the operation of raising to a negative exponent
This function takes a real positive number and a negative integer
as arguments.
x: float, y: int, and y < 0
"""
if int(y) >= 0:
return 'Error! y argument cannot be greater than zero'
try:
x != 0
return 1 / x ** -y
except ZeroDivisionError:
return 'Error! x argument cannot be zero'
# Вариант без использования встроенной функции возведения в степень
def my_2pow(x, y):
"""Function implementing the operation of raising to a negative exponent,
but does not use the exponentiation operation
This function takes a real positive number and a negative integer
as arguments.
x: float, y: int, and y < 0
"""
if int(y) >= 0:
return 'Error! y argument cannot be greater than zero'
try:
x != 0
res = 1
count = 0
while count != -y:
count += 1
res *= 1 / x
return res
except ZeroDivisionError:
return 'Error! x argument cannot be zero'
print(my_pow(2, -2))
print(my_2pow(2, -2))
|
1eaded5afd7676febe14409d999ba0699c2cb90a | AlSavva/Python-basics-homework | /homework4-7.py | 1,007 | 3.75 | 4 | # Реализовать генератор с помощью функции с ключевым словом yield, создающим
# очередное значение. При вызове функции должен создаваться объект-генератор.
# Функция должна вызываться следующим образом: for el in fact(n). Функция
# отвечает за получение факториала числа, а в цикле необходимо выводить только
# первые n чисел, начиная с 1! и до n!.
# Подсказка: факториал числа n — произведение чисел от 1 до n. Например,
# факториал четырёх 4! = 1 * 2 * 3 * 4 = 24.
def my_fackt(n:int):
from functools import reduce
for n in list(range(1, n + 1)):
yield reduce(lambda x, y: x * y, list(range(1, n + 1)))
for el in my_fackt(8):
print(el)
|
fd180a26aaf3b285ae1d738511f62e86398e18ac | AlSavva/Python-basics-homework | /homework6-5.py | 1,543 | 3.9375 | 4 | # Реализовать класс Stationery (канцелярская принадлежность). Определить в нем
# атрибут title (название) и метод draw (отрисовка). Метод выводит сообщение
# “Запуск отрисовки.” Создать три дочерних класса Pen (ручка), Pencil
# (карандаш), Handle (маркер). В каждом из классов реализовать переопределение
# метода draw. Для каждого из классов методы должен выводить уникальное
# сообщение. Создать экземпляры классов и проверить, что выведет описанный
# метод для каждого экземпляра.
class Stationery:
title = 'No-name'
def draw(self):
print(F'Drow start! {self.title}, line width is not defined.')
class Pen(Stationery):
title = 'Pen'
def draw(self):
print(f'Drow start! {self.title}, line width 3px.')
class Pencil(Stationery):
title = 'Pencil'
def draw(self):
print(f'Drow start! {self.title}, line width 5px.')
class Handle(Stationery):
title = 'Handle'
def draw(self):
print(f'Drow start! {self.title}, line width 15px.')
other = Stationery()
other.draw()
a = Pen()
b = Pencil()
c = Handle()
print(other.title, a.title, b.title, c.title)
a.draw()
b.draw()
c.draw()
|
9d53ed431fc3adbbb34c08123750600c7fbfff08 | catdog001/leetcode_python | /Tree/上海交大数据结构树的课程/树课程的相关代码/huffmanTree.py | 3,486 | 3.515625 | 4 | """
Huffman Tree used for compression
上海交大翁老师的:
https://www.bilibili.com/video/BV18t411U7tH?from=search&seid=14727695894489847315
青岛大学王卓老师的:
https://www.bilibili.com/video/BV18t411U7tz/?spm_id_from=trigger_reload
https://www.bilibili.com/video/BV18t411U7tz/?spm_id_from=trigger_reload
"""
class TreeNode(object):
"""
节点类
"""
def __init__(self, val="", weight=None):
"""
:param left: 某一个节点的左孩子
:param right: 某一个节点的右孩子
:param val: 某一个节点的值,默认为空
:param weight: 某一个节点的权重
"""
self.father = None
self.left = None
self.right = None
self.val = val
self.weight = weight
class HuffmanTree(object):
"""
Huffman Tree
"""
def __init__(self, word_frequency):
"""
:param word_frency: 字及其频率
"""
self.word_frequency = word_frequency
def create_huffman_tree(self):
"""
依据词及其词频创建huffman树
:return:
"""
# 先采用优先队列对word_frency按低频到高频进行排列
# 词和词的频次需要按(词的频次, 词)进行组合,python中的优先队列按(等级数字, 元素)中的等级数字进行排列,等级数字越小,优先级越高,越优先被弹出
from queue import PriorityQueue
word_frency_priority_queue = PriorityQueue()
# (词频,词)放入优先队列进行排序
for word_fre in self.word_frequency:
word_frency_priority_queue.put(word_fre)
# 每个词频建立以该词频为根的新树
trees_priority_queue = PriorityQueue()
while not word_frency_priority_queue.empty():
new_ele = word_frency_priority_queue.get()
new_ele_tree = TreeNode(val=new_ele[1], weight=new_ele[0])
trees_priority_queue.put((new_ele_tree.weight, new_ele_tree))
while trees_priority_queue.qsize() > 1:
# 取出最小和次小, 最小做左节点,次小做右节点
node_left = trees_priority_queue.get()[1]
node_right = trees_priority_queue.get()[1]
# 合并最小和次小,生成新的子树
# 新的子树的左右节点为上述最小和次小的数值生成的节点
father_node = TreeNode(weight=node_left.weight+node_right.weight)
father_node.left = node_left
father_node.right = node_right
# 将最小和次小的删除,添加新的树节点。其实,对于优先队列来说,get方法是已经从优先队列中删除了
# 新的树节点权重为 father_node.weight, 值默认为空
# 设置父节点
node_left.father = father_node
node_right.father = father_node
# 将新生成的子树的权重和值加入到优先队列中
trees_priority_queue.put((father_node.weight, father_node))
return trees_priority_queue.get()[1]
def get_huffman_encode(self):
"""
从huffman树拿到叶子结点的哈夫曼编码
:return:
"""
pass
if __name__ == '__main__':
word_fre = [(10, "a"), (15, "e"), (12, "i"), (3, "s"), (4, "t"), (13, "d"), (1, "n")]
huffman = HuffmanTree(word_fre)
huffman_tree = huffman.create_huffman_tree()
print(huffman_tree)
|
44da9a33162d262a1d588d67cd9b4d82c12b53ee | catdog001/leetcode_python | /BinarySearch/33.py | 1,100 | 3.890625 | 4 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
if not nums or len(nums) == 0:
return False
left, right = 0, len(nums) - 1
while left <= right:
mid = int(left + (right - left) / 2)
if nums[mid] == target or nums[left] == target or nums[right] == target:
return True
if nums[mid] > nums[0]:
if target >= nums[0] and target <= nums[mid]:
right = mid - 1
else:
left = mid + 1
elif nums[mid] < nums[0]:
if target >= nums[mid] and target <= nums[len(nums)-1]:
left = mid + 1
else:
right = mid - 1
elif nums[mid] == nums[0]:
return True
return False
if __name__ == '__main__':
nums = [2, 5, 6, 0, 0, 1, 2]
target = 3
solution = Solution()
result = solution.search(nums, target)
print(result) |
a8051d4c26e31ecb5a315948a9e3bdad44975aec | catdog001/leetcode_python | /Tree/leetcode_tree/easy/226.py | 1,546 | 4.15625 | 4 | """
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return root
def revert(root):
if not root:
return root
root.left, root.right = revert(root.right), revert(root.left)
return root
new_root = revert(root)
return new_root
def create_tree(self):
# A、L、B、E、 C、D、W、X
A = TreeNode("A")
L = TreeNode("L")
B = TreeNode("B")
E = TreeNode("E")
C = TreeNode("C")
D = TreeNode("D")
W = TreeNode("W")
X = TreeNode("X")
A.left = L
A.right = C
L.left = B
L.right = E
C.right = D
D.left = W
W.right = X
return A
if __name__ == '__main__':
solution = Solution()
root = solution.create_tree()
# 翻转一棵树
invertTree = solution.invertTree(root)
print("该树翻转后的树是{}".format(invertTree)) |
0961b93e1cebfd23c52773fa2ff942f42bd0ee5f | catdog001/leetcode_python | /Tree/leetcode_tree/easy/107.py | 2,900 | 3.984375 | 4 | """
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
"""
解题思路:当遍历树的根节点时,按(节点, 节点序号)压栈,根节点为(根节点, 0),然后其左右孩子为其父节点的序号加1压栈。最后按节点序号进行排序,同一个节点序号的合并
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
results = []
# 存入结果为[(节点值, 层次编号)],同一个层次编号的元素放在同一个列表中
single_result = []
if not root:
return []
# 队列元素中加入层次序号
queue = []
# 根节点为0号
queue.append((root, 0))
while len(queue) > 0:
# 注意队列,故而为pop(0)。如果是栈,为pop()
node = queue.pop(0)
# 当开始为空的时候,表明列表中需要加入新列表,列表元素为[(node[0].val, node[1])],因为node形式是(节点,层次编号)
if len(single_result) == 0:
single_result.append([(node[0].val, node[1])])
else:
# 如果该node的层次编号和single_result最新放入的元素编号相同,将新元素列表扩充,single_result形式为[[(节点值,节点编号)]]
if node[1] == single_result[-1][-1][1]:
single_result[-1] += [(node[0].val, node[1])]
else:
single_result.append([(node[0].val, node[1])])
# 如果存在左孩子,层次编号node[1]加1
if node[0].left:
queue.append((node[0].left, node[1] + 1))
# 如果存在右孩子,层次编号node[1]加1。如果同一个节点的左右孩子,层次编号一样
if node[0].right:
queue.append((node[0].right, node[1] + 1))
# [[(3, 0)], [(9, 1), (20, 1)], [(15, 2), (7, 2)]]
# print(single_result)
for ele in single_result:
result = []
for single_ele in ele:
result.append(single_ele[0])
results.append(result)
return results[::-1] |
317e00bba0d45bba71e4d31b5e8fd60e41badddb | mrled/education | /cryptopals-2013/cryptopals.py | 29,126 | 3.515625 | 4 | #!/usr/bin/env python3
import argparse
import base64
import string
import sys
import math
import binascii
import itertools
# requires pycrypto
from Crypto.Cipher import AES
########################################################################
## Backend libraryish functions
def safeprint(text, unprintable=False, newlines=False, maxwidth=None):
"""
Attempt to print the passed text, but if a UnicodeEncodeError is
encountered, print a warning and move on.
This is useful when printing candidate plaintext strings, because Windows
will throw a UnicodeEncodeError if you try to print a character it can't
print or something, and your program will stop.
If the appropriate options are passed, it will also filter the text through
safefilter().
"""
filtered = safefilter(text,
unprintable=unprintable,
newlines=newlines,
maxwidth=maxwidth)
try:
print(filtered)
except UnicodeEncodeError:
# this (usually?) only happens on Windows
wt = "WARNING: Tried to print characters that could not be displayed "
wt+= "on this terminal. Skipping..."
print(wt)
def safefilter(text, unprintable=False, newlines=False, maxwidth=None):
"""
Filter out undesirable characters from input text.
(Intended for debugging.)
If `unprintable` is set to True, any character not printable
be rendered as an underscore. Note that of course you may have actual
underscores in your `text` as well!
If `newlines` is set to True, ASCII characters 10 and 13 (CR and LF) will
be rendered as an underscore.
If `maxwidth` is set to an integer, text will be truncated and an elipsis
inserted.
"""
text = str(text)
if maxwidth and len(text) > maxwidth:
output1 = text[0:maxwidth-3] + "..."
else:
output1 = text
if unprintable or newlines:
output2 = ""
for character in output1:
#if unprintable and (chr(character) not in string.printable):
if unprintable and (character not in string.printable):
output2 += "_"
elif newlines and (ord(character) == 10 or ord(character) == 13):
output2 += "_"
else:
output2 += character
else:
output2 = output1
return output2
def split_len(seq, length):
"""
Take any sequence and split it evenly into sequences that are each <length>
long.
"""
return [seq[i:i+length] for i in range(0, len(seq), length)]
# idk if these are like cheating or something because they're using the base64
# module?
def base64_to_hex(x):
text = base64.b64decode(x.encode())
hexstring = ""
for character in text:
hexstring += '{:0>2}'.format(hex(character)[2:])
if len(hexstring)%2 is 1:
hextring = "0"+hexstring
return hexstring
def hex_to_string(hexstring):
# each PAIR of hex digits represents ONE character, so grab them by twos
character=""
decoded=""
for i in range(0, len(hexstring), 2):
decoded += chr(int(hexstring[i:i+2], 16))
return decoded
def hex_to_bin(hexstring):
bs = int(hexstring, 16)
return bs
def bin_to_hex(integer):
return hex(integer)
# this isn't used anywhere
# ... plus I think it actually doesn't work
# TODO: replace with hexlify or equialient
# TODO: look at other helper functions like this and replace them similarly
def string_to_hex(text):
hexstring = ""
# the last character is \x00 which just terminates it, ignore that
for char in text.encode()[0:-1]:
hexstring += '{:0>2}'.format(hex(char)[2:])
if len(hexstring)%2 is 1:
hextring = "0"+hexstring
return hexstring
def hex_to_base64(hexstring):
return base64.b64encode(hex_to_string(hexstring).encode())
def xor_hexstrings(plaintext, key):
"""
Take two hex strings and xor them together.
Return the result as a hex string.
The first is treated as the "plaintext" hex string.
The second is treated as the "key" hex string. If the key is shorter than
the plaintext, it is repeated as many times as is necessary until they
are of equal length.
"""
# repeat the key as many times as necessary to be >= len of the plaintext
repcount = math.ceil(len(plaintext)/len(key))
fullkey = key * repcount
# make sure the key didnt end up longer than the plaintext by the
# repetition
fullkey = fullkey[0:len(plaintext)]
xorbin = int(plaintext, 16) ^ int(fullkey, 16)
xorhex = '{:0>2x}'.format(xorbin) # chomp leading '0x'
# if the xor results in a number with leading zeroes, make sure they're
# added back so that the ciphertext is the same length as the plaintext
diff = len(plaintext) - len(xorhex)
for i in range(0, diff):
xorhex = "0" + xorhex
return xorhex
def xor_strings(plaintext, key):
"""
Xor the given plaintext against the given key.
Return the result in a hexstring.
If the plaintext is longer than the key, repeat the key as many times as is
necessary.
"""
# repeat the key as many times as necessary to be >= len of the plaintext
repcount = math.ceil(len(plaintext)/len(key))
fullkey = key * repcount
# make sure the key didnt end up longer than the plaintext by repetition
fullkey = fullkey[0:len(plaintext)]
phex = binascii.hexlify(plaintext.encode())
khex = binascii.hexlify(key.encode())
x = xor_hexstrings(phex, khex)
return(x)
def char_counts(text):
"""
Count different types of characters in a text. Useful for statistical
analysis of candidate plaintext.
"""
vowels = 'aeiouAEIOU'
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
count={'w':0, 'v':0, 'c':0, 'o':0,
'printable':0, 'unprintable':0,
'bad_lineendings':0}
index = 0
for character in text:
if character in string.whitespace:
count['w'] += 1
elif character in vowels:
count['v'] += 1
elif character in consonants:
count['c'] += 1
else:
count['o'] += 1
if character in string.printable:
count['printable'] += 1
else:
count['unprintable'] += 1
# check for linefeeds. if there's \r\n, assume OK (windows standard),
# but if \r by itself, assume bad (nothing uses \r by itself)
if ord(character) is 13:
if index+1 >= len(text) or ord(text[index+1]) is not 10:
pass
else:
count['bad_lineendings'] += 1
text[index-1]
index += 1
count['l'] = count['c'] + count['v']
return count
def winnow_wordlength(text):
"""
Return True if some text contains 1-9 letters per space, False otherwise.
English has an average word length of about five letters.
"""
count = char_counts(text)
try:
avg_length = count['l'] / count['w']
except ZeroDivisionError:
avg_length = count['l']
if 2 < avg_length < 12:
return True
else:
return False
def winnow_unprintable_ascii(text):
"""
Return False if a text contains any non-ascii (or non-printable ascii)
characters; True otherwise.
"""
cc = char_counts(text)
# spt = "UA: {} BLE: {} WUA: {}".format(
# cc['unprintable'], cc['bad_lineendings'], text)
# safeprint(spt, unprintable=True)
if cc['unprintable'] > 0 or cc['bad_lineendings'] > 0:
return False
else:
return True
def winnow_punctuation(text):
"""
Return False if a text contains too many non-letter non-space characters,
True otherwise.
"""
count = char_counts(text)
if count['o'] < len(text)/8:
return True
else:
return False
def winnow_vowel_ratio(text):
count = char_counts(text)
# in English text, v/c ratio is about 38/62 i.e. 0.612
# https://en.wikipedia.org/wiki/Letter_frequency
try:
vc_ratio = count['v']/count['c']
except ZeroDivisionError:
vc_ratio = 1
if 0.20 < vc_ratio < 0.99:
return True
else:
return False
# TODO: fix all the callers of this function so that they don't pass SCC
# objects, they should just pass a plaintext now
def winnow_plaintexts(candidates):
# if CRYPTOPALS_DEBUG:
# csup = sorted(candidates, key=lambda c: c.charcounts['unprintable'])
# for c in candidates:
# safeprint(c, underscores=True, maxwidth=80)
can2 = []
for c in candidates:
if winnow_unprintable_ascii(c):
can2 += [c]
if len(can2) == 0:
et = "Unprintable ASCII winnowing failed. "
et+= "Found no candidates which didn't result in unprintableascii "
et+= "characters for this hexstring: \n '{}'".format(
candidates[0].hexstring[0:72] + "...")
raise MCPWinnowingError(et)
candidates = can2
opt_winnowers = [winnow_punctuation,
winnow_vowel_ratio,
winnow_wordlength,
lambda x: True] # the final one must be a noop lol TODO
for w in opt_winnowers:
can2 = []
for c in candidates:
if w(c):
can2 += [c]
if len(can2) is 1:
candidates = can2
break
elif len(can2) is 0:
# ... and you don't actually have to roll back, you just have to
# ignore can2
pass
else:
candidates = can2
#ideally there will be only one candidate butttt
# TODO: winnow better so there's guaranteed to be just one candidate dummy
if len(candidates) == 0:
return False
elif len(candidates) > 1:
debugprint("WINNOWING COMPLETE BUT {} CANDIDATES REMAIN".format(
len(candidates)))
return candidates
# TODO: test before next commit
def detect_1char_xor(hexes):
candidates = []
for h in hexes:
candidates += SingleCharCandidate.generate_set(h)
can2 = winnow_plaintexts(candidates)
winner = can2[0]
return winner
def find_1char_xor(hexstring):
"""
Take a hex ciphertext string.
Xor it against every ASCII character.
Do some analysis about the resulting texts.
Get the resulting text most likely to be English.
Return a SingleCharCandidate object.
"""
candidates = []
if len(hexstring)%2 is 1:
# pad with zero so there's an even number of hex chars
# this way my other functions like work properly
h = "0" + h
for i in range(0, 128):
candidates += [SingleCharCandidate(hexstring, chr(i))]
can2 = winnow_plaintexts(candidates)
candidates = can2
#ideally there will be only one candidate butttt
# TODO: winnow better so there's guaranteed to be just one candidate dummy
if len(candidates) == 0:
return False
elif len(candidates) > 1:
debugprint("WINNOWING COMPLETE BUT {} CANDIDATES REMAIN".format(
len(candidates)))
return candidates[0]
class MCPWinnowingError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class SingleCharCandidate(object):
"""
Bundle for the following data:
- a hex cipherstring
- a single character to xor it against
- the result of that xor
"""
def __init__(self, hexstring, xorchar):
if len(hexstring)%2 == 1:
self.hexstring = "0" + hexstring
else:
self.hexstring = hexstring
if not 0 <= ord(xorchar) <= 127:
raise Exception("Passed a xorchar that is not an ascii character.")
self.xorchar = xorchar
self.hex_xorchar = "{:0>2x}".format(ord(self.xorchar))
self.length = len(self.hexstring)
hex_plaintext = xor_hexstrings(self.hexstring, self.hex_xorchar)
self.plaintext = hex_to_string(hex_plaintext)
self.charcounts = char_counts(self.plaintext)
def __repr__(self):
#return "xorchar: '{}'; hexstring: '{}'; plaintext: '{}'".format(
# self.xorchar, self.hexstring, self.plaintext)
if len(self.plaintext) > 50:
pt = safefilter(self.plaintext[0:47] + "...",
unprintable=True, newlines=True)
else:
pt = safefilter(self.plaintext,
unprintable=True, newlines=True)
r = "xorchar: {} plaintext: {}".format(self.xorchar, pt)
return(r)
@classmethod
def generate_set(self, hexstring):
candidates = []
for i in range(0, 128):
candidates += [SingleCharCandidate(hexstring, chr(i))]
return candidates
class TchunkCandidateSet(object):
"""
A set of candidates for a tchunk.
Contains the text of the tchunk itself, all 128 SingleCharCandidate objects
generated by SingleCharCandidate.generate_set(), and an array called
`winners` that contains the best of those SCC objects as judged by whether
they pass a series of winnowing tests.
"""
def __init__(self, text):
"""
- Take in text from a tchunk (a transposed chunk from a
MultiCharCandidate)
- Brute force a plaintext from that ciphertext by calling
SingleCharCandidate.generate_set()
- Winnow those 128 candidates down to (ideally) just one
winner.
"""
self.text = text
# calculate the possibilities for this chunk
self.candidates = SingleCharCandidate.generate_set(self.text)
self.solved = True
self.winners = []
# now winnow the plaintexts down for each tchunk
# TODO: note that right now this may have several winners! make sure to
# handle that elsewhere
tcwinners = winnow_plaintexts(self.candidates)
if tcwinners:
self.winners = tcwinners
else:
self.winners = False
self.solved = False
def __repr__(self):
if self.solved:
solvstring = "solved ({} winners)".format(len(self.winners))
else:
solvstring = "unsolved"
repr = "<TchunkCandidateSet: {}, ".format(solvstring)
return repr
class MultiCharCandidate(object):
"""
A bundle for the following related pieces of data:
- a single piece of ciphertext (represented in *hex*)
- a single key which is assumed to be multiple ascii characters long
(represented in *hex*)
- chunks: the ciphertext, divided into chunks len(key) long
- tchunks: those chunks, transposed
- the hamming code distance between chunks[0] and chunks[1]
- for each tchunk, a TchunkCandidateSet object
- a plain text that is reassembled from the TchunkCandidateSet objects
"""
def __init__(self, hexstring, keylen):
self.keylen = keylen
if int(len(hexstring)%2) != 0:
self.hexstring = "0" + hexstring
else:
self.hexstring = hexstring
self.cipherlen = len(self.hexstring)
self.tchunksize = math.ceil(self.cipherlen/self.keylen)
# only operate on even-length keys because two hits is one charater
if self.keylen%2 != 0:
es = "Cannot create a MultiCharCandidate object with an odd keylen"
raise Exception(es)
# divide the ciphertext into chunks
self.chunks = []
this_chunk = ""
# I have to use cipherlen+1 or this will stop on the second to last
# char... This is ugly and should be fixed probably, but I'm too tired
for i in range(0, self.cipherlen+1, 2):
this_chunk += self.hexstring[i:i+2]
if len(this_chunk) == self.keylen or i >= self.cipherlen:
self.chunks += [this_chunk]
this_chunk = ""
hd = hamming_code_distance(self.chunks[0], self.chunks[1])
self.hdnorm = hd/self.keylen
# build the transposed chunks
# you have len(chunks)/2 many chunks, that are all keylen/2 long
# you'll end up with keylen/2 many transposed chunks that are all
# len(chunks)/2 long.
# (you divide all of those by two because two hits make up one char)
self.tchunks = []
self.solved_all = True
for i in range(0, self.keylen, 2):
new_tchunk_text = ""
for c in self.chunks:
new_tchunk_text += c[i:i+2]
new_tchunk = TchunkCandidateSet(new_tchunk_text)
self.tchunks.append(new_tchunk)
if not new_tchunk.solved:
self.solved_all = False
self.plaintext = self.key = self.fullkey = ""
tchunk_count = len(self.tchunks)
for i in range(0, self.tchunksize):
for tc in self.tchunks:
# use an underscore as a temp value that gets printed if there
# was no winner
newpt = newxc = '_'
if tc.solved:
try:
tcw = tc.winners[0]
newpt = tcw.plaintext[i]
newxc = tcw.xorchar
except IndexError:
# this only ever happens for the last tchunks of the
# bunch, when the keylen doesn't divide evenly into
# the cipherlen
pass
#newpt = tc.winners[0].plaintext[i]
#newxc = tc.winners[0].xorchar
self.plaintext += newpt
self.fullkey += newxc
if i == 0:
self.key = self.fullkey
def __repr__(self):
repr = "<MultiCharCandidate: key(hex): {} hdnorm: ~{} tchunks: {}>"
repr = repr.format(
binascii.hexlify(self.key.encode()),
round(self.hdnorm, 4),
len(self.tchunks))
return repr
def diag(self):
repr = self.__repr__()
for tc in self.tchunks:
repr += "\n {}".format(tc.__repr__())
for w in tc.winners:
wrepr = w.__repr__()
wrepr = wrepr.replace("\n","_").replace("\r","_")
wrepr = "\n " + wrepr
repr += wrepr
safeprint(repr)
def winnow_aesecb_repetition(ciphertext, keylen):
"""
Examine a string of text that is suspected to be encrypted with AES-128-ECB
"Remember that the problem with ECB is that it is stateless and
deterministic; the same 16 byte plaintext block will always produce
the same 16 byte ciphertext."
If it has any repeated <keylen> byte segments, return true.
(keylen must be 16, 24, or 32)
"""
chunks = split_len(ciphertext, keylen)
if len(chunks) != len(set(chunks)):
debugprint(ciphertext)
# twins = []
# for idx1 in range(len(chunks)):
# try:
# for idx2 in range(idx1 + 1, len(chunks)):
# if chunks[idx1] == chunks[idx2]:
# twins += chunks[idx1]
# debugprint(" " + str(chunks[idx1]))
# break
# except IndexError:
# pass
# debugprint("----")
# for c in chunks:
# debugprint(" " + str(c))
# return twins
return True
else:
return False
def bruteforce_aesecb(ciphertext):
"""
brute force an aes-ecb ciphertext string.
"""
keystring = ""
for c in ciphertext:
# a space is the lowest-valued printable character in ascii
keystring += " "
candidates = []
for keytup in itertools.combinations(string.printable, len(ciphertext)):
keystring = ''.join(keytup)
cipher = AES.new(keystring, AES.MODE_ECB)
plaintext = cipher.decrypt(ciphertext).decode()
for c in plaintext:
if c not in string.printable:
break
else:
candidates += [plaintext]
print("There are {} candidates.".format(len(candidates)))
def hamming_code_distance(string1, string2):
"""
Compute the Hamming Code distance between two strings
"""
if len(string1) is not len(string2):
# If strings are different lengths, truncate the longer one so that you
# can do the compare
string1 = string1[0:len(string2)]
string2 = string2[0:len(string1)]
#raise Exception("Buffers are different lengths!")
bytes1=string1.encode()
bytes2=string2.encode()
i = 0
hamming_distance = 0
while i < len(bytes1):
char1 = bytes1[i]
char2 = bytes2[i]
bin1 = "{:0>8}".format(bin(char1)[2:])
bin2 = "{:0>8}".format(bin(char2)[2:])
j = 0
thisbyte_hd = 0
while j < 8:
if bin1[j] is not bin2[j]:
thisbyte_hd +=1
hamming_distance += 1
j +=1
i +=1
return hamming_distance
def find_multichar_xor(hexstring):
"""
Break a hexstring of repeating-key XOR ciphertext.
"""
# Remember that if we're assuming that our XOR key came from ASCII, it will
# have an even number of hex digits.
# Throughout this function and elsewhere, keylen is specificed in *hex*
# digits.
if len(hexstring)%2 is not 0:
hexstring = "0"+hexstring
keylenmin = 2
keylenmax = 80
cipherlen = len(hexstring)
dp = "min key length: {} / ".format(keylenmin)
dp+= "max key length: {} / ".format(keylenmax)
dp+= "hexstring length: {}".format(len(hexstring))
debugprint(dp)
attempts = []
# only operate on even-length keys because two hits is one charater:
for keylen in range(keylenmin, keylenmax, 2):
# if the MCC results in a winnowing error, ignore that keylen:
try:
na = [MultiCharCandidate(hexstring, keylen)]
attempts += na
except MCPWinnowingError:
debugprint("Winnowing exception for keylen {}".format(keylen))
attempts_sorted = sorted(attempts, key=lambda a: a.hdnorm, reverse=True)
winner = attempts_sorted[0]
if CRYPTOPALS_DEBUG:
print("######## winning MCC diagnostic: ########")
winner.diag()
print("######## sorted attempts diagnostic: ########")
for a in attempts_sorted[0:10]:
print(a)
print("######## ################### ########")
print()
return winner
########################################################################
## Challenge functions - one per challnge, plus maybe more for the extra credit
## sections
# this way I can just create a new function called chalX, and call
# challenger("chalX"), and it calls my new function. I use this in conjuunction
# with argparse
def challenger(args):
print("Running challenge {}...".format(args.chalnum))
globals()["chal"+args.chalnum]()
def chal01():
exh = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d'
exb = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
print("exh: " + exh)
print("exb->exh: " + base64_to_hex(exb))
print("exb: " + str(exb))
print("exh->exb: " + hex_to_base64(exh).decode())
print("orig str: " + hex_to_string(exh))
def chal02():
ex1 = '1c0111001f010100061a024b53535009181c'
ex2 = '686974207468652062756c6c277320657965'
res = '746865206b696420646f6e277420706c6179'
calculated = xor_hexstrings(ex1, ex2)
print("ex1: " + ex1)
print("ex2: " + ex2)
print("res: " + res)
print("calculated result:\n " + calculated)
def chal03():
ciphertext = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
print(find_1char_xor(ciphertext))
def chal04():
gist = open("data/challenge04.3132713.gist.txt")
hexes = [line.strip() for line in gist.readlines()]
gist.close()
winner = detect_1char_xor(hexes)
if winner:
print("Detected plaintext '{}'".format(winner.plaintext))
print("From hex string '{}'".format(winner.hexstring))
print("XOR'd against character '{}'".format(winner.xorchar))
else:
print("Could not find a winner.")
def chal05():
plaintext = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
repkey = "ICE"
solution = "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"
print("The calculated result:")
print(xor_strings(plaintext, repkey))
print("The official solution:")
print(solution)
def chal06():
f = open("data/challenge06.3132752.gist.txt")
gist = f.read().replace("\n","")
f.close()
hexcipher = base64_to_hex(gist)
winner = find_multichar_xor(hexcipher)
print("Winning plaintext:")
print(winner.plaintext)
print()
print("Key: '{}' of len {}".format(winner.key, winner.keylen))
def chal06a():
ex1="this is a test"
ex2="wokka wokka!!!"
print("Hamming code distance between: \n\t{}\n\t{}".format(ex1, ex2))
print("... is: {}".format(hamming_code_distance(ex1, ex2)))
def chal06b():
ciphertext = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
winner = find_multichar_xor(ciphertext)
print(winner.plaintext)
def chal07():
# note: requires pycrypto
key = b'YELLOW SUBMARINE'
cipher = AES.new(key, AES.MODE_ECB)
f = open("data/challenge07.3132853.gist.txt")
gist = f.read().replace("\n","")
f.close()
ciphertext = base64.b64decode(gist.encode())
plaintext = cipher.decrypt(ciphertext).decode()
print(plaintext)
def chal08():
f = open("data/challenge08.3132928.gist.txt")
hexes = [line.strip() for line in f.readlines()]
f.close()
candidates = []
idx = 0
for h in hexes:
asc = binascii.unhexlify(h)
chunks = split_len(asc, 16)
if len(chunks) != len(set(chunks)):
#print("hexes[{}] has identical chunks")
candidates += [asc]
idx +=1
print(candidates[0])
bruteforce_aesecb(candidates[0])
########################################################################
## main()
CRYPTOPALS_DEBUG=False
def strace():
pass
def debugprint():
pass
class DebugAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
global CRYPTOPALS_DEBUG
CRYPTOPALS_DEBUG = True
global debugprint
def debugprint(text):
"""
Print the passed text if the program is being run in debug mode.
"""
safeprint("DEBUG: " + str(text))
try:
import TotalBullshitIdk
from IPython.core.debugger import Pdb
global strace
strace = Pdb(color_scheme='Linux').set_trace
from IPython.core import ultratb
ftb = ultratb.FormattedTB(#mode='Plain',
mode='Verbose',
color_scheme='Linux', call_pdb=1)
sys.excepthook = ftb
except ImportError:
global strace
from pdb import set_trace as strace
global fallback_debug_trap
def fallback_debug_trap(type, value, tb):
"""
Print some diagnostics, colorize the important bits, and then
automatically drop into the debugger when there is an unhandled
exception.
NOTE: If IPython is installed, this is never used!
IPython.core.ultratb.FormattedTB() is used in that case.
"""
import traceback
import pdb
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
tbtext = ''.join(traceback.format_exception(type, value, tb))
lexer = get_lexer_by_name("pytb", stripall=True)
formatter = TerminalFormatter()
sys.stderr.write(highlight(tbtext, lexer, formatter))
pdb.pm()
sys.excepthook = fallback_debug_trap
if __name__=='__main__':
argparser = argparse.ArgumentParser(description='Matasano Cryptopals Yay')
argparser.add_argument('--debug', '-d', nargs=0, action=DebugAction,
help='Show debugging information')
subparsers = argparser.add_subparsers()
h="Run one of the challenge assignments directly"
subparser_challenges = subparsers.add_parser('challenge',
aliases=['c','ch','chal'],
help=h)
h='Choose the challenge number you want to run'
subparser_challenges.add_argument('chalnum', type=str, action='store',
help=h)
subparser_challenges.set_defaults(func=challenger)
parsed = argparser.parse_args()
parsed.func(parsed)
|
8812d73519fb3656dc2252f57a96fae758d2c174 | qwert100good/Python004 | /Week03/homework01/homework_v1.py | 3,247 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
@author : Yx
"""
# # 示例代码
# import threading
# class DiningPhilosophers:
# def __init__(self):
# pass
# # philosopher 哲学家的编号。
# # pickLeftFork 和 pickRightFork 表示拿起左边或右边的叉子。
# # eat 表示吃面。
# # putLeftFork 和 putRightFork 表示放下左边或右边的叉子。
# def wantsToEat(self,
# philosopher,
# pickLeftFork(),
# pickRightFork(),
# eat(),
# putLeftFork(),
# putRightFork())
import queue
import threading
import time
import random
class DiningPhilosopher(threading.Thread):
def __init__(self, philosopher, fork_locks, q, eat_times=1, *args, **kwargs):
super().__init__(*args, **kwargs)
self.philosopher_num = philosopher
self.philosopher_name = f'哲学家{philosopher}'
self.fork_locks = fork_locks
self.q = q
self.eat_times = eat_times
self.left_fork_num = self.philosopher_num % len(fork_locks)
self.right_fork_num = (self.philosopher_num + 1) % len(fork_locks)
def wantsToEat(self, *actions):
[action() for action in actions]
def run(self):
current_time = 1
self.think()
while current_time <= self.eat_times:
self.wantsToEat(
self._pickLeftFork,
self._pickRightFork,
self._eat,
self._putLeftFork,
self._putRightFork
)
current_time += 1
self.think()
def think(self):
think_time = random.randint(1, 5) / 100
time.sleep(think_time)
def _pickLeftFork(self):
self.fork_locks[self.left_fork_num].acquire()
self.q.put([self.philosopher_num, 1, 1])
print(f'philosopher {self.philosopher_num} pickLeftFork')
def _pickRightFork(self):
self.fork_locks[self.right_fork_num].acquire()
self.q.put([self.philosopher_num, 2, 1])
print(f'philosopher {self.philosopher_num} pickRightFork')
def _eat(self):
eat_time = random.randint(1, 3) / 100
time.sleep(eat_time)
self.q.put([self.philosopher_num, 0, 3])
print(f'philosopher {self.philosopher_num} eat noodle')
def _putLeftFork(self):
self.fork_locks[self.left_fork_num].release()
self.q.put([self.philosopher_num, 1, 2])
print(f'philosopher {self.philosopher_num} putLeftFork')
def _putRightFork(self):
self.fork_locks[self.right_fork_num].release()
self.q.put([self.philosopher_num, 2, 2])
print(f'philosopher {self.philosopher_num} putRightFork')
def main():
threads = []
fork_locks = []
result = []
q = queue.Queue()
for i in range(5):
fork_lock = threading.Lock()
fork_locks.append(fork_lock)
eat_times = 5
for i in range(5):
t = DiningPhilosopher(i, q=q, fork_locks=fork_locks, eat_times=eat_times)
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
while not q.empty():
result.append(q.get())
with open('result.txt', 'a', encoding='utf-8') as f:
f.write(str(result) + '\n')
if __name__ == '__main__':
main()
|
f1d8fd7ceeeef8fc1982dfee3213ef436334775c | NaruBeast/Basic-Python-Programs | /swap.py | 219 | 3.90625 | 4 | num1 = input("Enter 1st number: ")
num2 = input("Enter 2nd number: ")
print "Before swapping: num1 =", num1, "and num2 =", num2
num1, num2 = num2, num1
print "After swapping swapping: num1 =", num1, "and num2 =", num2
|
cd1bb66c9bdc5b05d8ec8e17a1a1d8b4fa255989 | NaruBeast/Basic-Python-Programs | /kilo-mile.py | 98 | 3.890625 | 4 | x = input("Enter distance in kilometers: ")
y = x * 0.621371
print x, 'kilometers = ', y, 'miles' |
f0a08661d9c12875149f811c016dbbd8fe3d3538 | getHecked/sample-repo | /tests/reading_documentation.py | 1,048 | 3.8125 | 4 | import re
file = open("test1.txt", 'r',encoding='utf-8').read()
words={}
slist=file.replace("\W+",'').split(" ")
for element in slist:
if element in words:
words[element]+= 1
else:
words[element]=1
words
lowest = min(words.values())
highest = max(words.values())
for word,freq in words.items():
if freq==lowest:
print(f"The least frequent word is '{word_lowest}' with a frequency of: {lowest}")
if freq==highest:
print(f"The most frequent word is '{word}' with a frequency of: {highest}")
######################################3
file = open("test1.txt", 'r',encoding='utf-8')
words = {}
words_capital = {}
for s in file:
if (s[0].isupper()==True):
words_capital[s] = s
else:
words[s] = s
for key,value in sorted(words_capital.items()):
print(value)
for key,value in sorted(words.items()):
print(value)
#######################################
word_list = input().split(' ')
print(sum(1 for i in word_list if i[::-1]==i ))
#######################################3
|
f4e4beb1d2975fd523ca7dd744aa7a96e686373a | WeiyiDeng/hpsc_LinuxVM | /lecture7/debugtry.py | 578 | 4.15625 | 4 | x = 3
y = 22
def ff(z):
x = z+3 # x here is local variable in the func
print("+++ in func ff, x = %s; y = %s; z = %s") %(x,y,z)
return(x) # does not change the value of x in the main program
# to avoid confusion, use a different symbol (eg. u) instead of x in the function
print("+++ before excuting ff, x = %s; y = %s") %(x,y)
y = ff(x)
print("+++ after excuting ff, x = %s; y = %s") %(x,y)
# in ipython>>> run debugtry.py
# outputs:
# before ff: x = 3, y = 22
# within ff: z = 3, x = 6, y = 22
# after ff: x = 3, y = 6 |
d4391135272c24e27386c954bc887af2c32918f1 | WaaberiIbrahim/pizzapi | /main.py | 1,211 | 3.6875 | 4 | from pizzapy import *
print('Bienvenue au DPPD')
print('Nous avons besoin de quelques informations avant de vous livrer')
name = input('Entrer votre nom (Premom et nom de famille seulement)')
email = input('Entrer votre email: ')
phone = input('Entrer votre numero de telephone')
addresse = input('Entrer votre adresse dans cette forme: addresse, ville, province, code postal')
postal = addresse.split(', ')[3]
n = name.split()
customer = Customer(n[0], n[1], email, phone, addresse)
my_local_dominos = StoreLocator.find_closest_store_to_customer(customer)
menu = my_local_dominos.get_menu()
stuff_to_add = []
while True:
stuff = input('Entrer votre item (Q pour finir)')
if stuff.upper == 'Q':
break
menu.search(Name=stuff)
code = input("Entrer le code")
stuff_to_add.append(code.upper())
order = Order.begin_customer_order(customer, my_local_dominos)
for item in stuff_to_add:
order.add_item(item)
code = input('Entrez le code de votre carte')
exp = input('Entrer la date dexpiration sans slash')
cvv2 = input('Entrer le coed de securite a larriere de votre carte')
card = CreditCard(code, exp, cvv2, postal)
order.place(card)
my_local_dominos.place_order(order, card)
|
f402afcc94362754bec35826f5b155d050b256e2 | Muntaha-Islam0019/HackerRank-Solutions | /Problem Solving/Algorithms/Mark and Toys.py | 594 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'maximumToys' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY prices
# 2. INTEGER k
#
def maximumToys(prices, k):
# Write your code here
s = 0
for i in prices:
if i <= k:
s += 1
k -= i
else:
break
return s
if __name__ == '__main__':
n,k = map(int,input().split())
prices = sorted(map(int,input().split()))
print(maximumToys(prices, k))
|
ec7cc31141437232aecb562f0a5c9f75b43e4184 | Muntaha-Islam0019/HackerRank-Solutions | /Problem Solving/Algorithms/Jim and the Orders.py | 705 | 3.75 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'jimOrders' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts 2D_INTEGER_ARRAY orders as parameter.
#
def jimOrders(orders):
# Write your code here
s = sorted(enumerate(orders,1),key=lambda x:sum(x[1]))
return (i[0] for i in s)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
orders = []
for _ in range(n):
orders.append(list(map(int, input().rstrip().split())))
result = jimOrders(orders)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.