blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
1d8e332c138f58671e4d84d1fd1bd138e1be260c | adityaramkumar/LeetCode | /589.py | 428 | 3.59375 | 4 | # Runtime: 124 ms, faster than 56.96% of Python online submissions for N-ary Tree Preorder Traversal.
# Difficulty: Easy
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
p_list = [root.val]
for child in root.children:
p_list.extend(self.preorder(child))
return p_list
|
3146090c54d237ba2d17d20780f447a5610a722d | adityaramkumar/LeetCode | /58.py | 298 | 3.71875 | 4 | # Runtime: 20 ms, faster than 99.23% of Python online submissions for Length of Last Word.
# Difficulty: Easy
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split()[-1]) if len(s.split()) > 0 else 0
|
fcb2d0b0cced1ec811c4f97be08ba07bc47453d4 | yuvraj1987/Acadgild_Assignment_2- | /.gitignore/Assignment2_list_Comphersion_nested_list.py | 984 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 16:27:42 2018
@author: jkdadhich
"""
Text = "acadgild"
Result = [x.upper() for x in Text] # Using Uppercase and iterate over character
Variable = "xyz"
# Mulitpy iteration with range
Result_1 = [ x*k for x in Variable for k in range(1,5)]
# mulitply range with iterator item
Result_2 = [ k*d for k in range(1,5) for d in Variable]
# Iteration over range creating list of list
Result_3 = [[i+j] for j in range(0,3) for i in range(2,5)]
# but as above change the input seq. as result
Result_4 = [[i+j for j in range(0,4)] for i in range(2,6)]
# nested loop over range store as outer as list inside as tuple
Result_5 = [(i,j) for j in range(1,4) for i in range(1,4)]
print ("~*~"*15)
print (Result)
print ("~*~"*15)
print (Result_1)
print ("~*~"*15)
print (Result_2)
print ("~*~"*15)
print (Result_3)
print ("~*~"*15)
print (Result_4)
print ("~*~"*15)
print (Result_5)
print ("~*~"*15)
|
4a17f972b166a9366ef4445409b707659fb8843f | abhineetmishra64/Algorithm | /python/sumevenfibo.py | 275 | 3.578125 | 4 | def evenfibo(limit):
if(limit<2):
return 0
ef1=0
ef2=2
sm=ef1+ef2
while(ef2<=limit):
ef3=4*ef2+ef1
if(ef3>limit):
break
ef1=ef2
ef2=ef3
sm=sm+ef2
return sm
limit=9
print(evenfibo(limit))
|
dc3416bc1ecc7f1546818662d475aa2fd7245194 | abhineetmishra64/Algorithm | /python/exam.py | 359 | 3.734375 | 4 | n=int(input("Enter no. of student: "))
std={}
for i in range(n):
info={}
info['name']=input("Enter name: ")
info['age']=int(input("Enter age: "))
info['marks']=int(input("Enter marks: "))
std[i]=info
print(std)
marks=[]
for i in range(n):
marks.append(std[i]['marks'])
print(sum(marks)/n)
ind=marks.index(max(marks))
print(std[ind])
|
102b3bd3f57932ce61c8eb3cacafb406d15929cd | to-besomeone/algorithm | /181009 - 2562.py | 197 | 3.734375 | 4 | arr = []
for i in range(9):
arr.append(int(input()))
maxValue = arr[0]
j = 0
for i in range(1, 9):
if arr[i] > maxValue :
maxValue = arr[i]
j = i
print(maxValue)
print(j+1) |
91c8697f3842b6adaf0481038f666f8c510d63a6 | to-besomeone/algorithm | /181111-2750_1.py | 314 | 3.59375 | 4 | N = int(input())
mat = [int(input()) for _ in range(N)]
for i in range(N-1, -1, -1): # for i in range(N-1):
for j in range(i): # for j in range(N-1):
if mat[j] > mat[j+1]:
tmp = mat[j]
mat[j] = mat[j+1]
mat[j+1] = tmp
for i in range(N):
print(mat[i]) |
5e6676fe294341190b98333567d7242eebb063a8 | pmillerschmidt/lockers | /https/docs.google.com/document/d/1puiqxz9kzwaWOi65MAb_kQtessXq86-zM4ITiX1Pd3k/lockers.py | 958 | 3.921875 | 4 | import random
from time import sleep
right = 0
i = 0
print("How many lockers and students are there?")
total_lockers = int(raw_input())
print("Cool! There are %d lockers and students" % total_lockers)
print("--------------")
sleep(1)
print("How many time do you want the program to run")
input = int(raw_input())
runs = (10 ** input)
print("Awesome! The program will run %d times" % runs)
sleep(0.1)
while i <= runs:
i = i + 1
population = range(1,(total_lockers + 1))
lockers2 = random.sample(population, (total_lockers - 1))
sumLocker = sum(lockers2)
sumPopulation = sum(population)
lastLocker = sumPopulation - sumLocker
if (lastLocker == total_lockers):
print("last student got his locker")
right = right + 1
else:
print("last student got a different locker")
accuracy = (float(right) / float(i)) * 100
accuracy = round(accuracy, 2)
print("-------------")
print(str(accuracy) + "%")
|
01c994d42749b26d6a32de3a6682a60f38ccc4eb | quantabox/hackerrank | /10-days-of-statistics/poisson_distribution_ii.py | 810 | 3.796875 | 4 | #!/usr/bin/env python
# Approach I
def fact(y):
if y <= 1:
return 1
return y*(fact(y-1))
poisson_random_variables = [float(x) for x in input().split()]
e = 2.71828
l_A = poisson_random_variables[0] # Machine A repair poisson random variable mean variance
l_B = poisson_random_variables[1] # Machine B repair poisson random variable mean variance
cost_A = 160 + 40 * (l_A + l_A**2)
cost_B = 128 + 40 * (l_B + l_B**2)
print("%.3f" % cost_A)
print("%.3f" % cost_B)
## Approach II
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def poisson(?, k):
return ? ** k * math.e ** (-?) / math.factorial(k)
def E(?):
return ? + ? ** 2
?1, ?2 = map(float, input().split())
print("{:.3f}".format(160 + 40 * E(?1)))
print("{:.3f}".format(128 + 40 * E(?2)))
|
2d425e371bd59c5a0ad3e6807a239378c5e44a12 | jiaoqiyuan/Tests | /Python/python-practice/chapter5-if/toppints.py | 1,428 | 4.25 | 4 | requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making you pizza!")
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers fight now.")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a pizza?")
avaliable_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in avaliable_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!") |
45246247635523f9d8a41c9402effce330e9c013 | jiaoqiyuan/Tests | /Python/python-practice/chapter4-uselist/animals.py | 180 | 3.984375 | 4 | animals = ['pig', 'chiken', 'tigger', 'bird', 'bull']
for animal in animals:
print("A dog would make a great pet " + animal)
print("Any of these animals would make a great pet!") |
1e3897dc264c6e7927e677227e6389f05dc7e062 | jiaoqiyuan/Tests | /Python/python-practice/chapter7-while/trival.py | 306 | 4.09375 | 4 | places = []
flag = True
while flag:
place = input("\nIf you could visit some places in the world, where would you go?\nEnter 'quit' to exit!")
if place == 'quit':
flag = False
else:
places.append(place)
print("\nYour places are: ")
for place in places:
print("\n" + place)
|
4be74b37275fdd68dac3287633b5001a4c6b357b | jiaoqiyuan/Tests | /Python/python-practice/chapter4-uselist/pisas.py | 458 | 4.0625 | 4 | pizzas = ['New-York-Style', 'Chicago-Style', 'California-Style', 'Pan-Pizza']
for pizza in pizzas:
print("I like pepperoni pizza " + pizza)
print("I like pizza very much, I really love pizza!")
friend_pizzas = pizzas[:]
pizzas.append('Take and Bake Style')
friend_pizzas.append('Stufffed')
print("My favorite pizza are:")
for pizza in pizzas:
print(pizza)
print("My friend's favorite pizzas are:")
for friend_pizza in friend_pizzas:
print(friend_pizza) |
59d7d9ba327ce1f559135bf000f5acb986578733 | Harishjm/Basic_Python | /Beark_Continue.py | 116 | 3.96875 | 4 | for i in range(0,9):
if(i%2==0):
continue ###break ###this is for printing odd numbersss
print(i) |
fef2bea17ffb60458cf22821fc4503494914b2ea | esselstyn/Homework_1 | /prime.Factor.py | 690 | 3.671875 | 4 | #!/usr/bin/env python
max = int(raw_input('Select the maximum value: '))
max = max + 1
#Make a list of all prime numbers between 1 and max
primes = []
for i in range(1, max):
x = 0
if i < 4:
primes.append(i)
else:
for j in range(2, i-1):
if i % j == 0:
x = 1
if x == 0:
primes.append(i)
##reduce the number to primes
for k in range(1, max):
if k in primes: ##if it is already a prime
answer = [k]
else:
z = 0
answer = []
for y in primes:
if y > 1:
while z not in primes:
if k % y == 0:
z = k / y
answer.append(y)
if z in primes:
answer.append(z)
break
else:
k = z
else:
break
print answer
|
4b65bba88943870e3121c6009e78563b8109ae5a | nagase2/nagaden | /module/CalcUtil.py | 960 | 3.546875 | 4 |
import datetime
def checkIfPastSpecificTimeInSec(lastTime, currentTime ,pastTimeInSec):
"""前に通知した時間よりも5分(5*60)以上たっているか判定する"""
#lastNotifiedTime =datetime.datetime(2017, 12, 28, 22, 5, 6, 620836)
#currentTime=datetime.datetime.now()
diff = currentTime-lastTime
print(diff.seconds)
if diff.seconds > pastTimeInSec:
return True
else:
return False
#return True
#print(dif.seconds)
#配列の中で今の温度よりも0.5度以上高いデータが無いか調べる
def checkIfHigerValueExist(tempArray, currentTemp):
if max(tempArray) >= currentTemp+0.5:
return True
else:
return False
#配列の中で今の温度よりも0.5度以上低いデータが無いか調べる
def checkIfLowerValueExist(tempArray, currentTemp):
if min(tempArray) <= currentTemp-0.5:
return True
else:
return False
|
48fc03d448664155dcc7edad585aea16e730618b | R0bertWell/estrutura-de-dados | /aula_01/meu_max.py | 663 | 3.78125 | 4 | from math import inf
from time import time
def meu_max(iteravel):
"""
Análise do algorítmo
Tempo de execução, algoritmo O(n)
Em memória O(1)
:param iteravel:
:return:
"""
max_num = -inf
for i in [1, 2, 3, 4, 5, 6]:
if i > max_num:
max_num = i
return max_num
if __name__ == '__main__':
print('Estudo experimental sobre o tempo de execução da função max:')
inicio = 10000000
for n in range(inicio, inicio * 20 + 1, inicio):
inicio = time()
meu_max(range(n))
fim = time()
tempo_de_exec = fim - inicio
print('*' * int(tempo_de_exec * 10), n)
|
971f92ebcde170ea9c198e1e5aba3b881427113b | shred2042/Forward-Space-Search | /FWD_Space_Search.py | 9,182 | 3.71875 | 4 | # returns true if the smaller set is included in the bigger set
def included(smaller, bigger):
for x in smaller:
if not x in bigger:
return False
return True
#taken from the lab
def NOT(P):
return "NOT_" + P
#main function
def makePlan(problemData):
problem = processInput(problemData)
answer = solveProblem(problem, problemData)
return answer
def solveProblem(problem, problemData):
graph = computeDistances(problemData["wormholes"], problemData["start"], "Sol")
answer = Search(problem, problem['initialState'], graph, [], 0, int(problemData["time"]))
return answer
def processInput(problemData):
Problem = {}
Problem['initialState'] = []
Problem['actions'] = {}
#initial state data
Problem['initialState'].append(("Fuel", 1))
Problem['initialState'].append(("Money", 0))
Problem['initialState'].append(("Empty", "StorageA"))
Problem['initialState'].append(("Empty", "StorageB"))
Problem['initialState'].append(("In", problemData["start"]))
#wormholes
for w in problemData["wormholes"]:
Problem['initialState'].append(("WormHole", w[0], w[1]))
Problem['actions'][("Jump", w[0], w[1])] = ([("In", w[0])], [("In", w[1]), (NOT("In"), w[0])])
Problem['actions'][("Jump", w[1], w[0])] = ([("In", w[1])], [("In", w[0]), (NOT("In"), w[1])])
#gas stations
for g in problemData["gas"]:
Problem['initialState'].append(("GasStation", g))
Problem['actions'][("BuyGas", g )] = ([("In", g)], [("Money", 0)])
#packages
for p in problemData["packages"]:
Problem['initialState'].append(("From", p[0] ,p[1]))
Problem['initialState'].append(("To", p[0], p[2]))
Problem['initialState'].append(("Reward", p[0] , p[3]))
Problem['actions'][("Pickup", p[0], "StorageA")] = ([("In", p[1]), ("Empty", "StorageA"), ("From", p[0], p[1])], [("Carries", "StorageA", p[0]), (NOT("Empty"), "StorageA"), (NOT("From"), p[0], p[1])])
Problem['actions'][("Pickup", p[0], "StorageB")] = ([("In", p[1]), ("Empty", "StorageB"), ("From", p[0], p[1])], [("Carries", "StorageB", p[0]), (NOT("Empty"), "StorageB"), (NOT("From"), p[0], p[1])])
Problem['actions'][("Deliver0", p[0])] = ([("In", p[2]), ("Carries", "StorageA", p[0]), ("To", p[0], p[2])], [(NOT("Carries"), "StorageA", p[0]), ("Empty", "StorageA"), (NOT("To"), p[0], p[2])])
Problem['actions'][("Deliver1", p[0])] = ([("In", p[2]), ("Carries", "StorageB", p[0]), ("To", p[0], p[2])], [(NOT("Carries"), "StorageB", p[0]), ("Empty", "StorageB"), (NOT("To"), p[0], p[2])])
#goal
Problem['goals'] = [("In", "Sol")]
return Problem
"""
This is basically a graph created by applying BFS starting from the goal system
"""
def computeDistances(edges, root, destination):
MAX_INT = 9999999
"""
Here we fill the graph with basic data
"""
graphNodes = {}
#Judging by the edges in the wormhole structure, find out the neighbours
for edge in edges:
if edge[0] not in graphNodes:
graphNodes[edge[0]] = {}
graphNodes[edge[0]]["neigh"] = []
graphNodes[edge[0]]["distance"] = MAX_INT
#Put the data for the first vertex in the neighbour list
graphNodes[edge[0]]["neigh"].append(edge[1])
if edge[1] not in graphNodes:
graphNodes[edge[1]] = {}
graphNodes[edge[1]]["neigh"] = []
graphNodes[edge[1]]["distance"] = MAX_INT
#Put the data for the second vertex in the neighbour list
graphNodes[edge[1]]["neigh"].append(edge[0])
#the BFS algorithm
queue = []
queue.append(destination)
distance = 0
graphNodes[destination]["distance"] = 0
while len(queue) != 0:
curNode = queue.pop(0)
distance = distance + 1
for neigh in graphNodes[curNode]["neigh"]:
if graphNodes[neigh]["distance"] == MAX_INT:
graphNodes[neigh]["distance"] = distance
queue.append(neigh)
return graphNodes
#forward space search algorithm
def Search(Problem, state, Graph, plan, time, LIMIT):
if time > LIMIT:
return False
currentState = state
currentPlan = plan
if included(Problem['goals'], currentState):
return currentPlan
validActions = getValidActions(currentState, Problem)
if validActions == {}:
return False
heuristicFunction = createHeuristicFunction(Problem, Graph, state, validActions)
heuristicFunction.sort(key=lambda x: x[1])
while len(validActions) != 0:
action = getAction(validActions, heuristicFunction)
nextState = getNextState(action, currentState)
currentPlan.append(format(action[0]))
if action[0][0] == 'JUMP':
answer = Search(Problem, nextState, Graph, currentPlan, time + 1, LIMIT)
else:
answer = Search(Problem, nextState, Graph, currentPlan, time, LIMIT)
#this path does not lead to a solution, backtrack
if answer == False:
del validActions[action[0]]
currentPlan.pop()
else:
return answer
return False
def format(action):
#differentiate the delivers
if action[0] == "Deliver0" or action[0] == "Deliver1":
ret = "Deliver("
else:
ret = action[0] + "("
#take all members of the action tuple except for the first one
for i in action[1:]:
ret = ret + str(i) + ","
#add the parantheses and remove the trailing comma
ret = ret[0:len(ret)-1] + ")"
return ret
def createHeuristicFunction(problem, graph, state, applicables):
heuristicFunction = []
for action in applicables:
if action[0] == 'JUMP':
setNo = 1
else:
setNo = 0
for preconditions in applicables[action][setNo]:
if preconditions[0] == "In":
strLocation = preconditions[1]
heuristicFunction.append((action, graph[strLocation]["distance"]))
break
return heuristicFunction
def getValidActions(currentState, Problem):
validActions = {}
for key, value in Problem['actions'].items():
preconditionsitions = value[0]
effects = value[1]
if key[0] == "Jump":
(newPreconditions, newEffects) = getJumpEffects(currentState)
if key[0] == "Deliver0" or key[0] == "Deliver1":
(newPreconditions, newEffects) = getDeliverEffects(currentState, key)
if key[0] == "Pickup":
(newPreconditions, newEffects) = ([], [])
if key[0] == "BuyGas":
(key, newPreconditions, newEffects) = getBuyGasEffects(currentState)
if newPreconditions == None:
continue
else:
if included(preconditionsitions + newPreconditions, currentState):
validActions[key] = (preconditionsitions + newPreconditions, effects + newEffects)
return validActions
def getJumpEffects(state):
for strFact in state:
if strFact[0] == "Fuel":
intValue = int(strFact[1])
if intValue != 0:
return ([strFact], [("Fuel", intValue - 1), (NOT("Fuel"), intValue)])
else:
return (None, None)
def getDeliverEffects(state, strKey):
strId = strKey[1]
tupReward = [fact for fact in state if fact[0] == "Reward" and fact[1] == strId][0]
intGain = int(tupReward[2])
for strFact in state:
if strFact[0] == "Money":
intValue = strFact[1]
preconditions = []
effects= []
preconditions.append(strFact)
effects.append((NOT("Money"), intValue))
intValue = intValue + intGain
effects.append(("Money", intValue))
return (preconditions, effects)
def getBuyGasEffects(state):
for strFact in state:
if strFact[0] == "Money":
intValue = strFact[1]
if intValue == 0:
return (None, None, None)
for strFact2 in state:
if strFact2[0] == "Fuel":
preconditions = []
effects= []
intValue2 = strFact2[1]
preconditions.append(strFact)
preconditions.append(strFact2)
effects.append((NOT("Money"), intValue))
effects.append(("Fuel", intValue + intValue2))
effects.append((NOT("Fuel"), intValue2))
key = ("BuyGas", intValue)
return (key, preconditions, effects)
def getAction(validActions, heuristicFunction):
for action in heuristicFunction:
if action[0] in validActions:
return (action[0], validActions[action[0]])
def getNextState(action, arrCurrState):
(preconditions, eff) = action[1]
newState = list(arrCurrState)
for e in eff:
if e[0][0:4] == "NOT_":
f = list(e)
f[0] = f[0][4:]
f = tuple(f)
if f in newState:
newState.remove(f)
else:
newState.append(e)
return newState
|
2a74b2bc17b8407ee6bdf8b060e89ce4d59bfe28 | collinskibetkenduiwa/UrlshortenerinPython | /ulshorner.py | 627 | 3.5625 | 4 | import pyperclip,pyshorteners
from tkinter import *
root=Tk()
root.geometry("400*200")
root.title("URL SHORENER")
def urlshortener():
urladdress=url.get()
url_short=pyshorteners.Shortener().tinyurl.short(urladdress)url_address.set(url_short)
def copyurl():
url_short=url
pyperclip.copy(url_short)
Label(root,Text="My URL shortner",font="poppins").pack(pady=10)
Entry(root,textvariable=url).pack(pady=5)
Button(root,text="Generate short URL",command=urlshortener()).pack(pady=7)
Entry(root,textvariable="url_address").pack(pady=5)
Button(root,text="Copy URL",command=copyurl).pack(pady=5)
root.mainloop()
|
248a5e497ca60c6f26a4a5958e537d5d06cc44f5 | steveding1/CS-1 | /task2.2-exer5.py | 403 | 4.03125 | 4 | #CS-1 Task 2.2 - Exercise 5 from Steve Ding
looping = True
while looping:
try:
celsius = float(input('\nEnter the Celsius temperature: '))
print ('Fahrenheit temperature is: ', (celsius*9/5+32))
ans1 = input('\ncontinue? y/n\n')
if ans1.upper() in ("NO", "N"):
looping = False
except ValueError:
print ("Man, learn to type a number.")
|
d145a98a8a7b5508c248d5163f1a066b8e04fa62 | steveding1/CS-1 | /task3.2-exer1.py | 199 | 4.03125 | 4 | pay = 0
hours = float(input('Enter Hours: '))
rate = float(input('Enter Rate: '))
if hours >40:
pay = 40*rate+(hours-40)*1.5*rate
else:
pay = hours*rate
print ('Pay: ', round(pay,2))
|
610962b96251fd0737edda69ef551c07eff2a598 | hdunlop310/small-projects | /gpa-calculator/calculator.py | 3,030 | 4.4375 | 4 | grades_vs_points = {'A1': 22, "A2": 21, 'A3': 20, 'A4': 19, 'A5': 18,
'B1': 17, 'B2': 16, 'B3': 15,
'C1': 14, 'C2': 13, 'C3': 12,
'D1': 11, 'D2': 10, 'D3': 9,
'E1': 8, 'E2': 7, 'E3': 6,
'F1': 5, 'F2': 4, 'F3': 3,
'G1': 2, 'G2': 1,
'H': 0}
def grade_validator():
valid_grade = False
while not valid_grade:
print("Invalid grade must be of the form A1-5, B1-3, C1-3, D1-3, E1-3, F1-3, G1-2, H")
grade = input('Enter your grade for course in the form A4, B3 etc...: ')
if grade in grades_vs_points:
valid_grade = True
return grade
def number_validator():
valid_number = False
while not valid_number:
print("Invalid entry - must be a number: ")
try:
number = int(input('Enter a valid number: '))
except ValueError:
number = number_validator()
valid_number = True
return number
def info(degree):
print('\x1B[3m GPA is calculated from all the courses you have completed in your degree course. - ', degree, '\n'
'Each grade is matched to a grade point, this is then multiplied by the credits that this course was worth \n'
'and then divided by the total number of credits that each course was worth')
print('ie. if you did 5 courses that were all worth 10 credits, and achieved an, \n'
'A4, B3, C2, B1, D2, then your GPA would be: \n'
'((22x10)+(15x10)+(13x10)+(17x10)+(10x10))/50 \n'
' = \033[1m 14.8 \033[0m \x1B[23m')
print()
def gpa_calculator():
degree = input("What is your degree subject? ")
info(degree)
grade_credits_dict = {}
try:
no_of_courses = int(input('How many ' + str(degree) + ' courses have you done over 1st and 2nd year? '))
except ValueError:
no_of_courses = number_validator()
print("Now for every course you have done, you will be asked to enter the grade you achieved and how many credits "
"that course was worth")
for counter in range(no_of_courses):
grade = input('Enter your grade for course in the form A4, B3 etc...: ')
if grade not in grades_vs_points:
grade = grade_validator(grades_vs_points)
try:
no_of_credits = int(input('Enter the amount of credits this course was worth: '))
print()
except ValueError:
no_of_credits = number_validator()
if grade in grade_credits_dict:
grade_credits_dict[grade] += no_of_credits
else:
grade_credits_dict[grade] = no_of_credits
grade_points = 0
total_no_of_credits = 0
for grade in grade_credits_dict.keys():
grade_points += grades_vs_points[grade] * grade_credits_dict[grade]
total_no_of_credits += grade_credits_dict[grade]
return grade_points / total_no_of_credits
print('Your GPA is: \033[1m', gpa_calculator(), '\033[0m')
|
fb2e5b02517723658017a75b6f743978d16aec12 | LeVeLoV1/GTC_Homeworks | /who_are_you_and_hello.py | 276 | 3.9375 | 4 | def who_are_you_and_hello():
y = True
x = input()
while y:
if x.isalpha() and x[0].istitle() and x[1:].islower():
y = False
else:
x = input()
print('Привет, ', x, '!', sep='')
who_are_you_and_hello()
|
01300e05d6763965061891651bfb312cc60fc95c | LeVeLoV1/GTC_Homeworks | /how_many_tens.py | 81 | 3.515625 | 4 | n = int(input())
q=0
m=1
while 5**m<n:
q += n//5**m
m += 1
print(q) |
2fbf06477ae032549d2a7b497d1689beed7f5a54 | LeVeLoV1/GTC_Homeworks | /Partial sums.py | 181 | 3.5625 | 4 | a = int(input())
def partial_sums(*a):
res = [0]
for i in range(len(a)):
res.append(res[i] + a[i])
return res
print(partial_sums(0, 1, 1.5, 1.75, 1.875)) |
6443be02fee53d170e239f51e5b940eff203d8b9 | mmaoga/bootcamp | /test.py | 269 | 3.578125 | 4 |
# for j in range (0, 10):
# # j += j
# print (j)
# # for friend in ["Mike", "Dennis", "Maoga"]:
# # invitation = "Hi "+friend+". Please come to my party on Saturday!"
# # print (invitation)
# i = 0
# while i < 10:
# i += 1
# print (i)
print ("Welcome") |
9fac6a0305889d4cdbe3bfa868aea21272314850 | mmaoga/bootcamp | /helloworld.py | 711 | 4.21875 | 4 | print ("hello, world")
print ("hi my name is Dennis Manyara")
print("This is my first code")
for _ in range(10):
print("Hello, World")
text = "Hello my world"
print(text)
text = "My name is Dennis Maoga Manyara"
print(text)
print("hello\n"*3)
name = "Dennis M."
print("Hello, World, This is your one and only",name)
print ('Hi {2}, {1} and {0}'.format ('Alice','Bob','Carol'))
print ('I love {1} more than {0}, how about you?'.format ('singing','coding'))
number = 1+2*3/4*5/5
print (number)
data = ("Alice", "Bob", "Carol")
date = ()
format_string = "Hi %s %s and %s."
print(format_string % data)
from datetime import date
today = date.today()
print ("Hi", name ,"today's date is", today)
x = 7
y = 0
print (x/y)
|
e264e005d7e618d6e875a582298169de37341a1f | ayub567/deep-learning-resources | /keras_xor.py | 936 | 3.734375 | 4 | #!/usr/bin/env python
"""Example of building a model to solve an XOR problem in Keras.
Running this example:
pip install keras
python keras_xor.py
"""
from __future__ import print_function
import keras
import numpy as np
# XOR data.
x = np.array([
[0, 1],
[1, 0],
[0, 0],
[1, 1],
])
y = np.array([
[1],
[1],
[0],
[0],
])
# Builds the model.
input_var = keras.layers.Input(shape=(2,), dtype='float32')
hidden = keras.layers.Dense(5, activation='tanh')(input_var)
hidden = keras.layers.Dense(5, activation='tanh')(hidden)
output_var = keras.layers.Dense(1, activation='sigmoid')(hidden)
# Create the model and compile it.
model = keras.models.Model([input_var], [output_var])
model.compile(loss='mean_squared_error', optimizer='sgd')
# Train the model.
model.fit([x], [y], nb_epoch=10000)
# Show the predictions.
preds = model.predict([x])
print(preds)
|
b710454eb9d28cb6220dfb6ba976506983673b21 | hyjoshi14/Hacking-Ciphers-With-Python | /Chp11.py | 3,164 | 4.3125 | 4 | ## Chapter 11 - Detecting English Programmatically""
from __future__ import division ## Similar to operator.truediv
import string, collections, os
os.chdir(r'C:\Users\Dell\Desktop\GithubRepo\Hacking Ciphers With Python')
## To detect if a message is in english, we check the percentage of characters and also
## the number of words in a message that are in english. An english dictionary and a string
## of english characters are required to achieve this.
## Create a string of characters
upper_case_letters = string.ascii_uppercase
letters_and_characters = ' '+upper_case_letters+upper_case_letters.lower()+'\t\n'
## Create an empty list to store the words in
words = []
messages = ["Robots are your friends. Except for RX-686. She will try to eat you.","&^%%hafybadf(())kkladfuan54","XXXXHello WorldXXXX",\
"***Hello World***"]
## Create a function to load the words from the dictionary into the empty list
def load_myDictionary():
"""Load dictionary with 354986 English Words"""
dictionary_file = open('EnglishDictionary.txt','r')
for word in dictionary_file.readlines():
words.append(word.replace('\n',''))
print 'Dictionary has been loaded'
print '\n'.join(words[:10])
def my_removeNonLetters(message):
"""Removes characters not in the "letters_and_characters" object"""
message = list(message)
message = filter(lambda x: x in letters_and_characters, message)
if len(message) == 0:
return 0
else:
return ''.join(message)
def my_EngCount(message):
"""Returns percentage of words in a message that are in English"""
message = my_removeNonLetters(message)
if message != 0:
message = message.lower()
message = message.split()
word_count = collections.Counter()
for word in message:
if word in words:
word_count.update([word])
count = sum([val for val in word_count.values()])
return count / len(message) * 100
else:
return 0
## Note: Default arguments here can be altered
def my_isEng(message, wordPerc = 20, letterPerc = 85):
"""Checks if a given message meets the threshold for wordPerc and letterPerc"""
wordPerc_message = my_EngCount(message)
cleaned_message = my_removeNonLetters(message)
letterPerc_message = len(cleaned_message) / len(message) * 100
if wordPerc_message >= wordPerc:
if letterPerc_message >= letterPerc:
print 'Message is in English.'
print 'Word Percentage: %d & Letter Percentage: %d' %(wordPerc_message,letterPerc_message)
return True
else:
print 'Message is not in English.'
print 'Word Percentage: %d & Letter Percentage: %d' %(wordPerc_message,letterPerc_message)
return False
else:
print 'Message is not in English.'
print 'Word Percentage: %d & Letter Percentage: %d' %(wordPerc_message,letterPerc_message)
return False
if __name__ == "__main__":
print os.listdir(os.getcwd())
load_myDictionary()## All words are in lower case
print my_removeNonLetters("ABCF23492)))(13123*&^")
for message in messages:
print
print message
print my_EngCount(message)
print my_removeNonLetters(message)
print my_isEng(message, letterPerc = 60)
print
|
25b5b499fa3f8c4198c2c57858c2c0b21b6a701d | gustav-gustav/Python-pokemon | /battle.py | 875 | 3.578125 | 4 | from trainer import Trainer
class Battle:
def __init__(self, trainer1, trainer2):
self.trainer1 = trainer1
self.trainer2 = trainer2
self.trainer1.in_battle = True
self.trainer2.in_battle = True
self.winner = None
self.main()
def main(self):
self.trainer1.active_pokemon = self.trainer1.party[0]
self.trainer2.active_pokemon = self.trainer1.party[0]
# while not self.winner:
# print(f"{self.trainer1} turn")
# eval(input('What will you do?\n'))
# print(f"{self.trainer2} turn")
# eval(input('What will you do?\n'))
def turn(self):
print(f"{self.trainer1} turn")
eval(input('What will you do?\n'))
if __name__ == '__main__':
Battle(Trainer('ash', 'charmander', level=5),
Trainer('gary', 'bulbasaur', level=5))
|
0c2107948d129a5638e15e286e3a3daee50ca793 | rawiwat/cs-module-project-hash-tables | /applications/word_count/word_count.py | 571 | 3.796875 | 4 | ignore = '":;,.-+=/\|[]{}()*^&'
def word_count(s):
# Your code here
result = {}
filtered_text = [
word.strip(ignore).lower()
for word in s.split()
if word.strip(ignore)
]
for text in filtered_text:
result[text] = result.get(text, 0) + 1
return result
if __name__ == "__main__":
print(word_count(""))
print(word_count("Hello"))
print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.'))
print(word_count('This is a test of the emergency broadcast network. This is only a test.'))
|
ac18a46a0d8af0c9178fb69369b311ae13ee21bf | ElenaDelgado/secretnumber | /numbereasy.py | 218 | 3.9375 | 4 | secret = 5
guess = int(raw_input("Guess the secret number (between 1 and 30): "))
if guess == secret:
print "Yes it is number 5!"
else:
print "Your guess is not correct... Secret number is not " + str(guess)
|
41d7eee44bf2c66cc465dd6160308221137a3da8 | jingwanha/algorithm-problems | /leetcode/771_easy.py | 460 | 3.5625 | 4 | # https://leetcode.com/problems/jewels-and-stones/
from collections import Counter
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
result = 0
cnt = Counter(stones)
for jewle in jewels:
result+=cnt[jewle]
return result
if __name__=='__main__':
jewels = "aA"
stones = "aAAbbbb"
sol = Solution()
result = sol.numJewelsInStones(jewels,stones)
print (result)
|
3783ffc32d99fa6ff6b91f617e634672609afb70 | jingwanha/algorithm-problems | /programers/K번쨰수.py | 314 | 3.5 | 4 | def solution(array, commands):
answer = []
for c in commands:
s_idx , e_idx , target_idx = c
answer.append(sorted(array[s_idx-1:e_idx])[target_idx-1])
return answer
array = [1, 5, 2, 6, 3, 7, 4]
commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
res = solution(array, commands)
print(res)
|
a9ce2df5e3ba5fef5b7d1ea6205b45e881608e08 | jingwanha/algorithm-problems | /leetcode/49_medium(1).py | 888 | 3.65625 | 4 | # https://leetcode.com/problems/group-anagrams/
from typing import List
class Solution:
# 첫 풀이 방법
# 수행시간이 n제곱이기 때문에 Time Limit Exceeded 에러 발생
# defaultdict를 이용하여 n 시간만에 풀이 가능
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = []
while strs:
word = strs.pop()
group = []
for s in strs:
if ''.join(sorted(s)) == ''.join(sorted(word)): # 문자열을 정렬하여 동일한지 비교
group.append(s)
if group:
for g in group : strs.remove(g)
group.append(word)
anagrams.append(group)
return anagrams
if __name__=='__main__':
strs = ["eat","tea","tan","ate","nat","bat"]
sol = Solution()
print(sol.groupAnagrams(strs)) |
415f650e2d1cc670b0ee9e8361488b6ee850d8f0 | jingwanha/algorithm-problems | /programers/주식가격_lv2.py | 610 | 3.625 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/42584
def solution(prices):
# 정답 초기화
answer = []
for i in range(len(prices), 0, -1): answer.append(i - 1)
# 인덱스가 저장될 임시 리스트
tmp = []
for i, cur_price in enumerate(prices):
while tmp and cur_price < prices[tmp[-1]]: # 가격이 떨어지면
last = tmp.pop()
answer[last] = i-last
tmp.append(i) # 가격이 떨이지지 않으면 해당 인덱스를 저장
return answer
if __name__ == '__main__':
prices = [5,4,3,2,1]
print (solution(prices)) |
a0716d4c67188d6e9e25e3e2220fa754fad57444 | NewmanJ1987/design_patterns_python | /creational/factory.py | 1,487 | 4.25 | 4 | # Factory pattern: Abstract away the creation of an object from the
# client that is creating object.
TWO_WHEEL_VEHICLE = 1
THREE_WHEEL_VEHICLE = 2
FOUR_WHEEL_VEHICLE = 3
class Vehicle():
def print_vechile(self):
pass
class TwoWheelVehicle(Vehicle):
def __init__(self):
super(TwoWheelVehicle, self).__init__()
def print_vechile(self):
print("Two Wheeler")
class FourWheelVehicle(Vehicle):
def __init__(self):
super(FourWheelVehicle, self).__init__()
def print_vechile(self):
print("Four Wheeler")
class ThreeWheelVehicle(Vehicle):
def __init__(self):
super(ThreeWheelVehicle, self).__init__()
def print_vechile(self):
print("Three Wheeler")
class VehicleFactory():
@staticmethod
def create_vehicle(vehicle_type):
# For a new vehicle we just modify the factory that is responsible for the creation.
if vehicle_type == TWO_WHEEL_VEHICLE:
return TwoWheelVehicle()
if vehicle_type == THREE_WHEEL_VEHICLE:
return ThreeWheelVehicle()
if vehicle_type == FOUR_WHEEL_VEHICLE:
return FourWheelVehicle()
class Client():
def __init__(self, vehicle_type):
# If we add a new vehicle we don't have to modify the code of the client. Which is an advantage when using a creational.
self.vehicle = VehicleFactory.create_vehicle(vehicle_type)
client = Client(TWO_WHEEL_VEHICLE)
client.vehicle.print_vechile()
|
4e26a4c5fd041c40188148825f8af7eed9861e1a | supreme-fiend/FiendNet | /Matrix.py | 2,494 | 3.828125 | 4 | """
Simple tool for matrix operations
"""
import numpy as np
def AdditionError (mat1, mat2):
print ("ADDITION ERROR !!")
print ("CANNOT ADD / SUBTRACT THESE TWO:")
print (mat1.matrix)
print (mat2.matrix)
def MultiplicationError (mat1, mat2):
print ("MULTIPLICATION ERROR !!")
print ("CANNOT MULTIPLY THESE TWO:")
print (mat1.matrix)
print (mat2.matrix)
def HadamardError (mat1, mat2):
print ("HADAMARD ERROR !!")
print ("CANNOT HADAMARD THESE TWO:")
print (mat1.matrix)
print (mat2.matrix)
class Matrix:
def __init__(self, numrows, numcols):
self.rows = numrows
self.cols = numcols
self.matrix = []
for i in range (self.rows):
row = []
for j in range (self.cols):
row.append(0)
self.matrix.append(row)
def set_values (self, mat):
for i in range (self.rows):
for j in range (self.cols):
self.matrix[i][j] = mat[i][j]
def transpose (self):
transmat = Matrix (self.cols, self.rows)
for i in range(self.rows):
for j in range(self.cols):
transmat.matrix[j][i] = self.matrix[i][j]
return transmat
def add (self, mat2):
addMat = Matrix(self.rows, self.cols)
if self.rows == mat2.rows and self.cols == mat2.cols:
for i in range (self.rows):
for j in range (self.cols):
addMat.matrix[i][j] = self.matrix[i][j] + mat2.matrix[i][j]
return addMat
else:
AdditionError(self, mat2)
exit()
def subtract (self, mat2):
subMat = Matrix(self.rows, self.cols)
if self.rows == mat2.rows and self.cols == mat2.cols:
for i in range (self.rows):
for j in range (self.cols):
subMat.matrix[i][j] = self.matrix[i][j] - mat2.matrix[i][j]
return subMat
else:
AdditionError(self, mat2)
exit()
def multiply (self, mat2):
mult = Matrix(self.rows, mat2.cols)
if self.cols == mat2.rows:
for i in range(len(self.matrix)):
for j in range(len(mat2.matrix[0])):
for k in range(len(mat2.matrix)):
mult.matrix[i][j] += self.matrix[i][k]*mat2.matrix[k][j]
return mult
else:
MultiplicationError(self, mat2)
exit()
def hadamard (self, mat2):
had = Matrix(self.rows, self.cols)
if self.rows == mat2.rows and self.cols == mat2.cols:
for i in range (self.rows):
for j in range(self.cols):
hadamard[i][j] = self.matrix[i][j]*mat2.matrix[i][j]
return had
else:
HadamardError(self, mat2)
exit()
|
cd6ebaf06897cfec8d7d1c33fa29090ce8c1e025 | MOULIES/DataStructures | /Merge_Output_Display.py | 999 | 3.515625 | 4 | # from .SingleLinkedList import SingleLinkedList
from Data_structure.SingleLinkeList.SingleLinkedList import SingleLinkedList
class Merge_Output_Print:
def __init__(self):
list1 = SingleLinkedList()
list2 = SingleLinkedList()
print('Create list1')
list1.create_list()
print('Create list2')
list2.create_list()
list1.bubble_sort_exdata()
list2.bubble_sort_exdata()
print('First List -'); list1.display_list()
print("Second list "); list2.display_list()
list3 = list1.merge1(list2)
print('Merge List - by creating new list'); list3.display_list()
print('First List -');list1.display_list()
print("Second list ");list2.display_list()
list3 = list1.merge2(list2)
print('Merge List - by rearranging link ');list3.display_list()
print('First List -');list1.display_list()
print("Second list ");list2.display_list()
|
3872a8cb98760e976a42f42993eb2011126c4516 | katewen/Python_Study | /study_1.py | 425 | 3.515625 | 4 | import re
from urllib.request import urlopen
from urllib.parse import urlencode
def getWithUrl(url):
res = urlopen(url)
def postWithUrl(url):
data = {'name': 'erik', "age": '25'}
s = urlencode(data)
res = urlopen(url, s.encode())
print(res.read().decode())
def getHTMLContent(url):
res = urlopen(url)
htmlText = res.read()
getWithUrl('http://www.baidu.com')
postWithUrl('http://www.baidu.com') |
27c2905d3bdec0938e06c6643aaf113e6c60d62e | felike/hello-world | /learn/python/cpu_test.py | 158 | 3.71875 | 4 | #! /usr/bin/python3
import datetime
print(datetime.datetime.now())
sum = 0
for i in range(1,100000000):
sum +=i
print(sum)
print(datetime.datetime.now())
|
1d16ee571e19b97631a9c7c1382c94aac004f1d8 | danielrwolff/Steganographic-Encryption-Program | /main.py | 2,276 | 3.8125 | 4 | from encrypt import Encryption
from decrypt import Decryption
from rawimage import RawImage
import os
def loadImage(filename) :
if os.path.isfile(filename) :
print "\tOpening", filename
images.append([RawImage(filename),filename])
else :
print "\tImage not found!"
print "====================================================="
print "| Welcome to the Steganographic Encryption Program! |"
print "====================================================="
print ""
print "> Type 'help' to get a list of commands."
print "> Type 'quit' to exit the program at any time."
print ">"
doQuit = False
images = []
while not doQuit :
switch = raw_input("> ").split()
if switch[0] == 'quit' : doQuit = True
elif switch[0] == 'help' :
print "\t'quit' -> Type to exit program."
print "\t'load' [FILENAME] -> Type to load an image."
print "\t'list' -> List the loaded image names."
print "\t'encrypt' [FILENAME] -> Type to encrypt text within an image of FILENAME."
print "\t'decrypt' [FILENAME] -> Type to decrypt text from an image of FILENAME."
elif switch[0] == 'load' :
loadImage(switch[1])
elif switch[0] == 'list' :
for i in images: print "\t",i[1]
elif switch[0] == 'encrypt' :
isLoaded = False
for i in images :
if switch[1] == i[1] :
isLoaded = True
print '\t' + i[1] + " found!"
Encryption(i[0]).encryptMessage(
raw_input("\tEnter the message to encrypt in the image: ")
)
print ""
loadImage(os.path.splitext(switch[1])[0] + "_encrypted" + os.path.splitext(switch[1])[1])
if not isLoaded : print "\tImage not loaded!"
elif switch[0] == 'decrypt' :
isLoaded = False
for i in images :
if switch[1] == i[1] :
isLoaded = True
print '\t' + i[1] + " found!"
print Decryption(i[0]).decryptMessage()
print ""
if not isLoaded : print "\tImage not loaded!"
print "> Thanks for using the Steganographic Encryption Program!"
|
d0420d342a14efe4e226617bda91bae05012e009 | dinnguyen1495/PythonSnakeGame | /snake_game_controller.py | 4,603 | 3.90625 | 4 | """
snake_game_controller.py
Snake game controller
"""
from tkinter import Tk, Canvas, Menu
from turtle import TurtleScreen, RawTurtle
from typing import Any
import time
from snakey import Snake
def get_move_function_from_key(snake: Snake, key: str) -> Any:
"""
Get function for snake's movement when key is pressed
:param snake:
Player's snake
:param key:
The pressed key, can only be 'w', 'a', 's', or 'd'
:return:
Move functions
"""
try:
move = snake.get_move_from_key(key)
if move == 1:
return snake.move_right
elif move == 2:
return snake.move_left
except ValueError:
return None
class GameController:
"""
Controller for the whole snake game
"""
def __init__(self, snake_block_size=25, speed=0.1, width_blocks=20, height_blocks=20):
"""
Initialize the controller
:param snake_block_size:
Size of a snake block in pixel. Default is 25
:param speed:
Speed of the snake. Default is 0.1, smaller number for greater speed
:param width_blocks:
Width of the board for snake to play around
:param height_blocks:
Height of the board for snake to play around
"""
self.snake_block_size = snake_block_size
self.width = (width_blocks + 1.5) * snake_block_size + (width_blocks - 1) * 2
self.height = (height_blocks + 1.5) * snake_block_size + (height_blocks - 1) * 2
self.width_range = int(width_blocks / 2)
self.height_range = int(height_blocks / 2)
self.speed = speed
self.window = Tk()
self.window.title("Simple Snake Game")
self.canvas = Canvas(self.window, width=self.width * 1.25, height=self.height * 1.25)
self.canvas.pack()
self.board = TurtleScreen(self.canvas)
self.menu_bar = Menu(self.window)
self.window.config(menu=self.menu_bar)
file_menu = Menu(self.menu_bar, tearoff=0)
file_menu.add_command(label="New Game (R)", command=self.start_snake_game)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.window.destroy)
self.menu_bar.add_cascade(label="Game", menu=file_menu)
def start_snake_game(self):
"""
UI for the snake game and its controller
"""
self.board.clear()
self.board.tracer(0)
border = RawTurtle(self.board)
border.penup()
border.setpos((-self.width_range - 1) * (self.snake_block_size + 2),
(self.height_range + 1) * (self.snake_block_size + 2))
border.pendown()
border.setpos((self.width_range + 1) * (self.snake_block_size + 2),
(self.height_range + 1) * (self.snake_block_size + 2))
border.setpos((self.width_range + 1) * (self.snake_block_size + 2),
(-self.height_range - 1) * (self.snake_block_size + 2))
border.setpos((-self.width_range - 1) * (self.snake_block_size + 2),
(-self.height_range - 1) * (self.snake_block_size + 2))
border.setpos((-self.width_range - 1) * (self.snake_block_size + 2),
(self.height_range + 1) * (self.snake_block_size + 2))
border.hideturtle()
snake = Snake(self.board, self.snake_block_size, self.width_range, self.height_range)
score = RawTurtle(self.board)
score.hideturtle()
score.penup()
score.setpos((-self.width_range - 2) * self.snake_block_size,
(self.height_range + 2) * self.snake_block_size)
self.board.listen()
while not snake.is_game_over():
score.clear()
score.write(f'Score: {snake.score}', False, align='left')
self.board.onkeypress(get_move_function_from_key(snake, 'w'), 'w')
self.board.onkeypress(get_move_function_from_key(snake, 'a'), 'a')
self.board.onkeypress(get_move_function_from_key(snake, 'd'), 'd')
self.board.onkeypress(get_move_function_from_key(snake, 's'), 's')
self.board.onkey(self.start_snake_game, 'r')
if not snake.key_pressed:
snake.move_forward()
else:
snake.key_pressed = False
self.board.update()
time.sleep(self.speed)
score.clear()
score.write(f'FINAL SCORE: {snake.score}. Press R to restart', False, align='left')
self.board.update()
self.board.mainloop()
self.window.mainloop()
|
ced1ba0dafae2c816b664e3c17225f1c6551d34c | behaoker/BBY162 | /uygulama03.py | 481 | 3.953125 | 4 | çeviriler={"Elma": "Apple", "Karpuz": "Watermelon", "Kavun": "Melon"}
Seçenekler="""
1: Anahtarları Gösterir.
2: Değerleri Gösterir.
3: Çıkış.
"""
while True:
print(Seçenekler)
işlem= input("Yapılacak İşlem:")
if işlem=="1":
print(çeviriler.keys())
elif işlem=="2":
print(çeviriler.values())
elif işlem=="3":
print("Program Sonlandırılıyor!..")
break
else:
print("HATA!") |
303fbdd2815a32d580ccd80192cd28da946a2865 | Tej-Singh-Rana/Code-War | /code3.py | 263 | 4.15625 | 4 | #!/bin/python3
#reverse !!
name=input("Enter the word you want to reverse : ")
print(name[::-1],end='') #to reverse infinite not adding value in parameters.
print('\n')
#print(name[4::-1],end='') #to reverse in max 4 index values.
#print('\n')
|
7251016b26478ec76ac2212da12d1893c6eb8182 | davidcphan/rebellion | /src/agent.py | 3,611 | 3.65625 | 4 | from turtle import Turtle
import config as cfg
import random
import functools as f
import math
# Represents an agent
class Agent(Turtle):
# Initialises all parameters of an agent
def __init__(self, x, y):
super().__init__(x, y)
# Agents are initially neutral
self.active = False # whether an agent is active
self.jailed_turns = 0 # how many turns is an agent jailed for
# Initialises local parameters uniformly at random
self.percieved_harship = random.uniform(0, 1)
self.risk_aversion = random.uniform(0, 1)
# multiplier used in exponential for calculating percieved risk
# set such that the probability of rebelling is approximately 0.9
# when C = 1 and A = 1
self.k = 2.3
# threshold for which grievence - percieved risk must exceed for an
# agent to go active. real number in [0,1]
self.threshold = 0.1
# Updates an agents state according to
# Movement rule B: Move to a random site within your vision
# Agent rule A: If grievence - net risk > threshold be active; else neutral
def update(self, grid):
# If an agent is jailed it cannot move
if not self.isJailed() and cfg.MOVEMENT:
self.move(grid)
self.determineBehaviour(grid)
else:
self.jailed_turns = self.jailed_turns - 1
# Calculates grievence as a function of percieved hardship and government
# legitimacy
def calculateGrievence(self, agents):
hardship = self.percieved_harship
# As per our first extension an agents hardship is affected by the
# hardship of other agents
if cfg.AVERAGE_HARDSHIP:
av_hardship = f.reduce(lambda acc, agent: \
agent.percieved_harship + acc, agents, 0) / len(agents)
hardship = (hardship + av_hardship) / 2
return hardship * (1 - cfg.GOVERNMENT_LEGITIMACY)
# Calculates net risk as a function of an agent's risk averseness and the
# probability of arrest.
def calculateNetRisk(self, num_actives, num_cops):
# Avoid divide by zero by counting yourself as active agent
num_actives = num_actives + 1
# Take the floor of (active agents / cops) as the netlogo model
# perscribes
arrest_probability = 1 - math.exp(-self.k \
* math.floor(num_cops / num_actives))
return self.risk_aversion * arrest_probability
# Updates the agents 'active' state according to
# Agent rule A: If grievence - net risk > threshold be active; else neutral
def determineBehaviour(self, grid):
active, neutral, cops = grid.searchNeighbourhood(self)
self.active = self.calculateGrievence(active+neutral) - \
self.calculateNetRisk(len(active), len(cops)) > self.threshold
# Jail an agent for some number of turns
def setJailed(self, turns):
self.jailed_turns = turns
if self.jailed_turns > 0:
self.active = False
# Returns whether an agent is active
def isActive(self):
return self.active
# Returns whether an agent is jailed
def isJailed(self):
return self.jailed_turns > 0
# Returns turtle type
def getType(self):
return cfg.Type.AGENT
# Color of agent
def color(self):
if self.isActive():
return cfg.Color.RED
elif self.isJailed():
return cfg.Color.BLACK
else:
return cfg.Color.GREEN
# String representation of agent
def __repr__(self):
return "A" |
d027f50503ad1e0ab782070bb1c4ccfb9941ead6 | changeAwei/homework | /P21016-叶春草/第四周/week4.py | 5,143 | 3.578125 | 4 | #!/usr/bin/env python
#coding=utf-8
'''
1. 什么是杨辉三角和转置矩阵(文字说明即可)?
2. 说明列表和Set集合的相同点和不同点。
3. 请写出Set集合支持的所有方法及说明(例如:add 向Set集合中添加一个元素)
4. 请写出字典支持的所有方法及说明(例如:pop 从字典中移除指定的key并返回其value)
5. 请写出Python内建函数及说明(参考:https://docs.python.org/3/library/functions.html)
'''
print('''
1、杨辉三角是指一个数字组成的等腰三角形,首尾是1,其他数字都是上一行两边数字之和。
转置矩阵是指将数字组成的矩阵,行、列互换。
2、列表与set集合的:
相同点:都是数据容器,可迭代,可修改
不同点:列表有序,能索引,能重复,在存储中占用连续空间
3、set支持的所有方法:
s.add() 添加元素入集合(如果已经存在则集合不改变)
s.clear() 清空集合
s.copy() 复制集合
s.difference(s1) 差集,在s中存在而不在s1中的集合
s.discard() 丢弃一个元素(元素不存在则不处理)
s.remove() 丢弃一个元素,元素必须存在
s.intersection() 交集,返回两个集合都存在的元素
s.intersection_update() 反正交集并修改自身
s.isdisjoint() 两集合无相同元素则返回True
set1.issubset(set2) set1是否是set2的子集
set1.issuperset(set2) set2是否是set1的子集
s.pop() 随机移除元素
s.symmetric_difference() 返回两个集合中不重复的元素集合
s.symmetric_difference_update() 修改成两个集合不不重复的元素集合
s.union() 并集
s.update() 给集合添加元素
4、字典支持的所有方法:
d.clear() 清空元素
d.copy() 复制字典
dict.fromkeys(iterable, value=None, /) 创建新字典,可迭代元素为key,value为字义的value
d.get(k[,d]) 获取k对应的value,无k则返回默认值d(无定义则是None)
d.items() 返回d的键值对
d.keys() 返回d的键
d.values() 返回d的值
d.pop(k[,d]) 移除一个k并返回v,如果k不存在时则返回d(如果d无设置则报错)
d3.popitem() 随机移除键值,如果为空则报错
d.setdefault(k[,d]) 跟get类似,如果不存在则会添加入字典
d1.update(d2) 把d2的键值更新至d1
5、常用的内建函数如下:
##类型转换或初始化:
set() 集合
dict() 字典
frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素
bin() 将其他进制转换成二进制
hex() 转换成十六进制的数字
oct() 转换成八进制
int() 将一个字符串或数字转换为整型
str() 转换成字符串
tuple() 元组
zip() 将对象中对应的元素打包成一个个元组
list() 列表
iter() 生成迭代器
type() 查看类型
format() 返回格式化后的字符串
##数值类
max() 查看最大值
min() 查看最小值
sum() 求和
float() 将整数和字符串转换成浮点数
range() 生成数字序列
sorted() 排序
round() 四舍六入五取偶
divmod() 返回商跟余数
##编码相关
bytes() 返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本
chr() 用一个整数作参数,返回一个对应的字符
compile() 将一个字符串编译为字节代码
##其他
all() 判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False
any() 判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。
hash() 计算哈希值
id() 查看内存地址
input() 在交互中取值
bool() 查看一个值的布尔值
help() 查看函数或模块用途的详细说明
isinstance() 判断类型
print() 打印
setattr() setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的。
open() 打开文件
globals() 以字典类型返回当前位置的全部全局变量
locals() 以字典类型返回当前位置的全部局部变量
callable() 判断是否可调用
len() 查看长度
next() 返回迭代器中的下一个值
slice() 切片取值
super() 转换成大写
vars() 返回对象object的属性和属性值的字典对象。
hasattr() 判断对象是否包含对应的属性
getattr() 用于返回一个对象属性值
property() 在新式类中返回属性值
enumerate() 用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中
eval() 执行shell命令
exec() 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码
bytearray() 返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。
filter() 过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换
map() 根据提供的函数对指定序列做映射。
reversed() 反转
''')
|
acbfbcc2bc6357c1319468fd1fdb7b9cf328e750 | changeAwei/homework | /P21061-韩道红/第四周作业/fourJob.py | 8,191 | 3.5625 | 4 | # 1. 什么是杨辉三角和转置矩阵(文字说明即可)?
"""杨辉三角是中国古代数学的杰出研究成果之一,它把二项式系数图形化,
把组合数内在的一些代数性质直观地从图形中体现出来,是一种离散型的数与形的结合"""
"""将矩阵的行列互换得到的新矩阵称为转置矩阵,转置矩阵的行列式不变"""
# 2. 说明列表和Set集合的相同点和不同点。
"""
列表使用有序的,set是无序的
列表的元素元素可以重复出现,set的元素不能重复,
set分为可变集合(set)和不可变集合(frozenset)两种,列表没有分类
list,set都是可以使用sort进行排序
list,set都是可迭代的
"""
# 3. 请写出Set集合支持的所有方法及说明(例如:add 向Set集合中添加一个元素)
"""
1.add() 向set中添加一个元素
2.update([]) 向set中条件多个元素值,参数为list,注意如果用add增加多个值,会报参数类型错误。
3.remove()用于删除一个set中的元素,这个值在set中必须存在,如果不存在的话,会引发KeyError错误。
4.discard()用于删除一个set中的元素,这个值不必一定存在,不存在的情况下删除也不会触发错误。
5.pop() 随机返回一个元素值,然后把这个值删除,如果set为空,调用这个函数会返回Key错误。
6.clear() 将set全部清空。
7.in 或者 not in 如果需要判断一个值在集合内是否存在,in就能满足要求,例如2 in set_num 如果存在则返回True,否则返回False.
8.s1.issubset(s2) 测试是否 s1 中的每一个元素都在 s2 中,运算符操作为 s1<=s2;
s2.issuperset(s1) 测试是否 s1 中的每一个元素都在 s2 中,运算符操作为 s1>=s2;//注意是s2调用,参数为s1.
9.union() 集合的并集运算
10.s1.difference(s2) 快速复制一个s1的元素到s2中
"""
# 4. 请写出字典支持的所有方法及说明(例如:pop 从字典中移除指定的key并返回其value)
"""
1.cmp() 比较两个字典的元素
2.len() 计算字典元素的个数
3.str() 把字典强制转换成字符串
4.clear() 清除字典里面的所有元素
5.copy() 返回一个字典的浅复制
6.get(key) 返回指定键的值,如果值不在字典中返回default值
7.has_key(key) 如果键在字典dict里返回true,否则返回false
8.items() 以列表返回可遍历的(键, 值) 元组数组
9.keys() 以列表返回一个字典所有的键
10.values() 以列表返回字典中的所有值
11.pop() 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12.popitem() 随机返回并删除字典中的一对键和值。
"""
# 5. 请写出Python内建函数及说明(参考:https://docs.python.org/3/library/functions.html)
"""
1.abs(x) 返回x(数字)的绝对值。
2.all() 用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
元素除了是 0、空、None、False 外都算 True。
3.any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。
元素除了是 0、空、FALSE 外都算 TRUE。
4.bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。bool 是 int 的子类。
print(issubclass(bool, int)) #打印True
5.bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
6.callable() 函数用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;
但如果返回 False,调用对象 object 绝对不会成功。
7.classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,
可以来调用类的属性,类的方法,实例化对象等。
8.cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。
9.compile() 函数将一个字符串编译为字节代码。
10.complex() 函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。
如果第一个参数为字符串,则不需要指定第二个参数。
11.dict() 函数用于创建一个字典。
12.eval() 函数用来执行一个字符串表达式,并返回表达式的值。
13.file() 函数用于创建一个 file 对象,它有一个别名叫 open(),
更形象一些,它们是内置函数。参数是以字符串的形式传递的。
14.filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,
然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
15.float() 函数用于将整数和字符串转换成浮点数。
16.format() 它增强了字符串格式化的功能。基本语法是通过 {} 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。
17.frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
18.getattr() 函数用于返回一个对象属性值。
19.globals() 函数会以字典类型返回当前位置的全部全局变量。
20.hash() 用于获取取一个对象(字符串或者数值等)的哈希值。
21.help() 函数用于查看函数或模块用途的详细说明。
22.hex() 函数用于将10进制整数转换成16进制,以字符串形式表示。
23.id() 函数用于获取对象的内存地址。
24.input() 函数接受一个标准输入数据,返回为 string 类型。
25.int() 函数用于将一个字符串或数字转换为整型。
26.isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。
27.issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类。
28.iter() 函数用来生成迭代器。
29.len() 方法返回对象(字符、列表、元组等)长度或项目个数。
30.list() 方法用于将元组转换为列表。
31.locals() 函数会以字典类型返回当前位置的全部局部变量。
32.long() 函数将数字或字符串转换为一个长整型。
33.map() 会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用
function 函数,返回包含每次 function 函数返回值的新列表。
34.max() 方法返回给定参数的最大值,参数可以为序列。
35.min() 方法返回给定参数的最小值,参数可以为序列。
36.next() 返回迭代器的下一个项目。
37.oct() 函数将一个整数转换成8进制字符串。
38.open() 函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。
39.pow() 方法返回 xy(x的y次方) 的值。
40.print() 方法用于打印输出,最常见的一个函数。
41.range() 函数可创建一个整数列表,一般用在 for 循环中。
42.reduce() 函数会对参数序列中元素进行累积
43.reload() 用于重新载入之前载入的模块
44.repr() 函数将对象转化为供解释器读取的形式。
45.reverse() 函数用于反向列表中元素。
46.round() 方法返回浮点数x的四舍五入值。
47.set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
48.slice() 函数实现切片对象,主要用在切片操作函数里的参数传递。
49.str() 函数将对象转化为适于人阅读的形式。
50.sum() 方法对系列进行求和计算。
51.super() 函数是用于调用父类(超类)的一个方法。
52.tuple() 函数将列表转换为元组。
53.type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。
54.unichr() 函数 和 chr()函数功能基本一样, 只不过是返回 unicode 的字符。
55.zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
"""
|
f2bea91cc4f1254d1d92e559661ca3f43ccde7d8 | changeAwei/homework | /P21061-韩道红/第三周作业/threeJob.py | 4,315 | 3.59375 | 4 | # 1. 说明列表的浅拷贝和深拷贝的区别
"""
浅拷贝: 通过copy模块里面的浅拷贝函数copy(),对指定的对象进行浅拷贝,浅拷贝会创建一个新的对象,
但是,对于对象中的元素,浅拷贝就只会使用原始元素的引用.
深拷贝: 通过copy模块里面的深拷贝函数deepcopy(),对指定的对象进行深拷贝,跟浅拷贝类似,
深拷贝也会创建一个新的对象,但是,对于对象中的元素,深拷贝都会重新生成一份,而不是简单的使用原始元素的引用
"""
# 2. 说明列表和元组的相同点和不同点
"""
1.列表属于可变序列,他的元素可以随时修改或删除;元组属于不可变序列,其中的元素不可以修改,除非整体替换。
2.列表可以使用append()、extend()、insert()、remove()、pop()等方法实现添加和修改列表元素,
而元组没有这几个方法,所以不能想元祖中添加和修改元素。同样,元组也不能删除元素。
3.列表可以使用切片访问和修改列表中的元素。元组也支持切片,但是他只支持通过切片访问元素,不支持修改。
4.元组比列表的访问和处理速度快,所以只是需要对其中的元素进行访问,而不进行任何修改时,建议使用元组。
5.列表不能为字典的键,而元组可以。
"""
# 3. 请写出字符串支持的所有方法及说明(例如: lower 返回字符串的小写)
"""
1.capitalize 把字符串第一个字母大写.
2.center(width) 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串.
3.count(str) 返回str在字符串中出现的个数.
4.decode 指定字符串的解码
5.encode 指定字符串的编码
6.endswith(obj) 指定字符串是否以obj结束
7.find(str) 检测 str 是否包含在字符串中,如果是返回第一个找到的索引值,否则返回 -1
8.format() 字符串格式化
9.index(str) 跟find()方法类似,但是如果str不存在字符串中,会报一个异常
10.isalnum 字符串字符是否全部是字母或全部是数字返回 True,否则返回 False
11.isalpnum 字符串是否包含数字很字母的混合返回True,否则返回False
12.isdecimal 字符串只包含十进制数字则返回 True 否则返回 False
13.isdigit 字符串只包含数字则返回 True 否则返回 False.
14.' '.join(seq) 以' '作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
15.lower 转换 string 中所有大写字符为小写.
16.lstrip 截掉 string 左边的空格
17.replace(str1, str2, num=string.count(str1)) 把字符串中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次
18.rfind 类似于 find()函数,不过是从右边开始查找.
19.rindex 类似于 index(),不过是从右边开始.
20.rstrip 删除 string 字符串末尾的空格.
21.split(str="", num=string.count(str)) 以 str 为分隔符切片字符串,如果 num 有指定值,则仅分隔 num+ 个子字符串
22.startswith(obj, beg=0,end=len(string)) 检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查.
23.swapcase 翻转 string 中的大小写
24.upper 转换字符串中的小写字母为大写
25.string[:10] 截取字符串
26.len(string) 计算字符串长度
"""
# 4. 使用选择排序算法实现排序[3, 5, 1, 7, 9, 6, 8]
the_list=[3, 5, 1, 7, 9, 6, 8]
i = 0
while i < len(the_list):
j = i+1
while j < len(the_list):
if the_list[i] > the_list[j]:
the_list[i], the_list[j] = the_list[j], the_list[i]
j = j+1
i = i+1
print(the_list)
# 5. 有如下一个字符串变量logs,请统计出每种请求类型的数量(提示:空格分割的第2列是请求类型),得到如下输出:
# POST 2
# GET 3
# 下边是logs变量:
logs = '''
111.30.144.7 "POST /mock/login/?t=GET HTTP/1.1" 200
111.30.144.7 "Get /mock/users/?t=POST HTTP/1.1" 200
111.13.100.92 "Post /mock/login/ HTTP/1.1" 200
223.88.60.88 "GET /mock/users/?t=POST HTTP/1.1" 200
111.30.144.7 "GET /mock/users/ HTTP/1.1" 200
'''
strs = logs.upper().strip().split('\n')
POST,GET = 0,0
for i in strs:
if i[:30].find('POST') != -1:
POST += 1
else:
GET += 1
print("POST: ",POST)
print("GET: ",GET)
|
ab044db0d35cebd0b559924ffbf134d7b6ab5637 | changeAwei/homework | /P21074-刘旭/homework-3/homework3.4.py | 463 | 3.5625 | 4 | # 4、使用选择排序算法实现排序[3, 5, 1, 7, 9, 6, 8]
nums = [3, 5, 1, 7, 9, 6, 8]
length = len(nums)
for i in range(length):
flag = False # 某一趟不用交换 就结束
for j in range(length-1-i):
if nums[j] > nums [j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
#nums[j],nums[j+1] = nums[j+1],nums[j]
flag = True
if not flag:
break
print(nums)
|
90f789b59d35d9564c24afc18bbf8db751aca155 | changeAwei/homework | /P21030-赵鑫/第八周/mycat.py | 839 | 3.8125 | 4 | #1. 使用本周和之前所学习的知识实现cat命令(支持查看内容和-n参数功能即可)
import argparse
class Mycat:
def __init__(self,file,number=False):
self.file = file
self.number = number
def filecontents(self):
with open(self.file) as f:
if self.number:
for i, line in enumerate(f):
print(i + 1, line, end='')
else:
for line in f:
print(line,end='')
parse = argparse.ArgumentParser(prog='cat',add_help=True,description='Display file contents')
parse.add_argument('file',nargs='?')
parse.add_argument('-n','-number',action='store_true',help='Number all lines of output starting with 1')
args = parse.parse_args('d:/tmp/123.txt -n'.split())
c = Mycat(args.file,args.n)
c.filecontents()
|
b489a3d700f36fce233503ea6bd352b44ffb099c | changeAwei/homework | /P21067-郝哲宇/第四周/第4周作业.py | 7,033 | 3.78125 | 4 | """
1. 什么是杨辉三角和转置矩阵(文字说明即可)?
杨辉三角的本质特征是:
他的俩条斜边有事由数值1组成,二其余的数则是等于他肩上的俩个数之和:
如果用二项式表示其推导式:
(a+b)^n
n=0 (a+b)^0 1 = 1
n=1 (a+b)^1 1 1 = 2
n=2 (a+b)^2 = a^2+2ab+b^2 1 2 1 = 4
n=3 (a+b)^3 = a^3+3a^2b+3ab^2+b^3 1 3 3 1 =8
n=4 (a+b)^4 = a^4+4a^3b+6a^2b^2+4ab^3+b^4 1 4 6 4 1 =16
转置矩形:
将矩阵的行列互换得到的新矩阵称为转置矩阵,转置矩阵的行列式不变。
例如:
m=[[1,2],[3,4],[5,6][7,8]] transfrom=[[1,3,5,7],[2,4,6,8]]
2. 说明列表和Set集合的相同点和不同点。
相同点:
它们都是容器,里边放置成员
不同点:
set的成员可以hash,list的成员不可hash
list的成员有索引,set的成员是无序的
3. 请写出Set集合支持的所有方法及说明(例如:add 向Set集合中添加一个元素)
s={"刘嘉玲","王祖贤","张曼玉"}
set的方法:
增加:
s.add("关之琳")
s.update(['王佳乐','田淑芬','郝英俊'])
删除:
s.pop() #随机跳出来一个
s.remove("王祖贤") #直接删除元素,没有会报错__KeyError
s.clear() #格式化这个set
修改: #应为集合中没有索引无法定义一个元素,修改只能是删除添加
s.remove("张曼玉") s.add("东方不败")
查询:
可以通过迭代的方式获取 for i in s: print(i)
set的运算:
s1 = {"刘嘉玲", "王祖贤", "张曼玉"}
s2 = {"姚贝娜","刘嘉玲"}
交集:print(s1&s2) print(s1.intersection(s2))
并集:print(s1|s2) print(s1.union(s2))
差集:print(s1-s2) print(s1.difference(s2))
反交集:print(s1 ^ s2) print(symmetric_difference(s2))
子集:print(s1<s2) print(s1.issubset(s2))
父集:print(s1>s2) print(s1.issuperset(s2))
4. 请写出字典支持的所有方法及说明(例如:pop 从字典中移除指定的key并返回其value)
字典(dict)是python中唯⼀的⼀个映射类型.他是以{ }括起来的键值对组成. 在dict中key是唯⼀的.在保存的时候, 根据key来计算出⼀个内存地址. 然后将key-value保存在这个地址中.
已知的可哈希(不可变)的数据类型: int, str, tuple, bool
不可哈希(可变)的数据类型: list, dict, set
dict的方法:
dic={}
增加:
dic['name']='张美玲'
dic['age']=18
dic.setdefault('王菲','歌手') #设置默认元素
删除:
print(dic.pop("王菲")) #删除对于的元素,并返回元素的值
print(dic.popitem()) #删除一个元素,范返回这个元素的k,v. 3.6默认删除最后一个(建议用第一种)
dic.clear() #格式化字典
改:
dic['王菲']='我女神' #给k重新赋值
dic.update({'age':18,'sex':'woman'}) #添加新的内容到字典中,有的话就覆盖
查:
print(dic['王菲']) #有k就返回,没有就报KeyError
dic.get("王菲") #有没有k都返回,不存在的k返回None
获取字典的健:
dic.keys()
获取字典的值:
dic.values()
获取字典的键值对:
dic.items()
5. 请写出内建函数及说明(参考:https://docs.python.org/3/library/functions.html)
abs() 取绝对值
delattr()与setattr() 删除一个对象的属性或方法和setattr() 相反
hash() 获取一个对象的hash值
memoryview() 返回给定参数的内存查看对象
set() 创建集合的的函数
all()与any() 判断一个可迭代对象,返回一个bool值any表示任意,all表示所有
dict() 创建字典的函数
help() 帮组函数
min()与max() 获取最小值 ,获取最大值
dir() 查看对象描述
hex() 进制转换(默认16进制)
next() 获取一个可迭代对象的下一个值(如获取生成器中yield值)
slice() 切片
ascii() 查看ascii编码
divmod() 取模
id() 查看内存地址
object() 默认的基类
sorted() 排序
bin() 将一个整数转换成二进制
enumerate() 枚举一个可迭代对象
input() 获取交互输入
oct() 转化成8进制
staticmethod() 在类中将一个方法转发成静态属性
bool() 判断一个对象的bool类型
eval() 执行一个字符串表达式,并返回表达式的值
int() 转化int类型
open() 打开一个文件默认‘r’
str() 转化str类型
breakpoint() 调试器3.7的新功能,没用过
exec() 执行代码
isinstance() 判断一个对象的类型
ord() 与chr() unicode编码
sum() 返回可迭代对象的累计求和值
bytearray() 字节数组(二进制,encode,decode)
filter() 过滤函数
issubclass() 判读是否是class的子类返回true
pow() 幂运算
super() 引用父类的属性
bytes() 返回字节码
float() 返回浮点数
iter() 返回一个迭代器对象 通过for I in iter(obj): 取值
print() 打印一个对象
tuple() 生成一个元组
callable() 判断参数是否可以调用
format() 格式化函数
len() 获取obj长度,实参可以是序列(如 string、bytes、tuple、list 或 range 等)或集合(如 dictionary、set 或 frozen set 等)
property() 获取class的方法
type() 获取对象类型
frozenset() 将一个新的可迭代对象变成一个不可变集合(tuple类型)
list() 创建一个列表
range() 返回一个不可变序列(tuple类型)
vars() 返回对象的描述信息__dict___
classmethod() 类方法
getattr() 获取class中传入的参数
locals()与globals() 本地 ,全局
repr() 转化为供解释器读取的形式
zip() 创建一个聚合了来自每个可迭代对象中的元素的迭代器。
compile() 将一个字符串编译为字节代码
map() 返回一个迭代器,将一个function和迭代器作为参数
reversed() 翻转
__import__() 没用过
complex() 返回一个复数
hasattr() 判断这个类中是否有这个方法或属性
round() 四舍五入
"""
|
d8a520b5d058f2bd006fd89bfc911de36c42d8e1 | changeAwei/homework | /P21062-刘庆归/第三周/4.sort.py | 211 | 3.671875 | 4 | lst = [3, 5, 1, 7, 9, 6, 8]
for i in range(len(lst)-1):
index = i
for j in range(i+1,len(lst)):
if lst[index] > lst[j]:
index = j
lst[i],lst[index] = lst[index],lst[i]
print(lst)
|
c434cacced85908bed62582a84614bd7b4f0b02d | DivyaKalash/Adams-Bashforth | /Adams_Bashforth/A_B.py | 2,727 | 3.640625 | 4 | import matplotlib.pyplot as plt
from tabulate import tabulate
from art import *
print(logo)
print("*" * 200)
def func(x, y):
"""
:return: returns function value by putting value of x and y.
"""
res = (1 + y)
return res
def predictor(y3, h, f3, f2, f1, f0):
"""
:return: returns predictor value by putting values in formula -> y3 + (h / 24) * ((55 * f3) - (59 * f2) + (37 * f1)
- (9 * f0))
"""
y4p = round(y3 + (h / 24) * ((55 * f3) - (59 * f2) + (37 * f1) - (9 * f0)), 4)
# y4p1 = round(y4p,4)
print(f"Predictor Value , y4p = {y4p}\n")
return y4p
def corrector(y3, h, f4p, f3, f2, f1):
"""
:return: returns corrector value by putting values in formula -> y3 + (h / 24) * ((9 * f4p) + (19 * f3) - (5 * f2)
+ f1)
"""
y4c = round(y3 + (h / 24) * ((9 * f4p) + (19 * f3) - (5 * f2) + f1), 4)
# y4c1 = round(y4c,4)
# print(f"Corrector Value, y4c = {y4c1}")
return y4c
# Taking User inputs
x0 = float(input("Enter Value of x0: "))
x1 = float(input("Enter Value of x1: "))
x2 = float(input("Enter Value of x2: "))
x3 = float(input("Enter Value of x3: "))
x4 = float(input("Enter Value of x4: "))
y0 = float(input("Enter Value of y0: "))
y1 = float(input("Enter Value of y1: "))
y2 = float(input("Enter Value of y2: "))
y3 = float(input("Enter Value of y3: "))
# Tabulating the given data.
data = [[x0, y0],
[x1, y1],
[x2, y2],
[x3, y3],
[x4, "?"]]
print("\nGiven Values in tabulated form: ")
print(tabulate(data, headers=["x", "y"]))
print(f"\nWe have to find y({x4})\n")
h = round((x1 - x0), 4)
print(f"Value of h i.e.(x1-x0) is: {h}\n")
f0 = round(func(x0, y0), 4)
print(f"f0 = {f0}")
f1 = round(func(x1, y1), 4)
print(f"f1 = {f1}")
f2 = round(func(x2, y2), 4)
print(f"f2 = {f2}")
f3 = round(func(x3, y3), 4)
print(f"f3 = {f3}\n")
y4p = predictor(y3, h, f3, f2, f1, f0)
f4p = round(func(x4, y4p), 4)
print(f"f4p1 = {f4p}")
y4c = corrector(y3, h, f4p, f3, f2, f1)
print(f"Corrector Value, y4c1 = {y4c}\n")
count = 2
# While loop to check previous corector value is not equal to current value.
while y4c != y4p:
y4p = y4c
f4p = round(func(x4, y4p), 4)
print(f"f4p{count} = {f4p}")
y4c = corrector(y3, h, f4p, f3, f2, f1)
print(f"Corrector Value, y4c{count} = {y4c}\n")
count += 1
print(f"\nAs y4c{count - 1} = y4c{count - 2}.Therefore, y({x4}) = {y4c}\n\n\n")
print(end)
# Graph Plotting of the given function.
x_axis = [x0, x1, x2, x3, x4]
y_axis = [y0, y1, y2, y3, y4c]
plt.plot(x_axis, y_axis)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("x-y graph of given function")
plt.show()
|
d55dbddcb5f571ff499e7dc5aefd1fb066fe83be | joshmi1902/PC2-2019-2 | /2.py | 884 | 3.65625 | 4 | import os
os.system("cls")
n = []
s = []
e = []
hombres = 0
mujeres = 0
#proceso
while len(n) < 5 and len (e) < 5 and len(s) < 5:
name = input("ingrese nombre: ")
n.append(name)
sexo = input("ingrese sexo: ")
if sexo == "masculino" or sexo == "femenino":
s.append(sexo)
if sexo == "masculino":
hombres += 1
if sexo == "femenino":
mujeres += 1
edad = int(input("ingrese edad: "))
if edad <=17 or edad >= 5:
e.append(edad)
else:
print("ingrese rango valido: ")
promedio = (e[0]+e[1]+e[2]+e[3]+ e[4])/5
print("*********LISTADO*******")
print("Nombre de los inscritos son: ", n)
print("Sexo de los inscritos: ", s)
print("Edad de los inscritos son: ", e)
print("Hay: " ,hombres, "hombres")
print("Hay: ", mujeres, "mujeres")
print("El promedio de edades es: ", promedio) |
0deae1c6773a018bef55d8e1bcbc5477eee7311c | yuuuhui/Basic-python-answers | /梁勇版_4.5rpy.py | 964 | 4.34375 | 4 | day = int(input("Enter today's day :"))
daye = int(input("Enter the number of days elaspsed since today:"))
dayf = day + daye
dayc = dayf % 7
print(dayc)
if day == 0:
print("Today is Sunday")
elif day == 1:
print("Today is Monday")
elif day == 2:
print("Today is Tuesday")
elif day == 3:
print("Today is Wednesday")
elif day == 4:
print("Today is Thursday")
elif day == 5:
print("Today is Friday")
elif day == 6:
print("Today is Saturday")
else:
print("Wrong input")
if dayc == 0:
print("The future day is Sunday")
elif dayc == 1:
print("The future day is Monday")
elif dayc == 2:
print("The future day is Tuesday")
elif dayc == 3:
print("The future day is Wednesday")
elif dayc == 4:
print("The future day is Thursday")
elif dayc == 5:
print("The future day is Friday")
elif dayc == 6:
print("The future day is Saturday")
else:
print("no else")
|
290b22fd0649a1009f8b03c8baa15abf28f5fc3e | yuuuhui/Basic-python-answers | /梁勇版_6.38.py | 303 | 3.609375 | 4 | import turtle
def turtlegoto(x,y):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
def drawline(x1,y1,x2,y2,color = "black",size = 1):
turtle.color(color)
turtle.pensize(size)
turtlegoto(x1,y1)
turtle.goto(x2,y2)
drawline(100,200,300,400)
|
1f0dec4bdd954b819dff92e4630ac144f8aa9989 | yuuuhui/Basic-python-answers | /梁勇版_4.24rpy.py | 5,483 | 3.96875 | 4 | ace = "Ace"
eleven = "Jack"
twelve = "Queen"
thirteen = "King"
c1 = "spades"
c2 = "Heart"
c3 = "diamonds"
c4 = "clubs"
import random
num = random.randint(1,14)
color = random.randint(1,4)
gsize = random.randint(0,1)
if num == 14:
if gsize == 0:
print("The card you picked is red King")
if gsize == 1:
print("The card you picked is black King")
else:
print("Error occured")
else:
if color == 1:
if num == 1:
print("The card you picked is {} of {}".format(ace,c1))
elif num == 2:
print("The card you picked is {} of {}".format(num,c1))
elif num == 3:
print("The card you picked is {} of {}".format(num,c1))
elif num == 4:
print("The card you picked is {} of {}".format(num,c1))
elif num == 5:
print("The card you picked is {} of {}".format(num,c1))
elif num == 6:
print("The card you picked is {} of {}".format(num,c1))
elif num == 7:
print("The card you picked is {} of {}".format(num,c1))
elif num == 8:
print("The card you picked is {} of {}".format(num,c1))
elif num == 9:
print("The card you picked is {} of {}".format(num,c1))
elif num == 10:
print("The card you picked is {} of {}".format(num,c1))
elif num == 11:
print("The card you picked is {} of {}".format(eleven,c1))
elif num == 12:
print("The card you picked is {} of {}".format(twelve,c1))
elif num == 13:
print("The card you picked is {} of {}".format(thirteen,c1))
elif color == 2:
if num == 1:
print("The card you picked is {} of {}".format(ace,c2))
elif num == 2:
print("The card you picked is {} of {}".format(num,c2))
elif num == 3:
print("The card you picked is {} of {}".format(num,c2))
elif num == 4:
print("The card you picked is {} of {}".format(num,c2))
elif num == 5:
print("The card you picked is {} of {}".format(num,c2))
elif num == 6:
print("The card you picked is {} of {}".format(num,c2))
elif num == 7:
print("The card you picked is {} of {}".format(num,c2))
elif num == 8:
print("The card you picked is {} of {}".format(num,c2))
elif num == 9:
print("The card you picked is {} of {}".format(num,c2))
elif num == 10:
print("The card you picked is {} of {}".format(num,c2))
elif num == 11:
print("The card you picked is {} of {}".format(eleven,c2))
elif num == 12:
print("The card you picked is {} of {}".format(twelve,c2))
elif num == 13:
print("The card you picked is {} of {}".format(thirteen,c2))
elif color == 3:
if num == 1:
print("The card you picked is {} of {}".format(ace,c3))
elif num == 2:
print("The card you picked is {} of {}".format(num,c3))
elif num == 3:
print("The card you picked is {} of {}".format(num,c3))
elif num == 4:
print("The card you picked is {} of {}".format(num,c3))
elif num == 5:
print("The card you picked is {} of {}".format(num,c3))
elif num == 6:
print("The card you picked is {} of {}".format(num,c3))
elif num == 7:
print("The card you picked is {} of {}".format(num,c3))
elif num == 8:
print("The card you picked is {} of {}".format(num,c3))
elif num == 9:
print("The card you picked is {} of {}".format(num,c3))
elif num == 10:
print("The card you picked is {} of {}".format(num,c3))
elif num == 11:
print("The card you picked is {} of {}".format(eleven,c3))
elif num == 12:
print("The card you picked is {} of {}".format(twelve,c3))
elif num == 13:
print("The card you picked is {} of {}".format(thirteen,c3))
elif color == 4:
if num == 1:
print("The card you picked is {} of {}".format(ace,c4))
elif num == 2:
print("The card you picked is {} of {}".format(num,c4))
elif num == 3:
print("The card you picked is {} of {}".format(num,c4))
elif num == 4:
print("The card you picked is {} of {}".format(num,c4))
elif num == 5:
print("The card you picked is {} of {}".format(num,c4))
elif num == 6:
print("The card you picked is {} of {}".format(num,c4))
elif num == 7:
print("The card you picked is {} of {}".format(num,c4))
elif num == 8:
print("The card you picked is {} of {}".format(num,c4))
elif num == 9:
print("The card you picked is {} of {}".format(num,c4))
elif num == 10:
print("The card you picked is {} of {}".format(num,c4))
elif num == 11:
print("The card you picked is {} of {}".format(eleven,c4))
elif num == 12:
print("The card you picked is {} of {}".format(twelve,c4))
elif num == 13:
print("The card you picked is {} of {}".format(thirteen,c4))
|
c9654b7176e0ca7f33a5329cd0b408a3d00bbf9c | yuuuhui/Basic-python-answers | /梁勇版_6.26.py | 804 | 4.09375 | 4 |
def isprime(z):
i = 2
divisor = 2
ispr = True
while divisor < z:
if z % divisor == 0:
ispr =False
else:
pass
divisor += 1
return ispr
def ismeiprime(x):
i = 2
isp = True
while 2 ** (i) - 1 <= x:
if (2 ** (i) - 1 )== x and isprime(x) == True and i <= 31:
isp = True
print(i,end = "\t")
print(2 ** (i) - 1,end = "\n")
break
else:
isp = False
i += 1
return isp
count = 0
y = 3
print("p \t 2^p -1")
while count < 31:
#ismeiprime(y)
if ismeiprime(y) == True :
count += 1
else:
pass
y += 1
|
c0ae04bcc6d3692e57532987778cecfa4d639334 | yuuuhui/Basic-python-answers | /梁勇版_5.4.py | 107 | 3.78125 | 4 | print("miles \t km")
for i in range(1,11):
km = i * 1.609
print("{} \t {:.3f}".format(i,km))
|
a79fd086a474a2f36a04ad9484f34c0dedd2f8d1 | yuuuhui/Basic-python-answers | /梁勇版_6.24.py | 763 | 3.859375 | 4 |
def isprime():
count = 0
i = 0
n = 1000
while i < n:
divisor = 2
isprimenumber = True
while divisor < i :
if i % divisor == 0:
isprimenumber = False
break
else:
pass
divisor += 1
i += 1
if isprimenumber == True and str(i)[::-1] == str(i):
print(i,end = "\t" )
count += 1
if count % 10 == 0:
print("\n")
while count >= 100:
break
else:
n += 1
isprime()
|
10b9b8c4daf1ea5730092711245e9bc4e2836deb | yuuuhui/Basic-python-answers | /梁勇版_6.39.py | 432 | 3.65625 | 4 | import turtle
def turtlegoto(x,y):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
def drawline(x1,y1,x2,y2,color = "black",size = 1):
turtle.color(color)
turtle.pensize(size)
turtlegoto(x1,y1)
turtle.goto(x2,y2)
def drawstar():
drawline(0,100,50,-150)
turtle.goto(-100,0)
turtle.goto(100,0)
turtle.goto(-50,-150)
turtle.goto(0,100)
drawstar()
|
78c1b55c46f5aad5e9361ee75feb79f3409e0743 | yuuuhui/Basic-python-answers | /梁勇版_1.9.py | 196 | 3.65625 | 4 | width = 4.5
height = 7.9
area = width * height
perimeter = 2 * ( width + height)
print("""
宽度为{}而高为{}的矩形面积为{},周长为{}
""".format(width,height,area,perimeter))
|
cf32a83c651d59598fd9708bf99266cb9d800cff | yuuuhui/Basic-python-answers | /梁勇版_2.14.py | 379 | 3.984375 | 4 | x1,y1,x2,y2,x3,y3 = eval(input("Enter three points for a triangle:"))
side1 = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
side2 = ((y3 - y2) ** 2 + (x3 - x2) ** 2) ** 0.5
side3 = ((x1 - x3) ** 2 + (y1 - y3) ** 2) ** 0.5
s = (side1 + side2 + side3) / 2
area = (s * (s - side1) * (s - side2) * (s - side3)) ** 0.5
print("the area of the triangle is {:.1f}".format(area))
|
e19e3398e3ad3667b4026be17f5a5c10eb26f1d8 | yuuuhui/Basic-python-answers | /梁勇版_4.7rpy.py | 620 | 3.78125 | 4 | amount = eval(input("Enter the amount:"))
remainingamount = int(amount * 100)
onedollar = remainingamount // 100
remainingamount = remainingamount % 100
quarters = remainingamount // 25
remainingamount = remainingamount % 25
dimes = remainingamount // 10
remainingamount = remainingamount % 10
nickles = remainingamount // 5
remainingamount = remainingamount % 5
pennies = remainingamount
print("Your amount",amount,"consists of\n",
"\t",onedollar,"dollars\n",
"\t",quarters,"quarters\n",
"\t",dimes,"dimes\n",
"\t",nickles,"nickles\n",
"\t",pennies,"pennies")
|
eb1e5ab98046948e5430c8fe9da76d0497ef0be7 | yuuuhui/Basic-python-answers | /梁勇版_4.11rpy.py | 1,308 | 3.96875 | 4 | #闰年和非闰年
year = int(input("Enter the year:"))
month = str(input("Enter the month:"))
if year < 0:
print("wrong input!")
elif year % 4 == 0 and month =="二月":
print("{}年{}月有29天".format(year,month))
else:
if month == "一月":
print("{}年{}份有31天".format(year,month))
elif month == "二月":
print("{}年{}份有28天".format(year,month))
elif month == "三月":
print("{}年{}份有31天".format(year,month))
elif month == "四月":
print("{}年{}份有30天".format(year,month))
elif month == "五月":
print("{}年{}份有31天".format(year,month))
elif month == "六月":
print("{}年{}份有30天".format(year,month))
elif month == "七月":
print("{}年{}份有31天".format(year,month))
elif month == "八月":
print("{}年{}份有31天".format(year,month))
elif month == "九月":
print("{}年{}份有30天".format(year,month))
elif month == "十月":
print("{}年{}份有31天".format(year,month))
elif month == "十一月":
print("{}年{}份有30天".format(year,month))
elif month == "十二月":
print("{}年{}份有31天".format(year,month))
else:
print("输入错误")
|
8057729bfad807fc5b23ed68b71e5746af7b26ee | yuuuhui/Basic-python-answers | /梁勇版_4.28rpy.py | 949 | 4.21875 | 4 | x1,y1,w1,h1 = eval(input("Enter r1's x-,y- coordinates,width,and height:"))
x2,y2,w2,h2 = eval(input("Enter r2's x-,y- coordinates,width,and height:"))
hd12 = abs(x2 - x1)
vd12 = abs(y2 - y1)
if 0 <= hd12 <= w1 /2 and 0 <= vd12 <= h1 / 2:
print("The coordinate of center of the 2nd rect is within the 1st rect")
if x1 == x2 and y1 == y2 and w1 == w2 and h1 == h2:
print("r2 overlaps completely with r1")
elif ((x2 + w2 / 2) > (x1 + w1 / 2)) or \
((x2 - w2 /2) < (x1 - w1 /2 )) or \
((y2 + h2 /2) > (y1 + h1 /2)) or \
((y2 - h2 /2) < (y1 - h1 /2)):
print("r2 overlaps with r1")
else:
print("r2 is inside r1")
else:
print("The coordinate of center of the 2nd rect is outside the 1st rect")
if hd12 <= (w1/2 + w2 /2) or vd12 <=(h1/2 + h2 /2 ):
print("r2 overlaps with r1")
else:
print("r2 is completely outside of r1")
|
98f0149fb41308f9e80baea2bb63055ebaf326f2 | yuuuhui/Basic-python-answers | /梁勇版_2.23py.py | 355 | 3.8125 | 4 | import turtle
r = int(input("Enter the radius:"))
turtle.showturtle()
turtle.circle(r)
turtle.penup()
turtle.goto(2 * r,0)
turtle.pendown()
turtle.circle(r)
turtle.penup()
turtle.goto(0,2 * r)
turtle.pendown()
turtle.circle(r)
turtle.penup()
turtle.goto(2 * r, 2 * r)
turtle.pendown()
turtle.circle(r)
turtle.done()
|
f22ac6d916ab358fb770e891bc9daa9044fb3ca1 | yuuuhui/Basic-python-answers | /梁勇版_5.46py.py | 264 | 3.875 | 4 | from math import *
xsquare = 0
sum = 0
numlist = []
for i in range(1,11):
num = eval(input("Enter ten numbers"))
xsquare += (num ** 2)
sum += num
mean = sum /10
sd = sqrt( ( xsquare - ((sum ** 2)/10) ) / (10 - 1))
print(mean,sd)
|
dfa4ad361b159743f8ecd2f3888e6e6e1420ed3d | yuuuhui/Basic-python-answers | /梁勇版_5.24py.py | 640 | 4.125 | 4 | loan = eval(input("Loan Amount"))
year = int(input("Number of Years:"))
rate = eval(input("Annual Interest Rate:"))
monthly = (loan * rate / 12) / (1 - 1 / ((1 + rate / 12) ** (year * 12)))
total = monthly * 12 * year
print("Monthly Payment:{:.2f}".format(monthly))
print("Total Payment:{:.2f}".format(total))
print("Payment# \t Interest \t Principal \t Balance")
count = 1
while count <= 12:
interest = loan * (rate / 12)
principal = monthly - interest
loan -= principal
print(count, "\t","\t","{:.2f}".format(interest), "\t\t","{:.2f}".format(principal),"\t","{:.2f}".format(loan))
count += 1
|
432d2e8a614fda318ec9242ce760fd13284de2cd | yuuuhui/Basic-python-answers | /梁勇版_6.34.py | 254 | 4.03125 | 4 | from math import *
n = eval(input("Enter the number of sides:"))
s = eval(input("Enter the side:"))
def area(n,s):
area = (n * (s ** 2)) / (4 * tan(pi / n))
print("The area of the polygon is {:.2f}".format(area))
area(n,s)
|
3a72bb27f435bd2bd4c9ab1df26fa671e5eb2263 | MalachiBlackburn/cti110new | /P2T1_SalesPrediciton_MalachiBlackburn.py | 345 | 3.890625 | 4 | #This program will convert pounds to kilograms
#2/12/19
#CTI-110 P2T1 - Sales Prediction
#Malachi Blackburn
#Gets the projected total sales
total_sales = float(input("Enter the projected sales: "))
#Calculates the profit as 23 percent of total sales
profit = total_sales * .23
#Display the profit
print("The profit is $", format(profit, ",.2f"))
|
7b156440fe82f681be466327acc244b6f980e637 | JamesMsuya/algorithms. | /maximum_cost_141044093.py | 1,690 | 3.5625 | 4 | """
This algorithm keeps tracks of two local defined list. For every i'th number in an list Y two assumtions are made
that is is itself or 1. The subsequent sums of when it is 1 or itself are kept in two list lis and li respectively.
The list lis[] and li[] are initialized to 0 assuming previous sum is 0.
lis[i] = The maximum i'th cost when X[i]= 1 which can be when i'th number 1 - 1 + previous sum lis[i-1](assuming in list X[i-1]=1) or
abs(1-X[i-1]) + li[i-1](assuming X[i]=1 and X[i-1]=Y[i-1]) and likewise
li[i] = The maximum i'th cost when X[i]= Y[i] which can be when i'th number X[i] - 1 + previous sum lis[i-1](assuming in list X[i-1]=1) or
abs(X[i]-X[i-1]) + li[i-1](assuming X[i]=Y[i] and X[i-1]=Y[i-1]) so this adds the elements in lis and li subsequently until
n'th position. So the maximum cost will be maximum value between li[n] or lis[n].
In all the cases it does addition N times in all the two list it keeps. So in worst case the algorithm is O(n).
"""
def find_maximum_cost(Y):
lis ,li =[0],[0]
for i in range(1,len(Y),1):
lis.append(max(lis[i-1],abs(Y[i-1]-1)+li[i-1]))
li.append(max(abs(Y[i]-1)+lis[i-1],abs(Y[i]-Y[i-1])+li[i-1]))
return max(lis[len(Y)-1],li[len(Y)-1])
Y = [14,1,14,1,14]
cost = find_maximum_cost(Y)
print(cost) #Output: 52
Y = [1,9,11,7,3]
cost = find_maximum_cost(Y)
print(cost) #Output: 28
Y = [50,28,1,1,13,7]
cost = find_maximum_cost(Y)
print(cost) #Output: 78
Z=[80, 22, 45, 11, 67, 67, 74, 91, 4, 35, 34, 65, 80, 21, 95, 1, 52, 25, 31, 2, 53]
print(find_maximum_cost(Z)) #output: 1107
Z=[79, 6 ,40, 68, 68, 16, 40, 63, 93, 49, 91]
print(find_maximum_cost(Z)) #output: 642
|
c51001c9f85d970cba0d7e06757e021919ec132e | joseluisvzg/EnvioClickChallenge | /Python/Exercise2.py | 415 | 4.34375 | 4 | #!/usr/bin/env python
consec_vowel = {
'a': 'e',
'e': 'i',
'i': 'o',
'o': 'u',
'u': 'a'
}
def vowels_changer(text):
new_text = []
for char in text.lower():
if char in consec_vowel:
char = consec_vowel[char]
new_text.append(char)
new_text = ''.join(new_text)
return new_text
if __name__ == "__main__":
text = input("Type a text: ")
new_text = vowels_changer(text)
print(f"New text: {new_text}") |
90306e40508ccd4f94c0cc690c3df9b3be41f639 | ensardemirci/BTKAkademi | /20 - Pandas/20.13 - Uygulama Nba Veri analizi.py | 920 | 3.609375 | 4 | import pandas as pd
df = pd.read_csv('20 - Pandas/Datasets/nba.csv')
# 1
result = df.head(10)
# 2
result = len(df.index)
# 3
result = df['Salary'].mean()
# 4
result = df['Salary'].max()
# 5
result = df[['Name','Salary']].sort_values('Salary', ascending=False).head(1)
# 6
result = df.query('20 <= Age < 25 ')[['Name','Team','Age']].sort_values('Age', ascending=False)
# 7
result = df.query('Name == "John Holland" ')['Team']
# 8
result = df.pivot_table(columns='Team', values='Salary').mean() # alternatif
result = df.groupby('Team').mean()['Salary']
# 9
result = df['Team'].nunique()
# 10
result = df.groupby('Team')['Name'].nunique() # Alternatif
result = df['Team'].value_counts()
# 11
df.dropna(inplace= True)
result = df['Name'].str.contains('and')
result = df[result]
def str_find(name): #Altrenatif
if 'and' in name.lower():
return True
return False
print(df[df['Name'].apply(str_find)]) |
135001be71705edc93df8521017c2968145f29d1 | wdj729115299/python_study_test | /hello_word2.py | 508 | 3.90625 | 4 | shoplist = ['apple', 'orange', 'banana', 'carrot']
print 'I have ', len(shoplist), ' items to purchase.'
print 'these items are:'
for item in shoplist:
print item,
print 'I alse have to buy rice'
shoplist.append('rice')
print 'these items are:'
for item in shoplist:
print item,
print 'I will sort my list'
shoplist.sort()
print 'these items are:'
for item in shoplist:
print item,
print '\n'
print 'fist item is'
print shoplist[0]
del shoplist[0]
print 'first item is'
print shoplist[0]
|
91c7ac1b5cb702cb02409c47af289d7229f58261 | huiqi2100/searchingsorting | /bubblesort.py | 288 | 4.03125 | 4 | # bubblesort.py
def bubblesort(array):
swapped = True
while swapped:
swapped = False
for i in range(1, len(array)):
if array[i-1] > array[i]:
array[i-1], array[i] = array[i], array[i-1]
swapped = True
return array
|
689936f0132a848679cc145a305f6594427e038d | UccelloLibero/Python_code_challenges | /list_challenges.py | 4,996 | 4.28125 | 4 | # 1.
# Create a function named double_index that has two parameters named lst and index.
# The function should return a new list where all elements are the same as in lst except for the element at index, which should be double the value of the element at index of lst.
# If index is not a valid index, the function should return the original list.
# Example: double_index([1, 2, 3, 4] 1) will return [1, 4, 3, 4] because the number at the index 1 was doubled
def double_index(lst, index):
if index >= len(lst):
return lst
else:
lst[index] = lst[index] * 2
return lst
# test the function
print(double_index([2, 1, -5, 12], 2))
# 2.
# Create a function named remove_middle which has three parameters named lst, start, and end.
# The function should return a list where all elements in lst with an index between start and end (inclusive) have been removed.
# Example: remove_middle([1, 2, 3, 4, 5, 6, 7], 1, 5) returns [1, 7] because indices 1,2,3,4,5 have been removed
def remove_middle(lst, start, end):
first_half = lst[:start]
second_half = lst[end+1:]
return first_half + second_half
# test the function
print(remove_middle([5, 11, 25, 17, 100, -99], 1, 3))
# 3.
# Create a function named more_than_n that has three parameters named lst, item, and n.
# The function should return True if item appears in the list more than n times. The function should return False otherwise.
def more_than_n(lst, item, n):
if lst.count(item) > n:
return True
else:
return False
#test the function
print(more_than_n([2, 5, 6, 1, 3, 5, 3, 2], 5, 3)) # returns False
# 4.
# Create a function named more_frequent_item that has three parameters named lst, item1, and item2.
# Return either item1 or item2 depending on which item appears more often in lst.
# If the two items appear the same number of times, return item1.
def more_frequent_item(lst, item1, item2):
if lst.count(item1) > lst.count(item2):
return item1
elif lst.count(item1) < lst.count(item2):
return item2
elif lst.count(item1) == lst.count(item2):
return item1
# test the function
print(more_frequent_item([2, 7, 1, 11, 9, 7, 7, 7, 11], 7, 11)) # output is 7
# 5.
# Create a function called middle_element that has one parameter named lst.
# If there are an odd number of elements in lst, the function should return the middle element. If there are an even number of elements, the function should return the average of the middle two elements.
def middle_element(lst):
if (len(lst) % 2) != 0:
return lst[((len(lst) - 1) // 2)]
elif (len(lst) % 2) == 0:
return (lst[len(lst) // 2] + lst[(len(lst) // 2) - 1]) / 2
# test the function
print(middle_element([5, 2, -10, -4, 4, 5])) # output -7
# 6.
# Write a function named append_sum that has one parameter named lst.s
# The function should add the last two elements of lst together and append the result to lst. It should do this process three times and then return lst.
def last_two_added(lst):
return lst[-1] + lst[-2]
def append_sum(lst):
lst.append(last_two_added(lst))
lst.append(last_two_added(lst))
lst.append(last_two_added(lst))
return lst
# test the function
print(append_sum([2, 4, 5])) # output will be [2, 4, 5, 9, 14, 23]
# 7.
# Write a function named larger_list that has two parameters named lst1 and lst2.
# The function should return the last element of the list that contains more elements. If both lists are the same size, then return the last element of lst1.
def larger_list(lst1, lst2):
if len(lst1) > len(lst2):
return lst1[-1]
elif len(lst1) < len(lst2):
return lst2[-1]
elif len(lst1) == len(lst2):
return lst1[-1]
# test the function
print(larger_list([4, 10, 2, 5], [-10, 2, 5, 10])) # output will be 5
# 8.
# Write a function named combine_sort that has two parameters named lst1 and lst2.
# The function should combine these two lists into one new list and sort the result. Return the new sorted list.
def combine_sort(lst1, lst2):
combo_list = lst1 + lst2
combo_list.sort()
return combo_list
# test the function
print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10])) # output will be [-10, 2, 2, 4, 5, 5, 10, 10]
# 9.
# Create a function called append_size that has one parameter named lst.
# The function should append the size of lst (inclusive) to the end of lst. The function should then return this new list.
def append_size(lst):
size = len(lst)
lst.append(size)
return lst
# test the function
print(append_size([4, 3, 2, 1])) # output will be [4, 3, 2, 1 ,4]
# 10.
# Create a function called every_three_nums that has one parameter named start.
# The function should return a list of every third number between start and 100 (inclusive).
def every_three_nums(start):
lst = list(range(start, 100, 3))
if start > 100:
lst = []
return lst
else:
return lst + [100]
# test the function
print(every_three_nums(50)) # output will be [50, 53, 56, 59, 62, 65, 68, 71, 74, 77, 80, 83, 86, 89, 92, 95, 98, 100]
|
e542f971074e637d708f209bb1be1237e97e59fb | belogurow/BMSTU_IU9 | /Bioinformatics/Lab2/Util.py | 274 | 3.65625 | 4 | def print_sequences(seq_1: str, seq_2: str):
sequence_len = len(seq_1)
start = 0
step = 80
end = start + step
while start < sequence_len:
print(seq_1[start:end])
print("|" * len(seq_1[start:end]))
print(seq_2[start:end])
print()
start += step
end += step |
94544d5793f5356e6a195efd153f4ae268426c22 | Sarumathikitty/guvi | /codekata/Array/print_ele_less_des_order.py | 254 | 3.84375 | 4 | #print all elements lesser than n in descending order
def function(N,n):
a=[]
for i in range(len(n)):
if(n[i]<N):
a.append(n[i])
a.reverse()
return(a)
N=int(input())
n=list(map(int,input().split()))
c=function(N,n)
print(*c)
|
ebacaa22aa8623a063016865b8faa790bb4d359a | Sarumathikitty/guvi | /codekata/Strings/find_len_str.py | 91 | 3.890625 | 4 | #Given a string find its length
n=str(input())
count=0
for i in n:
count+=1
print(count)
|
c281900a2efc288a4eb5e00b3b8bf0cb35dc6fe0 | Sarumathikitty/guvi | /codekata/Array/print_suffix_sum.py | 229 | 3.734375 | 4 | #Given a number print suffix sum of the array
def function(N,s):
sum,a=0,[]
for i in range(N):
sum=s[i]+sum
a.append(sum)
a.reverse()
return(a)
N=int(input())
s=list(map(int,input().split()))
c=function(N,s)
print(*c)
|
a68591df5fbf05b2b660b51d5991e7a5987842af | Sarumathikitty/guvi | /codekata/Mathematics/print_mod_c.py | 81 | 3.53125 | 4 | #Given a number print a*b mod c
a,b,c=map(int,input().split())
d=a*b
print(d%c)
|
3728c371427f3c1619302da9945650f66a453c33 | Sarumathikitty/guvi | /codekata/Basics/scalene_triangle.py | 259 | 3.828125 | 4 | #Given 3 numbers form a scalene triangle
def checkvalid(a,b,c):
if((a!=b) and (b!=c) and (a!=c)):
return True
else:
return False
a,b,c=map(int,input().split())
if checkvalid(a,b,c):
print("yes")
else:
print("no")
|
1e1b9210ab2b9a6f177149adeb043ec0a9da3576 | Sarumathikitty/guvi | /codekata/Strings/remove_char.py | 105 | 3.875 | 4 | #Given a string remove characters which are present in another string
s=str(input())
print(s+" Answer")
|
246dd56dd9d9b2a217a93a26949d9bed5fa69020 | Sarumathikitty/guvi | /codekata/Mathematics/print_a_pow_b.py | 94 | 3.640625 | 4 | #Given numbers A,B find A power of B
A,B=map(int,input().split())
res=A**B
print(res)
|
e174013d66f9135fd27ed24b666eff412b3f49c3 | Sarumathikitty/guvi | /codekata/Absolute_Beginner/check_odd_even.py | 264 | 4.5 | 4 | #program to check number whether its odd or even.
number=float(input())
num=round(number)
#check number whether it is zero
if(num==0):
print("Zero")
#whether the number is not zero check its odd or even
elif(num%2==0):
print("Even")
else:
print("Odd")
|
ce7593b19ffef271972cf5d3c8f1ae164c462832 | yaxinn/codingground | /New Project/maxmin.py | 3,363 | 3.703125 | 4 | import collections
class maxQueue():
def __init__(self):
self.size = 0
self.q = collections.deque()
self.mq = collections.deque()
def push(self, num):
while self.mq and self.mq[-1] < num:
self.mq.pop()
self.mq.append(num)
self.q.append(num)
self.size += 1
def pop(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
r = self.q.popleft()
if r == self.mq[0]: self.mq.popleft()
self.size -= 1
return r
def max(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
return self.mq[0]
class minQueue():
def __init__(self):
self.size = 0
self.q = collections.deque()
self.mq = collections.deque()
def push(self, num):
while self.mq and self.mq[-1] > num:
self.mq.pop()
self.mq.append(num)
self.q.append(num)
self.size += 1
def pop(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
r = self.q.popleft()
if r == self.mq[0]: self.mq.popleft()
self.size -= 1
return r
def min(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
return self.mq[0]
class minStack():
def __init__(self):
self.stack = []
self.min = None
self.size = 0
def push(self, x):
if self.size == 0: self.min = x
t = x - self.min
if t < 0: self.min = x
self.stack.append(t)
self.size += 1
def pop(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
r = self.stack.pop()
if r < 0:
old = self.min - r
self.min = old
self.size -= 1
def top(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
e = 0
if self.stack[-1] >= 0: e = self.stack[-1]
return self.min+e
def getMin(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
return self.min
class maxStack():
def __init__(self):
self.stack = []
self.max = None
self.size = 0
def push(self, x):
if self.size == 0: self.max = x
t = x - self.max
if t > 0: self.max = x
self.stack.append(t)
self.size += 1
def pop(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
r = self.stack.pop()
if r > 0:
old = self.max - r
self.max = old
self.size -= 1
def top(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
e = 0
if self.stack[-1] >= 0: e = self.stack[-1]
return self.max+e
def getMax(self):
if self.size == 0:
raise IndexError('pop from empty minQueue')
return self.max
# q = minQueue()
# q.push(4)
# print q.min()
# q.push(2)
# q.push(2)
# print q.min()
# q.push(3)
# q.pop()
# q.pop()
# q.pop()
# q.pop()
# # q.push(1)
# print q.min()
# s = maxStack()
# s.push(4)
# s.push(2)
# s.push(5)
# print s.getMax()
# s.pop()
# print s.getMax() |
400edf9a59ca355efe631e7ebbdaf8cd35ff6e3f | egillanton/samromur-asr | /preprocessing/ice-norm/text-cleaning/map_replacement.py | 2,575 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Uses replacement mapping files to replace symbols and strings in input using the replacement strings.
"""
import re
mp_file_path = '../mapping_tables/'
acro_file = 'acros.txt'
abbr_file = 'abbr.txt'
symbol_file = 'symbol_mapping.txt'
class ReplacementMaps:
def __init__(self):
self.acronym_map = {}
self.abbr_map = {}
self.symbol_map = {}
@staticmethod
def read_file(filename):
in_file = open(filename)
acronym_map = in_file.read().splitlines()
return acronym_map
@staticmethod
def create_map_from_list(tsv_list):
res_map = {}
for line in tsv_list:
arr = line.split('\t')
if len(arr) == 2:
res_map[arr[0]] = arr[1]
return res_map
def get_acronym_map(self):
if not self.acronym_map:
acr_list = self.read_file(mp_file_path + acro_file)
self.acronym_map = self.create_map_from_list(acr_list)
return self.acronym_map
def get_abbreviation_map(self):
if not self.abbr_map:
abbr_list = self.read_file(mp_file_path + abbr_file)
self.abbr_map = self.create_map_from_list(abbr_list)
return self.abbr_map
def get_symbol_map(self):
if not self.symbol_map:
symbol_list = self.read_file(mp_file_path + symbol_file)
self.symbol_map = self.create_map_from_list(symbol_list)
return self.symbol_map
def replace_acronyms(self, line):
res = line
for key in self.get_acronym_map():
res = res.replace(' ' + key + ' ', ' ' + self.acronym_map[key] + ' ')
return res
def replace_abbreviations(self, line):
res = line
for key in self.get_abbreviation_map():
res = re.sub(' ' + key + '\.? ', ' ' + self.abbr_map[key] + ' ', res)
return res
def replace_symbols(self, line):
res = line
for key in self.get_symbol_map():
res = res.replace(key, ' ' + self.symbol_map[key] + ' ')
res = res.replace(' ', ' ')
return res
def replace_from_maps(line):
repl = ReplacementMaps()
res = repl.replace_acronyms(line)
res = repl.replace_abbreviations(res)
res = repl.replace_symbols(res)
# delete puncutation
res = re.sub(r'[.,:?!]', '', res)
arr = res.split()
res = ' '.join(arr)
res = res.lower()
# special case for texts from dv.is
res = res.replace('ritstjórn dv ritstjorn @ dv', '')
return res
|
b4a16f1bdcbec1708a30ec89179ae36572a04a0a | enriqueaf/UniProyectos | /Colorear.py | 832 | 3.515625 | 4 | class MatrizIncidencia:
def __init__(self,lista):
self._lista = lista
self.vertices = len(lista)-1
def estan_unidos(self,a,b):
if self._lista[a][b]==1: return True
return False
def pintar(n,M):
pintura = coloreando(0,M,[])
if n in pintura: return False
return pintura
def coloreando(V,M,Colors):
temp = []
for i in range(V):
if M.estan_unidos(i,V): temp.append(Colors[i])
entro = False
a = 0
while not(entro):
if not(a in temp) and not(entro):
Colors.append(a)
entro = True
a += 1
if V == M.vertices: return Colors
else: return coloreando(V+1,M,Colors)
def main():
R = [[0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0]]
S = MatrizIncidencia(R)
print pintar(10,S)
if __name__=='__main__':
main()
|
45118f6aca17577fd9966d3512d708df950cd5b5 | PACOPEPE20/PROGRAMAS_PYTHON | /aplicacioncoche.py | 577 | 3.859375 | 4 | class Coche:
"""Abtraccion de los objetos coche"""
def __init__(self, gasolina): #self es el objeto y no cuenta como argumento
self.gasolina = gasolina
print("Tenemos", gasolina, "litros")
def arrancar(self):
if self.gasolina > 0:
print("Arrancar")
else:
print("No arrancar")
def conducir(self):
if self.gasolina > 0:
self.gasolina -= 1
print("Quedan", self.gasolina, "litros")
else:
print("No se mueve")
mi_coche = Coche(5)
|
307469ae45627409999676e6007c53d2157b81ea | PACOPEPE20/PROGRAMAS_PYTHON | /pregunta.py | 254 | 3.96875 | 4 |
#¿Cuál es el color dominante de la bandera de España?
fav = (input("¿Cuál es el color dominante de la bandera de España?: "))
if fav == "rojo":
print("SÍ")
print("Aceretaste")
else:
print(" NO")
print(" Qué lastima")
|
8971147b9464d531ec12b4f55a1efe01d06bc243 | isoscl/betterlifepsi | /psi/app/utils/date_util.py | 2,448 | 3.90625 | 4 | from datetime import datetime
def years_ago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
try:
return from_date.replace(year=from_date.year - years)
except ValueError:
# Must be 2/29!
assert from_date.month == 2 and from_date.day == 29
return from_date.replace(month=2, day=28,
year=from_date.year - years)
def num_years(begin, end=None):
if end is None:
end = datetime.now()
num_of_years = int((end - begin).days / 365.25)
if begin > years_ago(num_of_years, end):
return num_of_years - 1
else:
return num_of_years
def get_weeks_between(d1, d2):
"""
Calculating the difference in weeks between the Mondays within weeks of respective dates
:param d1: day one, the start date
:param d2: day two, the end date
:return: Returns 0 if both dates fall withing one week, 1 if on two consecutive weeks, etc.
"""
from datetime import timedelta
if d1 is None or d2 is None:
return 1
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))
return (monday2 - monday1).days / 7
def get_last_week(the_date):
"""
Get last ISO week of the date parameter
:param the_date: the date parameter
:return: last week and it's year
"""
current_year, current_week, current_weekday = the_date.isocalendar()
if current_week == 1:
last_week = the_date.replace(year=current_year - 1, month=12, day=31)
last_year = the_date.year - 1
else:
last_week = current_week - 1
last_year = the_date.year
return last_week, last_year
def get_last_month(month, year):
"""
Get last month of given month and year
:param month: given month
:param year: given year
:return: last month and it's year
"""
if month == 1:
last_month = 12
last_year = year - 1
else:
last_month = month - 1
last_year = year
return last_month, last_year
def get_last_quarter(month, year):
"""
Get last quarter of given month and year
:param month: given month
:param year: given year
:return: last quarter and it's year
"""
last_quarter = (month-1)//3
if last_quarter == 0:
last_quarter = 4
last_year = year - 1
else:
last_year = year
return last_quarter, last_year
|
a34a5cf032f82720848d4adaef67d135ad941e4c | pradyotpsahoo/P342_A1 | /A1_Q2.py | 500 | 4.46875 | 4 | # find the factorial of a number provided by the user.
# taking the input from the user.
num = int(input("Enter the number : "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Factorial does not exist for negative numbers. Enter the positive number.")
elif num == 0:
print("The factorial of 0 is 1")
else:
#loop iterate till num
for i in range(1,num+1 ):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
|
38eaad2f4ca9dd200e293f5c20b537d8053934a0 | Tricerator/DataStructuresAndAlgorithms | /DataStructures/LinkedList/LinkedList.py | 1,922 | 4 | 4 | #!/usr/bin/env python3
class Node:
def __init__(self, value):
self.value = value
self.descendant = None
class LinkedList(object):
def __init__(self, value=None):
if value is None:
self.root = None
return
if type(value).__name__ == 'list':
if len(value) == 0:
self.root = None
else:
self.root = Node(value[0])
for i in value[1:]:
self.Add(i)
else:
self.root = Node(value)
def AddToBeginning(self, value):
node = Node(value)
node.descendant = self.root
self.root = node
def Add(self, value):
node = self.root
while node.descendant is not None:
node = node.descendant
node.descendant = Node(value)
def PrintList(self):
print(self.createList())
def createList(self):
myList = []
myNode = self.root
while myNode is not None:
myList.append(myNode.value)
myNode = myNode.descendant
return myList
def Search(self, value):
myNode = self.root
while myNode is not None:
if myNode.value == value:
return True
myNode = myNode.descendant
return False
def RemoveValue(self, value):
node = self.root
if node.value == value:
self.root = self.root.descendant
return True
previousNode = node
node = node.descendant
while node is not None:
if node.value == value:
previousNode.descendant = node.descendant
return True
previousNode = node
node = node.descendant
return False
def RemoveAllPositionsOfValue(self, value):
a = True
while a:
a = self.RemoveValue(value)
|
1fdad2f80ff24e67e2ebff80f725f53369af384a | BobAnkh/MaC | /hw2/program/mytorch/loss.py | 2,167 | 3.75 | 4 | # Do not import any additional 3rd party external libraries as they will not
# be available to AutoLab and are not needed (or allowed)
import numpy as np
import os
# The following Criterion class will be used again as the basis for a number
# of loss functions (which are in the form of classes so that they can be
# exchanged easily (it's how PyTorch and other ML libraries do it))
class Criterion(object):
"""
Interface for loss functions.
"""
# Nothing needs done to this class, it's used by the following Criterion classes
def __init__(self):
self.logits = None
self.labels = None
self.loss = None
def __call__(self, x, y):
return self.forward(x, y)
def forward(self, x, y):
raise NotImplemented
def derivative(self):
raise NotImplemented
class SoftmaxCrossEntropy(Criterion):
"""
Softmax loss
"""
def __init__(self):
super(SoftmaxCrossEntropy, self).__init__()
self.sm = None
def forward(self, x, y):
"""
Argument:
x (np.array): (batch size, 10)
y (np.array): (batch size, 10)
Return:
out (np.array): (batch size, )
"""
self.logits = x
self.labels = y
# LogSumExp trick: please refer to https://www.xarg.org/2016/06/the-log-sum-exp-trick-in-machine-learning/
maxx = np.max(x, axis=1)
self.sm = maxx + np.log(np.sum(np.exp(x - maxx[:, np.newaxis]),
axis=1))
# log softmax sum
# DONE:
# Hint: use self.logits, self.labels, self.sm, and np.sum(???, axis = 1)
# return ???
return -np.sum(self.labels * (self.logits - self.sm[:, np.newaxis]),
axis=1)
def derivative(self):
"""
Return:
out (np.array): (batch size, 10)
"""
# DONE:
# Hint: fill in self.logits and self.labels in the following sentence
#return (np.exp(???) / np.exp(self.sm)[:, np.newaxis]) - ???
return (np.exp(self.logits) /
np.exp(self.sm)[:, np.newaxis]) - self.labels
|
8af7987d86f068aeba4978fc10098d9a21d2c36d | dennisbader/pd_analysis | /distributionset/Gaussiandistribution.py | 3,990 | 4.21875 | 4 | import math
import numpy as np
from matplotlib import pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
return np.mean(self.data)
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = int(self.data.shape[0] - 1)
else:
n = int(self.data.shape[0])
mean = self.calculate_mean()
return math.sqrt(np.sum((self.data - mean)**2) / n)
def replace_stats_with_data(self, sample=True):
"""Function to calculate mean and standard devation from the data set.
The function updates the mean and stdev variables of the object.
Args:
None
Returns:
float: the mean value
float: the stdev value
"""
self.mean = self.calculate_mean()
self.stdev = self.calculate_stdev(sample=sample)
return self.mean, self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
plt.show()
return
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces=50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = self.data.min()
max_range = self.data.max()
# calculates the interval between x values
interval = (max_range - min_range) / n_spaces
# calculate the x values to visualize
interval_counter = np.arange(n_spaces)
x = min_range + interval * interval_counter
y = self.pdf(x)
# make the plots
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
fig.subplots_adjust(hspace=.5)
ax1.hist(self.data, density=True)
ax1.set_title('Normed Histogram of Data')
ax1.set_ylabel('Density')
ax2.plot(x, y)
ax2.set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
ax1.set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev)
# x = Gaussian()
# x.read_data_file('/Users/Dennis/projects/udacity/data_science_course/pd_analysis/4a_binomial_package/numbers.txt')
# x.replace_stats_with_data() |
b5fc65a10dddac2ee66bff21157c80734ab2fc8a | butlerk/5023-OOP-scenarios | /students/main.py | 970 | 4 | 4 | from grades import Student
students = []
student1 = Student('Michael', 80, 70, 70, True)
students.append(student1)
student2 = Student('Angela', 60, 65, 75, True)
students.append(student2)
student3 = Student('Natalie', 60, 65, 100, False)
students.append(student3)
# Print the names and marks for each of the students
print('\nStudents:\n')
# TODO: Change code in loop to access Student objects' attributes, rather than dictionary
for student in students:
print('---')
print(f"Name: { student.name }")
print(f"English: { student.english_mark }")
print(f"Science: { student.science_mark }")
print(f"Mathematics: { student.mathematics_mark }")
average = Student.calc_average(student.english_mark, student.science_mark, student.mathematics_mark)
print(f"Average mark: {average}")
if student.completed_assessments == True:
print("Completed assessments: Yes")
else:
print("Completed assessments: No")
print('---\n')
|
aaaf7244971bdfe175e4c5b54e0589eaa0d05bec | Stuartlab-UCSC/stuartlab-scripts | /python/scipy-0.8.0/scipy/optimize/cobyla.py | 2,262 | 3.5 | 4 | """Interface to Constrained Optimization By Linear Approximation
Functions:
fmin_coblya(func, x0, cons, args=(), consargs=None, rhobeg=1.0, rhoend=1e-4,
iprint=1, maxfun=1000)
Minimize a function using the Constrained Optimization BY Linear
Approximation (COBYLA) method
"""
import _cobyla
from numpy import copy
def fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=1.0, rhoend=1e-4,
iprint=1, maxfun=1000):
"""
Minimize a function using the Constrained Optimization BY Linear
Approximation (COBYLA) method.
Parameters
----------
func : callable f(x, *args)
Function to minimize.
x0 : ndarray
Initial guess.
cons : sequence
Constraint functions; must all be ``>=0`` (a single function
if only 1 constraint).
args : tuple
Extra arguments to pass to function.
consargs : tuple
Extra arguments to pass to constraint functions (default of None means
use same extra arguments as those passed to func).
Use ``()`` for no extra arguments.
rhobeg :
Reasonable initial changes to the variables.
rhoend :
Final accuracy in the optimization (not precisely guaranteed).
iprint : {0, 1, 2, 3}
Controls the frequency of output; 0 implies no output.
maxfun : int
Maximum number of function evaluations.
Returns
-------
x : ndarray
The argument that minimises `f`.
"""
err = "cons must be a sequence of callable functions or a single"\
" callable function."
try:
m = len(cons)
except TypeError:
if callable(cons):
m = 1
cons = [cons]
else:
raise TypeError(err)
else:
for thisfunc in cons:
if not callable(thisfunc):
raise TypeError(err)
if consargs is None:
consargs = args
def calcfc(x, con):
f = func(x, *args)
k = 0
for constraints in cons:
con[k] = constraints(x, *consargs)
k += 1
return f
xopt = _cobyla.minimize(calcfc, m=m, x=copy(x0), rhobeg=rhobeg,
rhoend=rhoend, iprint=iprint, maxfun=maxfun)
return xopt
|
aa9b82d2376bccc0c2ee86a4458901fd1bb42707 | SireeshaPandala/Python | /Python_Lesson5/Python_Lesson5/LinReg.py | 936 | 4.15625 | 4 | import numpy as np
import matplotlib.pyplot as plt #for plotting the given points
x=np.array([2.9,6.7,4.9,7.9,9.8,6.9,6.1,6.2,6,5.1,4.7,4.4,5.8]) #converts the given list into array
y=np.array([4,7.4,5,7.2,7.9,6.1,6,5.8,5.2,4.2,4,4.4,5.2])
meanx=np.mean(x) #the meanvalue of x will be stored in meanx
meany=np.mean(y) #the meanvalue of y will be stored in meany
num=np.sum((x-meanx)*(y-meany)) #calculate the difference between the mean and given value
den=np.sum(pow((x-meanx),2)) #squares the difference between given x and meanx
m=num/den #slope calculation
intercept=meany-(m*meanx)
val=(m*x)+intercept #gives us the line equation
plt.plot(x,y,"ro") #plots the given x,y values
plt.plot(x,val)
plt.show() #plots the points on the graph |
Subsets and Splits