blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
6a8192187c62ab05b04cca015c7791217202ac65 | ishauchuk/crash_course | /10.4.py | 210 | 3.78125 | 4 |
filename = 'guest_book.txt'
while True:
name = input('Introduce yourself:\n')
if name:
with open(filename, 'a') as file_object:
file_object.write(f"Your name is {name}. I added you.\n")
else:
break |
de0d16cf9325655966a55ecec3e658c9e9d27a5f | ofk16fsm/DVG304 | /Assignment_1/Assignment_simple.py | 341 | 3.78125 | 4 | import csv
f = open(r'USCounties.csv','r')
reader = csv.reader(f) #creating the reader object
headers = next(reader) #getting the list of headers
print (headers)
r = list(reader)
uniq = []
for row in r:
STATE_NAME = row[1]
if STATE_NAME not in uniq:
uniq.append(STATE_NAME)
for i in uniq:
print(i)
print(len(uniq)) |
122c36b72655ab048c2e6ab7bd1772f27a59c5c9 | LiuKaiqiang94/PyStudyExample | /python_program/inputdialog.py | 1,219 | 3.796875 | 4 | #输入框
from graphics import *
from button import Button
class InputDialog:
def __init__(self,angle,vel,height):
self.win=win=GraphWin("Initial Values",200,300)
win.setCoords(0,4.5,4,.5)
Text(Point(1,1),"Angle").draw(win)
self.angle=Entry(Point(3,1),5).draw(win)
self.angle.setText(str(angle))
Text(Point(1,2),"Velocity").draw(win)
self.vel=Entry(Point(3,2),5).draw(win)
self.vel.setText(str(vel))
Text(Point(1,3),"Height").draw(win)
self.height=Entry(Point(3,3),5).draw(win)
self.height.setText(str(height))
self.fire=Button(win,Point(1,4),1.25,.5,"Fire!")
self.fire.activate()
self.quit=Button(win,Point(3,4),1.25,.5,"Quit")
self.quit.activate()
def interact(self):
while True:
pt=self.win.getMouse()
if self.quit.clicked(pt):
return "Quit"
if self.fire.clicked(pt):
return "Fire!"
def getValues(self):
a=float(self.angle.getText())
v=float(self.vel.getText())
h=float(self.height.getText())
return a,v,h
def close(self):
self.win.close()
|
1f0314c2810d669dd2a66679680273c6eb49a02a | renukadeshmukh/Leetcode_Solutions | /122_BestTimetoBuyandSellStockII.py | 1,659 | 4.28125 | 4 | '''
122. Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on
day i. Design an algorithm to find the maximum profit. You may complete as many
transactions as you like (i.e., buy one and sell one share of the stock multiple
times).
Note: You may not engage in multiple transactions at the same time (i.e., you
must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation:
Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation:
Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
'''
'''
ALGORITHM:
1. For every consecutive pair of prices, check if there is a profit.
2. If yes, add the difference to total profit.
RUNTIME COMPLEXITY: O(N)
SPACE COMPLEXITY: O(1)
'''
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
profit += (prices[i] - prices[i-1])
return profit
s = Solution()
print(s.maxProfit([7,1,5,3,6,4]))
print(s.maxProfit( [1,2,3,4,5]))
print(s.maxProfit([7,6,4,3,1])) |
bc3a8eda1fbf3060cd35dda88d4d60eca5915010 | ajmainankon/OOP | /task6.py | 2,348 | 3.59375 | 4 | class Bank:
def __init__(self, code, address):
self.code = code
self.address = address
def manages(self):
return (f'Manages Bnak with ID {code} at {address}')
def mantains(self, booth=None):
if booth != None:
return (f'mantains ATM at {booth.location}')
class ATM:
def __init__(self, location, managedby):
self.location = location
self.managedby = managedby
def identifies(self):
return f"Managed by {self.managedby}"
def transactions(self, tr):
print(f'Transaction in {self.location} details:')
print(tr)
class Customer:
def __init__(self, name, address, dob, card_num, pin):
self.name = name
self.address = address
self.dob = dob
self.card_num = card_num
self.pin = pin
def verify_pass(self, pin):
if self.pin == pin:
return True
return False
class Account:
def __init__(self, customer, number, balance):
self.customer = customer
self.number = number
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def createTransaction(self, amount):
self.balance -= amount
class CurAcc(Account):
def __init__(self, customer, number, balance):
super(customer, number, balance)
class SavingAcc(Account):
def __init__(self, customer, number, balance):
super(customer, number, balance)
class ATM_Transactions:
def __init__(self, tid, date, ttype, amount, post_bal):
self.tid = tid
self. date = date
self.ttype = ttype
self.amount = amount
self.post_bal = post_bal
def modifies(self, tid, date, ttype, amount, post_bal):
self.tid = tid
self. date = date
self.ttype = ttype
self.amount = amount
self.post_bal = post_bal
def __str__(self):
return f'{self.tid} {self.date} {self.amount}'
ankon = Customer('Ankon', 'Dhaka', 'June 16 1998', '12333', '123')
ucb = Bank('01', 'Motejheel')
ucb_atm = ATM('cumilla', 'Rohim')
transec = ATM_Transactions('2', '2 jan 2020', 'card', '2000', '40000')
ucb_atm.transactions(transec)
|
3e4b61ba79e9da36c85cf084ad9bbdfb54698fb1 | mdwcrft/python-scripts | /multiprocessing.py | 423 | 3.71875 | 4 | '''
Chad Meadowcroft
Credit to Sentdex (https://pythonprogramming.net/)
'''
import multiprocessing
def spawn(num):
print('Spawned! {}'.format(num))
if __name__ == '__main__':
for i in range(5):
# .process spawns a process object, works similar to threading.thread
p = multiprocessing.Process(target=spawn, args=(i,))
p.start() # Starts multiprocess
p.join() # Performs processes in order |
cdfa39192080ded154e8293f2c8cfb6799dcc5e6 | frankieliu/problems | /leetcode/python/617/sol.py | 898 | 4.125 | 4 |
Short Recursive Solution w/ Python & C++
https://leetcode.com/problems/merge-two-binary-trees/discuss/104301
* Lang: python3
* Author: zqfan
* Votes: 32
python solution
```
class Solution(object):
def mergeTrees(self, t1, t2):
if t1 and t2:
root = TreeNode(t1.val + t2.val)
root.left = self.mergeTrees(t1.left, t2.left)
root.right = self.mergeTrees(t1.right, t2.right)
return root
else:
return t1 or t2
```
c++ solution
```
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if ( t1 && t2 ) {
TreeNode * root = new TreeNode(t1->val + t2->val);
root->left = mergeTrees(t1->left, t2->left);
root->right = mergeTrees(t1->right, t2->right);
return root;
} else {
return t1 ? t1 : t2;
}
}
};
```
|
b51c44618813b1d9c2033d4df445ecd5691f57b7 | i-am-Shuvro/Project-GS-4354- | /Main File.py | 8,972 | 3.96875 | 4 | def greet(str):
name1 = input("[N.B: Enter your name to start the program.] \n\t* First Name: ")
name2 = input("\t* Last Name: ")
return "Hello, " + str(name1) + " " + str(name2) + "! Welcome to this program, sir!"
print(greet(str))
print("This program helps you with some information on tax-rate on building construction. "
"\nBesides it tells you about some facilities you can add to your cart within your budget.")
input("\tPress ENTER to start the program!")
from Module import getinput
def confirm():
while True:
budget = getinput("Please enter your budget amount for building construction in BDT (At least 1 crore): ")
if budget < 10000000:
print("\tThis budget is too low to construct a building, sir! The minimum budget should be of 1 crore!")
continue
else:
input(f"\tGreat! {budget} BDT is quite a sufficient amount. \nNow please press ENTER & choose various options!")
if budget >= 150000000:
while True:
try:
marble = int(input("\tDo you want marble-flooring in your building? Type 1 if you want & type 2 if you don't: "))
if marble == 1:
print("\t\tOkay! Your building will be of marble-flooring, sir.")
elif marble == 2:
print("\t\tGot you! You will get tiles-flooring, sir.")
else:
print("\t\tPlease choose to type one option from 1 and 2!")
continue
except ValueError:
print("\t\tOops! Something is wrong. Please choose to type one option from 1 and 2!")
continue
break
elif budget <= 50000000 or budget >= 15000000:
while True:
try:
tiles = int(input("\tDo you want tiles-flooring in your building? Type 1 if you want & type 2 if you don't: "))
if tiles == 1:
print("\t\tOkay! our building will be of tiles-flooring, sir.")
elif tiles == 2:
print("\t\tGot you! You will get cement-flooring, sir.")
else:
print("\t\tPlease choose to type one option from 1 and 2!")
continue
except ValueError:
print("\t\tOops! Something is wrong. Please choose to type one option from 1 and 2!")
continue
break
else:
print("\t\tAlight! You will get cement-flooring, sir.")
break
return budget
my_budget = confirm()
def free():
free_facilities = ["AI Security System", "Free Water Supply", "10 Years of free maintenance"]
serial = [1, 2, 3]
serial_of_services = [serial, free_facilities]
print("\nAs a small present, we give all our customers these 3 facilities for free: ", *free_facilities, sep="\n\t")
print("Besides you can suggest us for some more free-services.")
try:
n = int(input("Except these 3, enter how many facilities you would suggest us to provide for free (Press ENTER to skip): "))
j = 1
while j != n + 1:
free_demands = input("\t* Suggestion " + str(j) + ": ")
if not free_demands:
j -= 1
print("\tPlease enter your suggestions!")
else:
free_facilities.append(free_demands)
serial.append(4 + j)
j += 1
t = len(free_facilities)
print(f"Along with the 3 services, we will try to provide you with these {n} facilities:",
*free_facilities[3:], sep="\n\t")
print("\nSo, all you get from us as complementary is", *free_facilities, sep="\n\t")
try:
r = int(input("\nIf you wish to remove any of the above free services, just enter the serial number (Press ENTER to skip): "))
z = free_facilities.index(serial_of_services[1][r - 1])
free_facilities.pop(z)
print("\tSo you will get these free-services:", *free_facilities, sep="\n\t\t")
try:
more_delete = int(input("Want to remove some more services? Then write here the number of services you want to delete (Press ENTER to skip): "))
print("\t\tWrite down service name completely to delete from your cart! (eg: AI Security Service)")
for a in range(0, more_delete):
items = str(input(f"\t\t\t{a + 1}. Remove the service = "))
free_facilities.remove(items)
print("Alright! So, you are getting this fro free:", *free_facilities, sep="\n\t")
except:
print("So you do not want anything more to be removed. Great!")
except:
print("So, you don't want to remove anything from the list. Great!")
except:
print("So, you don't want to remove anything from the list. Great!")
free_service = free()
def paid():
print("\nWe also provide some services to our customers. You can purchase them from us. They are:")
internaldata = {1: 2000000,
2: 250000,
3: 800000,
4: 2000000,
5: 600000,
}
paid_facilities = {'1. Car Parking': 2000000,
'2. Elevator': 250000,
'3. Jacuzzi': 800000,
'4. Roof-top Swimming Pool': 2000000,
'5. Sauna': 600000,
}
for info in paid_facilities:
print("\t", info)
while True:
try:
y = int(input("To know the price in BDT, please list number (Press ENTER to skip): "))
if 1 <= y <= 5:
print("\tThe price of this item will be: ", internaldata.get(y))
else:
print("Please enter between 1 to 5 from this list!")
continue
z = input("Do you want to add more services? Type y to continue & press ENTER to skip: ")
if z.lower() == 'y':
continue
else:
print("Okay! No more prices!")
break
except:
print("Okay! No more prices!")
break
print("\nHere is a complete list of services. You can order them later if need be. Have a look:")
for key, value in paid_facilities.items():
print(key, ": Price", value, "BDT")
paid_service = paid()
from Module import getinput
building_type = ('1. Garment', '2. Residential', '3. Commercial', '4. Corporate')
print("\n Now to know about tax-rates & your total cost, choose a building type from this list - ", *building_type, sep="\n\t")
b = getinput("Enter the number for your building type?: ")
tax_list = (12, 10, 20, 25)
from Module import TaxCalc
maxtax = TaxCalc(tax_list)
print(f"\tThe maximum tax-rate will be {maxtax.get_max_tax()}% ", end="")
print(f"and the minimum tax-rate will be {maxtax.get_min_tax()}% for your building!")
class Gar(TaxCalc):
def get_addtax_gar(self):
return my_budget * (3 / 100)
gar = Gar(TaxCalc)
gar.get_addtax_gar()
class Corp(TaxCalc):
def get_addtax_corp(self):
return my_budget * (2 / 100)
corp = Corp(TaxCalc)
corp.get_addtax_corp()
class Com(TaxCalc):
def get_addtax_com(self):
return my_budget * (4 / 100)
com = Com(TaxCalc)
com.get_addtax_com()
addtax_list = [gar.get_addtax_gar(), 0, com.get_addtax_com(), corp.get_addtax_corp()]
while True:
if b == 1:
print(f"[N.B: There will be additional tax of {gar.get_addtax_gar()} BDT for garments contraction.]")
elif b == 2:
print("There will be no additional tax!")
elif b == 3:
print(f"[N.B: There will be additional tax of {com.get_addtax_com()} BDT for commercial building contraction.]")
elif b == 4:
print(
f"[N.B: There will be additional tax of {corp.get_addtax_corp()} BDT for corporate building contraction.]")
else:
print("Please enter between 1 & 4")
b = getinput("Please re-enter the number for your building type?: ")
continue
break
max_total = my_budget + int(addtax_list[int(b) - 1]) + my_budget * 0.25
min_total = my_budget + int(addtax_list[int(b) - 1]) + my_budget * 0.1
print("\nYou total cost will fluctuate between ", max_total, "BDT & ", min_total, "BDT while completing the whole construction project!")
input("\nThanks a ton for running this code! Press ENTER to close.")
|
0b4c5b32e2bafb7df915028484ca6965ce073309 | ggerod/Code | /PY/gcjCryptopangrams.py | 2,774 | 3.53125 | 4 | #!/usr/local/bin/python3
import sys
numcases = int(sys.stdin.readline())
alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def euc_gcd(a,b):
while (b!=0):
t=a
a=b
b=t%b
return(a)
def findfirstnonrepeat():
for i in range(1,len(cryptedpangram)):
if (cryptedpangram[i] != cryptedpangram[i-1]):
return(i)
def unzipbackward(goodindex):
for i in range(goodindex,0,-1):
# look at 2 prime factors
# see if the first is in the previous composites set
if (factorlist[i][0] not in factorlist[i-1]):
# swtich the order of factorlist[i]
factorlist[i].reverse()
# now see if you need to fix factorlist[i-1]
if (factorlist[i-1][1] != factorlist[i][0]):
# swtich the order of factorlist[i-1]
factorlist[i-1].reverse()
def unzipforward(goodindex):
for i in range(goodindex+1,len(factorlist)):
if (factorlist[i][0] != factorlist[i-1][1]):
factorlist[i].reverse()
def makefactorlist(complist):
Factored={}
factorlist=[]
for i in range(len(complist)-1):
gcdofprimes = euc_gcd(complist[i],complist[i+1])
n1otherprime = int(complist[i]/gcdofprimes)
n2otherprime = int(complist[i+1]/gcdofprimes)
n1list = [gcdofprimes,n1otherprime]
n2list = [gcdofprimes,n2otherprime]
if (1 not in n1list):
Factored[complist[i]] = n1list
if (1 not in n2list):
Factored[complist[i+1]] = n2list
for compnum in complist:
factorlist.append(Factored[compnum])
return(factorlist)
for casenum in range(numcases):
print("Case #"+str(casenum+1)+": ",end="")
(maxprimesize,listlength) = ((sys.stdin.readline()).rstrip()).split()
cryptedpangramin = (sys.stdin.readline()).rstrip()
cryptedpangram = [int(x) for x in cryptedpangramin.split()]
factorlist=[]
primeseq=[]
factorlist = makefactorlist(cryptedpangram)
# find the first non repeating composite number in the composite sequence
firstgoodindex = findfirstnonrepeat()
# unzip factorlist backwards from the first nonrepeating index point
unzipbackward(firstgoodindex)
# proceed arranging factorlist forward from the first nonrepeating index point
unzipforward(firstgoodindex)
# create the ordered list of primes which map to the alphabet
for i in range(len(factorlist)):
primeseq.append(int(factorlist[i][0]))
primeseq.append(int(factorlist[len(factorlist)-1][1]))
pseqordereduniq = (primeseq.copy())
pseqordereduniq = list(set(pseqordereduniq))
pseqordereduniq.sort()
# Now decode the message
for prime in primeseq:
print(alphabet[(pseqordereduniq.index(prime))],end="")
print()
|
8bf208f66541668c8d46cb705591b5c9be2e8444 | tmsteen/training | /python-IV/lab_flask.py | 1,495 | 4.03125 | 4 | #!/usr/bin/env python3
# *-* coding:utf-8 *-*
"""
:mod:`lab_flask` -- serving up REST
=========================================
LAB_FLASK Learning Objective: Learn to serve RESTful APIs using the Flask library
::
a. Using Flask create a simple server that serves the following string for the root route ('/'):
"<h1>Welcome to my server</h1>"
b. Add a route for "/now" that returns the current date and time in string format.
c. Add a route that converts Fahrenheit to Centigrade and accepts the value to convert
in the url. For instance, /fahrenheit/32.0 should return "0.0"
d. Add a route that converts Centigrade to Fahrenheit and accepts the value to convert
in the url. For instance, /centigrade/0.0 should return "32.0"
"""
from flask import Flask
import time
app = Flask(__name__)
@app.route('/')
def welcome():
return '<h1>Welcome to my server</h1>'
@app.route('/now')
def show_time():
return str(time.asctime())
@app.route('/farenheit/<float:temp>')
@app.route('/farenheit/<int:temp>')
def farenheit(temp=None):
return '{} *F converted to Centigrade is {} *C'.format(temp,
(temp - 32) * 5 / 9 )
@app.route('/centigrade/<float:temp>')
@app.route('/centigrade/<int:temp>')
def centigrade(temp=None):
return '{} *C converted to Farenheit is {} *F'.format(temp,
temp * 9 / 5 + 32 )
if __name__ == '__main__':
app.run(debug=True)
|
8eee5224dc63e7b790bcce7fc713371f78c43367 | apatti/csconcepts | /sorting/mergesort/python/mergeSort.py | 628 | 3.875 | 4 |
def Sort(input : list)->list:
if len(input)<=1:
return input
midPoint = len(input)//2
left = Sort(input[:midPoint])
right = Sort(input[midPoint:])
return merge(left,right)
def merge(left:list,right:list)->list:
merged = []
i=0
j=0
while i<len(left) and j<len(right):
if left[i]<right[j]:
merged.append(left[i])
i+=1
continue
else:
merged.append(right[j])
j+=1
continue
if i<len(left):
merged.extend(left[i:])
if j<len(right):
merged.extend(right[j:])
return merged
|
c2b3310565093c3e780d2dc69d7f407e4be5ea81 | AAlkaid/Learn_PyTorch | /nn.ReLu.py | 468 | 3.53125 | 4 | import torch
from torch import nn
from torch.nn import ReLU
input = torch.tensor([[1, -0.5],
[-1, 3]])
input = torch.reshape(input, (-1, 1, 2, 2))
print(input.shape)
class zhenyu(nn.Module):
def __init__(self):
super(zhenyu, self).__init__()
self.relu1 = ReLU()
def forward(self, input):
output = self.relu1(input)
return output
zy = zhenyu()
output = zy(input)
print(output)
a = SummaryWriter("ss") |
8d537b8649cf865382e1dd87a841634851d541e2 | huazhige/EART119_Lab | /hw1/late/passerscarlet_26789_1245979_HW 1 #3 .py | 1,607 | 4.3125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
#anaconda2/python2.7
#HW 1 #3
"""
HW 1 problem 3
This script does the following:
Given a circle with a radius r = 12.6mm, and a rectangle with sides 'a' and 'b'
with only 'a' known from the outset (a = 1.5mm). This program uses a while loop
to find the largest possible integer 'b' that gives the rectangle an area smaller
than, but as close as possible to, the area of the circle.
@author: scarletpasser
"""
from math import pi
#############################################################################
# parameters/variables
#############################################################################
r = 10.6 #radius of circle (mm)
area_circle = pi*r**2 #area of circle (mm**2)
b = 0 #height of rectangle (mm)
##############################################################################
# define functions
##############################################################################
def area_rectangle(b): #area of rectangle as function of b
a = 1.3 #base of rectangle (mm)
return b*a
##############################################################################
# computations/output
##############################################################################
#find what b value gives the closest possible area to the circle area
while area_rectangle(b) <= area_circle:
b += 1
print "area =", area_rectangle(b) - 1, "b =",(b - 1)
|
03e70e46652539d6a72d9b6f601128fbeb0473b9 | enw860/leetcode | /code37.py | 5,572 | 4.0625 | 4 | # 37. Sudoku Solver
# https://leetcode.com/problems/sudoku-solver/
# Write a program to solve a Sudoku puzzle by filling the empty cells.
# to be validated according to the following rules:
# Each row must contain the digits 1-9 without repetition.
# Each column must contain the digits 1-9 without repetition.
# Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
# Note:
# A Sudoku board (partially filled) could be valid but is not necessarily solvable.
# Only the filled cells need to be validated according to the mentioned rules.
from typing import List
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
dirty = False
missingGrids = []
for i in range(0, 9):
for j in range(0, 9):
if board[j][i] == ".":
options = self.getOptionsForGrid(board, i, j)
if len(options) == 1:
dirty = True
board[j][i] = options[0]
else:
missingGrids.append({
"position": (j, i),
"options": options
})
missingGrids.sort(key=lambda x: len(x["options"]))
while dirty:
dirty = False
completedItems = []
for index in range(0, len(missingGrids)):
grid = missingGrids[index]
j, i = grid["position"]
options = self.getOptionsForGrid(board, i, j)
if len(options) == 1:
dirty = True
board[j][i] = options[0]
completedItems.append(index)
else:
grid["options"] = options
completedItems.reverse()
for item in completedItems:
missingGrids.pop(item)
missingGrids.sort(key=lambda x: len(x["options"]))
if len(missingGrids) > 0:
uncertainItem = missingGrids.pop(0)
for option in uncertainItem["options"]:
j, i = uncertainItem["position"]
# make a proposal
board[j][i] = option
# clear dirty board
for grid in missingGrids:
grid_j, grid_i = grid["position"]
board[grid_j][grid_i] = "."
# try new board
self.solveSudoku(board)
# determine if the board is completed
if True not in ["." in row for row in board]:
return
def getOptionsForGrid(seld, board: List[List[str]], i: int, j: int) -> List[str]:
if board[j][i] != ".":
return []
constrains = set("")
options = set([str(x) for x in range(1, 10)])
# col
constrains.update([board[x][i] for x in range(0, len(board))])
# row
constrains.update(board[j])
# square
for x in range(0, 3):
constrains.update(board[j // 3 * 3 + x][(i // 3 * 3): (i // 3 * 3 + 3)])
return list(options - constrains)
def isValidSudoku(self, board: List[List[str]]) -> bool:
return self.validateRows(board) and self.validateCols(board) and self.validateSquares(board)
def validateRows(self, board: List[List[str]]) -> bool:
for subboard in board:
if not self.validateSubboard(subboard):
return False
return True
def validateCols(self, board: List[List[str]]) -> bool:
for i in range(0, len(board)):
subboard = [row[i] for row in board]
if not self.validateSubboard(subboard):
return False
return True
def validateSquares(self, board: List[List[str]]) -> bool:
for i in range(0, 3):
for j in range(0, 3):
subboard = []
subboard += board[j * 3 + 0][i * 3:(i + 1) * 3]
subboard += board[j * 3 + 1][i * 3:(i + 1) * 3]
subboard += board[j * 3 + 2][i * 3:(i + 1) * 3]
if not self.validateSubboard(subboard):
return False
return True
def validateSubboard(self, subboard: List[str]) -> bool:
hashTable = {}
for item in subboard:
item_key = f"key_{item}"
if item_key not in hashTable:
hashTable[item_key] = 1
else:
hashTable[item_key] += 1
if item_key != "key_.":
return False
return True
if __name__ == "__main__":
board = "board"
expectedResult = "expectedResult"
def temp(*args, **kargs):
pass
tests = [
{board: [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]},
{board: [
[".",".","9","7","4","8",".",".","."],
["7",".",".",".",".",".",".",".","."],
[".","2",".","1",".","9",".",".","."],
[".",".","7",".",".",".","2","4","."],
[".","6","4",".","1",".","5","9","."],
[".","9","8",".",".",".","3",".","."],
[".",".",".","8",".","3",".","2","."],
[".",".",".",".",".",".",".",".","6"],
[".",".",".","2","7","5","9",".","."]
]},
{board: [
[".",".",".","2",".",".",".","6","3"],
["3",".",".",".",".","5","4",".","1"],
[".",".","1",".",".","3","9","8","."],
[".",".",".",".",".",".",".","9","."],
[".",".",".","5","3","8",".",".","."],
[".","3",".",".",".",".",".",".","."],
[".","2","6","3",".",".","5",".","."],
["5",".","3","7",".",".",".",".","8"],
["4","7",".",".",".","1",".",".","."]
]}
]
s = Solution()
for test in tests:
print("-"*20)
result = s.solveSudoku(test[board])
[print(row) for row in test[board]] |
1448a1712fae70329d1df40488dffe22afd2e7d6 | bryner18/secretnumber | /secretnumber.py | 1,433 | 3.984375 | 4 | import random
import sys
def main():
guess_the_number()
try_again()
def guess_the_number():
number = (random.randint(0, 100))
tries = 0
print("---------------------------------------------\nYou need to guess a number between 0 and "
"100\n---------------------------------------------")
while tries < 999999999999999:
guess = float(int(input("Please enter a number: ")))
tries = tries + 1
if guess < number:
if (number - guess) < 10:
print("Your guess is hot")
else:
print("Your guess is cold")
print("Your guess is low.")
elif guess > number:
if (guess - number) < 10:
print("Your guess is hot")
else:
print("Your guess is cold")
print("Your guess is high.")
else:
break
print("-------------------------------------------\nGood job! You guessed my number in", tries,
"tries!\n-------------------------------------------")
def try_again():
again = "y"
while again == "y" or again == "Y" or again == "yes" or again == "Yes":
again = input("Would you like to play again? ")
if again == "y" or again == "Y" or again == "yes" or again == "Yes":
return main()
else:
return sys.exit(0)
main()
|
91be9b35a880c90150ae4bbbbd48454cfefce3b2 | Makhanya/PythonMasterClass | /Decorators/Decorator.py | 633 | 4.1875 | 4 | """
Decorator
*Decorators are functions
*Decorators wrap other functions and enhance their behavior
*Decorators are examples of higher order functions
*Decorators have their own syntax, using "@" (syntactic sugar)
"""
def be_polite(fn):
def wrapper():
print("What a pleasure to meet you!")
fn()
print("Have a great day!")
return wrapper
@be_polite
def greet():
print("My name is Makhanya")
@be_polite
def rage():
print("I hate you!")
rage()
greet()
# polite_rage()
# polite_rage()
# polite_rage()
# polite_rage()
# greet()
# greet()
# greet()
# greet()
|
0e2a69a0896adea308ffb622f5205f0c1d3ee0ff | holonking/ts-findSecurities | /loop.py | 172 | 3.578125 | 4 | import datetime
today=datetime.date.today()
for j in range (10):
if j==2: continue
delta=datetime.timedelta(days=j)
xday=today-delta
print(str(j)+ " - "+ str(xday) )
|
4d4ce89fc733be4fd022bcc522184c708e462019 | andrewsmedina/projecteuler | /python/1.py | 269 | 4.21875 | 4 | '''
Problem 1
If we list all the natural numbers below 10
that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
print sum(filter(lambda x: x%3==0 or x%5==0, range(1,1000))) |
30dc148e683f67eec7ece23fe74f6c4cf6ccfcdb | xingzhicn/MyLeetCode | /easy/1. 两数之和.py | 1,709 | 4.0625 | 4 | class Solution:
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
For Examples:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
def twoSum(self, nums: list, target: int) -> list:
"""
第一种直接双for循环暴力解法
Args:
nums:
target:
Returns:
"""
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
def twoSum1(self, nums: list, target: int) -> list:
"""
一遍哈希表
事实证明,我们可以一次完成。在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。
如果它存在,那我们已经找到了对应解,并立即将其返回。
Args:
nums:
target:
Returns:
"""
i_dict = {}
for i in range(len(nums)):
if target - nums[i] in i_dict:
return [i_dict[target - nums[i]], i]
else:
i_dict[nums[i]] = i
if __name__ == '__main__':
# 这道题的关键在于使用hash表来存储值,因为hash表get查询性能优越
assert Solution().twoSum([2, 7, 11, 15], 9) == [0, 1]
assert Solution().twoSum1([2, 7, 11, 15], 9) == [0, 1]
|
9539d81ff866aae9ccc9ebc51561e53d55f7524c | SubhamPanigrahi/Python_Programming | /copying_from_list.py | 226 | 4 | 4 | # there is a predefined list and a tuple, return the common elements in form of list
x = ["1", "2", "abc", "def", "ghi", "4", "5"]
y = ("abc", "2", "5", "def", 3)
z = []
for i in y:
if i in x:
z.append(i)
print(z)
|
5d83365afa1d15c306c4be3985bb0b26a6a6ff50 | diskpart123/xianmingyu | /python程序语言设计/E4.18/E4.18.py | 458 | 4.0625 | 4 | rate = eval(input("Enter the exchange rate from dollars to RMB: "))
convert = eval(input("Enter 0 to convert dollars to RMB and 1 vice versa: "))
if convert == 0:
dollars = eval(input("Enter the dollars amount: "))
amount = dollars * rate
print("$",dollars,"is",amount,"yuan.")
elif convert == 1:
rmb =eval(input("Enter the RMB amount: "))
amount = rmb / rate
print(rmb,"yuan is $",round(amount,2))
else:
print("Incorrect input") |
f197bbe8138cee951622ae7ea3e02c76248e18ae | Streetplayr1/STEM-Prep-Exercises | /Allen_Trey_STEM_Project_3.py | 3,758 | 3.5625 | 4 | #author: Trey Allen
#STEM Prep Project, Exercises 3
## START OF 3-1 ##
#the good ol' reliable
import random
#we will initialize variables, as per usual for keeping track of numbers
#first, our list(s), noting that activity (1) does not change
#we will need a list to keep track of the state, and a list of lists with the rest of the information
stateTracker = [[0, 1]]
animal = []
#next, our gut level, activity level, the timestep, and the prob. of success
timeStep = 0
gutLevel = 0
activityLevel = 1
probabilityOfSuccess = 0.5
#we need a for loop that runs 100 times
for i in range(1,101):
#we need a random number to test against our probability of success (b) value, let's call this "number"
number = random.random()
#as the PDF requests, check if this randomly generated number is <= our probability of success, then ...
if number <= probabilityOfSuccess:
#increase our gut level (h)
gutLevel += 1
#we need to keep track of the time step as well, so we can increase this after every loop
timeStep += 1
#add the results to the list
stateTracker.append([gutLevel, activityLevel])
#combined list
instance = [timeStep, number, stateTracker[i]]
animal.append(instance)
print(animal)
## END OF 3-1 ##
print("\nEND OF FIRST MODEL\n")
## START OF 3-2 ##
#we will intialize lists and constants as we did in the previous exercise
stateTracker = [[0,1]]
animal = []
timeStep = 0
gutLevel = 0
activityLevel = 1
probabilityOfSuccessfulFeed = 0.5
probablityOfSuccessfulRest = 0.5
huntingCounter = 0
restingCounter = 0
feedToRest = 0
restToFeed = 0
for i in range(1,101):
#we are going to increase which step we are on for every loop
timeStep += 1
s = random.random()
m = random.random()
if activityLevel == 0: #resting
if s <= probablityOfSuccessfulRest: #successful rest
gutLevel -= 1 #gets hungrier
activityLevel = 0
else: #hunting
if m <= probabilityOfSuccessfulFeed: #successful feed
gutLevel += 1 #gets fuller
activityLevel = 1
if gutLevel == 5:
activityLevel = 0
if gutLevel == 0:
activityLevel = 1
stateTracker.append([gutLevel, activityLevel])
instance = [timeStep, s, stateTracker[i]]
print(instance)
animal.append(instance)
print("\nEND OF FIRST 100\n")
stateTracker = [[0,1]]
animal = []
timeStep = 0
gutLevel = 0
activityLevel = 1
probabilityOfSuccessfulFeed = 0.5
probablityOfSuccessfulRest = 0.5
huntingCounter = 0
restingCounter = 0
feedToRest = 0
restToFeed = 0
for i in range(1,1001):
#we are going to increase which step we are on for every loop
timeStep += 1
s = random.random()
m = random.random()
if activityLevel == 0: #resting
restingCounter += 1
if s <= probablityOfSuccessfulRest: #successful rest
gutLevel -= 1 #gets hungrier
activityLevel = 0
else: #hunting
huntingCounter += 1
if m <= probabilityOfSuccessfulFeed: #successful feed
gutLevel += 1 #gets fuller
activityLevel = 1
if gutLevel == 5:
feedToRest += 1
activityLevel = 0
if gutLevel == 0:
restToFeed += 1
activityLevel = 1
stateTracker.append([gutLevel, activityLevel])
instance = [timeStep, s, stateTracker[i]]
print(instance)
animal.append(instance)
#print(animal) --- print this if needs to be list of lists; otherwise, just use line36
print("The animal rested", restingCounter, "times.")
print("The animal hunted", huntingCounter, "times.")
print("The animal stopped feeding and started resting", feedToRest, "times.")
print("The animal stopped resting and started feeding", restToFeed, "times.")
## END OF 3-2 ## |
e8fdf28ca8c48fad222d006331494595961296a7 | nefelinikiforou/compilers1718a1 | /scanner.py | 2,391 | 3.65625 | 4 | def getchar(words,pos,state): # added state
""" returns char at pos of words, or None if out of bounds """
if pos<0 or pos>=len(words): return None
c = words[pos]
if (c == '0' or c == '1') and state == 'q0' :
return 'HOUR_01'
if c == '2' and state == 'q0':
return 'HOUR_2'
if (c >= '3' and c <= '9') and state == 'q0' :
return 'HOUR_39'
if (c >= '0' and c <= '9') and state == 'q1':
return 'HOUR_09'
if (c == '.' or c == ':') and state == 'q1':
return 'SEPARATOR_1'
if (c >= '0' and c <= '3') and state == 'q2':
return 'HOUR_03'
if (c == '.' or c == ':') and state == 'q2':
return 'SEPARATOR_1'
if c == '.' or c == ':' :
return 'SEPARATOR'
if (c >= '0' and c <= '5') and state == 'q4':
return 'MINUTE_05'
if (c >= '0' and c <= '9') and state == 'q5':
return 'MINUTE_09'
def scan(text,transition_table,accept_states):
""" Scans `text` while transitions exist in 'transition_table'.
After that, if in a state belonging to `accept_states`,
returns the corresponding token, else ERROR_TOKEN.
"""
# initial state
pos = 0
state = 'q0'
while True:
c = getchar(text,pos,state) # get next char
if state in transition_table and c in transition_table[state]:
state = transition_table[state][c] # set new state
pos += 1 # advance to next char
else: # no transition found
# check if current state is accepting
if state in accept_states:
return accept_states[state],pos
# current state is not accepting
return 'ERROR_TOKEN',pos
# the transition table, as a dictionary
# Modified
td = { 'q0':{ 'HOUR_01':'q1', 'HOUR_2':'q2', 'HOUR_39':'q3' },
'q1':{ 'HOUR_09':'q3', 'SEPARATOR_1':'q4' },
'q2':{ 'HOUR_03':'q3', 'SEPARATOR_1':'q4' },
'q3':{ 'SEPARATOR':'q4' },
'q4':{ 'MINUTE_05':'q5' },
'q5':{ 'MINUTE_09':'q6' }
}
# the dictionary of accepting states and their
# corresponding token
# Modified
ad = { 'q6':'TIME_TOKEN' }
# get a string from input
text = input('give some input>')
# scan text until no more input
while text: # that is, while len(text)>0
# get next token and position after last char recognized
token,position = scan(text,td,ad)
if token=='ERROR_TOKEN':
print('unrecognized input at pos',position+1,'of',text)
break
print("token:",token,"string:",text[:position])
# remaining text for next scan
text = text[position:]
|
8a1e97db689c383b7299423085a6f01f4d48b7e7 | premkrish/Python | /Functions/func_default_args.py | 532 | 4.375 | 4 | """ this script contains functions with default arguments """
def cm_convert(feet=0, inches=0):
""" This function converts feet and inches to cms """
feet_to_cm = feet * 12 * 2.54
inch_to_cm = inches * 2.54
return feet_to_cm + inch_to_cm
# Convert 5 feet to cm
print(f"Convert 5 feet to cm(s): {cm_convert(feet=5)}")
# Convert 20 inches to cm
print(f"Convert 20 inches to cm(s): {cm_convert(inches=20)}")
# Convert 5 feet 3 inches to cm
print(f"Convert 5 feet 3 inches to cm(s): {cm_convert(feet=5, inches=3)}")
|
1111fb35c383062b2376200d8f4f7530da8b8bea | Gporfs/Python-s-projects | /dictdados.py | 510 | 3.515625 | 4 | from random import randint
from time import sleep
from operator import itemgetter
ranking = {}
jogador = {}
for num in range(1, 5):
jogador[f'jogador{num}'] = randint(1, 6)
print('Valores Sorteados:')
for k, v in jogador.items():
sleep(1)
print(f'O {k} tirou o número {v}')
print('-='*30)
print('Ranking dos jogadores: ')
ranking = sorted(jogador.items(), key=itemgetter(1), reverse=True)
for i, v in enumerate(ranking):
print(f'{i+1}°lugar: {v[0]} com {v[1]}')
sleep(1)
|
217181bd0b40fab7589d2e576c4f6a87fbb59f94 | suruisunstat/leetcode_practice | /amazon/python/110. Balanced Binary Tree.py | 1,974 | 4.03125 | 4 | # 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 getHeight(self, root):
# if not root:
# return -1
# return 1 + max(self.getHeight(root.left), self.getHeight(root.right))
# def isBalanced(self, root):
# """
# :type root: TreeNode
# :rtype: bool
# """
# if not root:
# return True
# return abs(self.getHeight(root.left) - self.getHeight(root.right)) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right)
# Time: O(nlogn)
# Space: O(n)
# def isBalancedHelper(self,root):
# if not root:
# return True, -1
# LeftBalanced, LeftHeight = self.isBalancedHelper(root.left)
# if not LeftBalanced:
# return False, 0 # 0 can be replaced by any number
# RightBalanced, RightHeight = self.isBalancedHelper(root.right)
# if not RightBalanced:
# return False, 0
# return abs(LeftHeight - RightHeight) < 2, 1 + max(LeftHeight, RightHeight)
# def isBalanced(self,root):
# return self.isBalancedHelper(root)[0]
# # Time: O(n)
# # Space: O(n)
# # Why it is faster? Because first method every recur step calculate the height, but the second method every recu deeper into the tree and calculate if a node is balanced from bottom to up.
def getHeight(self,root):
if not root:
return 0
left = self.getHeight(root.left)
right = self.getHeight(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return 1 + max(left,right)
def isBalanced(self,root):
return self.getHeight(root) != -1
# Same as method 2 above
|
fde7098fbcbc018a35b7063afe7dbfde4f0ef460 | andoorve/Neural-Net | /layer.py | 1,195 | 3.515625 | 4 | #Learned from "Neural Networks and Deep Learning" - http://neuralnetworksanddeeplearning.com by Michael Nielson
#See Neural-Net-2 for improved version
import numpy as np #www.numpy.org
import node
class layer:
def __init__(self, in_num, n_nodes, func):
self.input = in_num
self.func = func
self.nnodes = []
for i in range(n_nodes):
self.nnodes += [node.node(b = (2*np.random.random_sample())-1, input_num = in_num, w = (2*np.random.random_sample(in_num))-1, func = func)]
def compute(self, inp):
accum =[]
if (len(inp) != self.input):
return -1
else:
for i in self.nnodes:
accum += [i.compute(inp)]
return accum
def setweights(self, inlist, node = None):
if (node == None):
for i in range(len(self.nnodes)):
self.nnodes[i].setweights(inlist[i])
else:
self.nnodes[node].setweights(inlist)
def setbias(self, inlist, node = None):
if (node == None):
for i in range(len(self.nnodes)):
self.nnodes[i].setbias(inlist[i])
else:
self.nnodes[node].setbias(inlist)
|
69c9cf873f915fec0f4711722f9101f38f21a478 | gss13/Leetcode | /leetQ448_Find_All_Numbers_Disappeared_in_an_Array.py | 727 | 4.03125 | 4 | '''
448. Find All Numbers Disappeared in an Array
Given an array of intergers where 1 <= a[i] <= n (n = size of array),
some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the
returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
'''
def findDisappearedNumbers(nums):
for i in xrange(len(nums)):
idx = abs(nums[i]) - 1
nums[idx] = -1 * abs(nums[idx])
return [i+1 for i in xrange(len(nums)) if nums[i] > 0]
if __name__ == '__main__':
nums = [4, 3, 2, 7, 8, 2, 3, 1]
print findDisappearedNumbers(nums)
|
cb93dd4992deae12a521ba8b4c1c81d60a3abe4b | axllow91/python-tut | /classes.py | 1,874 | 4.25 | 4 | # A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it.
# Almost everything in Python is an object
class User:
# Constructor
# self is similar to this in java (mandatory to be passed on constructor when created, first in order)
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
# using similar like this.name in java or typescript, javascript
return f'My name is {self.name} and I am {self.age} years old'
def has_birthday(self):
self.age += 1
# Initialize user object
me = User('Marian', '[email protected]', 101)
girldUser = User('Daniela', '[email protected]', 50)
print('Creating new User...')
print('User: ' + me.name + '\n' + 'Email: ' +
me.email + '\n' + 'Age: ' + str(me.age))
# Edit property
myAge = me.age = 70
print(myAge)
girldUser.has_birthday()
# calling the greeting method one the user
print(girldUser.greeting())
# Customer class
class Customer:
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
self.balance = 0
def set_balance(self, balance):
self.balance = balance
def get_balance(self):
if self.balance == 0:
print(
f'Customers {self.name} balance is empty: ' + str(self.balance))
return self.balance
# toString() method equivalent in Python
def __str__(self):
return 'Name:' + self.name + '\nEmail: ' + self.email + '\nAge: ' \
+ str(self.age) + '\nBalance: ' + str(self.get_balance())
# Initialize Customer Object
john = Customer('John Wick', '[email protected]', 50)
print('-----------------------------------------')
print(john) # getting the to string __str__() methond
john.balance = 500
print(john)
|
2015515fc8b40ff8e1cf0370b58f7f03149e7c9d | nekapoor7/Python-and-Django | /HACKER_RANK/string_count.py | 799 | 4.1875 | 4 | '''In this challenge, the user enters a string and a substring.
You have to print the number of times that the substring occurs in the given string.
String traversal will take place from left to right, not from right to left.
NOTE: String letters are case-sensitive.
Input Format
The first line of input contains the original string. The next line contains the substring.'''
def count_substring(string, sub_string):
count = 0
start = 0
while (start < len(string)):
flag = string.find(sub_string, start)
if flag != -1:
start = flag + 1
count += 1
else:
return count
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count) |
d7ed0060a80629e0ed62ccf9e78f963b145550d1 | hansrajdas/random | /practice/is_linked_list_palindrome.py | 2,147 | 4.03125 | 4 | class Node:
def __init__(self, k):
self.k = k
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_begin(self, k):
if self.head is None:
self.head = Node(k)
return
n = Node(k)
n.next = self.head
self.head = n
def traverse(self):
if self.head is None:
return
p = self.head
while p:
print(p.k, end=' ')
p = p.next
print()
def insert_end(self, k):
if self.head is None:
self.head = Node(k)
return
p = self.head
while p.next:
p = p.next
p.next = Node(k)
def is_palindrome(self):
if not (self.head and self.head.next):
return True
slow = self.head
fast = self.head
stack = []
while fast and fast.next:
stack.append(slow.k)
slow = slow.next
fast = fast.next.next
if fast:
slow = slow.next
while slow:
x = stack.pop()
if slow.k != x:
return False
slow = slow.next
return True
def main():
print('# Case')
L = LinkedList()
for i in "123243454":
L.insert_end(i)
L.traverse()
assert L.is_palindrome() == False
print('# Case')
L = LinkedList()
for i in "1331":
L.insert_end(i)
L.traverse()
assert L.is_palindrome() == True
print('# Case')
L = LinkedList()
for i in "1":
L.insert_end(i)
L.traverse()
assert L.is_palindrome() == True
print('# Case')
L = LinkedList()
for i in "12":
L.insert_end(i)
L.traverse()
assert L.is_palindrome() == False
print('# Case')
L = LinkedList()
for i in "12344321":
L.insert_end(i)
L.traverse()
assert L.is_palindrome() == True
print('# Case')
L = LinkedList()
for i in "101":
L.insert_end(i)
L.traverse()
assert L.is_palindrome() == True
if __name__ == '__main__':
main()
|
37b288a080f02d54fd3b2bf2c6b7fd544a0ad0a6 | bdavies3/Calculator | /src/Calculator.py | 1,371 | 3.515625 | 4 | from CsvReader import CsvReader
import math
def addition(a, b):
c = a + b
return c
def subtraction(a, b):
c = b - a
return c
def division(a, b):
return float(a) / float(b)
def mean(data):
mean = data
return mean
def multiplication(a, b) -> object:
c = float(a) * float(b)
return c
def squared(a, b) -> object:
c = a ** b
return c
def square_root(a, b) -> object:
b = math.sqrt(a)
return b
class Calculator:
result = 0
def __init__(self):
pass
def add(self, a, b):
self.result = addition(a, b)
return self.result
def subtract(self, a, b):
self.result = subtraction(a, b)
return self.result
def mean(self, a, b):
self.result = mean(a, b)
return self.result
def divide(self, a, b):
self.result = division(a, b)
return self.result
def multiply(self, a, b):
self.result = multiplication(a, b)
return self.result
def squared(self, a, b):
self.result = squared(a, b)
return self.result
def square_root(self, a, b):
self.result = square_root(a, b)
return self.result
class CSVStats(Calculator):
data = []
def __init__(self, data_file):
self.data = CsvReader(data_file)
pass
def mean(self):
mean(self.data)
|
fbc152ea75844a42966274aac5509420eeab67b8 | massimilianocasini/misigram | /calcolatrice_web.py | 1,485 | 3.59375 | 4 | import math
print "-" * 60, "\n"
print "\t" * 2 ,"CALCOLATRICE", "\n"
print "Completamente sviluppato da Alessandro Alfieri.\n"
print "Licenza: Open Source "
print "Data: 17 Novembre 2010"
print "-" * 60, "\n" * 2
print "Scegli l'operazione che vuoi fare..."
print "1:Addizione-Sottrazione-Moltiplicazione-Divisione"
print "2:Elevazione a potenza"
print "3:Radice"
print "4:Esci"
print "\n" * 3
def Scelta(x):
if x == 1:
print input("Scrivi il calcolo: ")
Scelta(input ("Scegli l'operazione: "))
elif x == 2:
print input("Scrivi numero: ") ** input("Scrivi esponente: ")
Scelta(input ("Scegli l'operazione: "))
elif x == 3:
print math.sqrt (input("Scrivi numero: "))
Scelta(input ("Scegli l'operazione: "))
elif x == 4:
clear()
print "-" * 60, "\n"
print "\tGRAZIE PER AVER SCARICATO QUESTA CALCOLATRICE", "\n"
print "\t" * 2, "Alessandro Alfieri"
print "-" * 60, "\n"
exit()
else:
clear()
print "Scelta sbagliata, amico! Fatti meno seghe cosi' vedi meglio i numeri!!! ;)", "\n"
print "Scegli l'operazione che vuoi fare..."
print "1:Addizione-Sottrazione-Moltiplicazione-Divisione"
print "2:Elevazione a potenza"
print "3:Radice"
print "4:Esci"
Scelta(input ("Scegli l'operazione: "))
def clear():
import os
if os.name == "posix": os.system("clear")
elif os.name == "nt": os.system("cls")
else: print "\n" * 40
Scelta(input ("Scegli l'operazione: "))
|
6ee9fa76551f9fad26def5a2cf3809e6dafd7dab | titisarinurul/purwadhika_modul1 | /coret3.py | 206 | 3.609375 | 4 | # cuma jadi nama alias
testList = [1,2,3]
newList = testList
newList[2] = "test"
print(testList)
print(newList)
# duplikasi list
testList = [1,2,3]
newList = testList.copy()
print(testList)
print(newList) |
84d2c11bf4f886fca3fedf89eb3ce7274e72a0ed | andrei-kozel/100daysOfCode | /python/day002/project.py | 654 | 4.15625 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪
#Write your code below this line 👇
print("Welcome to the tip calculator!")
bill = float(input("What was the total bill? $"))
tip = int(input("How much tip would you like to give? 10, 12, or 15? "))
people_amount = int(input("How many people to split the bill? "))
result = (bill / people_amount) * (tip / 100) + (bill / people_amount)
print(f"Each person should pay: ${round(result, 2)}") |
ceac0e4f06857e739aee1e73f9b4566b5af5e5d6 | Rachanahande/python1 | /New folder/day2assign5.py | 206 | 3.953125 | 4 | '''5. Write a program to add the elements of 2 arrays that are of the same dimension'''
l1 = [1,2,3,4]
l2 = [5,6,7,8]
l3 = list(map(lambda x,y: x+y,l1,l2))
print(f"after adding l1{l1} and l2 {l2} is {l3}")
|
38accd5077279e0b8f5058dab3b4777217398fab | b1ueskydragon/PythonGround | /practice/switch-case.py | 344 | 3.515625 | 4 | import re
my_tuple = (
("t1", "path1"),
("t2", "path2"),
("t3", "path3"),
("t4", "path4")
)
my_func = lambda s: next(v for k, v in my_tuple if re.match(k, s))
print(my_func("t1"))
print(my_func("t3"))
my_dict = {
"a": "A",
"b": "B"
}
simple_func = lambda k: my_dict[k]
print(simple_func("b"))
print(my_dict["a"])
|
938fb7b11c7aaeb522fc8bc8326ec383990a78b6 | BenTimor/Sidur | /calculations.py | 6,359 | 4.125 | 4 | from typing import List
from .schedule import *
from random import shuffle
from . import config
def embedding(schedule: Schedule, employees: List[Employee]):
"""
Embedding all of the employees into the schedule
:param schedule: The schedule
:param employees: The employees
"""
# Embedding the priorities from 5 to 2
for priority in range(5, 1, -1):
for day_number in range(len(schedule)):
day = schedule[day_number]
for shift in day:
# In the first run of every shift, set all the empty shifts of the employees to 3
if priority == 5:
set_shift_employees(shift, employees)
# Get & Shuffle employees with this priority
available_employees = priority_employees(shift, employees, priority)
shuffle(available_employees)
# If the priority is 5 we must embed the employees
if priority == 5:
for employee in available_employees:
embed_employee(shift, schedule, employee)
continue
# Check how many employees needed, if there are not needed, continue
employees_needed = shift.employees_needed - len(shift.employees)
while available_employees:
# If needed, add the employees
least_working = least_working_employees(available_employees)
# If we don't need any more employees, break
if employees_needed <= 0:
break
# If we have more than enough employees, add just the right amount
if len(least_working) >= employees_needed:
for employee in least_working[:employees_needed]:
embed_employee(shift, schedule, employee)
available_employees.remove(employee)
employees_needed -= 1
# If we don't have enough employees (in this run!), add all of them
else:
for employee in least_working:
embed_employee(shift, schedule, employee)
available_employees.remove(employee)
employees_needed -= 1
else:
# Check if we have enough employees
if priority == 2 and employees_needed > 0:
print(f"Not enough employees for day {day_number} / shift {shift.start}-{shift.end}")
def embed_employee(shift: Shift, schedule: Schedule, employee: Employee, past_check=False):
"""
Adding an employee into a shift
:param shift: The shift
:param schedule: All of the schedule
:param employee: The employee
:param past_check: If it's true, the function won't add the employee to any shift, it'll just set the past shifts in config.hours range to -1.
"""
if not past_check:
shift.append(employee)
# Setting the shift to -2 so he won't be embedded again
employee[shift] = -2
allowed = False
add = 0
past_check = -1 if past_check else 1 # Past check just blocking past shifts via config time, so he won't be working in config.time hours before shift
for day in schedule[::past_check]:
if allowed:
add += 24
same_day = False
for day_shift in day[::past_check]:
# Since the moment we pass on his shift, we'll check the rest of the shifts
if day_shift == shift:
allowed = True
same_day = True
continue
# If needed, disabling all shifts in the same day
if same_day and config.one_shift_per_day:
employee[day_shift] = -1
continue
if allowed:
# If the shift starts in less than X hours (from the config) he won't be able to be embedded into it
if shift.end < shift.start: # If the shift ends before it's started (for example, 18-02), we have to add 24 hours to the end because it the day after
if day_shift.start + add > shift.end + 24 + config.time_between_shifts:
return
else:
employee[day_shift] = -1
else:
if day_shift.start+add > shift.end+config.time_between_shifts:
return
else:
employee[day_shift] = -1
if not past_check:
embed_employee(shift, schedule, employee, True)
# You can't have shift with not priority. So we'll set every shift to 3.
def set_shift_employees(shift, employees: List[Employee]):
"""
Setting the priority of the shift to 3 if it doesn't have any priority
:param shift: The shift
:param employees: List of employees to set it on
"""
for employee in employees:
if shift not in employee:
employee[shift] = 3
def priority_employees(shift: Shift, employees: List[Employee], priority: int) -> List[Employee]:
"""
:param shift: What shift you want the employees to work at
:param employees: List of all of the employees you want to check
:param priority: What is the priority
:return: List of all of the employees which has this priority for the shift
"""
return [employee for employee in employees if employee[shift] == priority]
def least_working_employees(employees: List[Employee]) -> List[Employee]:
"""
:param employees: List of the employees to check
:return: The employees which work the least
"""
if not employees:
return []
available_employees = []
least = shifts_amount(employees[0])
for employee in employees:
shifts = shifts_amount(employee)
if shifts == least:
available_employees.append(employee)
if shifts < least:
least = shifts
available_employees = [employee]
return available_employees
def shifts_amount(employee: Employee) -> int:
"""
:param employee: The employee to check
:return: The amount of shifts that the employee has
"""
return len([v for v in employee.values() if v == -2]) |
736a02dc221c3e421d0be1f2a92191c9d730e185 | rekiko/geekbrains.python | /lesson02/home_work/hw02_normal.py | 2,532 | 3.78125 | 4 | # Задача-1:
# Дан список заполненный произвольными целыми числами, получите новый список элементами которого будут
# квадратные корни элементов исходного списка, но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2]
import math
a = [1, 4, 9, 10, 16, -4, -16, 36]
b = []
for i in a:
if i >= 0:
c = math.sqrt(i)
if c.is_integer():
b.append(c)
else:
continue
else:
continue
print(b)
# Решение:
# - получить список
# - через конструкцию "elif" обращаясь к каждому элементу списка вычислять его корень и проверять остаток от деления
# - if остаток == 0 => переносить число в новый список
# - else
# Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013.
# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года.
# Склонением пренебречь (2000 года, 2010 года)
# Задача-3: Напишите алгоритм заполняющий список произвольными целыми числами в диапазоне от -100 до 100
# В списке должно быть n - элементов
# Подсказка: для получения случайного числа изпользуйте функцию randint() модуля random
import random
n = int(input("Введите числе элементов в списке: "))
c = []
while len(c) <= n:
c.append(random.randint(-100, 100))
print(c)
# Задача-4: Дан список заполненный произвольными целыми числами
# Получите новый список, элементами которого будут только уникальные элементы исходного
import random
n = int(input("Введите числе элементов в списке: "))
c = [1, 1, 1, 1, 2, 3, 2, 5, 3, 2, 4, 6, 4]
while len(c) <= n:
c.append(random.randint(-100, 100))
print(c)
print("Dubl")
a = list(set(c))
print(a) |
e9ec9bfe76d578bf6e85f24e8a5f72ac88890365 | Jelowis/Ejercicios-Python-U | /EJERCICIO4.py | 623 | 3.765625 | 4 | # Comprehension – [var for var in datos condicion]
[car for car in['a','e','i','o','u'] if car not in('a','i','o')]
edad,_peso = 50, 70.5
nombres = 'Daniel Vera'
dirDomiciliaria= "Chile y Guayaquil"
Tipo_sexo = 'M'
civil = True
usuario = ('dchiki','1234','[email protected]')
materias = ['Programacion Web','PHP','POO']
docente = {'nombre':'Daniel','edad':50}
print("""Mi nombre es {}, tengo {} años""".format(nombres,edad))
print(usuario,materias,docente)
import math
num1, num2, num, men = 12.572, 15.4, 4, '1234'
print(math.ceil(num1), '\t',math.floor(num1))
print(round(num1,1),'\t',type(num),'\t',type(men)) |
3531e074c981cd0bd7cad07ee4c7e9e94062f6fb | josephkuhn/CS581-Social-Networks | /Triads/triad_graphs.py | 4,747 | 4.125 | 4 | # Author: Joseph Kuhn
# triad_graphs.py takes data from a CSV file and determines how many triangles there are,
# as well as how many different types of relationships exist.
# This program identifies triads and calculates a lot of different data, including the expected
# number of different relationships vs. the actual number.
# to run from terminal window:
# python3 triad_graphs.py
# When asked to input a file name, enter the file name with the extension
# For example: epinions96.csv
import csv
import networkx
#setting up variables
numEdges = 0
numSelfLoops = 0
TotEdges = 0 # numEdges - numSelfLoops
numTrust = 0
numDistrust = 0
probabilityPos = 0 # num positive edges / totEdges
probabilityNeg = 0 # 1 - probabilityPos
numTriangles = 0
TTT = 0
TTD = 0
TDD = 0
DDD = 0
graph = networkx.Graph() # sets up a graph
f = input("Enter file name with extension: ") # takes in file name
with open(f, 'r') as openFile:
readFile = csv.reader(openFile, delimiter = ',')
for line in readFile: # runs through every line of the file
numEdges = numEdges + 1
if int(line[0]) == int(line[1]): # check for self-loops
numSelfLoops = numSelfLoops + 1
continue
graph.add_edge(int(line[0]), int(line[1]), relation = int(line[2])) # add new edges
if int(line[2]) == 1: # check if it's a trusted edge
numTrust = numTrust + 1
elif int(line[2]) == -1: # check if it's not a trusted edge
numDistrust = numDistrust + 1
for edge in graph.edges:
for node in graph.nodes:
if graph.has_edge(edge[0], node) and graph.has_edge(edge[1], node): # go through nodes of each edge and see if there's a triad
relat1 = graph[node][edge[0]]["relation"]
relat2 = graph[node][edge[1]]["relation"]
relat3 = graph[edge[0]][edge[1]]["relation"]
counter = 0 # keep note of the relationships of each triad
if relat1 == 1:
counter = counter + 1
if relat2 == 1:
counter = counter + 1
if relat3 == 1:
counter = counter + 1
if counter == 3:
TTT = TTT + 1
elif counter == 2:
TTD = TTD + 1
elif counter == 1:
TDD = TDD + 1
else:
DDD = DDD + 1
numTriangles = numTriangles + 1
numTriangles = int(numTriangles / 3)
TTT = int(TTT / 3)
TTD = int(TTD / 3)
TDD = int(TDD / 3)
DDD = int(DDD / 3)
totEdges = numEdges - numSelfLoops
probabilityPos = round(numTrust / totEdges, 2)
probabilityNeg = round(1 - probabilityPos, 2)
# probability of getting these different relationships
TTTprob = round(100 * probabilityPos * probabilityPos * probabilityPos, 1)
TTDprob = round(3 * 100 * probabilityPos * probabilityPos * probabilityNeg, 1)
TDDprob = round(3* 100 * probabilityPos * probabilityNeg * probabilityNeg, 1)
DDDprob = round(100 * probabilityNeg * probabilityNeg * probabilityNeg, 1)
# number of these relationships in the data
TTTnum = round(TTTprob / 100 * numTriangles, 1)
TTDnum = round(TTDprob / 100 * numTriangles, 1)
TDDnum = round(TDDprob / 100 * numTriangles, 1)
DDDnum = round(DDDprob / 100 * numTriangles, 1)
TTTprobAct = round(100 * TTT / numTriangles, 1)
TTDprobAct = round(100 * TTD / numTriangles, 1)
TDDprobAct = round(100 * TDD / numTriangles, 1)
DDDprobAct = round(100 * DDD / numTriangles, 1)
# print everything
print("Edges in network: " + str(numEdges))
print("Self-loops: " + str(numSelfLoops))
print("Total Edges (edges used - self-loops): " + str(totEdges))
print("Trust Edges: " + str(numTrust))
print("Distrust Edges: " + str(numDistrust))
print("Probability that an edge will be positive (p): " + str(probabilityPos))
print("Probability that an edge will be negative (1 - p): " + str(probabilityNeg))
print("Triangles: " + str(numTriangles))
print("Expected Distribution")
print("Type Percent Number")
print("TTT " + str(TTTprob) + " " + str(TTTnum))
print("TTD " + str(TTDprob) + " " + str(TTDnum))
print("TDD " + str(TDDprob) + " " + str(TDDnum))
print("DDD " + str(DDDprob) + " " + str(DDDnum))
print("Total " + str(round(TTTprob + TTDprob + TDDprob + DDDprob, 1)) + " " + str(round(TTTnum + TTDnum + TDDnum + DDDnum, 1)))
print("")
print("Actual Distribution")
print("Type Percent Number")
print("TTT " + str(TTTprobAct) + " " + str(TTT))
print("TTD " + str(TTDprobAct) + " " + str(TTD))
print("TDD " + str(TDDprobAct) + " " + str(TDD))
print("DDD " + str(DDDprobAct) + " " + str(DDD))
print("Total " + str(round(TTTprobAct + TTDprobAct + TDDprobAct + DDDprobAct, 1)) + " " + str(numTriangles)) |
4ca575e0ea60d7dd2014da6960a29f867174021c | JustEmpty/algorithms | /problems/max_depth.py | 476 | 3.859375 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.right = None
self.left = None
# Time complexity: O(n), visit each node exactly once
# Space complexity: O(n)(worst case: completely unbalanced), O(log(n))(best case: the height of the tree would be log(n))
def max_depth(root):
if root is None:
return 0
left_height = max_depth(root.left)
right_height = max_depth(root.right)
return max(left_height, right_height) + 1 |
ffb14de6057125b15aec75993f3ededcabbe8758 | ghazi-naceur/python-tutorials | /3-statements/if_elif_else_statements.py | 237 | 3.875 | 4 | def compare(a):
if a == 3:
print("Equal to 3")
elif a == 5:
print("Equal to 5")
else:
print("This is another value")
if __name__ == '__main__':
compare(3)
compare(5)
compare("something")
|
f98480d32647d5a2a63b66882864deb3cd173555 | kabmkb/Python-DeepLearning | /ICP5/Sourcecode/Program3.py | 1,754 | 3.9375 | 4 | """Importing pandas library"""
import pandas as pd
"""Using linear_model from sklearn library"""
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
"""Importing numpy library as np"""
import numpy as np
"""Importing matplotlib.pyplot library for plotting graphs"""
import matplotlib.pyplot as plt
"""Reading data through data2.csv file"""
restaurant_data = pd.read_csv("data2.csv")
"""selecting train_data and test_data"""
train_data = restaurant_data.drop(['revenue', 'City Group', 'Type'], axis=1)
test_data = restaurant_data["revenue"].astype(str)
"""Implementing linear model using library function"""
REGRESSION = linear_model.LinearRegression()
REGRESSION.fit(train_data, test_data)
REVENUE_prediction = REGRESSION.predict(train_data)
"""Printing R2 score"""
print("R2: %.2f" % r2_score(test_data, REVENUE_prediction))
"""Printing RMSE score"""
print("RMSE: %.2f" % mean_squared_error(test_data, REVENUE_prediction))
""" Working with numeric features"""
numeric_features = restaurant_data.select_dtypes(include=[np.number])
corr = numeric_features.corr()
print(corr['revenue'].sort_values(ascending=False)[0:6],'\n')
quality_pivot = restaurant_data.pivot_table(index=['P2'], values=['revenue'], aggfunc=np.median)
quality_pivot.plot(kind='bar', color='red')
plt.show()
correlated_features = restaurant_data[['P2', 'P28', 'P6', 'P21', 'P11']]
correlation = restaurant_data['revenue']
Regression_1 = linear_model.LinearRegression()
Regression_1.fit(correlated_features, correlation)
prediction = Regression_1.predict(correlated_features)
print("R2: %.2f" %r2_score(correlation, prediction))
print("RMSE:", mean_squared_error(correlation, prediction)) |
6d577d4f07fea159e8573dbd540bea95aec2b39f | 33Da/pytorch | /1_线性回归.py | 2,374 | 3.5625 | 4 | import torch
learning_rate = 0.01
# 准备数据
x = torch.rand([500, 1]) # 500行1列
y_true = x * 3 + 0.8
# 通过模型计算y_predict
w = torch.rand([1, 1], requires_grad=True)
b = torch.tensor(0, requires_grad=True, dtype=torch.float32)
# 4. 通过循环,反向传播,更新参数
# for i in range(2000):
#
# y_predict = torch.matmul(x, w) + b # matmul矩阵乘法
# # 3 计算loss
# loss = (y_true - y_predict).pow(2).mean()
#
# if w.grad is not None: # 计算了之前的梯度
# w.data.zero_() # 清空之前的梯度
# if b.grad is not None:
# b.data.zero_()
#
# loss.backward() # 反向传播
# w.data = w.data - learning_rate * w.grad
# b.data = b.data - learning_rate * b.grad
# if i % 50 == 0:
# print("w,b,loss:", w.item(), b.item(), loss.item())
# # 画图
# import matplotlib.pyplot as plt
# plt.figure(figsize=(20,8))
# # 正确的线
# plt.scatter(x.numpy().reshape(-1),y_true.numpy().reshape(-1))
# y_predict = torch.matmul(x,w) + b
# # 预测的线
# plt.scatter(x.numpy().reshape(-1),y_predict.detach().numpy().reshape(-1),c="r")
# plt.show()
##########################################################################
# 用api实现
from torch import nn
from torch.optim import SGD
class Lr(nn.Module):
def __init__(self):
super(Lr, self).__init__()
self.linear = nn.Linear(1, 1) # 输入和输出的列数,特征数量
def forward(self, x):
"""
__call__方法实际调了forward
"""
out = self.linear(x)
return out
model = Lr()
optimizer = SGD(model.parameters(), 0.01) # 获取参数,学习率
loss_fn = nn.MSELoss() # 定义损失
for i in range(20000):
# 得到预测值
predict = model(x) # 调用forward
loss = loss_fn(predict, y_true)
# 梯度置为0
optimizer.zero_grad()
loss.backward() # 反向传播
optimizer.step() # 更新参数
if i % 500 == 0:
params = list(model.parameters())
print("w,b,loss:", params[0].item(), params[1].item(), loss.item())
model.eval() # 设置为评估模式
predict = model(x)
# 画图
import matplotlib.pyplot as plt
plt.figure(figsize=(20,8))
# 正确的线
plt.scatter(x.numpy().reshape(-1),y_true.numpy().reshape(-1))
# 预测的线
plt.scatter(x.numpy().reshape(-1),predict.data.numpy(),c="r")
plt.show() |
cdaba15e987b834f5d69679ab7fad4a84664fd9b | Keonhong/IT_Education_Center | /Jumptopy/Codding_dojang/namedtuple( ).py | 1,732 | 3.75 | 4 | # collections.nametuple()의 메소드들
# 1) _make(iterable)
import collections
# Person 객체 만들기
Person = collections.namedtuple("Person", 'name age gender')
P1 = Person(name='Jhon', age=28, gender='남')
P2 = Person(name='Sally', age=28, gender='여')
# _make()를 이용하여 새로운 객체 생성
P3 = Person._make(['Peter', 24, '남'])
P4 = Person._make(['Ary', 23, '여'])
for n in [P1, P2, P3, P4]:
print('%s은(는) %d세의 %s성 입니다.' % n)
# 2) _asdict() >>> 기존에 생선된 namedtuple()의 인스턴스(객체)를 OrderedDict로 변환하는 함수
# _asdict()를 이용하여 OrderedDict로 변환
print(P3._asdict())
# 3) _replace(kwargs) >>> 기존에 생성된 nametuple()의 인스턴스의 값을 변경할때 사용
# _replace()를 이용하여 인스턴스 값 변경
P1 = P1._replace(name='Neo')
P2 = P2._replace(age=27)
P3 = P3._replace(age=26)
P4 = P4._replace(name='Ari')
print('-'*20)
for n in [P1, P2, P3, P4]:
print('%s은(는) %d세의 %s성 입니다.' % n)
# 4) _fields >>> 생성된 namedtuple()dml 필드명(field_names)를 tuple()형식으로 return해준다.
# _fields를 이용하여 필드명 출력
print(P1._fields)
# ('name', 'age', 'gender')
# 5) getattr() >>메소드는 아니지만 field_names로 namedtuple() 인스턴스의 값을 추출해준다.
print(getattr(P1,'name'))
print(getattr(P2, 'gender'))
print(getattr(P3, 'age'))
print(getattr(P4, 'age'))
# 6) dictionary에서 namedtuple()로 변환(**dict)
# double-star-operator(**)는 딕셔너리를 namedtuple()로 변환해준다.
dic = {'name': 'Tom', 'age':24, 'gender': '남'}
P3 = Person(**dic)
for n in [P1,P2,P3,P4]:
print('%s은(는) %d세의 %s성 입니다.'% n)
print(n) |
fc1d3ba12a5e13e8e002d503e2a5e1f9e16e4736 | RLuckom/python-graph-visualizer | /abstract_graph/Edge.py | 1,026 | 4.15625 | 4 | #!/usr/bin/env python
class Edge(object):
"""Class representing a graph edge"""
def __init__(self, from_vertex, to_vertex, weight=None):
"""Constructor
@type from_vertex: object
@param from_vertex: conventionally a string; something unambiguously
representing the vertex at which the edge originates
@type to_vertex: object
@param to_vertex: conventionally a string; something unabiguously
representing the vertex at which the edge terminates
@type weight: number
@param weight: weight of the edge, defaults to None.
"""
self.from_vertex = from_vertex
self.to_vertex = to_vertex
self.weight = weight
def __str__(self):
"""printstring
@rtype: str
@return: printstring
"""
return "Edge {0}{1}, weight {2}.".format(self.from_vertex, self.to_vertex, self.weight)
if __name__ == '__main__':
x = Edge('A', 'B', 5)
print x
|
01740c52fdd43d9e8ed2e305c7771c43ebcb4053 | howardbyrd/SortingVisualizer | /bubbleSort.py | 422 | 3.9375 | 4 | import time
# O(N^2) Time Complexity
# O(1) Space Complexity
def bubbleSort(data, drawData, timeTick):
for i in range(0, len(data) - 1):
for j in range(0, len(data) - 1 - i):
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
drawData(data, ['red' if x == j or x == j + 1 else 'blue' for x in range(len(data))])
time.sleep(timeTick) |
b314f76577a9988d992043245da553a7552682a8 | davidlwr/InternetExplorers | /web/Entities/activity.py | 2,437 | 3.578125 | 4 | import datetime
class Activity(object):
'''
This class represents an activity event created from 2 sensor_logs
'''
daytime_start = datetime.time(6, 30)
daytime_end = datetime.time(21, 30)
def __init__(self, uuid=None, start_datetime=None, end_datetime=None, start_log=None, end_log=None):
'''
Constructor, object can be created either by passing all params except start_log and end_log.
or by passing only start_log and end_log
Inputs:
uuid (str) -- (default None)
start_datetime (datetime) -- datetime obj (default None)
end_datetime (datetime) -- datetime obj (default None)
start_log (Entities.sensor.log) -- g class obj (default None)
end_log (Entities.sensor_log) -- Entities.log class obj (default None)
'''
if start_log == None and end_log == None: # No logs given, use start and end datetime params
self.uuid = uuid
self.start_datetime = start_datetime
self.end_datetime = end_datetime
self.seconds = (self.end_datetime - self.start_datetime).total_seconds()
else:
self.uuid = start_log.uuid
self.start_datetime = start_log.recieved_timestamp
self.end_datetime = end_log.recieved_timestamp
self.seconds = (self.end_datetime - self.start_datetime).total_seconds()
def in_daytime(self):
'''
Returns True if Activity is anywhere within the daytime period set of 06.30 > 21.30
'''
obj_start = self.start_datetime.time()
obj_end = self.end_datetime.time()
if obj_start >= Activity.daytime_start and obj_start <= Activity.daytime_end:
return True
elif obj_end >= Activity.daytime_start and obj_start <= Activity.daytime_end:
return True
else:
return False
def __str__(self):
'''
Returns str representation of object
'''
return f"ACTIVITY: uuid: {self.uuid}, secs: {self.seconds}, start_ts: {self.start_datetime.strftime('%Y-%m-%d %H:%M:%S')}, end_ts: {self.end_datetime.strftime('%Y-%m-%d %H:%M:%S')}"
def __repr__(self):
'''
Override python built in function to return string prepresentation of oject
'''
return self.__str__()
|
189c16119be11e8199ca842ba29b8d39c4e19e94 | newking9088/Data-Science-Materials-from-Coursera | /Python-Classes-and-Inheritance/testingClasses.py | 2,910 | 4.78125 | 5 | """To test whether the class constructor (the __init__) method is working
correctly, create an instance and then make tests to see whether its instance
variables are set correctly. Note that this is a side effect test: the
constructor method’s job is to set instance variables, which is a side
effect. Its return value doesn’t matter.
A method like distanceFromOrigin in the Point class you saw does its work by
computing a return value, so it needs to be tested with a return value test.
A method like move in the Turtle class does its work by changing the contents
of a mutable object (the point instance has its instance variable changed) so
it needs to be tested with a side effect test. Try adding some more tests in
the code below, once you understand what’s there."""
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy
import test
#testing instance variables x and y
#class test..test if attributes are set correctly
p = Point(3, 4)
test.testEqual(p.y, 4)
test.testEqual(p.x, 3)
#testing the distance method
# Return value test
p = Point(3, 4)
test.testEqual(p.distanceFromOrigin(), 5.0)
#testing the move method
#side-effect test
p = Point(3, 4)
p.move(-2, 3)
test.testEqual(p.x, 1)
test.testEqual(p.y, 7)
"""test-3-1: For each function, you should create exactly one test case.
A. True
B. False (Correct)
It's a good idea to check some extreme cases, as well as the typical cases.
test-3-2: To test a method that changes the value of an instance variable, which kind of test case should you write?
A. return value test
B. side effect test (Correct)
The move method of the Point class above is a good example.
test-3-3: To test the function maxabs, which kind of test case should you write?
def maxabs(L):
L should be a list of numbers (ints or floats). The return value should be the maximum absolute value of the numbers in L.
return max(L, key=abs)
A. return value test (Correct)
B. side effect test
You want to check if maxabs returns the correct value for some input.
test-3-4: We have usually used the sorted function, which takes a list as input and returns a new list containing
the same items, possibly in a different order. There is also a method called sort for lists (e.g. [1,6,2,4].sort()).
It changes the order of the items in the list itself, and it returns the value None. Which kind of test case
would you use on the sort method?
A. return value test
B. side effect test (Correct)
You want to check whether it has the correct side effect, whether it correctly mutates the list."""
|
9cc0c0864a28633dca337f1a4d793db6c4ce346f | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/287/82711/submittedfiles/testes.py | 150 | 3.890625 | 4 | # -*- coding: utf-8 -*-
n=int(input('digite o valor de n: '))
i=1
cont=0
while (i<n):
if i%2==1:
cont=cont+1
i=i+1
print(cont) |
552ce70b7429f583a86e43f0cc572104ba7655b0 | sycoumba/TPPYTHON | /EX06.py | 160 | 3.921875 | 4 | import math
x1=int(input("x1?"))
x2=int(input("x2?"))
y1=int(input("y1?"))
y2=int(input("y2?"))
d=math.sqrt(pow(x1-x2)+(pow(y1-y2)2)
print("la racine est",+d)
|
2bc740fef9a2588d0d0376b7eaaf6daeda4b067d | rookiy/Leetcode | /MinimumDepthOfBinaryTree_2rd.py | 929 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 递归方式得出最小高度,根,左子树,右子树
class Solution:
# @param {TreeNode} root
# @return {integer}
def minDepth(self, root):
if not root:
return 0
if not root.left:
return 1 + self.minDepth(root.right)
if not root.right:
return 1 + self.minDepth(root.left)
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
def main():
root = TreeNode(1)
root.left = TreeNode(-2)
root.right = TreeNode(-3)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(-2)
root.left.left.left = TreeNode(-1)
solution = Solution()
print solution.minDepth(root)
if __name__ == '__main__':
main() |
b83621385f9685613f566deef56849499cd27786 | c940606/leetcode | /Path Sum.py | 1,000 | 3.78125 | 4 | from listcreatTree import creatTree
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
self.all_sum = []
self.find_all_sum(root,0)
return sum in self.all_sum
def find_all_sum(self, root,temp):
# print(root.val)
if not root:
return
if not root.right and not root.left:
# print(root.val)
self.all_sum.append(temp+root.val)
# print(self.all_sum)
return
# elif (not root.right and root.left) or (not root.left and root.right):
# return
else:
print(root.val)
self.find_all_sum(root.left,temp+root.val)
# print("s",root.val)
self.find_all_sum(root.right,temp+root.val)
treelist = [1,2,3,'#',4,5]
treelist1 = [5,4,8,11,"#",13,4,7,2]
tree_obj = creatTree()
tree = tree_obj.list_to_tree(treelist1,TreeNode,0)
a = Solution()
print(a.hasPathSum(tree,0)) |
634b9269b5a586fee579722d81c7619921fb62bb | djarufes/Python_Crash_Course | /Excercises/HW07/pet.py | 1,107 | 3.53125 | 4 | ########################################################
# Author: David Jarufe
# Date: April. 19 / 2019
# This program is a Class that can be imported
# for later use
########################################################
#The Pet class (pet.py)
class Pet:
def __init__(self, petName, petType, petAge):
self.__name = petName
self.__animal_type = petType
self.__age = petAge
#Method that assigns a value to the __name field
def set_name(self, nameOfPet):
self.__name = nameOfPet
#Method that assigns a value to the __animal_type field
def set_animal_type(self,typeOfPet):
self.__animal_type = typeOfPet
#Method that assigns a value to the __age field
def set_age(self,ageOfPet):
self.__age = ageOfPet
#This method returns the value of the __name field
def get_name(self):
return(self.__name)
#This method returns the value of the __animal_type field
def get_animal_type(self):
return(self.__animal_type)
#This method returns the value of the __age field
def get_age(self):
return(self.__age)
|
c331b015cb0e381b0f71de34dd1f1ce853a51c50 | lixiang2017/leetcode | /explore/2021/april/Triangle.py | 1,345 | 3.546875 | 4 | '''
approach: Iteration / DP
Time: O(N*N) = O(N^2), where N is the length of triangle.
Space: O(N + N) = O(N)
You are here!
Your runtime beats 59.65 % of python3 submissions.
You are here!
Your memory usage beats 95.11 % of python3 submissions
'''
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
N = len(triangle)
presums = [0] * N
sums = [0] * N
for i in range(N):
presums = sums[:]
for j in range(i + 1):
if 0 == j:
sums[j] = presums[j] + triangle[i][j]
elif i == j:
sums[j] = presums[j - 1] + triangle[i][j]
else:
sums[j] = min(presums[j] + triangle[i][j], presums[j - 1] + triangle[i][j])
return min(sums)
'''
approach: Thinking Reversely, add from bottom to top
Time: O(N^2)
Space: O(1)
You are here!
Your runtime beats 59.65 % of python3 submissions.
You are here!
Your memory usage beats 66.62 % of python3 submissions.
'''
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
N = len(triangle)
for i in range(N - 2, -1, -1):
for j in range(i + 1):
triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1])
return triangle[0][0] |
1c8b669ff5b78cda4ff56753e91fd4dc57bcab70 | blendmaster/Rokkit-Tanx | /PhysicsObject.py | 20,970 | 3.625 | 4 | from math import *
from Vector import *
import pygame
from pygame.locals import *
DEBUG_DRAW_HULLS = True
DEBUG_DRAW_VELOCITY = False
GRAVITY_ENABLED = True
GRAVITY = Vector(0.0, -1.0)
ELASTIC_COLLISION_DAMPENING = .95
class PhysicsObject:
"""
An circle exibiting rigid body non angular velocity physics ( no force ). This is supposed to be an abstract class
so, you know, don't make any or whatever. kthxbai
"""
def __init__(self,x,y,width,height,mass,velocity=Vector(0,0),color=pygame.Color('blue')):
self.velocity = velocity # velocity in other words, dx and dy
self.mass = mass
#damn rect object doesn't store float values
self.x = float(x)
self.y = float(y)
self.prevCenterX = self.x
self.prevCenterY = self.y
self.width = float(width)
self.height = float(height)
self.centerx = self.x + self.width/2
self.centery = self.y + self.height/2
self.center = (self.centerx,self.centery)
#moar rect variables made floaty
self.topleft = (self.x,self.y)
self.topright = (self.x+self.width,self.y)
self.bottomleft = (self.x,self.y+self.height)
self.bottomright = (self.x+self.width,self.y+self.height)
self.top = self.y
self.bottom = self.y + self.height
self.left = self.x
self.right = self.x + self.width
self.hull = pygame.Rect(x,y,width,height) # the collision hull, even though the image
# overlayed might be different
self.color = color
def setX(self,x):
self.x = float(x)
self.centerx = self.x + self.width/2
self.center = (self.centerx,self.centery)
self.topleft = (self.x,self.y)
self.topright = (self.x+self.width,self.y)
self.bottomleft = (self.x,self.y+self.height)
self.bottomright = (self.x+self.width,self.y+self.height)
self.left = self.x
self.right = self.x + self.width
self.hull.x = x
def setY(self,y):
self.y = float(y)
self.centery = self.y + self.width/2
self.center = (self.centerx,self.centery)
self.topleft = (self.x,self.y)
self.topright = (self.x+self.width,self.y)
self.bottomleft = (self.x,self.y+self.height)
self.bottomright = (self.x+self.width,self.y+self.height)
self.top = self.y
self.bottom = self.y + self.height
self.hull.y = y
def intersects(self,o):
"""
This returns true if the other physics object is too far away from this one
"""
if abs( self.centerx - o.centerx ) > 500 and abs( self.centery - o.centery ) > 500:
return False
return True
def posRelTo(self,o): #abstract
"""
This one is annoying but I also don't know a better way to do this
It returns an int based on where this object is to the other one. a-like so:
// above returns 1;
// left returns 2;
// right returns 3;
// bottom returns 4;
// middle returns 0;
// weird error returns -1;
excuse the java comment markers pl0xorz
"""
return 0
def uncollide(self,o): pass #abstract
def addVelocity(self,v):
self.velocity = self.velocity.add(v)
def applyVelocity(self): pass #abstract
def addGravity(self):
self.velocity = self.velocity.add(GRAVITY)
def counteractGravity(self):
#this removes the effect of gravity, in case you are on the ground and don't want to keep
#goin down
self.velocity = velocity.add(Vector(GRAVITY.x*-1,GRAVITY.y*-1))
def move(self, deltaV, others): return [] # abstract, kind of
def draw(self,win):
"""
Draws the velocity if needed, which is the thing that all Physics Objects have
"""
if DEBUG_DRAW_VELOCITY:
pygame.draw.line(win, pygame.Color('red'), self.center, (int(self.centerx + self.velocity.x*10.0), int(self.centery - self.velocity.y*10.0) ) )
def __str__(self):
return "PhysicsObject("+str(self.x)+","+str(self.y)+"), velocity("+str(self.velocity)
class PhysicsCircle(PhysicsObject):
"""These move and behave well, like good little 2d circles"""
def __init__(self,x,y,width,height,mass,velocity=Vector(0,0),color=pygame.Color('blue')):
PhysicsObject.__init__(self,x,y,width,height,mass,velocity,color)
def applyVelocity(self):
"simple: applies the velocity , and updates prevX and Y"
self.prevCenterX = self.centerx
self.prevCenterY = self.centery
self.setX( self.x + self.velocity.x)
self.setY( self.y - self.velocity.y)
def __str__(self):
return "Circle"+PhysicsObject.__str__(self)
def draw(self,win):
"""
Draw that. this will probably be overridden to draw an image, but for debugging it draws
the hull
"""
PhysicsObject.draw(self,win)
if DEBUG_DRAW_HULLS:
pygame.draw.ellipse(win, self.color, self.hull, 1 )
def elasticCollision(self,o):
"""
Elastic collision with another object
This changes the velocity of both objects
"""
normal = Vector( o.x - self.x, self.y - o.y )
normal.setVector( normal.getUnitVector() )
tangent = Vector( -normal.y, normal.x )
m1 = self.mass
m2 = o.mass
v1n = normal.dotProduct( self.velocity )
v1t = tangent.dotProduct( self.velocity )
v2n = normal.dotProduct( o.velocity )
v2t = tangent.dotProduct( o.velocity )
v1tPrime = v1t
v2tPrime = v2t
v1nPrime = (v1n*(m1-m2)+v2n*m2*2)/(m1+m2)
v2nPrime = (v2n*(m2-m1)+v1n*m1*2)/(m1+m2)
vectorV1nPrime = normal.multiply(v1nPrime)
vectorV1tPrime = tangent.multiply(v1tPrime)
vectorV2nPrime = normal.multiply(v2nPrime)
vectorV2tPrime = tangent.multiply(v2tPrime)
self.velocity = vectorV1nPrime.add(vectorV1tPrime).multiply(ELASTIC_COLLISION_DAMPENING)
o.velocity = vectorV2nPrime.add(vectorV2tPrime).multiply(ELASTIC_COLLISION_DAMPENING)
def uncollide(self,o):
"""
moves this object out of the other object
which prevents collision detection from changing velocity moar than once
DOESN'T CHANGE VELOCITY
"""
if o.isCircle():
normal = Vector( o.centerx - self.centerx, self.centery - o.centery )
distanceToMove = self.width/2.0 + o.width/2.0 - normal.getMagnitude()
normal.setVector( Vector (-normal.x, -normal.y ) )
normal.setVector( normal.getUnitVector() ) # set's to 1 so we can multiply better
normal = normal.multiply( distanceToMove ); #gets short vector
self.setX( self.x + normal.x)
self.setY( self.y - normal.y)
else:
posRel = self.posRelTo(o)
if posRel == 1: self.setY( self.y - ( self.y + self.height - o.y ) )
elif posRel == 2: self.setX( self.x - ( self.x + self.width - o.x ) )
elif posRel == 3: self.setX( self.x + ( o.x + o.width - self.x ) )
elif posRel == 4: self.setY( self.y + ( o.y + o.height - self.y ) )
else: self.setY( self.y - ( self.y + self.height - o.y ) ) #just move it up
def posRelTo(self,o):
"""
This one is annoying but I also don't know a better way to do this
It returns an int based on where this object is to the other one. a-like so:
// above returns 1;
// left returns 2;
// right returns 3;
// bottom returns 4;
// middle returns 0;
// weird error returns -1;
excuse the java comment markers pl0xorz
"""
#this tests where the PREVIOUS center of self was in relation to
# object
# a like so
# 0 1 2
# 3 x 5
# 6 7 8
# it shouldn't ever be 4
# and THEN it checks for sure in spaces 0 2 6 8 for which direction
# the object was going
if o.isCircle():
centerAngle = atan2( o.centery - self.centery, self.centerx - o.centerx )/pi
if (1.0/4.0) < centerAngle and centerAngle < (3.0/4.0):
return 1
if (-1.0/4.0) < centerAngle and centerAngle < (1.0/4.0) :
return 3;
if (-3.0/4.0) < centerAngle and centerAngle < (-1.0/4.0) :
return 4;
if (-3.0/4.0) < centerAngle or centerAngle > (3.0/4.0) :
return 2
else:
switchX = 0
switchY = 0
if o.left > self.prevCenterX:
#print "left"
switchX = 0
elif o.left <= self.prevCenterX and self.prevCenterX <= o.right:
#print "middle"
switchX = 1
else:
#print "right"
switchX = 2
if o.top > self.prevCenterY:
#print "top"
switchY = 0
elif o.top <= self.prevCenterY and self.prevCenterY <= o.bottom:
#print "middle"
switchY = 1
else:
#print "bottom"
switchY = 2
switch = switchY*3 + switchX
#print str(self) + " is in octant " + str(switch) + " of " + str(o)
if switch == 1: return 1
elif switch == 3: return 2
elif switch == 5: return 3
elif switch == 7: return 4
elif switch == 0:
angle = atan2( o.top - self.prevCenterY, self.prevCenterX - o.left )
if self.velocity.getDirection() <= angle:
return 1
else: return 2
elif switch == 2:
angle = atan2( o.top - self.prevCenterY, self.prevCenterX - o.right )
if self.velocity.getDirection() >= angle:
return 1
else: return 3
elif switch == 6:
angle = atan2( o.bottom - self.prevCenterY, self.prevCenterX - o.left )
if self.velocity.getDirection() >= angle:
return 4
else: return 2
elif switch == 8:
angle = atan2( o.bottom - self.prevCenterY, self.prevCenterX - o.right )
if self.velocity.getDirection() <= angle:
return 4
else: return 3
elif switch == 4:
#let's just assume it came from above
return 1
return -1
def intersects(self,o):
if PhysicsObject.intersects(self,o):
if o.isCircle():
#distance between centers is less than their two radiuses, moveable objects are always circles, hopefully
return (self.centerx - o.centerx)**2 + (self.centery - o.centery)**2 <= (self.width/2.0+o.width/2.0)**2
else:
#sigh, no circle to rect collision, so they'll be some weirdness at the edges of boxen
return self.hull.colliderect(o.hull)
return False
def isCircle(self):
return True
def move(self, deltaV, others):
"""
mods velocity and collides against PhysicsObjects in the others list
"""
self.addVelocity(deltaV)
if GRAVITY_ENABLED:
self.addGravity()
self.applyVelocity()
collidedWith = []
for o in others:
if o == self: continue
if self.intersects(o):
self.uncollide(o)
if o.isCircle():
self.elasticCollision(o)
else:
o.rectCollision(self)
collidedWith.append(o)
return collidedWith
class PhysicsRect(PhysicsObject):
"""These don't move because since there's no angular velocity, it looks weird"""
def __init__(self,x,y,width,height,bouncemod,friction,color=pygame.Color('green')):
PhysicsObject.__init__(self,x,y,width,height,100,Vector(0,0),color)
self.bouncemod = bouncemod
self.friction = friction
def isCircle(self):
return False
def rectCollision(self,o):
"""
changes other object's velocity accordingly when
it collides with this platform
"""
posRel = o.posRelTo(self)
if posRel == 1:
o.velocity.y = -o.velocity.y*self.bouncemod
o.velocity.x = o.velocity.x*self.friction
elif posRel == 2:
o.velocity.x = -o.velocity.x*self.bouncemod
o.velocity.y = o.velocity.y*self.friction
elif posRel == 3:
o.velocity.x = -o.velocity.x*self.bouncemod
o.velocity.y = o.velocity.y*self.friction
elif posRel == 4:
o.velocity.y = -o.velocity.y*self.bouncemod
o.velocity.x = o.velocity.x*self.friction
else:
o.velocity.y = -o.velocity.y*self.bouncemod #just bounce it up
o.velocity.x = o.velocity.x*self.friction
def __str__(self):
return "Rect"+PhysicsObject.__str__(self)
def intersects(self,o):
if PhysicsObject.intersects(self,o):
return self.hull.colliderect(o.hull)
return False
def applyVelocity(self):
"since these shouldn't move, let's apply no velocity"
pass
def draw(self,win):
"""
Draw that. this will probably be overridden to draw an image, but for debugging it draws
the hull
"""
PhysicsObject.draw(self,win)
if DEBUG_DRAW_HULLS:
pygame.draw.rect(win, self.color, self.hull, 1 )
# testing
def main():
import random
pygame.init()
window = pygame.display.set_mode((1024,768),0,32)
pygame.display.set_caption("Physics Test")
player = PhysicsCircle( 250, 250, 50,50,15 )
things = [player]
leftPressed = False
rightPressed = False
downPressed = False
upPressed = False
fuel = 1024.0
font = pygame.font.Font(None, 15)
text = font.render('Fuel', True, (255,255, 255))
textRect = text.get_rect()
textRect.x = 20
textRect.y = 0
#something clevar to draw new platforms
firstclick = None
secondclick = None
tempsecondclick = None
pewpewpew = pygame.mixer.Sound("lazor.wav")
platforms = [PhysicsRect(0,80,80,768-160,.5,.90),
PhysicsRect(0,0,1024,80,.5,.90),
PhysicsRect(1024-80,80,80,768-160,.5,.90),
PhysicsRect(0,768-80,1024,80,.5,.90)
#PhysicsRect(1024/2-200,768/2,400,50,.20,.90)
]
isRunning = True
while isRunning:
window.fill(pygame.Color('black'))
events = pygame.event.get()
for event in events:
#if event.type == QUIT:
# exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
newDiam = random.randint(10,30)
newVector = Vector((event.pos[0] - player.x)/10.0, (player.y - event.pos[1])/10.0)
newNormal = newVector.getUnitVector()
newCenterx = player.centerx + newNormal.multiply(player.width/2.0 + newDiam/2.0).x
newCentery = player.centery - newNormal.multiply(player.width/2.0 + newDiam/2.0).y
newX = newCenterx - newDiam/2.0
newY = newCentery - newDiam/2.0
newThing = PhysicsCircle(newX,newY,newDiam ,newDiam , newDiam/10.0, newVector,(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
things.append(newThing)
pewpewpew.play()
elif event.button == 3:
if firstclick == None:
firstclick = event.pos
else:
#clicked two times
secondclick = event.pos
#no negative rectangles
second = False
if firstclick[0]>secondclick[0]:
secondclick = None
firstclick = None
tempsecondclick = None
break
else:
width = secondclick[0]-firstclick[0]
if firstclick[1]>secondclick[1]:
secondclick = None
firstclick = None
tempsecondclick = None
break
else:
height = secondclick[1]-firstclick[1]
platforms.append(PhysicsRect(firstclick[0],firstclick[1],width,height,0,.90))
secondclick = None
firstclick = None
tempsecondclick = None
elif event.type == MOUSEMOTION and firstclick != None:
#draw temprect where the platform would be named
tempsecondclick = event.pos
elif event.type == KEYDOWN:
if event.key == K_UP:
upPressed = True
if event.key == K_LEFT:
leftPressed = True
if event.key == K_RIGHT:
rightPressed = True
if event.key == K_DOWN:
downPressed = True
if event.key == K_ESCAPE:
isRunning = False
elif event.type == KEYUP:
if event.key == K_UP:
upPressed = False
if event.key == K_LEFT:
leftPressed = False
if event.key == K_RIGHT:
rightPressed = False
if event.key == K_DOWN:
downPressed = False
#move "player"
if fuel > 0:
if leftPressed:
player.addVelocity(Vector(-1.0,0))
fuel = fuel - 2
if downPressed:
player.addVelocity(Vector(0.0,-1.0))
fuel = fuel - 2
if rightPressed:
player.addVelocity(Vector(1.0,0.0))
fuel = fuel - 2
if upPressed:
player.addVelocity(Vector(0.0,1.5))
fuel = fuel - 4
fuel += .5
for i in things:
touched = len(i.move(Vector(0,0),things+platforms))
#print "Collision:" + str(j)
if( i == player ):
fuel += touched*5
i.draw(window)
for i in platforms:
i.draw(window)
if fuel > 1024: fuel = 1024
if fuel > 0:
if leftPressed:
pygame.draw.rect(window, pygame.Color('orange'), pygame.Rect(player.right,player.centery-5,10,10))
if downPressed:
pygame.draw.rect(window, pygame.Color('orange'), pygame.Rect(player.centerx-5,player.top-10,10,10))
if rightPressed:
pygame.draw.rect(window, pygame.Color('orange'), pygame.Rect(player.left-10,player.centery-5,10,10))
if upPressed:
pygame.draw.rect(window, pygame.Color('orange'), pygame.Rect(player.centerx-7,player.bottom,15,15))
pygame.draw.rect(window, pygame.Color('orange'), pygame.Rect(0,0,fuel,10))
#draw current click
if firstclick != None and tempsecondclick != None:
pygame.draw.rect(window,pygame.Color('firebrick'),pygame.Rect(firstclick,(tempsecondclick[0] - firstclick[0], tempsecondclick[1] - firstclick[1])),1)
window.blit(text, textRect)
pygame.display.flip()
pygame.time.Clock().tick(30)
pygame.display.quit()
pygame.quit()
if __name__ == "__main__":
main()
|
e0352e5c5217ed1bbad0cc7cffefcc1021fe8443 | gguillamon/PYTHON-BASICOS | /python_ejercicios basicos_III/bucles/ejercicio4.py | 741 | 3.90625 | 4 | # Realizar un algoritmo que pida números (se pedirá por teclado la cantidad de números a introducir).
# El programa debe informar de cuantos números introducidos son mayores que 0, menores que 0 e iguales a 0.
num=input("Introduzca numeros o 's' para salir:")
contador1=0
contador2=0
contador3=0
sumacontadores=contador1+contador2+contador3
while num != 's':
if int(num) > 0:
contador1+=1
elif int(num) < 0:
contador2+=1
elif int(num) == 0:
contador3+=1
else:
print("Introduzca un valor valido.")
num=input("Introduzca numeros o enter para salir:")
print("Hay",contador1,"numeros mayores de 0,",contador2,"menores de cero, y",contador3, "ceros.") |
7c57ed35f105ae0fafce3681846f9e702cc865f8 | ck-unifr/hackerrank-cracking-the-code-interview | /bit-manipulation-lonely-integer.py | 800 | 3.671875 | 4 | # https://www.hackerrank.com/challenges/ctci-lonely-integer/problem
# !/bin/python3
# Input format
# The first line contains a single integer n, denoting the number of integers in the array.
# The second line contains n space-separated integers describing the respective values in A.
# Output format
# Print the unique number that occurs only once in A on a new line.
import sys
def lonely_integer(a):
dict_a = dict()
str_output = ''
for val in a:
if val not in dict_a:
dict_a[val] = 1
else:
dict_a[val] += 1
for key, val in dict_a.items():
if val == 1:
str_output += str(key) + ' '
return str_output
n = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]
print(lonely_integer(a))
|
2cd4c5fef290fb28c914ad2ba8cef584cc35854b | MichalGilprog/PythonBasic | /tutorial_python/dziedziczenie.py | 640 | 3.515625 | 4 | class Osoba:
def __init__(self, imie, nazwisko):
self.imie = imie
self.nazwisko = nazwisko
def przedstaw_sie(self):
return "nazywam sie " + self.imie + " " + self.nazwisko
class Student(Osoba):
def __init__(self, imie, nazwisko, numer_indeksu):
Osoba.__init__(self, imie, nazwisko)
self.index = numer_indeksu
def podaj_numer_indeksu(self):
return "Moj nr indeksu: "+ str(self.index)
def przedstaw_sie(self):
return "jestem studentem i mam na imie " +self.imie
osoba = Osoba("Tomek","Kot")
print(osoba.przedstaw_sie())
#print(student.podaj_numer_indeksu()) |
95a9fbc51e15c488e4a94ac11e9d9d2e7a11750e | Ramezcua/PythonCardGames | /Cards/War.py | 478 | 3.671875 | 4 | import Cards
def main():
print('Welcome to war!')
while(True):
user_input = input('Would you like to start the game? [y/n]')
if user_input.lower() in ['yes', 'y', 'ya']:
print('Start game')
elif user_input.lower() in ['no', 'n', 'nah']:
print('Quitting game')
break
else:
print('Invalid input')
if __name__ == '__main__':
main() |
f5445e04295d17e270163ba13c242c04e45bf6e9 | Mujju-palaan/Flask01 | /section2/28)Inheritance.py | 649 | 3.640625 | 4 | class student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks/ len(self.marks))
def friend(self, friend_name):
return student(friend_name, self.school)
class Workingstudent(student):
def __init__(self, name, school, salary):
self.name = name
self.school = school
self.salary = salary
self.marks = []
anna = Workingstudent("Anna", "Oxford", 40000)
print(anna.salary)
friend = Workingstudent.friend("Mujju", 50000)
print(friend.name)
print(friend.school)
print(friend.salary) |
a541f87159190ed55ed1f7ba3ccecf9580693193 | zhsee/daily_coding_challenge | /day41_itinerary.py | 2,227 | 4.0625 | 4 | # Given an unordered list of flights taken by someone, each represented as (origin, destination) pairs, and a starting airport, compute the person's itinerary. If no such itinerary exists, return null. If there are multiple possible itineraries, return the lexicographically smallest one. All flights must be used in the itinerary.
# For example, given the list of flights [('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')] and starting airport 'YUL', you should return the list ['YUL', 'YYZ', 'SFO', 'HKO', 'ORD'].
# Given the list of flights [('SFO', 'COM'), ('COM', 'YYZ')] and starting airport 'COM', you should return null.
# Given the list of flights [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')] and starting airport 'A', you should return the list ['A', 'B', 'C', 'A', 'C'] even though ['A', 'C', 'A', 'B', 'C'] is also a valid itinerary. However, the first one is lexicographically smaller.
# no working for flight with cycle loop
def itinerary(start):
print(route)
if len(route) == N_route:
route.append(start)
return True
if start in flights:
route.append(start)
if itinerary(flights[start]):
return True
route.pop()
return False
# alist = [('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')]
# start = 'YUL'
alist = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')]
# alist = [('A', 'C'), ('A', 'B'), ('B', 'C'), ('C', 'A')]
start = 'A'
flights = dict(alist)
N_route = len(flights)
route = []
if itinerary(start):
print(route)
else:
print('no route')
# def get_itinerary(flights, current_itinerary):
# # If we've used up all the flights, we're done
# if not flights:
# return current_itinerary
# last_stop = current_itinerary[-1]
# for i, (origin, destination) in enumerate(flights):
# # Make a copy of flights without the current one to mark it as used
# flights_minus_current = flights[:i] + flights[i + 1:]
# current_itinerary.append(destination)
# if origin == last_stop:
# return get_itinerary(flights_minus_current, current_itinerary)
# current_itinerary.pop()
# return None
# print(get_itinerary(alist, ['A']))
|
892e4b12c8e1b2b19fdc437d3a3b50b795ade06c | johnta0/AtCoderSolutions | /abc/164/a/main.py | 128 | 3.546875 | 4 | s, w = map(int, input().split())
print('un' * (w >= s) + 'safe')
# if w >= s:
# print('unsafe')
# else:
# print('safe')
|
92140e190a034d7908563141c402a5091ea3db31 | gjkim44/Test | /Module05/Module05Demo/Lab5-1test.py | 1,118 | 4.25 | 4 | # 2) Add code that lets users appends a new row of data.
# 3) Add a loop that lets the user keep adding rows.
# 4) Ask the user if they want to save the data to a file when they exit the loop.
# 5) Save the data to a file if they say 'yes'
lstRow0 = ['Id','Name','Email']
lstRow1 = ['1','Bob Smith','[email protected]']
lstRow2 = ['2','Sue Jones','[email protected]']
lstRow3 = ['3','Joe James','[email protected]']
lstTable =[lstRow0,lstRow1,lstRow2,lstRow3]
print(lstTable)
# 2) Add code that lets users appends a new row of data.
#Make a New Row
while True:
intId = int(input("Enter a ID: "))
strName = input("Enter a Name: ")
strEmail = input("enter a Email: ")
lstNewRow = [intId,strName,strEmail]
#Add to Table
lstTable.append(lstNewRow)
strAnswer = input("Add more data (y/n)")
if strAnswer == 'n': break
print(lstTable)
strAnswer = input("Save Data to file (y/n)")
if strAnswer.lower() == "y":
fileName = input("Please enter file name: ")
objFile = open(fileName +".txt", "a")
# objF = open("MyData.txt", "a")
for lstRow in lstTable:
objFile.write(str(lstRow)+ '\n')
objFile.close()
|
86af50de4673f8470f4e9388b2d866ae4a38ecd6 | GreenBlitz/Deep-Space-Vision | /utils/image_objects.py | 7,379 | 3.546875 | 4 | import cv2
import numpy as np
from pipeline import PipeLine
class ImageObject:
def __init__(self, area, shape=None ,shape3d=None):
"""
constructor of the image object
which is an object on field
:param area: the square root of the area of the object (in squared meters), float
:param shape: optional, the shape of the object (2d)
used to test if a recorded object is the object represented by the image object
:param three_d_shape: the three dimensional shape of the object
used to estimate things like the center of the actual object
"""
self.area = area
self.shape = shape
self.shape3d = shape3d
def distance(self, camera, pipeline, frame=None):
"""
:param camera: the camera, can be either Camera or CameraList
:param pipeline: a pipeline that returns a float representing the square root of the area of the object
(in pixels)
:param frame: optional, a frame to be used instead of the next image from the camera
:return: the norm of the vector between the camera and the object (in meters)
"""
return camera.constant*self.area/pipeline(camera.read()[1] if frame is None else frame)
def location2d(self, camera, pipeline, frame=None):
"""
calculates the 2d location [x z] between the object and the camera
:param camera: the camera, can be either Camera or CameraList
:param pipeline: a pipeline that returns the contour of the object
:param frame: optional, a frame to be used instead of the next image from the camera
:return: a 2d vector of the relative [x z] location between the object and the camera (in meters)
"""
frame = camera.read() if frame is None else frame
cnt = pipeline(frame)
d_norm = self.distance_by_contours(camera, cnt)
m = cv2.moments(cnt)
frame_center = np.array(frame.shape[:2][::-1]) / 2
vp = m['m10'] / (m['m00'] + 0.000001), m['m01'] / (m['m00'] + 0.000001)
x, y = np.array(vp) - frame_center
alpha = x*camera.view_range/frame_center[0]
return np.array([np.sin(alpha), np.cos(alpha)])*d_norm
def distance_by_contours(self, camera, cnt):
"""
:param camera: the camera, can be either Camera or CameraList
:param cnt: the contours of this object in the frame
:return: the norm of the vector between the camera and the object (in meters)
"""
return self.area*camera.constant/np.sqrt(cv2.contourArea(cnt))
def location2d_by_contours(self, camera, cnt):
"""
:param camera: the camera, can be either Camera or CameraList
:param cnt: the contours of this object in the frame
:return: a 2d vector of the relative [x z] location between the object and the camera (in meters)
"""
frame_center = camera.get(cv2.CAP_PROP_FRAME_WIDTH), camera.get(cv2.CAP_PROP_FRAME_HEIGHT)
frame_center = np.array(frame_center)/2
m = cv2.moments(cnt)
vp = m['m10'] / (m['m00'] + 0.000001), m['m01'] / (m['m00'] + 0.000001)
x, y = np.array(vp) - frame_center
alpha = x * camera.view_range / frame_center[0]
return np.array([np.sin(alpha), np.cos(alpha)]) * self.distance_by_contours(camera, cnt)
def distance_by_params(self, camera, area):
"""
:param camera: the camera, can be either Camera or CameraList
:param area: a float representing the square root of the area of the object
(in pixels)
:return: the norm of the vector between the camera and the object (in meters)
"""
return camera.constant * self.area / area
def location2d_by_params(self, camera, area, center):
"""
:param camera: the camera, can be either Camera or CameraList
:param area: a float representing the square root of the area of the object
(in pixels)
:param center: the center (x,y) of this object in the frame
:return: a 2d vector of the relative [x z] location between the object and the camera (in meters)
"""
frame_center = camera.get(cv2.CAP_PROP_FRAME_WIDTH), camera.get(cv2.CAP_PROP_FRAME_HEIGHT)
frame_center = np.array(frame_center) / 2
x, y = np.array(center) - frame_center
alpha = x * camera.view_range / frame_center[0]
return np.array([np.sin(alpha), np.cos(alpha)]) * self.distance_by_params(camera, area)
def location3d(self, camera, pipeline, frame=None):
"""
calculates the 2d location [x z] between the object and the camera
:param camera: the camera, can be either Camera or CameraList
:param pipeline: a pipeline that returns the contour of the object
:param frame: optional, a frame to be used instead of the next image from the camera
:return: a 3d vector of the relative [x y z] location between the object and the camera (in meters)
"""
frame = camera.read() if frame is None else frame
cnt = pipeline(frame)
d_norm = self.distance_by_contours(camera, cnt)
m = cv2.moments(cnt)
frame_center = np.array(frame.shape[:2][::-1]) / 2
vp = m['m10'] / (m['m00'] + 0.000001), m['m01'] / (m['m00'] + 0.000001)
x, y = np.array(vp) - frame_center
alpha = x*camera.view_range/frame_center[0]
beta = y*camera.view_range/frame_center[1]
return np.array([np.sin(alpha), np.sin(beta), np.sqrt(1 - np.sin(alpha)**2 - np.sin(beta) ** 2)])*d_norm
def location3d_by_contours(self, camera, cnt):
"""
:param camera: the camera, can be either Camera or CameraList
:param cnt: the contours of this object in the frame
:return: a 2d vector of the relative [x z] location between the object and the camera (in meters)
"""
frame_center = camera.get(cv2.CAP_PROP_FRAME_WIDTH), camera.get(cv2.CAP_PROP_FRAME_HEIGHT)
frame_center = np.array(frame_center)/2
m = cv2.moments(cnt)
vp = m['m10'] / (m['m00'] + 0.000001), m['m01'] / (m['m00'] + 0.000001)
x, y = np.array(vp) - frame_center
alpha = x * camera.view_range / frame_center[0]
beta = y * camera.view_range / frame_center[1]
return np.array([np.sin(alpha), np.sin(beta), np.sqrt(1 - np.sin(alpha) ** 2 - np.sin(beta) ** 2)])\
* self.distance_by_contours(camera, cnt)
def location3d_by_params(self, camera, area, center):
"""
:param camera: the camera, can be either Camera or CameraList
:param area: a float representing the square root of the area of the object
(in pixels)
:param center: the center (x,y) of this object in the frame
:return: a 2d vector of the relative [x z] location between the object and the camera (in meters)
"""
frame_center = camera.get(cv2.CAP_PROP_FRAME_WIDTH), camera.get(cv2.CAP_PROP_FRAME_HEIGHT)
frame_center = np.array(frame_center) / 2
x, y = np.array(center) - frame_center
alpha = x * camera.view_range / frame_center[0]
beta = y * camera.view_range / frame_center[1]
return np.array([np.sin(alpha), np.sin(beta), np.sqrt(1 - np.sin(alpha) ** 2 - np.sin(beta) ** 2)])\
* self.distance_by_params(camera, area)
|
4d17279a9670b6c07d337bf8ce907df0d1eb3e65 | CCChang1996/-python- | /Numpy.py | 1,198 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 20:13:22 2019
@author: 13486
"""
import matplotlib.pyplot as plt
import numpy as np
# 创建数组
myarray = np.array([1, 2, 3])
print(myarray)
print(myarray.shape)
# 创建多维数组
myarray = np.array([[1, 2, 3], [2, 3, 4],[3, 4, 5]])
print(myarray)
print(myarray.shape)
#访问数据
print('这是第一行:%s' % myarray[0])
print('这是最后一行:%s' % myarray[-1])
print('访问整列(3列)数据:%s' % myarray[:, 2])
print('访问指定行(2行)和列(3列)的数据:%s' % myarray[1, 2])
myarray1 = np.array([[1, 2, 3], [2, 3, 4],[3, 4, 5]])
myarray2 = np.array([[11, 21, 31], [21, 31, 41], [31, 41, 51]])
print('向量加法运算:')
print(myarray1 + myarray2)
print('向量乘法运算:')
print(myarray1 * myarray2)
#绘制线条图
#初始化绘图
plt.plot(myarray)
#设定x轴和y轴
plt.xlabel('x axis')
plt.ylabel('y axis')
#绘图
plt.show()
#绘制散点图
myarray1 = np.array([1, 2, 3])
myarray2 = np.array([11, 21, 31])
#初始化绘图
plt.scatter(myarray1, myarray2)
#设定x轴和y轴
plt.xlabel('x axis')
plt.ylabel('y axis')
#绘图
plt.show() |
42fff1cc764c42451433406b2710336bac618064 | julianShi/chess_game | /TestChessGame.py | 382 | 3.515625 | 4 | from ChessGame import ChessGame
chessGame = ChessGame()
chessGame.initializeBoard()
# chessGame.printBoard()
# steps = [("e2","e4"),("d7","d5"),("e4","d5")]
steps = [("e2","e4"),("f7","f5"),("d1","h5"),("g8","f6"),("h5","e8")]
for startPosition,endPosition in steps:
if(chessGame.move(startPosition,endPosition)):
chessGame.printBoard()
else:
print("-- Stopped!!")
break
|
cb17c242facb138920202c80ee988a149363ac20 | ljw1126/python-for-coding-test | /7장이진탐색/bisect_lib_method.py | 749 | 3.609375 | 4 | """
값이 특정 범위에 속하는 데이터 개수 구하기
>> bisect 라이브러리를 활용하여
해당 값에 대한 count도 구할 수 있고
해당 범위내에 데이터 갯수도 구할 수 있음
# 실행결과
2
6
"""
from bisect import bisect_left, bisect_right
# 값이 [left_value, right_value]인 데이터의 개수를 반환하는 함수
def count_by_range(a, left_value, right_value):
right_index = bisect_right(a,right_value)
left_index = bisect_left(a,left_value)
return right_index - left_index
# 배열 선언
a = [1,2,3,3,3,3,4,4,8,9]
# 값이 4인 데이터 개수 출력
print(count_by_range(a,4,4))
# 값이 [-1,3] 범위에 있는 데이터 개수 출력
print(count_by_range(a,-1,3)) |
53e0fb6b92e0b8c8b6b54d2048f971276261fddd | mydevops-ec-projectsapps/paytm | /devops.py | 120 | 3.734375 | 4 | print("PLease Name")
name = input("Please enter your name please")
add= input("Please address please")
print(name,add)
|
a1c0f1b591b3af569836a8ce79b6e49560d9194e | seanchen513/leetcode | /tree/binary_tree.py | 3,857 | 3.875 | 4 | """
class TreeNode()
print_tree(root, depth=0)
array_to_bt(arr)
array_to_bt_lc(arr) # arr in LeetCode format
bt_find(root, val):
"""
from typing import List
import collections
class TreeNode():
def __init__(self, val, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
def print_tree(root, depth=0):
if root is None:
return
print_tree(root.right, depth + 1)
print(" "*depth + str(root.val))
print_tree(root.left, depth + 1)
"""
Converts array to binary tree.
If current node has index i, then its children have indices 2n+1 and 2n+2.
It's parent has index (i-1)//2.
Last possible parent has index (n-2)//2, where n = len(arr).
Assumes input array includes all possible None's.
Example use:
arr = [6, 2,8, 0,4,7,9, None,None,3,5]
#root, nodes = array_to_bt(arr)
nodes = array_to_bt(arr)
root = nodes[0]
print_tree(root)
node1 = nodes[arr.index(2)]
node2 = nodes[arr.index(8)]
test(root, node1, node2)
"""
def array_to_bt(arr):
if not arr:
#return None
return [None]
n = len(arr)
nodes = [None] * n
for i in range(n):
if arr[i] is not None:
nodes[i] = TreeNode(arr[i])
for i in range(n//2):
if arr[2*i + 1] is not None:
nodes[i].left = nodes[2*i + 1]
if arr[2*i + 2] is not None:
nodes[i].right = nodes[2*i + 2]
#return nodes[0]
#return nodes[0], nodes
return nodes
"""
Converts array in LeetCode format to binary tree.
Example input array:
[5,4,8,11,None,13,4,7,2,None,None,5,1]
What about [None] or [None, ...] ? Return None.
"""
def array_to_bt_lc(arr):
if (not arr) or (arr[0] is None):
return None
root = TreeNode(arr[0])
n = len(arr)
if n == 1:
return root
level = [root]
index = 1
while level:
next_level = []
for node in level:
if arr[index] is not None:
node.left = TreeNode(arr[index])
next_level.append(node.left)
index += 1
if index >= n:
return root
if arr[index] is not None:
node.right = TreeNode(arr[index])
next_level.append(node.right)
index += 1
if index >= n:
return root
level = next_level
return root # this point is never reached, I think.
###############################################################################
"""
Returns the first node encountered with given value.
"""
def bt_find(root, val):
if not root:
return
if root.val == val:
return root
node = bt_find(root.left, val)
if node:
return node
node = bt_find(root.right, val)
if node:
return node
###############################################################################
if __name__ == "__main__":
#arr = [5,4,8,11,None,13,4,7,2,None,None,5,1] # LC format
#arr = [5,4,8,11,None,13,4,7,2,None,None,None,None,5,1] # all nodes at last level shown
#root = array_to_bt(arr)
#print_tree(root)
### test array_to_bt_lc()
arr = [5,4,5,4,4,5,3,4,4,None,None,None,4,None,None,4,None,None,4,None,4,4,None,None,4,4]
#arr = [1]
#arr = None
#arr = [None]
#arr = [0]
#arr = [1,None,3]
#arr = [1,2,3]
root = array_to_bt_lc(arr)
print_tree(root)
### test array_to_bt() returning nodes
arr = [3, 5,1, 6,2,0,8, None,None,7,4,None,None]
nodes = array_to_bt(arr)
root = nodes[0]
p = nodes[arr.index(5)]
q = nodes[arr.index(1)]
#p = bt_find(root, 5)
#q = bt_find(root, 1)
#test(root, p, q)
#q = bt_find(root, 4)
q = nodes[arr.index(4)]
#test(root, p, q)
|
668f62fdbc35dc29a224978647092b60235376cb | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/smitco/lesson02/series.py | 1,057 | 3.703125 | 4 | #lesson 02 series
#step 1- print fibonacci value
def fibonacci(n):
fib = []
for num in range(n+1):
if num == 0:
fib.append(0)
elif num == 1:
fib.append(1)
else:
f = fib[num-1] + fib[num-2]
fib.append(f)
return(fib[n])
#step 2- print lucas value
def lucas(n):
luc = []
for num in range(n+1):
if num == 0:
luc.append(2)
elif num == 1:
luc.append(1)
else:
l = luc[num-1] + luc[num-2]
luc.append(l)
return(luc[n])
#step 3= generalize the formula for fib and luc series
def sum_series(n, z=0, o=1):
ser = []
for num in range(n+1):
if num == 0:
ser.append(z)
elif num == 1:
ser.append(o)
else:
s = ser[num-1] + ser[num-2]
ser.append(s)
return(ser[n])
#using assert to check code
assert sum_series(15) == 610
assert sum_series(9) == 34
assert sum_series(12, 2, 1) == 322
assert sum_series(4, 2, 1) == 7 |
b453626e87b3091c8c409f586bd10fe8edda6dde | BiswasAngkan/BasicPython | /NewItem_Insertion.py | 536 | 4.21875 | 4 | # Angkan Biswas
# 26.5.2020
# To insert a new item in a list or a dictionary
''' Empty list '''
x = []
print('x = {}'.format(x))
''' Insert new items in a list '''
x.append('Angkan')
print('x = {}'.format(x))
x.append(23.44444444)
print('x = {}'.format(x))
''' Empty dictionary '''
y = {}
print('y = {}'.format(y))
''' Insert new items in a dictionary '''
y['a'] = 12
print('y = {}'.format(y))
y['b'] = ['Angkan', 1, 890, 'Biswas']
print('y = {}'.format(y))
y['c'] = ('Dhaka', 1215, 0, 9, 'Farmgate')
print('y = {}'.format(y))
|
f1887e458f05e99281ce352d195ab43796815cb9 | gauravsaxena1997/pycode | /webscrap.py | 186 | 3.609375 | 4 | import urllib.request, urllib.error, urllib.parse
url = input ("Enter the URL: ")
fhand = urllib.request.urlopen('http://'+url)
for line in fhand:
print ( line.decode().strip() )
|
ac5e5362017d3e398c85bba8b2ca4cea4b06787a | lafabo/i-love-tutorials | /lpthw/ex5.py | 774 | 3.828125 | 4 | name = 'D\'artanyan'
age = 35 # i don't know exactly
height = 185 # cm
#height cm -> inches
height_inc = height * 0.39
weight = 75 # kg
#weight kg -> pounds
weight_pou = weight * 2.2
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print 'Let\'s talk about %s.' % name
print 'He\'s %d cm tall.' % height
print 'He\'s %d kg heavy' % weight
print 'Actually that\'s not too heavy'
print 'He\'s got %s eyes and %s hair.' % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
#this line is tricky, try to get it exactly right
print "If i add %d, %d and %d I get %d." % (age, height, weight, age + height + weight)
print "In pounds / centemiters it will be like: %u pounds and %u inches" % (weight_pou, height_inc)
print('%r' % (2*'hi' + str(2.2)))
|
61d264882bd557541e26548d58a644b1ccdd1322 | ColinTing/Python-Specialization | /ex_15_enrollment/enrollment.py | 1,707 | 3.609375 | 4 | import json
import sqlite3
conn = sqlite3.connect('enrollmentdb.sqlite')
cur = conn.cursor()
# 表命名不要加复数 “Users” 改成 “User”
#改了建表语句及插入sql中的User,却忘了删除表中的User
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXISTS Member;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY(user_id, course_id)
);
''')
fname = input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'roster_data.json'
#只需open(file),我却写成了urllib.request.urlopen(url)
#请命名规范些
#data = open(fname).read()
#js = json.loads(data)
#好的命名方法
str_data = open(fname).read()
json_data = json.loads(str_data)
for entry in json_data:
name = entry[0]
title = entry[1]
role = entry[2]
print(name, title, role)
cur.execute('''INSERT OR IGNORE INTO User (name)
VALUES ( ? )''', ( name, ) )
cur.execute('SELECT id FROM User WHERE name = ? ', (name, ))
user_id = cur.fetchone()[0]
#形式参数又比实际参数多写了一个
cur.execute('''INSERT OR IGNORE INTO Course (title)
VALUES ( ?)''', ( title,) )
cur.execute('SELECT id FROM Course WHERE title = ? ', (title, ))
course_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Member (user_id,course_id,role)
VALUES ( ?, ?, ? )''', ( user_id, course_id, role ) )
conn.commit()
conn.close()
|
dc10e1d5c334d49ecb73610ccc9ef87435d0728c | gudianirudha/python_programs | /find.py | 147 | 3.78125 | 4 | sent='Anirudh'
find=input("Enter what you want to search")
pos=sent.find(find)
if pos > 0:
print("found",pos)
else:
print("Not found",pos)
|
baaa352456549d8b3ff7bd1cedade8e1f08f4ae5 | eecs110/winter2021 | /course-files/lectures/lecture14/answers/02b_list_animation_different_speeds.py | 1,353 | 3.765625 | 4 | from tkinter import Canvas, Tk
import time
import utilities
import math
import random
gui = Tk()
gui.title('Animation')
canvas = Canvas(gui, width=500, height=500, background='white')
canvas.pack()
########################## YOUR CODE BELOW THIS LINE ##############################
# 1. generate a list of rules that each bubble should follow:
data = []
for i in range(1, 101):
x = random.randint(0, 500)
y = random.randint(0, 500)
r = random.randint(5, 25)
speed = random.randint(1, 5)
tag_name = 'circle' + str(i)
bubble_rule = [x, y, r, speed, tag_name]
data.append(bubble_rule)
# 2. use the data to generate 100 bubbles:
for bubble_rule in data:
x = bubble_rule[0]
y = bubble_rule[1]
r = bubble_rule[2]
speed = bubble_rule[3]
tag_name = bubble_rule[4]
utilities.make_circle(canvas, (x, y), r, color=None, tag=tag_name)
while True:
for bubble_rule in data:
speed = bubble_rule[3]
tag_name = bubble_rule[4]
utilities.move(canvas, tag_name, x=0, y=speed)
top = utilities.get_top(canvas, tag_name)
if top > 550:
utilities.move(canvas, tag_name, x=0, y=-600)
gui.update()
time.sleep(.001)
########################## YOUR CODE ABOVE THIS LINE ##############################
# makes sure the canvas keeps running:
canvas.mainloop()
|
d3becaf2eb46765e15254df1784c5f4b42f4d80b | wheresmichel/my-first-blog | /hello.py | 265 | 4.09375 | 4 | print("hello")
print("hi alex")
x = "hi alex"
print(x)
x = "there are two alex"
print(x)
x = "django girls project"
print(x)
x = ["tomato","potato","ice cream"]
print(x)
for food in x:
print(food)
x = [1,2,3,4,5]
sum = 0
for num in x:
sum += num
print(sum)
|
71c347ea25381ea29856d2de1e0fe8eef5b26265 | danila28/laba | /4.py | 1,541 | 3.578125 | 4 | filename = input("Введите имя файла для чтения:> ")
f = open(filename, 'r')
f = f.read()
numb = "0123456789"
latin = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
rusodnglas = "уыаоэиУЫАОЭИ"
rusdvuglas = "еёюяЕЁЮЯ"
rusship = "жшчщЖШЧЩ"
ruszvonk = "бвгдзжлмнрБВГДЗЖЛМНР"
dlina = len(filename)
numb1 = 0
latin1 = 0
rusodnglas1 = 0
rusdvuglas1 = 0
rusship1 = 0
ruszvonk1 = 0
other = 0
i=0
print(f)
while i < len(f):
if f[i] in latin: latin1 += 1
elif f[i] in rusodnglas: rusodnglas1 += 1
elif f[i] in numb: numb1 += 1
elif f[i] in rusdvuglas: rusdvuglas1 += 1
elif f[i] in rusship: rusship1 += 1
elif f[i] in ruszvonk: ruszvonk1 += 1
else: other += 1
i+= 1
print("Всего символов:> ", len(f))
print("Всего цифр:> ", numb1, round((numb1/len(f)),2))
print("Всего латинских букв:> ", latin1, round((latin1/len(f)),2))
print("Всего русских однозвучных гласных:> ",rusodnglas1, round((rusodnglas1/len(f)),2))
print("Всего русских двузвучных гласных:> ",rusdvuglas1, round((rusdvuglas1/len(f)),2))
print("Всего русских шипящих согласных букв:> ", rusship1, round((rusship1/len(f)),2))
print("Всего русских звонких согласных:> ", ruszvonk1, round((ruszvonk1/len(f)),2))
print("Прочих символов:> ", other, round((other/len(f)),2))
|
9bafc9c67022ced2577c0f4091fff787c7036c6e | ykim5470-Lewis/westagram | /Info1110/week03/seminar.py | 150 | 3.59375 | 4 | ham = "10"
int(ham)
print("This is"+ ham)
print("This is" +str(ham))
report= "progess: {:.2f}".format(12.345)
print(report)
x= 10
x= x == x
print(x) |
0af6bedee66312a51569e1e36a23d53d4b3ed2ac | adityak74/HackerrankSolutions | /ai-ml-corrreg1-numpy.py | 602 | 3.546875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import numpy as np
phy_scores = [15,12,8,8,7,7,7,6,5,3]
his_scores = [10,25,17,11,13,17,20,13,9,15]
phy_his = np.multiply(phy_scores,his_scores)
phy_sqr = np.power(phy_scores, 2)
his_sqr = np.power(his_scores, 2)
phy_his_sum = np.sum(phy_his)
phy_sum = np.sum(phy_scores)
his_sum = np.sum(his_scores)
phy_sqr_sum = np.sum(phy_sqr)
his_sqr_sum = np.sum(his_sqr)
carl_coeff = (10*phy_his_sum - (phy_sum)*(his_sum)) / np.sqrt( (10*phy_sqr_sum - np.power(phy_sum,2))*(10*his_sqr_sum - np.power(his_sum,2)) )
print "%.3f" % carl_coeff |
ac56e5f46136818dba4fd1ea3aa87f822159fe37 | kritikagupta0007/Guess-Number | /main.py | 452 | 4.09375 | 4 | import random
def guess(num):
random_number = random.randint(1,num)
guess = 0
while guess != random_number :
guess = int(input(f"Guess the number between 1 to {num} : "))
if guess > random_number :
print(f"Number you choose is too high")
elif guess < random_number :
print(f"Number you choose is too low")
print(f"Yupss...!! You guess the correct number {random_number}....")
guess(10) |
e56977acf4b461bcf27df539efb45712be8cbd07 | Nan-Do/DailyCoding | /Daily_54.py | 3,270 | 3.515625 | 4 | def get_free_positions(sudoku):
free_positions = []
for r in range(9):
for c in range(9):
if sudoku[r][c] == -1:
free_positions.append((r, c))
return free_positions
def get_square_val(position):
r = position[0]
c = position[1]
ri = 0
re = 3
if r >= 3 and r <= 5:
ri = 3
re = 6
if r >= 6 and r <= 8:
ri = 6
re = 9
ci = 0
ce = 3
if c >= 3 and c <= 5:
ci = 3
ce = 6
if c >= 6 and c <= 8:
ci = 6
ce = 9
return ri, re, ci, ce
def get_possible_values(sudoku, position):
values = set(range(1, 10))
r = position[0]
c = position[1]
values = values.difference(sudoku[r])
for x in range(9):
values.discard(sudoku[x][c])
ri, re, ci, ce = get_square_val(position)
for x in range(ri, re):
for y in range(ci, ce):
values.discard(sudoku[x][y])
return iter(values)
def check_board(sudoku, position, value):
r = position[0]
c = position[1]
for v in range(9):
if sudoku[r][v] == value or\
sudoku[v][c] == value:
return False
ri, re, ci, ce = get_square_val(position)
for x in range(ri, re):
for y in range(ci, ce):
if sudoku[x][y] == value:
return False
return True
def sudoku_solver(sudoku):
free_positions = get_free_positions(sudoku)
pos = 0
positions_generator = {}
while True and len(free_positions):
position = free_positions[pos]
if position not in positions_generator or \
positions_generator[position] is None:
positions_generator[position] = get_possible_values(
sudoku, position)
try:
value = next(positions_generator[position])
except StopIteration:
if pos == 0:
return False
else:
positions_generator[position] = None
sudoku[position[0]][position[1]] = -1
pos -= 1
continue
if check_board(sudoku, position, value):
sudoku[position[0]][position[1]] = value
pos += 1
if pos == len(free_positions):
return True
else:
if pos > 0:
sudoku[position[0]][position[1]] = -1
positions_generator[position] = None
pos -= 1
return True
# sudoku = [[1,5,2,4,8,9,3,7,6],
# [7,3,9,2,5,6,8,4,1],
# [4,6,8,3,7,1,2,9,5],
# [3,8,7,1,2,4,6,5,9],
# [5,9,1,7,6,3,4,2,8],
# [2,4,6,8,9,5,7,1,3],
# [9,1,4,6,3,7,5,8,2],
# [6,2,5,9,4,8,1,3,7],
# [8,7,3,5,1,2,9,6,4]]
sudoku = [[-1, 5, 2, -1, -1, 9, -1, -1, -1], [7, 3, -1, 2, -1, -1, -1, -1, 1],
[-1, 6, -1, -1, 7, 1, -1, -1, 5], [-1, -1, -1, 1, -1, -1, 6, -1, 9],
[-1, -1, 1, -1, 6, -1, 4, 2, -1], [-1, -1, 6, -1, 9, -1, 7, 1, 3],
[-1, 1, -1, 6, -1, -1, 5, -1, -1], [6, -1, -1, -1, 4, -1, 1, -1, -1],
[-1, -1, 3, -1, 1, -1, -1, 6, 4]]
for r in sudoku:
print(" ".join(map(str, r)))
print(sudoku_solver(sudoku))
for r in sudoku:
print(" ".join(map(str, r)))
|
b76bb07d524c7698b89801534d32da9a5fd3f3db | Victor-Deidon/Python | /lab5/lab5.py | 683 | 3.578125 | 4 | class __task1():
Nu = []
St = []
for i in range (0,5):
print("type number")
Nu.append(input())
for j in range (0,5):
print("type string")
St.append(input())
def f(Nu):
res = 0
for h in range (0,5):
res = res + Nu[h]
print(res)
def u(St):
for h in range (0,5):
print (St[h][::-1])
class __task2():
Y="y"
while len(Y) > 50 or len(Y)<30:
print("input")
Y= str(input())
textoutput=open("textfile.txt","w")
textoutput.write(Y)
textoutput=open("textfile.txt","r")
print(textoutput.read())
textoutput.close
|
7f9a9d78888058dd8f96387862a1b0cd631e6702 | salabhsg/PY-Projects | /Python_ALPHA.py | 912 | 3.984375 | 4 | #Excercise (1)=====================================>>>>>>>>>>>
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
# write your code here
numbers = [1,2,3]
strings = ["Hello","World"]
second_name = names[1]
# this code should write out the filled arrays and the second name in the names list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name)
#Excercise (2)=======================================>>>>>>>>>>>
x = object()
y = object()
# TODO: change this code
x_list = [x] * 10
y_list = [y] * 10
big_list = x_list + y_
print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))
# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
print("Great!") |
a8bd64094cad2b2a47f0a20999a4d0619b62af5f | alexandraback/datacollection | /solutions_5738606668808192_0/Python/johnclyde/jamcoin.py | 625 | 3.90625 | 4 | #!/usr/bin/env python
from sys import argv
script, N, J = argv
def integer_to_binary_string(n):
if n == 0:
return '0'
binstr = ''
x = n
while x > 0:
binstr = '{}{}'.format(x % 2, binstr)
x = int(x / 2)
return binstr
print "Case #1:"
num_zeroes = int(N) / 2 - 1
starting_point = 1
for i in range(0, num_zeroes):
starting_point *= 2
starting_point += 1
for k in range(0, int(J)):
disp = integer_to_binary_string(starting_point)
disp = disp.replace('1', '11')
disp = disp.replace('0', '00')
starting_point += 2
print "{} 3 4 5 6 7 8 9 10 11".format(disp)
|
3dbf5904fcac88dcdda8cafa897313e2c8046d10 | justcodemore/python | /requsentslearn/test.py | 278 | 3.75 | 4 | # __author__ = 'admin'
# -*- coding: utf-8 -*-
score = raw_input('please write your score:')
score = int(score)
if score >= 90:
print 'excellent'
elif score >= 80:
print 'good'
elif score >= 60:
print 'passed'
else:
print 'failed'
f = lambda a: a+2
print f(2)
|
8a516cc3fc02c62e6bc982d7901da945f1800d49 | saded/volume3Ds | /elips.py | 2,599 | 4.03125 | 4 | import bpy
from random import randint, random
from math import sqrt, pi
# Function to calculate the distance between two points
def distance(a, b) :
'''
list , list --> float
a = list with three element
b = list with three element
return the distance between two points in float
'''
return sqrt((a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)
# How many Sphere you want to add
count = 100
# Sphere properties
size = 0.1
# Ellispoid properties
ellipsoidSize = [0.1, 0.2, 0.1]
# The sphere will be created between -domain <--> domain
domain = 2
# Max time to try finding a new location before break the loop
maxTry = 100000
# Variable to count how many try has been done
Try = 0
# list with three element to generate locations
location = [0, 0, 0]
# Variable to hold the distant between balls
dist = 0
# True == Won't collide , False == Will collide
State = True
# This tuple will hold centers of created spheres
locList = ()
while count > 0 :
# Calculate x, y, z position
location[0] = round(random()*(domain-size*2)-(domain-size*2)/2, 5)
location[1] = round(random()*(domain-size*2)-(domain-size*2)/2, 5)
location[2] = round(random()*(domain-size*2)-(domain-size*2)/2, 5)
# Start check if it will collide with other spheres
for x in locList :
# Calculate the distant
dist = distance(x, location)
# If it's too close make State = False
if dist < size*2 + 0.1 :
State = False
break
# If it's in a good position State = True
else :
State = True
# The distant is too close , recalculate the location
if State == False :
Try += 1
continue
# After Try reach maxTry break the loop
if Try > maxTry :
break
# Successfully found a New location
# Add this point
locList += (location[:],)
# Create a new Sphere
#bpy.ops.mesh.primitive_uv_sphere_add(size = size, location = location)
# Smooth the faces
bpy.ops.object.shade_smooth()
#Create a new sphere at the same location, and resize it to an ellipsoid
bpy.ops.mesh.primitive_uv_sphere_add(size = 1.0, location = location)
bpy.ops.transform.resize(value=ellipsoidSize)
#Give the ellipsoid a random orientation
bpy.ops.transform.rotate(value=(2*pi*random()-1), axis=((2*pi*random()-1), (2*pi*random()-1), (2*pi*random()-1)))
#Smooth the faces
bpy.ops.object.shade_smooth()
# reset Try
Try = 0
# Decrease the counter
count -= 1
|
a3948c2d2d70b34eb1d3c1be25050e082e9d83c2 | banggeut01/algorithm | /code/list/5120.py | 2,461 | 3.71875 | 4 | # 5120.py 암호
import sys
sys.stdin = open('5120input.txt', 'r')
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def printList(self):
if self.head is None:
print('빈리스트')
return
cur = self.head
while cur is not None:
print(cur.data, end=' ')
cur = cur.next
print()
def insertLast(self, node):
if self.head is None: #빈리스트
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
def insertAt(self, idx, k): # idx:삽입위치, k:반복횟수
if self.head is None:
return
# 삽입 위치 찾기
prev, cur = None, self.head
for _ in range(k):
i = idx
while i > 0:
if cur is None: # 리스트 끝
cur = self.head
prev = cur
cur = cur.next
i -= 1
if prev is None: # 첫번째
node = Node(cur.data + self.tail.data)
self.head = node
node.next = cur
cur = self.head
elif cur is None: # 마지막
node = Node(self.head.data + prev.data)
self.tail.next = node
self.tail = node
cur = self.tail
else:
node = Node(cur.data + prev.data)
prev.next = node
node.next = cur
cur = prev.next
def printListReverse(self):
if self.head is None: # 빈리스트
print('빈리스트')
return
cur, tmp = self.head, []
while cur is not None:
tmp.append(cur.data)
cur = cur.next
for i in range(1, 11):
if len(tmp) < i:
break
print(tmp[-i], end=' ')
print()
t = int(input())
for tc in range(1, t + 1):
n, m, k = map(int, input().split()) # n: 수열크기, m: 삽입 위치, k: 반복 횟수
inputs = list(map(int, input().split()))
mylist = LinkedList()
# 리스트 생성
for data in inputs:
mylist.insertLast(Node(data))
mylist.insertAt(m, k)
print('#{} '.format(tc), end='')
mylist.printListReverse()
|
707526bb1b2c25856c19f5d4fc48dad1dc92e35f | Yuchen1995-0315/review | /01-python基础/day08/exercise02.py | 195 | 4.03125 | 4 | # 练习:定义函数,多个数值相加的函数.
def sum(*args):
result = 0
for item in args:
result += item
return result
print(sum(1,2))
print(sum(1,2,3,54,3,5,65,67))
|
c69a2133c61655fbfe3a6f4bb73e1fa07de06de6 | paulorjmx/bd_pt3 | /Controller.py | 1,754 | 4 | 4 | from Atividade import Atividade as A
# Controlador principal, recebe os inputs necessários para realizar operações.
class Controller:
class Insert:
def atividade(self):
nome = input("Digite o nome da atividade: ")
descricao = input("Digite a descrição: ")
tipo = input("Digite o tipo: 'PESQUISA' ou 'ESTAGIO: '")
data_inicio = input("Digite a data de inicio no formato dd/mm/aaaa: ")
data_fim = input("Digite a data de fim no formato dd/mm/aaaa: ")
qtde_participantes = input("Digite a quantidade de participantes: ")
A().insert(nome, descricao, tipo, data_inicio, data_fim, qtde_participantes)
print("Inserção realizada com sucesso!")
class Update:
def atividade(self):
nome = input("Digite o nome da atividade: ")
print("Caso não queira alterar algum campo, aperte enter")
inputDict = {}
inputDict['descricao'] = input("Digite a descrição: ").strip()
inputDict['tipo'] = input("Digite o tipo: 'PESQUISA' ou 'ESTAGIO: '").strip()
inputDict['data_inicio'] = input("Digite a data de inicio no formato dd/mm/aaaa: ").strip()
inputDict['data_fim'] = input("Digite a data de fim no formato dd/mm/aaaa: ").strip()
inputDict['qtde_participantes'] = input("Digite a quantidade de participantes: ").strip()
print(inputDict)
inputDict = {k:v for (k,v) in inputDict.items() if len(v) > 0}
if len(input) > 0:
A().update(nome, inputDict)
print("Update realizado com sucesso!")
else:
print("Erro! Você precisa de pelo menos um campo a ser alterado!")
class Search:
def atividade(self):
nome = input('Digite o nome da atividade que deseja buscar (aperte ENTER para buscar tudo): ')
if nome == '':
A().searchForMany('')
else:
A().searchForOne(nome) |
dcb61a2cecd01d6bde7b7540d9a47569a15386c6 | rafaelperazzo/programacao-web | /moodledata/vpl_data/396/usersdata/288/81075/submittedfiles/av1_programa2.py | 2,259 | 4.03125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
a=int(input("Digite um numero: "))
b=int(input("Digite um numero: "))
c=int(input("Digite um numero: "))
d=int(input("Digite um numero: "))
e=int(input("Digite um numero: "))
f=int(input("Digite um numero: "))
g=int(input("Digite um numero sorteado: "))
h=int(input("Digite um numero sorteado: "))
i=int(input("Digite um numero sorteado: "))
j=int(input("Digite um numero sorteado: "))
k=int(input("Digite um numero sorteado: "))
l=int(input("Digite um numero sorteado: "))
if (a==g or a==h or a==i or a==j or a==k or a==l) and (b==g or b==h or b==i or b==j or b==k or b==l) and (c==g or c==h or c==i or c==j or c==k or c==l) and (d==g or d==h or d==i or d==j or d==k or d==l) and (e==g or e==h or e==i or e==j or e==k or e==l) and (f==g or f==h or f==i or f==j or f==k or f==l):
print ("sena")
elif (a==g or a==h or a==i or a==j or a==k or a==l) and (b==g or b==h or b==i or b==j or b==k or b==l) and (c==g or c==h or c==i or c==j or c==k or c==l) and (d==g or d==h or d==i or d==j or d==k or d==l) and (e==g or e==h or e==i or e==j or e==k or e==l):
print ("quina")
elif (a==g or a==h or a==i or a==j or a==k or a==l) and (b==g or b==h or b==i or b==j or b==k or b==l) and (c==g or c==h or c==i or c==j or c==k or c==l) and (d==g or d==h or d==i or d==j or d==k or d==l):
print ("quadra")
elif (a==g or a==h or a==i or a==j or a==k or a==l) and (b==g or b==h or b==i or b==j or b==k or b==l) and (c==g or c==h or c==i or c==j or c==k or c==l):
print ("terno")
elif (b==g or b==h or b==i or b==j or b==k or b==l) and (c==g or c==h or c==i or c==j or c==k or c==l) and (d==g or d==h or d==i or d==j or d==k or d==l) and (e==g or e==h or e==i or e==j or e==k or e==l) and (f==g or f==h or f==i or f==j or f==k or f==l):
print ("quina")
elif (c==g or c==h or c==i or c==j or c==k or c==l) and (d==g or d==h or d==i or d==j or d==k or d==l) and (e==g or e==h or e==i or e==j or e==k or e==l) and (f==g or f==h or f==i or f==j or f==k or f==l):
print ("quadra")
elif (d==g or d==h or d==i or d==j or d==k or d==l) and (e==g or e==h or e==i or e==j or e==k or e==l) and (f==g or f==h or f==i or f==j or f==k or f==l):
print ("terno")
else:
print ("azar") |
c850601c3c98b0ff6ccd9d18f02e4f5c7447f2e5 | mohdsanadzakirizvi/algos | /document_distance.py | 1,605 | 3.515625 | 4 | from math import sqrt, acos
from string import maketrans
def openFile(docname):
with open(docname, 'r') as doc:
return doc.readlines()
def wordSplit(lines):
lines2 = []
tranTable = maketrans('?.!;:,-(){}[]_\n\t', ' '*16)
for line in lines:
line = (line.lower()).translate(tranTable)
lines2.append(line.split())
return lines2
def linesToDict(splittedLines):
dictTable = {}
listLength = 0
for groups in splittedLines:
listLength = len(groups)
if listLength > 1:
for word in groups:
if word not in dictTable:
dictTable[word] = 0
if word in dictTable:
dictTable[word] += 1
elif listLength <= 1:
groups = str(groups).strip('[]')
if groups not in dictTable:
dictTable[groups] = 0
if groups in dictTable:
dictTable[groups] += 1
return dictTable
def innerProduct(dictA, dictB):
num = 0
for word in dictA:
if word in dictB:
num += dictA[word]*dictB[word]
return num
def docDist(dictA, dictB):
num = innerProduct(dictA, dictB)
denom = sqrt(innerProduct(dictA, dictA)*innerProduct(dictB, dictB))
return acos(num/denom)
def main():
file1 = raw_input("Enter file 1 name ")
file2 = raw_input("Enter file 2 name ")
dictA = linesToDict(wordSplit(openFile(file1)))
dictB = linesToDict(wordSplit(openFile(file2)))
print "The document distance is:", docDist(dictA, dictB)
if __name__ == '__main__':
main()
|
0aa848a4ed5653aef2243e63e1708f5f755d2440 | shubhamshah14102/robospark-2021-prog-rohan-gaikwad | /12_10_DS_task_17_Shubham Shah/prog.py | 1,832 | 3.6875 | 4 | # 1. Shape detection: Images contains different shapes with different colors.
# Your task is to detect the shape by knowing the number of sides present on that shape.
# Draw the edges on the shape masked.
import cv2
import numpy as np
img = cv2.imread("vllCR.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, threshold = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
cv2.drawContours(img, [contour], 0, (0, 0, 255), 5)
M = cv2.moments(contour)
if M["m00"] != 0.0:
x = int(M["m10"] / M["m00"])
y = int(M["m01"] / M["m00"])
if len(approx) == 3:
cv2.putText(
img, "Triangle", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2
)
elif len(approx) == 4:
height, width, _, _ = cv2.boundingRect(approx)
shape = "Rectangle" if height != width else "Square"
cv2.putText(
img,
shape,
(x, y),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(255, 255, 255),
2,
)
elif len(approx) == 5:
cv2.putText(
img, "Pentagon", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2
)
elif len(approx) == 6:
cv2.putText(
img, "Hexagon", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2
)
elif len(approx) < 14:
cv2.putText(
img, "ellipse", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2
)
else:
cv2.putText(
img, "circle", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2
)
cv2.imwrite("predictedShapes.png", img) |
dfc69a3eada7da7e5cad63646d52269f8303dc0b | Elephant333/Project-Euler | /p9-SpecialPythagoreanTriplet.py | 949 | 3.734375 | 4 | #Nathan Li - 3/11/2021 - P9: Special Pythagorean Triplet
import time
startTime = time.time()
flag = False
"""for a in range(1,999):
for b in range(a, 1000):
for c in range(b,1001):
if a**2 + b**2 == c**2:
if a+b+c == 1000:
print(a*b*c)
flag = True
break
if flag:
break
if flag:
break"""
#The above method was very slow, took 49.43 seconds, so I gave it a second try below
for a in range(1, 1000):
for b in range(1, 1000):
c = 1000-a-b #Problem says that sum of abc must by 1000, so we can avoid doing a third for loop by setting c equal to 1000-a-b
if a**2 + b**2 == c**2:
print(a*b*c)
flag = True
break
if flag:
break
#Much better! It got the right answer in just 0.13 seconds
endTime = time.time()
totalTime = endTime - startTime
print(totalTime) |
959b3a80152fa964739145d187f3ed4efcf73e18 | arnet95/Project-Euler | /euler297.py | 1,311 | 3.515625 | 4 | #Project Euler 297: Zeckendorf Representation
import time
fib_cache = {0: 1, 1: 1}
def fib(n):
if n in fib_cache:
return fib_cache[n]
else:
tmp = fib(n-1) + fib(n-2)
fib_cache[n] = tmp
return tmp
S_cache = {1: 0, 2: 1, 3: 2, 5: 5}
def S(n):
if n in S_cache:
return S_cache[n]
else:
i = 1
while fib(i) <= n:
i += 1
i -= 1
f = fib(i)
if f == n:
return 2 * S(fib(i-2)) + S(fib(i-3)) + fib(i-3) + fib(i-2)
else:
m = n - 1 - f
return S(f) + m + 1 + S(m+1)
def main(n):
i = 1
while fib(i) <= n:
S_cache[fib(i)] = S(fib(i))
i += 1
return S(n)
print main(10**17)
#There is one essential property of the Zeckendorf representation we need,
#which is that using a greedy algorithm is enough to find a number's Zeckendorf
#representation. (Meaning that we can always take the largest Fibonacci number
#not exceeding n as the first number in the Zeckendorf representation.)
#What this means, is that z(n) = 1 + z(f(n)) where f(n) is the largest Fibonacci
#number not exceeding n. If we let S(n) = sum(z(k) for k in xrange(1, n)), we can
#use this to write S(n) recursively. If n is a Fibonacci number, (say fib(i)), we
#have S(fib(i)) =
|
774c5b6528c921f08815b0065445fae948cf360a | safakhan413/interview-faangs | /codesignal/easy/isLucky.py | 561 | 3.9375 | 4 | # path: Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.
# Given a ticket number n, determine if it's lucky or not.
def isLucky(n):
newS = str(n)
lenN = len(newS)
halfLen = lenN // 2
print(lenN // 2)
sum1 = sum(int(n) for n in newS[:halfLen])
print(sum1)
sum2 = sum(int(n) for n in newS[halfLen:])
print(f'im sum2 {sum2}')
if sum1 == sum2:
return True
else:
return False
|
f9f85f8911132feacf62a656ad56b59451d76511 | sijanbhandari/captcha-solver-1 | /model/src/models/Network.py | 865 | 3.65625 | 4 | from torch import nn
class NeuralNetwork(nn.Module):
"""
Neural networ class. Contains a Stack with the different layers to be used.
The first layer size is fixed to the size of a digit image.
The output is fixed to 36. 26 letters and 10 digits.
"""
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Conv2d(1, 128, (3, 3)),
nn.ReLU(),
nn.AvgPool2d((3, 3)),
nn.Conv2d(128, 32, (3, 3)),
nn.ReLU(),
nn.Conv2d(32, 32, (3, 3)),
nn.ReLU(),
nn.Flatten(),
nn.Linear(320, 36),
)
def forward(self, x):
x = self.linear_relu_stack(x) # Pass the image into the ordered container of modules
return x
|
decc31eb60f4bba93e6099bb8e5933fa7f4ae852 | melany202/programaci-n-2020 | /clases/segundaclase.py | 455 | 3.96875 | 4 | nombre =input("Ingrese el nombre : ")
print ("Hola" , nombre, "eres bienvenido a este código")
edad = int(input("Por favor ingrese su edad : "))
estatura = float(input("Por favor ingrese su estatura : "))
print (edad)
print (estatura)
print (type(nombre))
print (type(edad))
print (type(estatura))
if (edad >= 18):
print ("Usted es mayor de edad")
if (estatura>1.70):
print("Hola eres muy alto")
print ("Chao!! que te vaya super bien") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.