blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
16525fa3b1d7239a42f73707fa92c3f463d115f5 | jerry-mkpong/DataCamp | /Intermediate_Python_for_Data_Science/3.Logic_Control_Flow_and_Filtering/Cars per capita (1).py | 711 | 4.28125 | 4 | '''
Let's stick to the cars data some more. This time you want to find out which countries have a high cars per capita figure. In other words, in which countries do many people have a car, or maybe multiple cars.
Similar to the previous example, you'll want to build up a boolean Series, that you can then use to subset the cars DataFrame to select certain observations. If you want to do this in a one-liner, that's perfectly fine!
'''
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Create car_maniac: observations that have a cars_per_cap over 500
cpc = cars['cars_per_cap']
many_cars = cpc > 500
car_maniac = cars[many_cars]
# Print car_maniac
print(car_maniac)
|
9d61cc79f7980694035dd0435c30b4a021aab85d | trungnob/cs188 | /src/proj2/multiAgents.py | 18,820 | 3.796875 | 4 | from util import manhattanDistance
from game import Directions
import random, util
from game import Agent
class ReflexAgent(Agent):
"""
A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change it
in any way you see fit.
"""
def getAction(self, gameState):
"""
You do not need to change this method, but you're welcome to.
getAction chooses among the best options according to the evaluation function.
Just like in the previous project, getAction takes a GameState and returns
some Directions.X for some X in the set {North, South, West, East, Stop}
"""
# Collect legal moves and successor states
legalMoves = gameState.getLegalActions()
# Choose one of the best actions
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestIndices)
"Add more of your code here if you want to"
return legalMoves[chosenIndex]
def evaluationFunction(self, currentGameState, action):
"""
Design a better evaluation function here.
The evaluation function takes in the current and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
"""
# Useful information you can extract from a GameState (pacman.py)
returnScore=float(0)
successorGameState = currentGameState.generatePacmanSuccessor(action)
newPos = successorGameState.getPacmanState().getPosition()
oldFood = currentGameState.getFood()
newGhostStates = successorGameState.getGhostStates()
newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]
"*** YOUR CODE HERE ***"
foodList=oldFood.asList()
foodList.sort(lambda x,y: util.manhattanDistance(newPos, x)-util.manhattanDistance(newPos, y))
foodScore=util.manhattanDistance(newPos, foodList[0])
GhostPositions=[Ghost.getPosition() for Ghost in newGhostStates]
if len(GhostPositions) ==0 : GhostScore=0
else:
# Sort ghost by their distances from Pacman
GhostPositions.sort(lambda x,y: disCmp(x,y,newPos))
if util.manhattanDistance(newPos, GhostPositions[0])==0: return -99
else:
GhostScore=2*-1.0/util.manhattanDistance(newPos, GhostPositions[0])
if foodScore==0: returnScore=2.0+GhostScore
else: returnScore=GhostScore+1.0/float(foodScore)
return returnScore
def disCmp(x,y,newPos):
if (util.manhattanDistance(newPos, x)-util.manhattanDistance(newPos, y))<0: return -1
else:
if (util.manhattanDistance(newPos, x)-util.manhattanDistance(newPos, y))>0: return 1
else:
return 0
def scoreEvaluationFunction(currentGameState):
"""
This default evaluation function just returns the score of the state.
The score is the same one displayed in the Pacman GUI.
This evaluation function is meant for use with adversarial search agents
(not reflex agents).
"""
return currentGameState.getScore()
class MultiAgentSearchAgent(Agent):
"""
This abstract class** provides some common elements to all of your
multi-agent searchers. Any methods defined here will be available
to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.
You *do not* need to make any changes here, but you can if you want to
add functionality to all your adversarial search agents. Please do not
remove anything, however.
**An abstract class is one that is not meant to be instantiated. It's
only partially specified, and designed to be extended. Agent (game.py)
is another abstract class.
"""
def __init__(self, evalFn = scoreEvaluationFunction):
self.index = 0 # Pacman is always agent index 0
self.evaluationFunction = evalFn
def setDepth(self, depth):
"""
This is a hook for feeding in command line argument -d or --depth
"""
self.depth = depth # The number of search plies to explore before evaluating
def useBetterEvaluation(self):
"""
This is a hook for feeding in command line argument -b or --betterEvaluation
"""
betterEvaluationFunction.NumOriginal=0;
betterEvaluationFunction.firstCalled=True;
self.evaluationFunction = betterEvaluationFunction
class MinimaxAgent(MultiAgentSearchAgent):
"""
Your minimax agent (question 2)
"""
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
"""
"*** YOUR CODE HERE ***"
numOfAgent=gameState.getNumAgents();
trueDepth=numOfAgent*self.depth
LegalActions=gameState.getLegalActions(0)
if Directions.STOP in LegalActions:
LegalActions.remove(Directions.STOP)
listNextStates=[gameState.generateSuccessor(0,action) for action in LegalActions ]
# Max of all miniMax Values
v=[self.MiniMax_Value(numOfAgent,1,nextGameState,trueDepth-1) for nextGameState in listNextStates]
MaxV=max(v)
listMax=[]
# obtain the index of MaxV
for i in range(0,len(v)):
if v[i]==MaxV:
listMax.append(i)
# random when there is a tie
i = random.randint(0,len(listMax)-1)
action=LegalActions[listMax[i]]
return action
def MiniMax_Value(self,numOfAgent,agentIndex, gameState, depth):
LegalActions=gameState.getLegalActions(agentIndex)
listNextStates=[gameState.generateSuccessor(agentIndex,action) for action in LegalActions ]
# terminal state is whether the final depth is reached or Pacman dies or loses
if (gameState.isLose() or gameState.isWin() or depth==0):
return self.evaluationFunction(gameState)
else:
# if it's Pacman then it's a max layer
if (agentIndex==0):
return max([self.MiniMax_Value(numOfAgent,(agentIndex+1)%numOfAgent,nextState,depth-1) for nextState in listNextStates] )
# else if it's a ghost, then it's a min layer
else :
return min([self.MiniMax_Value(numOfAgent,(agentIndex+1)%numOfAgent,nextState,depth-1) for nextState in listNextStates])
class AlphaBetaAgent(MultiAgentSearchAgent):
"""
Your minimax agent with alpha-beta pruning (question 3)
"""
def Alpha_Beta_Value(self, numOfAgent, agentIndex, gameState, depth, alpha, beta):
LegalActions=gameState.getLegalActions(agentIndex)
if (agentIndex==0):
if Directions.STOP in LegalActions:
LegalActions.remove(Directions.STOP)
listNextStates=[gameState.generateSuccessor(agentIndex,action) for action in LegalActions ]
# terminal test
if (gameState.isLose() or gameState.isWin() or depth==0):
return self.evaluationFunction(gameState)
else:
# if Pacman
if (agentIndex == 0):
v=-1e308
for nextState in listNextStates:
v = max(self.Alpha_Beta_Value(numOfAgent, (agentIndex+1)%numOfAgent, nextState, depth-1, alpha, beta), v)
if (v >= beta):
return v
alpha = max(alpha, v)
return v
# if Ghost
else:
v=1e308
for nextState in listNextStates:
v = min(self.Alpha_Beta_Value(numOfAgent, (agentIndex+1)%numOfAgent, nextState, depth-1, alpha, beta), v)
if (v <= alpha):
return v
beta = min(beta, v)
return v
def getAction(self, gameState):
"""
Returns the minimax action using self.depth and self.evaluationFunction
"""
"*** YOUR CODE HERE ***"
numOfAgent=gameState.getNumAgents();
trueDepth=numOfAgent*self.depth
LegalActions=gameState.getLegalActions(0)
# remove stop action from list of legal actions
if Directions.STOP in LegalActions:
LegalActions.remove(Directions.STOP)
listNextStates = [gameState.generateSuccessor(0,action) for action in LegalActions ]
# check whether minimax value for -l minimaxClassic are 9, 8 , 7, -492
# as long as beta is above the upper bound of the eval function
v = [self.Alpha_Beta_Value(numOfAgent,1,nextGameState,trueDepth-1, -1e307, 1e307) for nextGameState in listNextStates]
MaxV=max(v)
listMax=[]
for i in range(0,len(v)):
if v[i]==MaxV:
listMax.append(i)
# random when there is a tie
i = random.randint(0,len(listMax)-1)
action=LegalActions[listMax[i]]
return action
class ExpectimaxAgent(MultiAgentSearchAgent):
"""
Your expectimax agent (question 4)
"""
def Expectimax_Value(self,numOfAgent,agentIndex, gameState, depth):
LegalActions=gameState.getLegalActions(agentIndex)
listNextStates=[gameState.generateSuccessor(agentIndex,action) for action in LegalActions ]
if (gameState.isLose() or gameState.isWin() or depth==0):
return self.evaluationFunction(gameState)
else:
# if it's Pacman then it's a max node
if (agentIndex==0):
return max([self.Expectimax_Value(numOfAgent,(agentIndex+1)%numOfAgent,nextState,depth-1) for nextState in listNextStates] )
# if it's a Ghost then it's a chance node
else :
listStuff=[self.Expectimax_Value(numOfAgent,(agentIndex+1)%numOfAgent,nextState,depth-1) for nextState in listNextStates]
return sum(listStuff)/len(listStuff)
def getAction(self, gameState):
"""
Returns the expectimax action using self.depth and self.evaluationFunction
All ghosts should be modeled as choosing uniformly at random from their
legal moves.
"""
"*** YOUR CODE HERE ***"
numOfAgent=gameState.getNumAgents();
trueDepth=numOfAgent*self.depth
LegalActions=gameState.getLegalActions(0)
if Directions.STOP in LegalActions:
LegalActions.remove(Directions.STOP)
listNextStates=[gameState.generateSuccessor(0,action) for action in LegalActions ]
v=[self.Expectimax_Value(numOfAgent,1,nextGameState,trueDepth-1) for nextGameState in listNextStates]
MaxV=max(v)
listMax=[]
for i in range(0,len(v)):
if v[i]==MaxV:
listMax.append(i)
# random when there is a tie
i = random.randint(0,len(listMax)-1)
action=LegalActions[listMax[i]]
return action
# Obtain actual ghost distance using A* Search with Heuristic function equals the manhanttan distance
def actualGhostDistance(gameState, ghostPosition):
from game import Directions
from game import Actions
visited = {}
ghostPosition=util.nearestPoint(ghostPosition)
curState=startPosition = gameState.getPacmanPosition()
fringe = util.FasterPriorityQueue()
Hvalue=util.manhattanDistance(startPosition,ghostPosition)
curDist=0;
priorityVal=Hvalue+curDist
fringe.push(tuple((startPosition,curDist)), priorityVal)
visited[startPosition] = True
walls = gameState.getWalls()
foodGrid = gameState.getFood()
isFood = lambda(x, y): foodGrid[x][y]
while not fringe.isEmpty():
curState,curDist = fringe.pop()
# terminal test: if the position has a ghost
if (curState==ghostPosition):
return (curState, curDist)
break
for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = curState
dx, dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy)
nextState = (nextx, nexty)
if ((not walls[nextx][nexty]) and (nextState not in visited)):
newcurDist = curDist + 1
priorityVal=util.manhattanDistance(nextState,ghostPosition)+newcurDist
visited[nextState] = True
fringe.push(tuple((nextState,newcurDist)), priorityVal)
return (curState,curDist)
# Obtain actual food distance using A* Search with Heuristic function equals the manhanttan distance
def actualFoodDistance(gameState, targetFood):
from game import Directions
from game import Actions
visited = {}
curState=startPosition = gameState.getPacmanPosition()
fringe = util.FasterPriorityQueue()
Hvalue=util.manhattanDistance(startPosition,targetFood)
curDist=0;
priorityVal=Hvalue+curDist
fringe.push(tuple((startPosition,curDist)), priorityVal)
visited[startPosition] = True
walls = gameState.getWalls()
foodGrid = gameState.getFood()
isFood = lambda(x, y): foodGrid[x][y]
while not fringe.isEmpty():
curState,curDist = fringe.pop()
# terminal test: if you found the food
if (curState==targetFood):
return (curState, curDist)
break
for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = curState
dx, dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy)
nextState = (nextx, nexty)
if ((not walls[nextx][nexty]) and (nextState not in visited)):
newcurDist = curDist + 1
priorityVal=util.manhattanDistance(nextState,targetFood)+newcurDist
visited[nextState] = True
fringe.push(tuple((nextState,newcurDist)), priorityVal)
return (curState,curDist)
def betterEvaluationFunction(currentGameState):
"""
Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
evaluation function (question 5).
DESCRIPTION: <write something here so we know what you did>
"""
if (betterEvaluationFunction.firstCalled):
#This indicates the function whether first called or not
#use this to initialize any variable which you wish don't do this again and again
betterEvaluationFunction.NumOrginal=currentGameState.getFood().count()
print "betterEvaluationFunction is at first Called"
if currentGameState.isLose():
return -1e307
if currentGameState.isWin() :
return 1e307
returnScore= 0.0
newPos = currentGameState.getPacmanState().getPosition()
# Obtain all ghost positions on the board
GhostStates = currentGameState.getGhostStates()
GhostStates.sort(lambda x,y: disCmp(x.getPosition(),y.getPosition(),newPos))
GhostPositions = [Ghost.getPosition() for Ghost in GhostStates]
# Obtain scared Ghosts informations
newScaredTimes = [ghostState.scaredTimer for ghostState in GhostStates]
closestGhost=GhostStates[0]
# Sort the food list and find the closest food to Pacman
FoodList = currentGameState.getFood().asList()
minPos = FoodList[0]
minDist = util.manhattanDistance(minPos, newPos)
for food in FoodList:
curDist = util.manhattanDistance(food, newPos)
if curDist==1 :
minPos=food
minDist=curDist
break
if (curDist < minDist):
minDist = curDist
minPos = food
# Find the actual distance to that food
targetFoodPosition, closestFoodDistance = actualFoodDistance(currentGameState, minPos)
# Find the actual distance to the closest Scared Ghost and the closest Normal Ghost
closestScaredGhostDist=1e307
closestScaredGhost=None
closestNormalGhostDist=1e307
closestNormalGhost=None
allScaredGhost=[Ghost for Ghost in GhostStates if Ghost.scaredTimer>0]
allRealScaredGhostDistance=[actualGhostDistance(currentGameState,Pos) for Pos in [ScaredGhost.getPosition() for ScaredGhost in allScaredGhost]]
allDistScaredGhosts=[Ghost[1] for Ghost in allRealScaredGhostDistance]
if len(allDistScaredGhosts)!=0:
closestScaredGhostDist=min(allDistScaredGhosts)
closestScaredGhost=allScaredGhost[allDistScaredGhosts.index(closestScaredGhostDist)]
allNormalGhost=[Ghost for Ghost in GhostStates if Ghost.scaredTimer<=0]
allRealNormalGhostDistance=[actualGhostDistance(currentGameState,Pos) for Pos in [NormalGhost.getPosition() for NormalGhost in allNormalGhost]]
allDistNormalGhosts=[Ghost[1] for Ghost in allRealNormalGhostDistance]
if len(allDistNormalGhosts)!=0:
closestNormalGhostDist=min(allDistNormalGhosts)
closestNormalGhost=allNormalGhost[allDistNormalGhosts.index(closestNormalGhostDist)]
# Default weights on Food, Normal Ghost, Scared Ghost
wFood, wGhost, wScaredGhost = [2.0, -6.0, 4.0];
# if the closest ghost ate Pacman
if (closestNormalGhostDist==0):
return -1e307
if (closestScaredGhostDist==0):
closestScaredGhostDist=0.1
# if the closest normal ghost is further away than 2 steps
# different weights are assigned whether they are < 7, or < 12
# of whether it is possible to eat a scared ghost before it recovers
if (closestNormalGhostDist > 2):
if closestScaredGhost!=None:
if (closestScaredGhostDist<closestScaredGhost.scaredTimer):
if(closestScaredGhostDist<7):
wFood, wGhost, wScaredGhost= [0.0, -0.0,10.0];
else:
if(closestScaredGhostDist<12):
wFood, wGhost, wScaredGhost= [3.0, 0.0, 8.0];
else :
wFood, wGhost, wScaredGhost= [3.0, 0.0, 0.0];
else:
wFood, wGhost, wScaredGhost = [4.0, -0.0, 0.0];
else :
wFood, wGhost, wScaredGhost = [4.0, -0.0, 0.0];
else:
if (closestScaredGhostDist<5):
if (closestScaredGhost.scaredTimer>5):
wFood, wGhost, wScaredGhost= [1.0, -6.0, 4.0];
else:
wFood, wGhost, wScaredGhost= [1.0, -6.0, -3.0];
else:
wFood, wGhost, wScaredGhost= [1.0, -6.0, 1.0];
# if there are only a few food left there should be more weights on food
if len(FoodList) < 3 :
wFood, wGhost, wScaredGhost= [6.0, -8.0, 0.0];
else:
if len(FoodList) < 2:
wFood, wGhost, wScaredGhost= [10.0, -8.0, 0.0];
returnScore=(wFood/(closestFoodDistance)+(wGhost)/closestNormalGhostDist+(wScaredGhost)/(closestScaredGhostDist))+currentGameState.getScore()
betterEvaluationFunction.firstCalled=False;
return returnScore
DISTANCE_CALCULATORS = {}
|
ee42807c96a6ecfb0343d21e72b7033520f5b853 | joshmedeski/dc-cohort-week-one | /day2/string-interpolation.py | 121 | 3.78125 | 4 | first_name = input('First Name: ')
last_name = input('Last Name: ')
print(f'Hello, My name is {first_name}, {last_name}') |
ef9864a7d29d05a2e98324eb4a448db4d110bc0b | ngoldsworth/Proj-Euler | /p003.py | 1,249 | 4.1875 | 4 | from primes.primelist import PrimesList
from math import ceil, sqrt
def is_prime(n:int):
is_it_prime = True # Boolean variable to hold whether n is prime or not
# n is assumed prime until proven otherwise
root = ceil(sqrt(n)) # if a number isn't prime, it has factors both above and below its square root
for j in range(2,root+1): # start at 2, since every number is divisible by 1
if n % j == 0: # if j divides evenly into n, then n is not prime
is_it_prime = False
break # Don't need to test more now that we know n is not prime
return is_it_prime
def largest_prime_factor(num: int):
if not isinstance(num, int):
raise TypeError('Need an integer, you dimwit')
found_largest_prime_factor = False # Haven't found a prime factor of num, until we do
i = 1 # start at i=1, that way if num/1 is a factor, then we know it is its own largest prime factor
while not found_largest_prime_factor:
if int(num/i) == num/i and is_prime(int(num/i)):
return int(num/i)
elif i >= num:
raise ValueError('You broke math. Somehow `num` has no prime factors and is not prime')
i += 1
|
cbed02406bc14980c2ef0ce851e7b09a5cc96289 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/19_iterative_search_BST.py | 768 | 3.9375 | 4 | ''' Iterative search BST '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def iterative_search(root, key):
if not root:
return -1
cur = root
while cur != None:
if cur.val == key:
return True
elif cur.val > key:
cur = cur.left
else:
cur = cur.right
return False
root = Node(5)
root.left = Node(2)
root.right = Node(12)
root.left.left = Node(1)
root.left.right = Node(3)
root.right.left = Node(9)
root.right.right = Node(21)
root.right.right.left = Node(19)
root.right.right.right = Node(25)
print iterative_search(root, 25)
print iterative_search(root, 3)
print iterative_search(root, 30) |
d7bfb8e296974fd7639a8ca0d9cc2522fc41e2c1 | bobcaoge/my-code | /python/leetcode/1387_Sort_Integers_by_The_Power_Value.py | 732 | 3.8125 | 4 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
class Solution(object):
def getKth(self, lo, hi, k):
"""
:type lo: int
:type hi: int
:type k: int
:rtype: int
"""
def get_step(num):
ret = 0
while num != 1:
if num % 2 == 0:
num //= 2
else:
num = num*3+1
ret += 1
return ret
nums = []
for i in range(lo, hi+1):
nums.append([get_step(i), i])
return sorted(nums)[k-1][1]
def main():
s = Solution()
print(s.getKth(7,11,4))
print(s.getKth(lo = 12, hi = 15, k = 2))
if __name__ == "__main__":
main()
|
bd8c2eee9454dff520a88727e8507c34edf378ca | chatreesr/py-project-euler | /p004.py | 761 | 3.921875 | 4 | # Problem 004 - Largest palindrome product
# TODO: Make this function work with any n?
def is_palindrome(n: int) -> bool:
if ( (n // 100000) == (n % 10) and
(n % 100000) // 10000 == (n % 100) // 10 and
(n % 10000) // 1000 == (n % 1000) // 100 ):
return True
else:
return False
if __name__ == '__main__':
largest_palindrome = 0
n1 = 0
n2 = 0
for i in range(999, 100, -1):
for j in range(999, 100, -1):
k = i * j
if k > 100000 and is_palindrome(k):
if largest_palindrome < k:
largest_palindrome = k
n1 = i
n2 = j
print(f'The largest palindrome product: {n1} x {n2} = {largest_palindrome}') |
c63d59604912233758b319ad9093b260bdfdb130 | dlc9113/yoyoyo | /lib/helpers/concurrent.py | 548 | 3.5 | 4 | from threading import Thread
from queue import Queue
class Concurrent(object):
"""docstring for Concurrent"""
def __init__(self):
super(Concurrent, self).__init__()
self.queue = Queue()
def add(self):
arg = self.queue.get()
self.method(arg)
self.queue.task_done()
def start(self, method, args):
num = len(args)
self.method = method
self.threads = [Thread(target=self.add) for _ in range(num)]
[self.queue.put(arg) for arg in args]
[thread.start() for thread in self.threads]
self.queue.join()
|
1ec1e3479fe0a7068cff5d4a71fe166d146b9763 | DishantK1807/Leetcode-Practice | /189 - Rotate Array/PythonSolution.py | 459 | 3.578125 | 4 | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
temp = 0
length = len(nums)
if k > length:
k -= length
if k == length:
k = 0
for i in range(k):
temp = nums[length-1]
for j in range(length-1, 0, -1):
nums[j] = nums[j-1]
nums[0] = temp |
ca08175253d45686d220b671bffe67ad3004f35f | lucascortes96/Rosalind_Solutions- | /09. Finding_a_Motif_in_DNA.py | 392 | 3.625 | 4 | ## Got to get the position(s) of a given substring in your string
def motif_count(test_str, test_sub):
# if char in test starts with sub then add to list 'res'
res = [i for i in range(len(test_str)) if test_str.startswith(test_sub, i)]
## Adding one to each int in list for question format
new_res = [x+1 for x in res]
print(*new_res, sep = ' ')
motif_count('', '')
|
e9285ee8b0b16847eaca22f66c95850f7660a3c5 | nmaswood/Random-Walk-Through-Computer-Science | /lessons/day3/exercises.py | 1,177 | 4.21875 | 4 | from random import randint
def create_random(number_of_elements, n):
"""
Use the function randint which takes an integer n and produce a random number [0,n]
to generate a list of size number_of_elements where the numbers are between [0,n]
e.g.
create_random(3, 1000) -> [234, 512, 999]
"""
return []
def double_list(l):
"""
Return a new list which is every element in l doubled
e.g.
double_list([1,2,3]) -> [2, 4, 6]
"""
return []
def abbreviate(list_of_words):
"""
Return a dictionary which maps the first letter of a word to the word
e.g.
abbbreiate(['dog', 'cat', 'shoe']) -> {'d': 'dog', 'c': 'cat', 's': 'shoe'}
"""
return {}
def list_of_lists(n):
"""
return a list of n lists. where each element is the list ['X', 'X', 'X']
e.g.
list_of_lists(2) -> [['X', 'X', 'X'],['X', 'X', 'X']]
"""
return []
def is_prime(x):
"""
Return true if the number x is prime.
is_prime(3) -> True
is_prime(4) -> False
"""
return False
def tic_tac_toe():
"""
Create a playable version of the game tic tac toe
"""
return |
330a01657bffc5fb2315ab05fc1198be46f12caf | vyahello/upgrade-python-kata | /kata/06/padovan.py | 913 | 4.4375 | 4 | """
The Padovan sequence is the sequence of integers P(n) defined by the initial values
P(0)=P(1)=P(2)=1
and the recurrence relation
P(n)=P(n-2)+P(n-3)
The first few values of P(n) are
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...
"""
def padovan(number: int) -> int:
"""
Examples:
>>> assert padovan(2) == 1
>>> assert padovan(5) == 3
"""
result = [0, 1, 1]
for c in range(2, number):
result.append(result[0] + result[1])
del result[0]
return result[0] + result[1]
def padovan_pythonic(number: int) -> int:
"""
Examples:
>>> assert padovan_pythonic(2) == 1
>>> assert padovan_pythonic(5) == 3
"""
p0 = p1 = p2 = 1
for _ in range(number):
p0, p1, p2 = p1, p2, p0 + p1
return p0
if __name__ == "__main__":
print(padovan(5))
print(padovan_pythonic(5))
|
9b07794a2e9046c36a73dc4aedf2631e4248c780 | dbgkswn7581/python_basic_questions | /1094.py | 148 | 3.65625 | 4 | a = int(input())
b = input().split()
arr = []
for i in range(a):
arr.append(b[i])
arr.reverse()
for i in range(a):
print(arr[i], end=' ') |
060181bf0bc19b4413d6666bebf811c808bce39f | TheAlgorithms/Python | /other/h_index.py | 1,843 | 4.34375 | 4 | """
Task:
Given an array of integers citations where citations[i] is the number of
citations a researcher received for their ith paper, return compute the
researcher's h-index.
According to the definition of h-index on Wikipedia: A scientist has an
index h if h of their n papers have at least h citations each, and the other
n - h papers have no more than h citations each.
If there are several possible values for h, the maximum one is taken as the
h-index.
H-Index link: https://en.wikipedia.org/wiki/H-index
Implementation notes:
Use sorting of array
Leetcode link: https://leetcode.com/problems/h-index/description/
n = len(citations)
Runtime Complexity: O(n * log(n))
Space Complexity: O(1)
"""
def h_index(citations: list[int]) -> int:
"""
Return H-index of citations
>>> h_index([3, 0, 6, 1, 5])
3
>>> h_index([1, 3, 1])
1
>>> h_index([1, 2, 3])
2
>>> h_index('test')
Traceback (most recent call last):
...
ValueError: The citations should be a list of non negative integers.
>>> h_index([1,2,'3'])
Traceback (most recent call last):
...
ValueError: The citations should be a list of non negative integers.
>>> h_index([1,2,-3])
Traceback (most recent call last):
...
ValueError: The citations should be a list of non negative integers.
"""
# validate:
if not isinstance(citations, list) or not all(
isinstance(item, int) and item >= 0 for item in citations
):
raise ValueError("The citations should be a list of non negative integers.")
citations.sort()
len_citations = len(citations)
for i in range(len_citations):
if citations[len_citations - 1 - i] <= i:
return i
return len_citations
if __name__ == "__main__":
import doctest
doctest.testmod()
|
edbab93e91e368ea46f59df573aecf21cdd89745 | Colcothar/Stock-Cast | /testScaler.py | 629 | 3.578125 | 4 | import yfinance as yf
import lxml
import pandas
import numpy
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
def downloadStockData(stockTicker):
rawData=[]
stock = yf.Ticker(str(stockTicker)) #creates request
history = stock.history(period="max") #gets history
for i in range(len(history)):
rawData.append(history["High"][i]) #writes the max stock price of the day to the array
return(rawData) #return array
data = [1,2,3,4,54,6,90]
arr = numpy.array(data)
arr= arr.reshape(-1,1)
print(arr)
arr= sc.fit_transform(arr)
newArr= arr.tolist()
|
3a5fd383173d1755733d8681eab5e3da91f58fc4 | Taras-code/basis | /Spider/V1.py | 387 | 3.5 | 4 | from urllib import request
if __name__ == '__main__':
url = 'https://translate.google.cn/'
wd = input("Input your keyword:")
rsp = urllib.request.urlopen(url)
print(type(rsp))
print(rsp)
print("URL:{0}".format(rsp.geturl()))
print("Info:{0}".format(rsp.info()))
print("Code:{0}".format(rsp.code()))
html = rsp.read()
html = html.decode()
|
067cec12ca82e2cb46d4873c396fb310edbd85f0 | WeiYongqiang55/code_git | /19.py | 109 | 3.515625 | 4 | a = "OurWorldIsFullOfLOVE"
a=a.lower()
if a.__contains__("love"):
print("LOVE")
else:
print("single") |
dcb05c48b27817fce6fee462047826839d1fb710 | cooperfaber/Parallel-Programming | /hw1/part2/homework1_part2_skeleton.py | 6,175 | 3.703125 | 4 | import os
import argparse
# Top of C++ file with includes and namespaces
top_source_string = """
#include <iostream>
#include <assert.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
typedef double reduce_type;
"""
# The reference loop simply adds together all elements in the array
def reference_reduction_source():
# function header
function = "void reference_reduction(reduce_type *b, int size) {"
# loop header
loop = " for (int i = 1; i < size; i++) {"
#simple reduction equation
eq = " b[0] += b[i];"
# closing braces
loop_close = " }"
function_close = "}"
# joining together all parts
return "\n".join([function, loop, eq, loop_close, function_close])
# Your homework will largely take place here. Create a loop that
# is semantically equivalent to the reference loop. That is, it computes
# a[0] = a[0] + a[1] + a[2] + a[3] + a[4] ... + a[size]
#
# where size is passed in by the main source string.
#
# You should unroll by a factor of "partitions". This is done logically
# by splitting a into N partitions (where N == partitions). You will compute
# N reductions, one computation for each partition per loop iteration.
#
# You will need a cleanup loop after the main loop to combine
# the values in each partition.
#
# You can assume the size and the number of partitions will be
# a power of 2, which should make the partitioning logic simpler.
#
# You can gain confidence in your solution by running the code
# with several power-of-2 unroll factors, e.g. 2,4,8,16. You
# should pass the assertion in the code.
#
# The reference slides for this part of the assignment are slides 81 -
# 92 of April 8 lecture. The example shows reduction for
# partitions=2. You need to generalize partitions to be any
# power-of-two. You can assume partition is less than size.
def homework_reduction_source(partitions):
# header
function = "void homework_reduction(reduce_type *a, int size) {"
# implement me!
function_body = []
function_body.append(" int delta_x = size/"+str(partitions)+";")
function_body.append(" for(int i = 1; i < delta_x; i++){")
#partition and sum to first memory location in partition
for i in range(0, partitions):
function_body.append(" a[delta_x*"+str(i)+"] += a[delta_x*"+str(i)+"+i];")
# closing brace for body
function_body.append(" }")
#cleanup (add all summed values to base memory location)
#loop header
function_body.append(" for(int i = 1; i < "+str(partitions)+"; i++){")
function_body.append(" a[0] += a[delta_x*i];")
# closing brace for cleaup loop
function_body.append(" }")
# closing brace
function_close = "}"
return "\n".join([function, "\n".join(function_body),function_close])
# String for the main function, including timings and
# reference checks.
main_source_string = """
#define SIZE (1024*1024*16)
int main() {
reduce_type *a;
a = (reduce_type *) malloc(SIZE * sizeof(reduce_type));
reduce_type *b;
b = (reduce_type *) malloc(SIZE * sizeof(reduce_type));
for (int i = 0; i < SIZE; i++) {
a[i] = 1;
b[i] = 1;
}
auto new_start = high_resolution_clock::now();
homework_reduction(a,SIZE);
auto new_stop = high_resolution_clock::now();
auto new_duration = duration_cast<nanoseconds>(new_stop - new_start);
double new_seconds = new_duration.count()/1000000000.0;
auto ref_start = high_resolution_clock::now();
reference_reduction(b,SIZE);
auto ref_stop = high_resolution_clock::now();
auto ref_duration = duration_cast<nanoseconds>(ref_stop - ref_start);
double ref_seconds = ref_duration.count()/1000000000.0;
cout << "new loop time: " << new_seconds << endl;
cout << "reference loop time: " << ref_seconds << endl;
cout << "speedup: " << ref_seconds / new_seconds << endl << endl;
return 0;
}
"""
# Create the program source code
def pp_program(partitions):
# Your function is called here
homework_string = homework_reduction_source(partitions)
# View your homework source string here for debugging
return "\n".join([top_source_string, reference_reduction_source(), homework_string, main_source_string])
# Write a string to a file (helper function)
def write_str_to_file(st, fname):
f = open(fname, 'w')
f.write(st)
f.close()
# Compile the program. Don't change the options here for the official
# assignment report. Feel free to change them for your own curiosity.
# Some notes:
#
# I am using a recent version of C++ to use the chrono library.
#
# I am disabling the compiler's loop unrolling so we can ensure the
# reference loop and the homework loops are not unrolled "behind our backs"
#
# I am using the highest optimization level (-O3) to illustrate that
# the compiler is not even brave enough to perform this optimization!
def compile_program():
cmd = "clang++ -std=c++17 -fno-unroll-loops -O3 -o homework homework.cpp"
print("running: " + cmd)
assert(os.system(cmd) == 0)
# Run the program
def run_program():
cmd = "./homework"
print("running: " + cmd)
print("")
assert(os.system(cmd) == 0)
# This is the top level program function. Generate the C++ program,
# compile it, and run it.
def generate_and_run(partitions):
print("")
print("----------")
print("generating and running for:")
print("partitions = " + str(partitions))
print("-----")
print("")
# get the C++ source
program_str = pp_program(partitions)
# write it to a file (homework.cpp)
write_str_to_file(program_str, "homework.cpp")
# compile the program
compile_program()
# run the program
run_program()
# gets one command line arg unroll factor (UF)
def main():
parser = argparse.ArgumentParser(description='Part 2 of Homework 1: exploiting ILP by unrolling reduction loop iterations.')
parser.add_argument('unroll_factor', metavar='UF', type=int,
help='how many loop iterations to unroll')
args = parser.parse_args()
UF = args.unroll_factor
generate_and_run(UF)
if __name__ == "__main__":
main()
|
ee3d9b56de336ea2d52e94a8004d48958e6f671c | RenanVenancio/TabelaHash | /aluno.py | 359 | 3.546875 | 4 | class Aluno:
def __init__(self, matricula, nome, idade):
self.matricula = matricula
self.nome = nome
self.idade = idade
def printar(self):
print(self.matricula, self.nome, self.idade)
def __str__(self):
return 'MAT: ' + str(self.matricula) + ' - NOME: ' + str(self.nome) + ' - IDADE: ' + str(self.idade) |
012b06dd0a1c7f07a15c32a9525c2cc42e7efea0 | SorensenAndrew/DPW | /Python/day3.py | 457 | 3.640625 | 4 | class Student:
def __init__(self, n):
print "student created"
self.name = n
self.gender = ""
self.grades = []
def getAvg(self):
total = 0
for i in self.grades:
total += i
return total/len(self.grades)
john = Student("John")
john.grades = [70,80,90]
print john.getAvg()
print john.name
# Import
# from "file name" import "class"
# * in class argument imports all from that file |
c528d32c8e660c0eb779b170bdfc60f9bc7595b5 | lsa-src/EXPython | /실습예제/Set.py | 1,031 | 4.21875 | 4 | '''
집합 set, 자료형으로 쓰기 보단 데이터 처리용으로 많이 사용, 데이터 중복없이 하나만 필요할 때..좀 더 프로그램을 편하게 하고자 할 때
컬렉션 데이터 타입은 for in
파이썬은 사람의 마인드와 유사...
'''
lst = [1,2,3]
st = {1,2,4}
print(type(lst))
print(type(st))
print(lst[0])
# print(st[0])
# print(st[0]), TypeError: 'set' object is not subscriptable, set은 인덱싱이 안됨 순서가 없음
lst1 = [1,2,2,2,3,3]
st1 = set(lst1) #중복 데이터 제거, 리스트를 set으로 변환하는 편한 방법
lst2 = list(st1)
print(type(st1))
print(type(lst2))
print(st1)
print(lst2)
st2 = {1,3,4,5,10}
print("교집합 :", st1&st2)
print("합집합 :", st1|st2)
print("차집합 :", st1-st2)
print('-'*50)
print(sorted(st2)) #메소드가 아니라 콜렉션 함수당 리턴값은 정렬된 값 반환, 원본자료는 바뀌진 않는다.
sortedLst = sorted(st2) #반환값을 sortedLst에 저장
print(sortedLst)
|
678d60190d77e5084c2f1ac7d3a820bc9452356b | lamasnicolas/PostgreSQL-comparator | /comparator.py | 2,594 | 3.71875 | 4 | import argparse
from db_checker import DbCompare, Parameters
parser = argparse.ArgumentParser(description='The program will check if two PostgreSQL databases contains the same '
'tables and same rows in each one. '
'Default behaviour is to check contents for each table in db 1.')
parser.add_argument("db1", help="Name of the first database")
parser.add_argument("host1", help="Host location of the first database")
parser.add_argument("port1", help="Port of the first database")
parser.add_argument("user1", help="Username for the first database")
parser.add_argument("pass1", help="Password for the first database")
parser.add_argument("db2", help="Name of the second database")
parser.add_argument("host2", help="Host location of the second database")
parser.add_argument("port2", help="Port of the second database")
parser.add_argument("user2", help="Username for the second database")
parser.add_argument("pass2", help="Password for the second database")
parser.add_argument("-t", "--tables", help="Tables to be checked. Leaving this empty will check all tables.", nargs="*",
type=str, default=[])
parser.add_argument("-n", "--name_check", action="store_true", help="Will check that both databases contains the same "
"tables, and then will check contents.")
parser.add_argument("-c", "--complete", action="store_true", help="Will do every check available.")
parser.add_argument("-rl", "--right_to_left", action="store_true", help="Will do the check queries for each table for"
"both sides (Default is row contained in table "
"from db one, check if it exists in same table "
"in db two)")
parser.add_argument("-o", "--output_path", type=str, default="", help="Location of the output folder. Do not use / at the end"
" (Default is the same location that the script is run)")
args = parser.parse_args()
params = Parameters(args.db1, args.host1, args.port1, args.user1, args.pass1,
args.db2, args.host2, args.port2, args.user2, args.pass2,
args.tables, args.name_check, args.complete, args.right_to_left,
args.output_path)
dc = DbCompare(params)
dc.process()
|
7e592fa59879156377769aba54192f3db05c7f86 | Azimusss/Azis | /Classes.py | 1,204 | 3.734375 | 4 | import math
class Vector:
def __init__(self, coords):
self.x = coords[0]
self.y = coords[1]
def get_len(self):
return math.sqrt(self.x**2 + self.y**2)
@property
def len(self):
return self.get_len()
def as_point(self):
return self.x, self.y
def rotate(self, angle):
angle = math.radians(angle)
x1 = self.x * math.cos(angle) - self.y * math.sin(angle)
y1 = self.x * math.sin(angle) + self.y * math.cos(angle)
return Vector((x1, y1))
def __add__(self, other):
xs = self.x + other.x
ys = self.y + other.y
return Vector((xs, ys))
def __mul__(self, other):
m1 = other * self.x
m2 = other * self.y
return Vector((m1, m2))
def __sub__(self, other):
xs = self.x - other.x
ys = self.y - other.y
return Vector((xs, ys))
def __repr__(self):
return "v (%s, %s)" % (self.x, self.y)
def normalize(self):
x = self.x / self.get_len()
y = self.y / self.get_len()
return Vector((x, y))
if __name__ == "__main__":
v1 = Vector((10, 10))
print(v1)
v1 = v1.rotate(45)
print(v1)
|
170dc08f997091bc689ce4ed85a303e7f4804b6f | Phillips1031/Clue-Less | /board/location.py | 1,898 | 4.125 | 4 | '''
Created on Oct 10, 2017
@author: Zack
'''
class Location(object):
'''
Areas of the game board that a character can occupy.
TODO: Start Locations?
'''
def __init__(self, name):
self.roomType = name
self.connectingLocations = set()
def add_connecting_locations(self, connectingLocation):
self.connectingLocations.add(connectingLocation)
def available_to_enter(self):
pass
def show_connecting_locations(self):
# Simple function for test
for k in self.connectingLocations:
print( "{} is connected to {}".format(self, k))
def return_connecting_locations(self):
return self.connectingLocations
class Hallway(Location):
'''
Connections between rooms.
'''
def __init__(self, hallwayName):
'''
Constructor
'''
super().__init__(hallwayName)
self.occupied = False
def __str__(self):
return self.roomType
def available_to_enter(self):
#Return true if the hallway is not already occupied
if self.occupied == False:
result = True
else:
result = False
return result
class Room(Location):
'''
Locations that characters can occupy and make suggestions in.
'''
def __init__(self, roomname):
'''
Constructor
'''
super().__init__(roomname)
def __str__(self):
return self.roomType.name
def available_to_enter(self):
return True
class StartLocation(Location):
'''
Connections between rooms.
'''
def __init__(self, startLocation):
'''
Constructor
'''
super().__init__(startLocation)
def __str__(self):
return self.roomType
|
99eb0a7d4d0f9b20c45ca9923de7782cdff89c42 | JPTIZ/graph | /graph.py | 4,787 | 3.953125 | 4 | '''Defines graph structures.'''
import random
from typing import Set, TypeVar
K = TypeVar('K')
class Vertex:
'''A graph's vertex.'''
def __init__(self, key: K):
self.key = key
self.neighbours = set()
def degree(self) -> int:
'''Returns the vertex's degree.'''
return len(self.neighbours)
class Graph:
'''The graph itself.'''
def __init__(self):
self.vertices = {}
# Basic operations
def add(self, v: Vertex):
'''Adds a vertex to the graph.
Args:
v: Vertex to be add.
'''
self.vertices[v] = Vertex(v)
def remove(self, v: Vertex):
'''Removes a vertex from the graph.
Args:
v: Vertex to be removed.
'''
del self.vertices[v]
def link(self, v1: Vertex, v2: Vertex):
'''Links two vertices by a bidirectional edge.
Args:
v1: First vertex.
v2: Second vertex.
'''
self.vertices[v1].neighbours.add(self.vertices[v2])
self.vertices[v2].neighbours.add(self.vertices[v1])
def unlink(self, v1: Vertex, v2: Vertex):
'''Unlinks two vertices.
Args:
v1: First vertex.
v2: Second vertex.
'''
self.vertices[v1].neighbours.discard(self.vertices[v2])
self.vertices[v2].neighbours.discard(self.vertices[v1])
def order(self) -> int:
'''Graph's order.'''
return len(self.vertices)
def random_vertex(self) -> Vertex:
'''Gets a random vertex from the graph.'''
return random.choice(list(self.vertices.values()))
def neighbours(self, key: K) -> Set[Vertex]:
'''Gets a set with a vertex's neighbours.
Args:
key: The vertex.
'''
return self.vertices[key].neighbours
def degree(self, key: K) -> int:
'''Gets a vertex's degree.
Args:
key: The vertex.
'''
return self.vertices[key].degree()
# Derived actions
def regular(self) -> bool:
'''Checks if the graph is regular.'''
common_degree = len(self.random_vertex().neighbours)
for v in self.vertices.values():
if v.degree() != common_degree:
return False
return True
def complete(self) -> bool:
'''Checks if the graph is complete.'''
for _, v in self.vertices.items():
for _, other_v in self.vertices.items():
if v != other_v and other_v not in v.neighbours:
return False
return True
def transitive_closure(self, key: K) -> Set[Vertex]:
'''Gets the transitive closure starting from the given key.
Args:
key: Reference vertex.
'''
if isinstance(key, Vertex):
v = key
else:
v = self.vertices[key]
visited = set()
return search_transitive_closure(v, visited)
def connected(self) -> bool:
'''Checks if the graph is connected. An empty graph is considered
disconnected.'''
if not self.vertices:
return false
trans = self.transitive_closure(self.vertices[0])
values = set(self.vertices.values())
return len(trans ^ values) == 0
def tree(self) -> bool:
'''Checks if the graph is a tree.'''
return self.connected() and not self.has_cycle()
def has_cycle(self,
v: Vertex = None,
prev: Vertex = None,
visited: Set[Vertex] = None):
'''Check if the graph has a cycle.
Args:
v: Vertex to be checked against visited set.
If None, begins searching recursively for a cycle.
prev: Reference vertex.
visited: Set of already visited vertices.
'''
if v is None:
v = self.vertices[0]
return self.has_cycle(v, v, set())
if v in visited:
return True
visited.add(v)
for v_ in v.neighbours:
if v_ != prev and self.has_cycle(v_, v, visited):
return True
visited.remove(v)
return False
# Extra
def __getitem__(self, key: K) -> Vertex:
'''Overrides operator [] to get a vertex by a given key.
Args:
key: The vertex's key.
'''
return self.vertices[key]
def search_transitive_closure(v: Vertex, visited: Set[Vertex]) -> Set[Vertex]:
'''Searchs for a transitive closure.
Args:
v: Reference vertex.
visited: Already visited vertices.
'''
visited.add(v)
for v_ in v.neighbours:
if not v_ in visited:
search_transitive_closure(v_, visited)
return visited
|
afc9a71ac8558aa3ea6d89450c95496b89ea1730 | UW-ParksidePhysics/Bencs-Michael | /univariate_statistics.py | 1,393 | 3.859375 | 4 | from matplotlib.pyplot import *
from numpy import *
from statistics import stdev
def univariate_statistics(data):
#"Calculate statistical characteristics of a data set
# Module name:
# univariate_statistics
# Parameters:
# data: ndarray, shape(2, M)
# x-y data to be characterized. M is the number of data points.
# Returns:
# statistics: ndarray, shape (6,)
# Mean of y, standard deviation of y, minimum x-value, maximum x-value, minimum y-value, maximum y-value
# Raises:
# IndexError
# When data array has inapproriate dimensions (!=2 rows, or <=1 column)."
if not len(data) ==2:
print ('IndexError: data array dimensions are all wrong')
elif (len(data[0]) or len(data[1])) <= 1:
print('IndexError: data array dimensions are all wrong')
else:
min_x= min(data[0])
max_x= max(data[0])
min_y= min(data[1])
max_y= max(data[1])
# Mean
Sum = sum(data[0]) + sum(data[1])
Len = len(data[0]) + len(data[1])
mean = Sum / Len
# Standard deviation
standard_dev= stdev(data[1])
# Statistics
statistics = [mean, standard_dev,
min_x, max_x,
min_y, max_y]
return statistics
|
c99baf7b7ff6098ecacb9e87e85138662fa2d9cf | AKolumbic/Intro-Python | /src/dicts.py | 713 | 4.3125 | 4 | # Make an array of dictionaries. Each dictionary should have keys:
#
# lat: the latitude
# lon: the longitude
# name: the waypoint name
#
# Make up three entries of various values.
waypoints = [
{
"lat": 34.046145,
"lon": -118.345499,
"name": "Leo's Tacos"
},
{
"lat": 34.096467,
"lon": -118.389694,
"name": "Dr Dre's House"
},
{
"lat": 37.800286,
"lon": -122.437998,
"name": "Izzy's"
}
]
# Write a loop that prints out all the field values for all the waypoints
for place in waypoints:
print(place['name'], place['lat'], place['lon'])
for name in waypoints:
print("The name of the waypoint is {0[name]}.".format(name)) |
6f4b172cb917fa66f34179b97f5124cb7f1392ce | jerryyang747/SemiPy | /SemiPy/Plotting(decom)/Plotting.py | 2,333 | 3.546875 | 4 | """
Basic Plotting object
"""
import plotly.graph_objects as go
import numpy as np
class BasePlotlyPlot(object):
def __init__(self, *args, **kwargs):
self.fig = go.Figure()
@staticmethod
def _check_array(array):
array = np.array(array)
assert len(array.shape) == 2 or len(array.shape) == 1, 'The array data you gave is off. It has a dimension of {0} but should ' \
'only have a dimension of 1 or 2'.format(len(array.shape))
return array
class Base2DPlot(BasePlotlyPlot):
def __init__(self, x_data, y_data, classes=None, *args, **kwargs):
"""
Args:
x_data (np.ndarray): X data of the plot. Should have 1 or 2 dimensions. If 2 dimensions, the classes should be the 2nd dimension
y_data (np.ndarray): Y data of the plot. Should have same shape as x_data.
classes (None or np.ndarray): The class labels of the data. Either None or np.ndarray with 1 dimension and shape equal to x_data.shape[0]
*args:
**kwargs:
"""
super(Base2DPlot, self).__init__(args, kwargs)
self.x_data, self.y_data, self.classes = self.__check_shapes(x_data, y_data, classes)
# now add to the
def __check_shapes(self, x_data, y_data, classes):
# check arrays
x_data = self._check_array(x_data)
y_data = self._check_array(y_data)
assert x_data.shape == y_data.shape, 'The x_data shape {0} is not the same as the y_data shape {1}'.format(x_data.shape,
y_data.shape)
if classes is not None:
classes = self._check_array(classes)
assert classes.shape[0] == x_data.shape[1], 'The classes shape {0} and data shapes {1} are off. Make sure the classes shape ' \
'equals the 2nd dimension of x and y_data'.format(classes.shape, x_data.shape)
assert len(classes.shape) == 1, 'The classes dimension is off. It is {0} but should be 1'.format(len(classes.shape))
return x_data, y_data, classes
class Base3DPlot(object):
def __init__(self, x_data, y_data, z_data):
pass
|
c93de6105a00387259bf38bb6c8dd026435c6e3c | jasonkrone/Infection | /utils.py | 1,588 | 4.1875 | 4 |
'''
By Jason Krone for Khan Academy
Implementation of subset sum Utils
'''
BASE_TUPLE = (True, 0, 0)
def subset_sum_within_range(nums, n, delta):
'''
returns a subset of the given numbers that sum within the given range
(n - delta, n + delta) if such a subset exists. Otherwise, returns None
'''
assert nums
subset = None
subset_sum_arr = positive_subset_sum_table(nums, n + delta)
# loop through values in range n - k to n + k
for i in range(n - delta, n + delta + 1):
# check if there is a sum set sum to i
if type(subset_sum_arr[i]) is tuple and subset_sum_arr[i] != BASE_TUPLE:
# get the subset that sums to i
subset = get_subset_with_sum(subset_sum_arr, i)
break
return subset
def get_subset_with_sum(table, n):
'''
returns the subset of numbers listed in the table that sum to n
'''
assert table
subset = []
i = n
while i > 0:
subset.append(table[i][1])
i = table[i][2]
return subset
def positive_subset_sum_table(A, x):
'''
attribution: this code was modified from
http://www.geekviewpoint.com/python/dynamic_programming/positive_subset_sum
'''
assert A
# algorithm
sub_sum = [None] * ( x + 1 )
sub_sum[0] = BASE_TUPLE
p = 0
while not sub_sum[x] and p < len( A ):
a = A[p]
q = x
while not sub_sum[x] and q >= a:
if not sub_sum[q] and sub_sum[q - a]:
sub_sum[q] = (True , a, q - a)
q -= 1
p += 1
return sub_sum
|
f69130c73fafadbb549e76dbdff4710c7e8091cb | netka78087/lesson2 | /string-challenges.py | 80 | 3.96875 | 4 | word = "Архангельск"
print(word[-1])
print(word.lower().count('а'))
|
fb98f5d02cad394472b23186e5dbc4b42ae391c6 | tt-n-walters/saturday-advanced-python | /f.py | 750 | 4.3125 | 4 | # Recursion, or a recursive function, is a function that calls itself.
import sys
sys.setrecursionlimit(10000)
counter = 0
cache = {}
fib = int(input("What number in the Fibonacci sequence do you want to calculate?\n"))
def fibonacci(n):
global counter
# print("Calculating:", n)
if n in cache:
return cache[n]
counter += 1
if n == 1 or n == 2:
# print("Anchor point")
return 1
temp = fibonacci(n - 1) + fibonacci(n - 2)
cache[n] = temp
return temp
print(fibonacci(fib))
print("Run", counter, "times.")
# print(cache)
# for items in cache.items():
# print(items)
# print(cache.items())
# for x in cache.items():
# print(x)
# Recursive explosive problem
# The solution is "cache" |
d08c01f1ff1794759a4ce0b327475e2e11bc402b | konstant-in/example1 | /p4.py | 1,405 | 4.09375 | 4 | '''
Использование декоратора, выполняющего необходимые вычисления
Если вернуться к исходному примеру,
то для подсчёта числа вызовов функции будет также может быть удобно использовать декораторы.
Это позволит в том числе и переиспользовать код.
При желании вы можете скомбинировать этот способ с каким-нибудь из описанных ранее.
'''
# Для Python 3 код может выглядеть, например, так:
from functools import wraps
def call_count(func):
count = 0
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal count
count += 1
func(*args, **kwargs)
print(count)
return wrapper
# Использоваться это будет следующим образом:
@call_count
def f():
pass
f() # 1
f() # 2
f()
f()
'''
В Python 2 нет nonlocal, но можно использовать изменяемые переменные:
from functools import wraps
def call_count(func):
count = [0]
@wraps(func)
def wrapper(*args, **kwargs):
count[0] += 1
func(*args, **kwargs)
print(count[0])
return wrapper
'''
|
e286b04458be9c0c645de176eb2f3525d35376fb | tonyshou015/python-homework | /作業5.py | 160 | 3.75 | 4 | year=eval(input("請輸入一個年份:"))
if (year%400 == 0) or ((year%4 == 0) and (year%100 != 0)):
print("閨年")
else:
print("平年")
|
8fc54278acf8731142acd51953f4a47e351ea6a6 | Hexexe/ML | /HighestSummit.py | 1,005 | 3.765625 | 4 | import math
import random
# generate random mountains
w = [.05, random.random()/3, random.random()/3]
h = [1.+math.sin(1+x/.6)*w[0]+math.sin(-.3+x/9.)*w[1]+math.sin(-.2+x/30.)*w[2] for x in range(100)]
def climb(x, h):
# keep climbing until we've found a summit
summit = False
#five steps either left or right.
while not summit:
summit = True # stop unless there's a way up
for x_new in range(max(0, x-5), min(99, x+5)):
print("x_new",x_new)
print("x",x)
if h[x + 1] > h[x]:
x = x + 1 # right is higher, go there
summit = False # and keep going
return x
def main(h):
# start at a random place
x0 = random.randint(1, 98)
x = climb(x0, h)
return x0, x
main(h) |
528b82b0494f06786ac7cc0aed0090234e8df36c | subham-dhakal/python-practice-files | /area.py | 192 | 4.40625 | 4 | #It prints the area of circle
r= float(input("Enter the radius of the circle\n"))
result=3.14*r*r
print("The area of the circle with radius {} is {} ".format(r,result))
print(50*'*')
|
b53ddce5170cd37973f00e7f9e8dc000f468af1f | gn0/sacsv | /sacsv/csvfindsortkey.py | 1,167 | 3.9375 | 4 | import argh
import csv
import sys
def is_ascending(iterable):
prev_value = None
for value in iterable:
if prev_value is not None and prev_value > value:
return False
prev_value = value
return True
def is_descending(iterable):
prev_value = None
for value in iterable:
if prev_value is not None and prev_value < value:
return False
prev_value = value
return True
def main():
reader = csv.reader(sys.stdin)
header = next(reader)
data = tuple(r for r in reader)
for k, column in enumerate(header):
if (is_ascending(r[k] for r in data)
or is_descending(r[k] for r in data)):
print(column)
sys.exit(0)
try:
if is_ascending(float(r[k]) for r in data):
print(column)
sys.exit(0)
except:
pass
try:
if is_descending(float(r[k]) for r in data):
print(column)
sys.exit(0)
except:
pass
def dispatch():
argh.dispatch_command(main)
if __name__ == "__main__":
dispatch()
|
ba750884bc4ab956934c4f6b824f1442dbacc7a6 | brandoneng000/LeetCode | /easy/2363.py | 743 | 3.703125 | 4 | from typing import List
class Solution:
def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
items = {}
for value, weight in items1:
items[value] = items.get(value, 0) + weight
for value, weight in items2:
items[value] = items.get(value, 0) + weight
return sorted(items.items())
def main():
sol = Solution()
print(sol.mergeSimilarItems(items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]))
print(sol.mergeSimilarItems(items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]))
print(sol.mergeSimilarItems(items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]))
if __name__ == '__main__':
main() |
4dcf7d760073da3776356f2c141e2fdde4deb551 | JeremiahZhang/gopython | /python-programming-an-introduction-to-CS/src/ch02/mass_convert.py | 395 | 4.15625 | 4 | # mass_convert.py
# A program to convert mass measured in kilogram to Pound
def main():
print("This is a program to convert mass measured")
print("in kilogram to pound.")
# input
kilogram = eval(input("Enter the mass measured in kilogram:_> "))
# process
pound = 2.20462 * kilogram
# output
print("The pound of the mass is: {} puounds".format(pound))
main()
|
069740854d3f61f6de62b2ccfad00ecd5b09a5f8 | vrunda13/1BM17CS126 | /2a.py | 151 | 3.75 | 4 | bol=0
l=eval(input("enter the string"))
key=int(input("enter the key"))
if key in l:
bol=1
if(bol==1):
print("true")
else print("false")
|
64b2825459d6057edd48c001b30188b735b2a602 | DidiRaggio/python_blockchain_test | /main.py | 1,088 | 4.125 | 4 | # from block import Block
# # Create the blockchain that functions like a LinkedList.
# class Node():
# def __init__(self):
# self.data = 5
# self._next = None
# # In a linked list each node is linked to each other by the _next attribute, so they are nested one within the other.
# # In a blockchain, we embed one block within the other using the hash. The hash garantees the chain has not been manipulated.
# block = Block("Hello World!")
# block.mine(20)
# print(f"Block's hash: {block.hash.hexdigest()}\nBlock's nonce: {block.nonce}\nBlock's data: {block.data}\n\n")
# block = Block("Hello WorlD!")
# block.mine(20)
# print(f"Block's hash: {block.hash.hexdigest()}\nBlock's nonce: {block.nonce}\nBlock's data: {block.data}\n\n")
from chain import Chain
chain = Chain(difficulty=20)
# i = 0
# while(True):
# data = input("Add something to the chain: ")
# chain.add_to_pool(data)
# chain.mine()
# if i % 5 == 0:
# print(chain.blocks[i])
# i += 1
for i in range(5):
chain.add_to_pool(f" Block #{i} ")
chain.mine()
|
30f9cc33f751c42cef2819306e00db4575db82e8 | MinaBasem/Basic-Projects | /BiggestNumber.py | 551 | 4.375 | 4 | # Biggest number
# Returns the biggest number from 3 user inoutted integers
import time
num1 = int(input("Please input the first number: "))
num2 = int(input("Please input the second number: "))
num3 = int(input("Please input the third number: "))
if (num1 > num2 and num1 > num3):
print("The largest number is %s" % num1)
time.sleep(6)
if (num2 > num1 and num2 > num3):
print("The largest number is %s" % num2)
time.sleep(6)
if (num3 > num1 and num3 > num2):
print("The largest number is %s" % num3)
time.sleep(6) |
d87b42438a60275a9408caf80db48d03ebdb7968 | RhevanP/BlackJackGame | /inputUserCheck.py | 1,117 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 21:38:08 2020
@author: antho
"""
def inputUserCheck(drawUserValue) :
if (len(drawUserValue) > 1) :
while True :
userInput = input('Do you want to Draw (1) or Stop (2) ?')
try :
userInput = int(userInput)
if userInput != 2 and userInput != 1 :
print("You did not enter a valid number, it's either 0 or 1!")
else :
break
except :
userInputLowered = userInput.lower()
if userInputLowered == 'draw' or userInputLowered == 'd' :
userInput = 1
print('drawing')
break
elif userInputLowered == 'stop' or userInputLowered == 's' :
userInput = 2
print('stopping')
break
else :
print('you did not input a correct option')
else :
userInput = 1
print('Drawing...')
return userInput |
5517b39e65edcc1fbad99755d1b3dd42380cd733 | alec-deason/ihme-python-course | /basic_python_exercises/topics/01_basic_syntax/03_strings/test_A.py | 467 | 3.984375 | 4 | from A import every_other_character, every_other_character_capitalized
def test_every_other_character():
for s in ['test', 'two words', 'a'*1000, '']:
assert every_other_character(s) == ''.join([c for i, c in enumerate(s) if i%2 != 0])
def test_every_other_character_capitalized():
for s in ['test', 'two words', 'a'*1000, '']:
assert every_other_character_capitalized(s) == ''.join([c if i%2 == 0 else c.upper() for i, c in enumerate(s)])
|
48fcb36b05b0c16ecf7ed0369882f2835372e8fe | florim14/projectEuler | /DigitFactorials/DigitFactorials.py | 394 | 3.671875 | 4 | import math
def digitFactorials():
result = 0
for i in range(10, 100000):
factorial = 0
for letter in str(i):
factorial += math.factorial(int(letter))
if i == factorial:
result += i
print(f'Number: {i} and his factorial is: {factorial}')
print(f'Result is: {result}')
if __name__ == '__main__':
digitFactorials()
|
dd8eccfdfa5cdcf7141de52b5403cfa355bbb339 | NeonedOne/Basic-Python | /Second Lab (2)/17.3. Дни рождения – 2.py | 287 | 3.65625 | 4 | # Алексей Головлев, группа БСБО-07-19
birthday_calendar = [input().split() for _ in range(int(input()))]
birthday_calendar.sort(key=lambda x: (int(x[1]), x[0]))
for i in range(int(input())):
month = input()
print(*[f'{i[0]} {i[1]}' for i in birthday_calendar if i[2] == month])
|
9b927b15f4fe471b80c7c449b112584e7c2097fe | alsofro/GB_algorithms | /7/2.py | 1,145 | 3.96875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
import random
array_1 = [random.random() * 50 for i in range(10)]
def merge_sort(arr):
if len(arr) < 2:
return arr
half = len(arr) // 2
left = merge_sort(arr[:half])
right = merge_sort(arr[half:])
out = []
li = ri = 0 # index of next element from left, right halves
while True:
if li >= len(left): # left half is exhausted
out.extend(right[ri:])
break
if ri >= len(right): # right half is exhausted
out.extend(left[li:])
break
if left[li] < right[ri]:
out.append(left[li])
li += 1
else:
out.append(right[ri])
ri += 1
return out
print(array_1)
array_2 = merge_sort(array_1)
print(array_2) |
82091c0f366db45db0a7cb39896f74e1ac9a8875 | 8v10/eprussas | /1_LogicaDeProgramacao/0_Python/3_Python_Parte3/6 - Classes e Objetos/2.2 Pessoa - Métodos.py | 323 | 3.78125 | 4 | class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
def apresentacao(self):
print("Olá, meu nome é: " + self.nome)
print ("Tenho " , self.idade , "anos.\n")
p1 = Pessoa("Hugo", 26)
p2 = Pessoa("João", 18)
p2.idade=21
p1.apresentacao()
p2.apresentacao()
|
553ae4066bd9f6b6071c1d1110c449736547c11c | mthompson36/newstuff | /Exercise2.py | 207 | 4.34375 | 4 | #This program will return in your number is odd or even.
number = int(input("Please enter a number:"))
if (number % 2) == 0:
print(str(number) +" Can be divided by 2")
else:
print("This is an odd number") |
12c65dc7ddc74bdaaab9c6badf673b3d6e960ea5 | MadHypnofrog/cutting-rule-predictor | /datasets/stats_collector.py | 4,873 | 3.5 | 4 | import pandas as pd
import numpy as np
import os
from utils.html_builder import HTMLBuilder
from .stats_calculator import StatsCalculator
calc = StatsCalculator()
"""
A class that provides utility functions used to collect the statistics.
"""
"""
Collects the statistics on a single dataset and writes them to a HTMLBuilder.
Parameters
----------
ds_path : str
Path to the folder with the datasets.
ds_name : str
The dataset name.
builder : HTMLBuilder
HTMLBuilder to write the results to.
metrics : array-like
Array of metrics to use in calculations. All elements should be valid metrics to use in
StatsCalculator.stats_for_rules.
stats_d : dict of pairs (metric_name, [baseline, metrics]), optional
Statistics for the dataset (same format as in StatsCalculator.read_stats or write_stats). If present, no
calculation is done and the statistics are just written to the HTMLBuilder.
Returns
-------
dict of pairs (metric_name, [baseline, metrics]) - statistics for the dataset. Returns stats_d if it is not None.
"""
def process_ds(ds_path, ds_name, builder, metrics, stats_d=None):
df = pd.read_csv(ds_path + "\\" + ds_name + ".csv", dtype='int8')
data, target = df.drop('class', axis=1), df['class']
if stats_d is None:
stats_d = {}
stats = calc.stats_for_rules(data, target, metrics)
baselines = calc.baseline(data, target, metrics)
for i in range(len(metrics)):
stats_d[metrics[i]] = [baselines[i], stats[i]]
builder.write_ds(df, ds_name, stats_d)
return stats_d
"""
Iterates through all datasets in a specified folder, collects their statistics and writes them to a HTMLBuilder.
Parameters
----------
html_path : str
Path to the folder where all the html documents would be created.
table_name : str
Table name to use. The builder writes its content to html_path + table_name.
ds_path : str
Path to the folder with the datasets.
start : str, optional
If not None, all datasets that are lexicographically smaller than start would be skipped.
log : str, optional
Path to the log file. If present, calculated statistics would be saved into that file.
metrics : array-like, optional
Array of metrics to use in calculations. All elements should be valid metrics to use in
StatsCalculator.stats_for_rules.
stats : dict of pairs (ds_name, dict of pairs (metric_name, [baseline, metrics])), optional
Precomputed stats for the datasets. Would be also saved to the log file if it is present. See StatsCalculator
for dict format.
Returns
-------
None
"""
def run_all(html_path, table_name, ds_path, start=None, log=None, metrics=['f1_micro'], stats=None):
if start is None:
builder = HTMLBuilder(html_path, table_name)
else:
builder = HTMLBuilder(html_path, table_name, new=False)
if log is not None:
logh = open(log, 'wb')
skip = True
stats_write = {}
for filename in os.listdir(ds_path):
ds_name = os.path.splitext(filename)[0]
if start != None and ds_name != start and skip:
continue
skip = False
if stats is not None and ds_name in stats:
process_ds(ds_path, ds_name, builder, metrics, stats_d=stats[ds_name])
else:
stats_write[ds_name] = process_ds(ds_path, ds_name, builder, metrics)
builder.write_ending()
if stats_write != {}:
if stats is not None:
stats_write.update(stats)
calc.write_stats(logh, stats_write)
"""
Collects statistics of a single dataset and writes them into a separate table.
Parameters
----------
html_path : str
Path to the folder where all the html documents would be created.
single_table_name : str
Table name to use. The builder writes its content to html_path + (single_table_name % ds_name).
ds_path : str
Path to the folder with the datasets.
ds_name : str
The dataset name.
metrics : array-like, optional
Array of metrics to use in calculations. All elements should be valid metrics to use in
StatsCalculator.stats_for_rules.
stats_d : dict of pairs (metric_name, [baseline, metrics]), optional
Statistics for the dataset (same format as in StatsCalculator.read_stats or write_stats). If present, no
calculation is done and the statistics are just written to the HTMLBuilder.
Returns
-------
None
"""
def run_single(html_path, single_table_name, ds_path, ds_name, metrics=['f1_micro'], stats_d=None):
builder = HTMLBuilder(html_path, single_table_name % ds_name)
process_ds(ds_path, ds_name, builder, metrics, stats_d=stats_d)
builder.write_ending()
|
41721542914420018b8d115320e8ae93dbc84930 | alexbalonperin/university-projects | /AI Programming/Natural Language Processing/src/MachineLearning/Classifier/ProbDistI.py | 3,661 | 3.984375 | 4 | '''
Created on Nov 23, 2011
@author: alex
'''
import random, warnings, math
_NINF = float('-1e300')
class ProbDistI(object):
"""
A probability distribution for the outcomes of an experiment. A
probability distribution specifies how likely it is that an
experiment will have any given outcome. For example, a
probability distribution could be used to predict the probability
that a token in a document will have a given type. Formally, a
probability distribution can be defined as a function mapping from
samples to nonnegative real numbers, such that the sum of every
number in the function's range is 1.0. C{ProbDist}s are often
used to model the probability distribution of the experiment used
to generate a frequency distribution.
"""
SUM_TO_ONE = True
"""True if the probabilities of the samples in this probability
distribution will always sum to one."""
def __init__(self):
if self.__class__ == ProbDistI:
raise AssertionError, "Interfaces can't be instantiated"
def prob(self, sample):
"""
@return: the probability for a given sample. Probabilities
are always real numbers in the range [0, 1].
@rtype: float
@param sample: The sample whose probability
should be returned.
@type sample: any
"""
raise AssertionError()
def logprob(self, sample):
"""
@return: the base 2 logarithm of the probability for a given
sample. Log probabilities range from negitive infinity to
zero.
@rtype: float
@param sample: The sample whose probability
should be returned.
@type sample: any
"""
# Default definition, in terms of prob()
p = self.prob(sample)
if p == 0:
# Use some approximation to infinity. What this does
# depends on your system's float implementation.
return _NINF
else:
return math.log(p, 2)
def max(self):
"""
@return: the sample with the greatest probability. If two or
more samples have the same probability, return one of them;
which sample is returned is undefined.
@rtype: any
"""
raise AssertionError()
# deprecate this (use keys() instead?)
def samples(self):
"""
@return: A list of all samples that have nonzero
probabilities. Use C{prob} to find the probability of
each sample.
@rtype: C{list}
"""
raise AssertionError()
# cf self.SUM_TO_ONE
def discount(self):
"""
@return: The ratio by which counts are discounted on average: c*/c
@rtype: C{float}
"""
return 0.0
# Subclasses should define more efficient implementations of this,
# where possible.
def generate(self):
"""
@return: A randomly selected sample from this probability
distribution. The probability of returning each sample
C{samp} is equal to C{self.prob(samp)}.
"""
p = random.random()
for sample in self.samples():
p -= self.prob(sample)
if p <= 0: return sample
# allow for some rounding error:
if p < .0001:
return sample
# we *should* never get here
if self.SUM_TO_ONE:
warnings.warn("Probability distribution %r sums to %r; generate()"
" is returning an arbitrary sample." % (self, 1-p))
return random.choice(list(self.samples())) |
8f18b62bda492bbf65c61fd420761637eb01015a | tylerdowney1337/Bacteria_Program | /Bacteria_Program.py | 12,560 | 4.3125 | 4 | # Bacteria Program
# Date: April 21st, 2021
# Authors: Tyler Downey, Troy Green, Wesley Squires, Ciaran Kelly
""" This program is used to track bacteria samples that are being used to test new medications."""
""" Key Features:
- Date entry box (current date as default)
- ID number of the bacterial culture
- Dropdown menu to select the type of bacteria in that culture (options read from bacteria.dat)
- Dropdown menu for the type of medicine being tested on that culture (options read from medicine.dat)
- Morning (6 am) bacteria count entry box
- Evening (6 pm) bacteria count entry box
- "Confirm" button that adds data as an entry in a list box in following format:
- date - culture id – bacteria type – medicine type – morning population reading – evening population
reading – calculated rate of change ((evening population reading)/(morning population reading)) -1).
- We can use this button to also validate the entries
- "Save" button that writes the data to separate lines in a file of the user's choosing.
- Need an entry box for filename.
- "Graph" button which plots a graph (matplotlib) of the bacteria's growth or decline.
- Formula: y = a*x + b, where b = (morning population reading), and
a = ((evening population reading) – (morning population reading))/12
- When the “Graph” button is pressed, the user can be prompted to enter the starting x value for the
plot, and the ending x value for the plot.
- "Add Bacteria" button: When this button is pressed, a window is opened, and a bacterial culture is added to the dropdown
menu, as well as to the file bacteria.dat.
- “Add Medicine” button: opens a new window that allows the user to enter the name of a new bacteria, and upon hitting
a confirm button then, it will be added to the appropriate dropdown menu and added to the file medicine.dat.
- "Exit" button: exits the program when user is finished.
"""
from tkinter import *
from tkinter import ttk, messagebox
import datetime
import matplotlib.pyplot as plt
### FUNCTIONS ###
confirmed = False
def confirm():
# GLOBALIZE VARIABLES
global date
global id_number
global bacteria
global medicine
global morning_count
global evening_count
global confirmed
# DEFINE VALIDATIONS
valid_numbers = set("1234567890-")
valid_letters = set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ")
# DATE
if date_var.get() == "":
messagebox.showerror(title="Input Error", message="Date cannot be blank.")
date_entry.focus_set()
return
elif set(date_var.get()).issubset(valid_numbers):
date = date_var.get()
else:
messagebox.showerror(title="Input Error", message="Date can only contain numbers.")
date_entry.focus_set()
return
# ID NUMBER
if id_number_var.get() == "":
messagebox.showerror(title="Input Error", message="ID number cannot be blank.")
id_number_entry.focus_set()
return
elif set(id_number_var.get()).issubset(valid_numbers):
id_number = id_number_var.get()
else:
messagebox.showerror(title="Input Error", message="ID number can only contain numbers.")
id_number_entry.focus_set()
return
# BACTERIA
bacteria = bacteria_var.get()
# MEDICINE
medicine = medicine_var.get()
# MORNING COUNT
if morning_var.get() == "":
messagebox.showerror(title="Input Error", message="Morning count cannot be blank.")
morning_entry.focus_set()
return
elif set(morning_var.get()).issubset(valid_numbers):
morning_count = morning_var.get()
else:
messagebox.showerror(title="Input Error", message="Morning Count can only contain numbers.")
morning_entry.focus_set()
return
# EVENING COUNT
if evening_var.get() == "":
messagebox.showerror(title="Input Error", message="Evening count cannot be blank.")
evening_entry.focus_set()
return
elif set(evening_var.get()).issubset(valid_numbers):
evening_count = evening_var.get()
else:
messagebox.showerror(title="Input Error", message="Evening Count can only contain numbers.")
evening_entry.focus_set()
return
confirmed = True
# PRINT TO LISTBOX
bacteria_listbox.delete(0, END)
bacteria_listbox.insert(0, "Date: {}".format(date))
bacteria_listbox.insert(1, "ID Number: {}".format(id_number))
bacteria_listbox.insert(2, "Bacteria: {}".format(bacteria))
bacteria_listbox.insert(3, "Medicine: {}".format(medicine))
bacteria_listbox.insert(4, "Morning Count: {}".format(morning_count))
bacteria_listbox.insert(5, "Evening Count: {}".format(evening_count))
def save():
if confirmed == True:
#Creates Save Window
save_window = Tk()
#Creates title for window
save_window.title("Save")
#Sets Dimensions for window
save_window.geometry("205x85")
#input Box and Variable
savelabel= Label(save_window, text="Filename: ", padx=5, pady=5)
#shows label on grid
savelabel.grid(row=0, column=0, sticky=E)
#shows entry box
filename_entry = Entry(save_window, width=16)
filename_entry.grid(row=0, column= 1, sticky=W, pady= 5, padx= 5)
# SAVE TO FILE FUNCTION
def save_to_file():
file = open(f"{filename_entry.get()}", "w")
file.writelines(f"Date: {date}\n")
file.writelines(f"Bacteria: {bacteria}\n")
file.writelines(f"ID Number: {id_number}\n")
file.writelines(f"Medicine: {medicine}\n")
file.writelines(f"Morning Count: {morning_count}\n")
file.writelines(f"Evening Count: {evening_count}\n")
file.close()
# SAVE BUTTON
save_to_file_button = Button(save_window, text="SAVE", command=save_to_file)
save_to_file_button.grid(row=1, column=0, columnspan=2, padx=5, pady=5, ipadx=10, ipady=5)
else:
messagebox.showerror(title="CONFIRMATION ERROR", message="Data must be confirmed before saving...")
def graph():
# x axis values
x = [0, 6, 12, 18, 24, 30]
# Y axis values
y = [100, 80, 60, 40, 20, 0]
# plotting the points
plt.plot(x, y, color='red', linestyle='solid', linewidth=2,
marker='o', markerfacecolor='black', markersize=12)
# setting x and y axis range
plt.ylim(1, int(f"{morning_count}"))
plt.xlim(1, 30)
# naming the x axis
plt.xlabel('Bacteria')
# naming the y axis
plt.ylabel('Medicine')
# giving a title to my graph
plt.title('Information')
# function to show the plot
plt.show()
def add_bacteria():
#Creates Window for bacteria
bacteria_window = Tk()
#Creates title for window
bacteria_window.title("Add Bacteria")
#Sets dimensions of window
bacteria_window.geometry("225x90")
#Input Box and Variable
bacteria_add_label = Label(bacteria_window, text="Bacteria Name: ", pady=2)
bacteria_add_label.grid(row=0, column=0, sticky=E)
bacteria_add_entry = Entry(bacteria_window, width=16)
bacteria_add_entry.grid(row=0, column=1, sticky=W, pady=5, padx=5)
def add_bacteria_button():
bacteria_list = open("bacteria.dat", 'a')
bacteria_added = bacteria_add_entry.get()
bacteria_list.writelines("{}\n".format(bacteria_added))
bacteria_list.close()
#Add Button
add_button = Button(bacteria_window, text="Add", width=15, height=2, command=add_bacteria_button)
add_button.grid(row=1, column=0, columnspan=2, padx=5, pady=5)
def add_medicine():
# Creates Window for bacteria
medicine_window = Tk()
# Creates title for window
medicine_window.title("Add Medicine")
# Sets dimensions of window
medicine_window.geometry("225x90")
# Input Box and Variable
medicine_add_label = Label(medicine_window, text="Medicine Name: ", pady=2)
medicine_add_label.grid(row=0, column=0, sticky=E)
medicine_add_entry = Entry(medicine_window, width=16)
medicine_add_entry.grid(row=0, column=1, sticky=W, pady=5, padx=5)
def add_medicine_button():
medicine_list = open("medicine.dat", 'a')
medicine_added = medicine_add_entry.get()
medicine_list.writelines("{}\n".format(medicine_added))
medicine_list.close()
# Add Button
add_button = Button(medicine_window, text="Add", width=15, height=2, command=add_medicine_button)
add_button.grid(row=1, column=0, columnspan=2, padx=5, pady=5)
def exit():
quit()
### MAIN WINDOW ###
root = Tk()
root.geometry("550x355")
root.title("Medrix Database")
root.iconbitmap("pill.ico")
# FRAMES
frame1 = LabelFrame(root, text="Culture Data")
frame1.grid(column=0, row=0, padx=5, pady=5, ipadx=10, ipady=10)
frame2 = LabelFrame(root, text="Bacteria Counts")
frame2.grid(row=1, column=0, padx=5, pady=5, ipadx=10, ipady=10)
frame3 = Frame(root)
frame3.grid(row=0, column=1, rowspan=2, padx=5, pady=5, ipadx=10, ipady=10)
frame4 = Frame(root)
frame4.grid(row=2, column=1, padx=5, pady=5, ipadx=10, ipady=10)
### LABELS AND BOXES ###
# DATE
current_date = datetime.datetime.today().strftime('%d-%m-%y')
date_var = StringVar()
date_label = Label(frame1, text="Date: ")
date_label.grid(row=0, column=0, pady=5, padx=5, sticky="w")
date_entry = Entry(frame1, textvariable=date_var)
date_entry.grid(row=0, column=1, pady=5, padx=5)
date_var.set(current_date)
# ID NUMBER
id_number_var = StringVar()
id_number_label = Label(frame1, text="ID Number: ")
id_number_label.grid(row=1, column=0, pady=5, padx=5, sticky="w")
id_number_entry = Entry(frame1, textvariable=id_number_var)
id_number_entry.grid(row=1, column=1, padx=5, pady=5)
# BACTERIA
bacteria_list = []
bacteria_file = open("bacteria.dat", "r")
for line in bacteria_file:
bacteria_list.append(line.strip())
bacteria_var = StringVar()
bacteria_label = Label(frame1, text="Bacteria: ")
bacteria_label.grid(row=2, column=0, padx=5, pady=5, sticky="w")
bacteria_combobox = ttk.Combobox(frame1, values=bacteria_list, textvariable=bacteria_var, width=17)
bacteria_combobox.grid(row=2, column=1, padx=5, pady=5)
# MEDICINE
medicine_list = []
medicine_file = open("medicine.dat", "r")
for line in medicine_file:
medicine_list.append(line.strip())
medicine_var = StringVar()
medicine_label = Label(frame1, text="Medicine: ")
medicine_label.grid(row=3, column=0, padx=5, pady=5, sticky="w")
medicine_combobox = ttk.Combobox(frame1, values=medicine_list, textvariable=medicine_var, width=17)
medicine_combobox.grid(row=3, column=1, padx=5, pady=5)
# MORNING COUNT
morning_var = StringVar()
morning_label = Label(frame2, text="Morning (6 AM) Count: ")
morning_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
morning_entry = Entry(frame2, textvariable=morning_var, width=10)
morning_entry.grid(row=0, column=1, padx=5, pady=5)
# EVENENING COUNT
evening_var = StringVar()
evening_label = Label(frame2, text="Evening (6 PM) Count: ")
evening_label.grid(row=1, column=0, padx=5, pady=5, sticky="w")
evening_entry = Entry(frame2, textvariable=evening_var, width=10)
evening_entry.grid(row=1, column=1, padx=5, pady=5)
# CONFIRM BUTTON
confirm_button = Button(root, text="CONFIRM", command=confirm)
confirm_button.grid(row=2, column=0, ipadx=15, ipady=5, sticky="n")
# BACTERIA LISTBOX TITLE
bacteria_listbox_label = Label(frame3, text="BACTERIA DATA")
bacteria_listbox_label.grid(row=0, column=0, padx=5)
# BACTERIA DATA LISTBOX
bacteria_listbox = Listbox(frame3, height=14, width=40)
bacteria_listbox.grid(row=1, column=0, padx=5, pady=5)
# SAVE BUTTON
save_button = Button(frame4, text="SAVE", command=save)
save_button.grid(row=0, column=0, padx=5, ipadx=15, ipady=5)
# SAVE BUTTON
graph_button = Button(frame4, text="GRAPH", command=graph)
graph_button.grid(row=0, column=1, padx=5, ipadx=10, ipady=5)
# EXIT BUTTON
exit_button = Button(frame4, text="EXIT", command=exit)
exit_button.grid(row=0, column=2, padx=5, ipadx=15, ipady=5)
### MENU ###
### MENUS ###
root_menu = Menu(root, tearoff=False)
root.config(menu=root_menu)
# File Menu
file_menu = Menu(root_menu, tearoff=False)
root_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Exit", command=exit)
# Edit Menu
edit_menu = Menu(root_menu, tearoff=False)
root_menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Add Bacteria", command=add_bacteria)
edit_menu.add_command(label="Add Medicine", command=add_medicine)
root.mainloop()
|
5402eb86778aebbfdc42f7e74b759a9e2aa63633 | maryoohhh/pythoncourse | /sort_print_list.gyp | 1,112 | 4.4375 | 4 | # Building three functions: sort, reverse sort, and print list
pizza_toppings = [
'Hawaiian',
'Champagne Ham & CheeseBeef & Onion',
'Pepperoni',
'Simply Cheese',
'Bacon & Mushroom',
'Italiano',
'The Deluxe',
'Ham, Egg & Hollandaise',
'Americano',
'Mr Wedge',
'BBQ Meatlovers'
]
def sort_list(lst): #defining function sort_list that takes 1 parameter called lst
return sorted(lst, key=str.lower) #sorting lst case insensitive without changing the list
def sort_reverse_list(lst): #defining function sort_reverse_list that takes 1 parameter called lst
return [ele for ele in reversed(sorted(lst, key=str.lower))] #reverse sorting lst case insensitive without changing the list
def print_list(lst): #defining function print_list that takes 1 parameter called lst
for i in sorted(lst, key=str.lower): #iterating, sorting lst case insensitive
print (i) #printing each element in sorted list
print(pizza_toppings)
print("\n")
print(sort_list(pizza_toppings))
print("\n")
print(sort_reverse_list(pizza_toppings))
print("\n")
print_list(pizza_toppings) |
f077d35368564785ad90ed067f7b20a2661418e9 | AminaAbdallah/Assignment-4 | /Looking_for_a_specificTopic.py | 1,591 | 3.796875 | 4 | import json
import pandas
import requests
#MyApiKey : 'b7de039e294740bb84d8dff8c2bbf97d'
# The headers for the authentification
print('NB : the result of this request will be found in the console or in the csv file that you choose its location in the code in the end')
print('Please, enter your Apikey for APInews or you can use mine in the comment up')
headers = {'Authorization':input()}
#we will use the endpoint Everything in this case
everything_news_url = 'https://newsapi.org/v2/everything'
print('Which topic are you asking for ? ')
#qInTitle to search the topic in the title of articles
everything_payload = {'qInTitle':input()}
response = requests.get(url=everything_news_url, headers=headers, params=everything_payload)
print(response)
# Priny the response in json file
pretty_json_output = json.dumps(response.json(), indent=4)
#print(pretty_json_output)
# Convert response to a json string
response_json_string = json.dumps(response.json())
print(response_json_string)
# retrieve json objects to a python dict
response_dict = json.loads(response_json_string)
# Info about articles is represented as an array in the json response
# A json array is equivalent to a list in python
articles_list = response_dict['articles']
# sources_list = response_dict['sources'] if we want info only about sources
# Convert articles list to json string , convert json string to dataframe , write df to csv!
df = pandas.read_json(json.dumps(articles_list))
# Using Pandas write the json data to a csv
#You can edit the emplacement of the csv file here
df.to_csv(r'C:\Users\octet plus\Desktop\theTopic.csv')
|
9fbc579942a50a5f1c6e8f4f1cdeddef1c0b7e4e | DIVYAKHYANI/data_structures_with_python | /Delete_node(linked_list).py | 404 | 3.90625 | 4 |
def deleteNode(head, position):
current = head
# next will point to None if there is
# not another item in the list
if position == 0:
head = head.next
else:
# iterate to the right node
for i in range(position-1):
current = current.next
# and alter the next pointer
current.next = current.next.next
return head
|
38d424c1d811c8de0c8403996047f4fd75e99a73 | SThiara/learning-python | /full_speed_python/lists/even_squares_not_three.py | 177 | 3.890625 | 4 | def getSquare():
l1=[ x**2 for x in range(0, 21, 2) if x % 3 != 0]
#l1 = [num for num in [num**2 for num in range(0, 21, 2)] if (num % 3 != 0)]
return l1
print(getSquare()) |
b97e91d1cada52eda9505cd6925573068cf65699 | Rvioleck/python_noj_exmination | /noj_041佩尔数.py | 189 | 3.75 | 4 | def pell_number(n):
pell = [0, 1]
for i in range(2, n+1):
num = 2 * pell[i-1] + pell[i-2]
pell.append(num)
return pell[n]
n = int(input())
print(pell_number(n)) |
9332eee3c716dc325513c442ccbc8c3100df360f | DiyanKalaydzhiev23/fundamentals---python | /Final exam 3/Mirror Words.py | 622 | 3.859375 | 4 | import re
pattern = r"(@|#)(?P<word1>[a-zA-Z]{3,})\1\1(?P<word2>[A-Za-z]{3,})\1"
words = [el.groupdict() for el in re.finditer(pattern, input())]
if not words:
print("No word pairs found!")
print("No mirror words!")
else:
print(f"{len(words)} word pairs found!")
mirror_words = []
for el in words:
if el['word1'] == el['word2'][::-1]:
if not mirror_words:
print(f"The mirror words are:")
mirror_words.append(f"{el['word1']} <=> {el['word2']}")
if not mirror_words:
print("No mirror words!")
else:
print(*mirror_words, sep=", ")
|
18e5a47cd62dd44507f1ba4459774a86a03c4783 | DincerDogan/Data-Science-Learning-Path | /Data Scientist Career Path/3. Python Fundamentals/6. Python Loop/1. Intro to Loop/1. loop.py | 518 | 3.984375 | 4 | # Write 10 print() statements below!
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!") |
d11db2e2e3bc1ff0856de20800259a9dd418bae6 | demonzyz/huice | /yearText.py | 239 | 3.84375 | 4 | # coding=utf-8
input_year = raw_input("请输入测试年份:")
year = int(input_year)
if ((year%4 == 0 and year%100 != 0) or (year%400 == 0)):
print('%d年是闰年!' % year)
else:
print('%d年是平年、不是闰年!' % year) |
89081f11fd2ae26e7d17551e3bed8c37bb16630b | katur/rc-warmups | /h02_tens.py | 714 | 4 | 4 | '''Write a function that takes a list of numbers and returns all adjacent
sublists that sum to 10. You can assume that all numbers are non-negative.
E.g.
tens([2, 3, 5, 5, 4, 1, 0, 9, 1])
-> [ [2,3,5], [5,5], [5,4,1], [5,4,1,0], [1,0,9], [0,9,1], [9,1]]
'''
TEN = 10
def tens(all_numbers):
start = 0
end = 1
while start < len(all_numbers):
numbers = all_numbers[start:end]
sum_numbers = sum(numbers)
if sum_numbers == TEN:
yield numbers
if sum_numbers > TEN or end >= len(all_numbers):
start += 1
end = start + 1
else:
end += 1
if __name__ == '__main__':
print list(tens([2, 3, 5, 5, 4, 1, 0, 9, 1]))
|
2be60e318e5396f52ef3e24cf69597f3eb71be27 | PrachiNayak89/Prachi-rampUp | /ticTacToeUserInput.py | 1,248 | 3.890625 | 4 | #!/usr/bin/python
#This program is to take the user input for the game
#default board
game=[[0,0,0],
[0,0,0],
[0,0,0]]
print game
count=1
#1 for player 1 and 2 for player 2
userInput1=None
userInput2=None
while True and userInput1!="exit" and userInput2!="exit":
if count%2!=0:
userInput1=raw_input('Player 1 please enter row <space> col for number in position :')
if userInput1=="exit":
break
rowCol=userInput1.split(" ")
row=int(rowCol[0])
col=int(rowCol[1])
row-=1
col-=1
if game[row][col]==0:
game[row][col]=1
else:
print 'Already filled position!'
continue
print game
count+=1
if count==10:
break
if count%2==0:
userInput2=raw_input('Player 2 please enter row <space> col for number in position :')
if userInput2=="exit":
break
rowCol=userInput2.split(" ")
row=int(rowCol[0])
col=int(rowCol[1])
row-=1
col-=1
if game[row][col]==0:
game[row][col]=2
else:
print 'Already filled position!'
continue
print game
count+=1
|
aeb0329976587d6d5f1aa07ca94a58ddecfd7d23 | Italo-Neves/Python | /Curso-Em-Video/M2/ex42.py | 759 | 4 | 4 | # -*- coding: utf-8 -*-
r1 = float(input('Digite o valor da reta 01: '))
r2 = float(input('Digite o valor da reta 02: '))
r3 = float(input('Digite o valor da reta 03:'))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r2 + r1:
triangulo = True
print('Esse valores geram um triagunlo ')
else:
triagunlo = False
print('Esse valores não geram um triagunlo')
if triangulo == True and r1 == r2 == r3:
print('Por possuir todos os lados iguais esse triagunlo é EQUILATERO')
elif triangulo == True and r1 == r2 != r3 or r2 == r3 != r1 or r3 == r1 != r2:
print('Por possuir dois lados iguais esse triangulo é isórceles')
elif triangulo == True and r1 != r2 != r3:
print('Por possuir todos os lados diferentes esse triangulo é Escaleno')
|
288eb7d63c4456fd5fc3ce5dac26dc3dad4bc35b | Kvazar78/Skillbox | /11_float_round/dz/task_11.py | 1,992 | 4.125 | 4 | # В рамках разработки шахматного ИИ стоит новая задача. По заданным вещественным координатам
# коня и второй точки программа должна определить может ли конь ходить в эту точку. Используйте
# как можно меньше конструкций if и логических операторов. Обеспечьте контроль ввода.
#
# Пример:
#
# Введите местоположение коня:
# 0.071
# 0.118
#
# Введите местоположение точки на доске:
# 0.213
# 0.068
#
# Конь в клетке (0, 1). Точка в клетке (2, 0).
# Да, конь может ходить в эту точку.
flag_coordinates = False
while flag_coordinates ==False:
print('Введите местоположение коня')
x = float(input(': '))
y = float(input(': '))
print('\nВведите местоположение точки на доске')
x_dot = float(input(': '))
y_dot = float(input(': '))
if 0 < x < 0.8 and 0 < y < 0.8 and 0 < x_dot < 0.8 and 0 < y_dot < 0.8:
flag_coordinates = True
else:
print('Придется вводить все заново - где-то опечата!')
x = int((x * 10) % 10)
y = int((y * 10) % 10)
x_dot = int((x_dot * 10) % 10)
y_dot = int((y_dot * 10) % 10)
print(f'Конь в клетке ({x}, {y}). Точка в клетке ({x_dot}, {y_dot}).')
flag_Xmove = False
flag_Ymove = False
list_x = [x + 2, x - 2, x + 1, x - 1]
list_y = [y + 2, y - 2, y + 1, y - 1]
for i in list_x:
if i == x_dot:
flag_Xmove = True
break
for i in list_y:
if i == y_dot:
flag_Ymove = True
break
if flag_Xmove and flag_Ymove:
print('Да, конь может ходить в эту точку.')
else:
print('Сюда ходить нельзя') |
ffb7ea774a493d89a97da369540f52f90a85e877 | zeppertrek/my-python-sandpit | /python-training-courses/pfc-sample-programs/tuple_example_003.py | 580 | 4.28125 | 4 | #tuple_example_003.py
# Weird declarations of a tuple
# Python lets you do this
# Question is - Does it make sense ?
# Model your tuples on real world data
#
myTuple1 = ([],(),[], "a", 1, 1.6, 444555, "goosebumps", {1,2,3,4})
print (myTuple1)
x = 100
myTuple2 = ("aaabbbbbbbbcccccccccccc", type(myTuple1), id(myTuple1), x + 1, print, [[[[[]]]]], {})
print (myTuple2)
myTuple3 = (1,2,3,4,5,6,7)
print (myTuple3)
#myTuple3[0] = 9 ;
print ( "Length / Size of the tuple - 3 is " , len (myTuple3))
myTuple4 = myTuple3[:]
print (myTuple4)
|
0c3f68f0e0623c4132a8a676555fcce6bf3a6746 | MrHamdulay/csc3-capstone | /examples/data/Assignment_1/bxxbub001/question3.py | 1,496 | 3.671875 | 4 | #B.Booi 3 march 2014
#spam msg
name = input ("Enter first name:\n")
last = input ("Enter last name:\n")
money = eval(input("Enter sum of money in USD:\n"))
country = input("Enter country name:\n")
print("")
print('Dearest ', name ,sep='')
print('It is with a heavy heart that I inform you of the death of my father,',sep='')
print('General Fayk ',last,', your long lost relative from Mapsfostol.',sep='')
print('My father left the sum of ',money,'USD for us, your distant cousins.',sep='')
print('Unfortunately, we cannot access the money as it is in a bank in ',country,'.',sep='')
print('I desperately need your assistance to access this money.')
print('I will even pay you generously, 30% of the amount - ',money*0.3,'USD,',sep='')
print('for your help. Please get in touch with me at this email address asap.')
print('Yours sincerely')
print('Frank ',last,sep='')
#Below is retype to find space error
#print('Dearest ',name,sep='')
#print('It is with a heavy heart that I inform you of the death of my father,')
#print('General Fayk ',last,', your long lost relative from Mapsfostol.',sep='')
#print('My father left the sum of ',money,'USD for us, your distant cousins.',sep='')
#printUnfortunately, we cannot access the money as it is in a bank in South Africa.
#I desperately need your assistance to access this money.
#I will even pay you generously, 30% of the amount - 370.2USD,
#for your help. Please get in touch with me at this email address asap.
#Yours sincerely
#Frank Star
|
ee644c00dc2b083aee9a4c56f0709bdc7b50f89d | Hidenver2016/Leetcode | /Python3.6/243-Py3-Shortest-Word-Distance.py | 2,026 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 17:44:03 2019
@author: hjiang
"""
"""
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
"""
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {string[]} words
# @param {string} word1
# @param {string} word2
# @return {integer}
# def shortestDistance(self, words, word1, word2):
# dist = float("inf")
# i, index1, index2 = 0, None, None
# while i < len(words):
# if words[i] == word1:
# index1 = i
# elif words[i] == word2:
# index2 = i
#
# if index1 is not None and index2 is not None:
# dist = min(dist, abs(index1 - index2))#对应于多个有重复的情况,比如有两个makes
# i += 1
#
# return dist
#自己写的,一定要注意while的用法,因为最后的i+=1如果是在一个条件里面的话,while的i是只有满足条件才更新的
def shortestDistance(self, words, word1, word2):
dist = float("inf")
i, index1, index2 = 0, None, None
for i in range(len(words)):
if words[i] == word1:
index1 = i
elif words[i] == word2:
index2 = i
if index1 is not None and index2 is not None:
dist = min(dist, abs(index1 - index2))#对应于多个有重复的情况,比如有两个makes
# i += 1
return dist
if __name__ == "__main__":
print(Solution().shortestDistance(["practice", "makes", "perfect", "coding", "makes"], "coding", "practice")) |
d7aead547d4e8e95ae181d76fada1c0fc73b572d | rhanmiano/100days-coding-challenge | /py/day4-multiples-3-5.py | 794 | 4.28125 | 4 | ##
# 100 Days Coding Challenge
#
# @author Rhan Miano
# @since November 6, 2018
#
# Pushing myself to do this 100 Days Coding Challenge.
##
# Day 4 Reverse a string
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below the provided parameter value number.
# Iterate throught the number, and along the loop
# check for all multiples of 3 and 5 by
# using modulo. If index is a multiple, then add
# it on to nSum.
def getSumMulti(args):
nSum = 0
for i in range(1, args):
if(i%3 == 0 or i%5 == 0):
nSum = nSum + i;
return nSum
num = 10
print("Number: {} | Sum of multiples of 3 and 5: {}".format(num, getSumMulti(num))) |
7b14b3163b9e7b153d34548d248362cfddb468bb | EugenenZhou/leetcode | /nowcoder/jzoffer/Merge.py | 1,397 | 3.9375 | 4 | # -*- coding:utf-8 -*-
# 合并两个链表
# 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
#
######################################################################
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def ToListNode(l):
reason = ListNode(0)
list = reason
for num in l:
list.next = ListNode(int(num))
list = list.next
return reason.next
######################################################################
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
head = ListNode(0)
dump = head
if not pHead1:
return pHead2
if not pHead2:
return pHead1
one = pHead1
two = pHead2
while one != None and two != None:
if one.val < two.val:
dump.next = ListNode(one.val)
dump = dump.next
one = one.next
else:
dump.next = ListNode(two.val)
dump = dump.next
two = two.next
if one == None:
dump.next = two
else:
dump.next = one
return head.next
# write code here
######################################################################
|
50bada4376a1f366eb4a2e97e8944703297f4963 | parry1233/Pyrthon_practice | /pamdas_dataframe.py | 482 | 3.546875 | 4 | import pandas as pd
names = ['United States','Australia','Japan','India','Russia','Morocco','Egypt']
dr =[True,False,False,False,True,True,True]
cpc=[809,731,588,18,200,70,45]
cars_dict={'country':names,'drives_right':dr,'cars_per_capital':cpc}
print('Before dataframed:')
print(cars_dict)
print('After dataframed:')
cars_df=pd.DataFrame(cars_dict)
print(cars_df)
#specify rows label
row_labels = ['US','AUS','JPN','IN','RU','MOR','EG']
cars_df.index = row_labels
print(cars_df) |
42ac00be509f5f5aed7e5469f6aa858a736a4664 | athul-santhosh/The-Daily-Byte | /gather n ary traversal.py | 681 | 3.625 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root : return []
cur = []
next = []
result = []
cur.append(root)
while cur:
each_level = []
for node in cur:
each_level.append(node.val)
for child in node.children:
next.append(child)
cur = next
result.append(each_level)
next = []
return result |
bf16a579749459eb2e5bf382ae4c22981b2ea0ca | imd8594/GroupMeTic-Tac-Toe | /groupme_tictactoe.py | 5,986 | 3.703125 | 4 | """
Ian Dansereau
groupme_tictactoe.py
April 5, 2016
Groupme tic tac toe game made using only a bot.
GroupyAPI docs here: http://groupy.readthedocs.org/en/master/
GroupMe Dev page: https://dev.groupme.com/
"""
from groupy import Bot, Group
#groupme constents
groupid = ""
bot_name = ""
bot = [bot for bot in Bot.list() if bot.name == bot_name][0]
bot_triggers = ["!"+bot_name]
games = []
def printHelp():
bot.post("To start a game do '!<bot_name> start, @Yourname, @Opponentsname'\nTo move do '!ttt move, @Yourname, Position(0-8)'\nTo End a game do '!<bot_name> end'")
def getBot():
return [bot for bot in Bot.list() if bot.name == bot_name][0]
#TODO: figure out how to fix groupme output
def printBoard(game):
post = " " + game['board'][0] + " | " + game['board'][1] + " | " + game['board'][2] + "\n " + "--------" + "\n " + game['board'][3] + " | " + game['board'][4] + " | " + game['board'][5] + "\n " + "--------" + "\n " + game['board'][6] + " | " + game['board'][7] + " | " + game['board'][8] + "\n"
bot.post(post)
def getLatestMessage():
return [group for group in Group.list() if group.group_id == groupid][0].messages().newest
#Checks to see if the player is already participating in a game
#Returns True if player is currently in a game
def playerAlreadyInGame(playerName):
for game in games:
if game['p1']['name'] == playerName or game['p2']['name'] == playerName:
return True
return False
#Checks if there is a tie or someone has won the game
#Returns True if there is an end-game condition
def checkForWin(game):
board = game['board']
if board[0] == board[1] == board[2] != " ":
endGame(game)
return True
if board[3] == board[4] == board[5] != " ":
endGame(game)
return True
if board[0] == board[3] == board[6] != " ":
endGame(game)
return True
if board[1] == board[4] == board[7] != " ":
endGame(game)
return True
if board[2] == board[5] == board[8] != " ":
endGame(game)
return True
if board[0] == board[4] == board[8] != " ":
endGame(game)
return True
if board[2] == board[4] == board[6] != " ":
endGame(game)
return True
if checkForTie(game):
endGame(game)
return True
return False
def checkForTie(game):
board = game['board']
if " " not in board:
return True
else:
return False
#Move validation done by making sure target space is empty and it is your turn
#Returns True if move is valid
def isValidMove(game, playerName, position):
try:
if game['board'][int(position)] != " ":
return False
except IndexError:
return False
if game['p1']['name'] == playerName:
if game['p1']['turn'] == False:
return False
if game['p2']['name'] == playerName:
if game['p2']['turn'] == False:
return False
return True
#Creates a new game and allows for multiple games at the same time
#Returns True is creating new game is successful
#Returns False if Creator of game still has an ongoing game
def newGame(player1Name, player2Name):
player1 = {'name':player1Name, 'piece':'X', 'turn':True}
player2 = {'name':player2Name, 'piece':'O', 'turn':False}
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
for game in games:
if game['creator'] == player1Name:
return False
games.append({'creator':player1Name, 'p1':player1, 'p2':player2, 'board':board})
printBoard(games[-1])
return True
#Method for allowing the creator of the game to end it early
#Returns true if Ending game is successful
def playerEndGame(playerName):
index = ""
for game in games:
if game['creator'] == "@"+playerName:
index = game
try:
games.remove(game)
bot.post("Game over!")
return True
except Exception:
return False
#Ends game when there is a winner or a tie
#Returns True if ending the game is successful
def endGame(game):
try:
games.remove(game)
bot.post("Game over!")
return True
except Exception:
return False
#Moves players piece to board position
#Returns True if PlayerMove is successful
def doPlayerMove(playerName, boardPosition):
move_game = ""
playerNumber = ""
for game in games:
if game['p1']['name'] == playerName:
move_game = game
playerNumber = 'p1'
if game['p2']['name'] == playerName:
move_game = game
playerNumber = 'p2'
if isValidMove(move_game, playerName, boardPosition):
move_game['board'][int(boardPosition)] = move_game[playerNumber]['piece']
if playerNumber == 'p1':
move_game['p1']['turn'] = False
move_game['p2']['turn'] = True
if playerNumber == 'p2':
move_game['p2']['turn'] = False
move_game['p1']['turn'] = True
printBoard(move_game)
checkForWin(move_game)
return True
else:
return False
#Parses command to make sure it is valid
#Returns True if command is valid
def parseCommand(name, command):
command = command.split(",")
command = [option.strip() for option in command]
if command[0] == 'help':
printHelp()
return True
if command[0] == 'start' and command[1][0] == "@" and command[2][0] == "@":
if not playerAlreadyInGame(command[1]) and not playerAlreadyInGame(command[2]):
return newGame(command[1], command[2])
else:
return False
if command[0] == 'end':
return playerEndGame(name)
if command[0] == 'move' and command[1][0] == "@" and int(command[2]) <= 8:
if name not in command[1]:
return False
if playerAlreadyInGame(command[1]):
return doPlayerMove(command[1], command[2])
else:
return False
return False
#Main process. Runs forever and will keep trying to reconnect after network failure
#Probably bad but there is no way to get notified of new messages that I know of
def runBot():
while True:
try:
bot = getBot()
message = getLatestMessage().text.lower()
name = getLatestMessage().name.lower()
if any(substring in message for substring in bot_triggers):
command = message.split(bot_name)[1]
if parseCommand(name, command):
pass
else:
bot.post("Invalid Command")
except Exception as e:
print(e)
runBot()
|
9a2c91c655c7ba7daac34460e858802bcb0b8237 | Blackoutta/python_tutorials | /treehouse/object/instance.py | 345 | 3.609375 | 4 | my_list = ["apple", 5.2, "dog", 8, True, False]
def combiner(mlist):
words = ''
nums = 0
for i in mlist:
if isinstance(i, str):
words += i
elif i == True:
pass
elif isinstance(i, (int, float)):
nums += i
output = words + str(nums)
print(output)
combiner(my_list) |
9ec4e55c043c9b431d8995dc2ad5a52e233dbeaa | leogtzr/python-cookbook-code-snippets | /data_structures_and_algorithms/combining_multiple_mappings_into_single_mapping1.py | 473 | 3.859375 | 4 | from collections import ChainMap
# A ChainMap takes multiple mappings and makes them logically appear as one.
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
c = ChainMap(a, b)
for k, v in c.items():
print(c[k])
print('~~~~~~~~~~~~')
print(c['x'])
print(c['y'])
print(c['z'])
print('~~~~~~~~~~~~~~~~~~~~>')
for k in c.keys():
print(k)
c['_'] = 'Leonardo'
print(c)
# Mutate an element:
c['z'] = 7456
print(c['z'])
# Removing an element:
del c['x']
print(c)
|
dc2561155abaafd3b2e6dade63433c8777fe692d | Alice86/StatsProgramming | /20170929Start.py | 4,486 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
""" arithmetics """
print 2 + 2
print 50 - 5*6
print (50 - 5.0*6) / 4
print 8 / 5.0
print 8 / 5
# power **
5**2
""" floating vs int """
# operators with mixed type operands convert the integer operand to floating point
# int / int -> int
print 17 / 3
# int / float -> float
print 17 / 3.0
# the % operator returns the remainder of the division
print 17 % 3
# print and combine string and arithmetics
print '5 * 3 + 2 = ', 5 * 3 + 2
"""" variables """
width = 20
height = 5 * 9
width * height
print 'width * height =', width * height
""" Lists """
# most versatil, comma-separated values (items) between square brackets
# might contain items of different types, but usually of the same type.
squares = [1, 4, 9, 16, 25]
print squares
""" Indexing, slicing, modification, length """
# Indexing from 0
# Indices may also be negative, to start counting from the right
# -0 is the same as 0, negative indices start from -1.
print squares[0]
print squares[-3]
# slicing, obtain a sublist of items.
# defaults: omitted first index defaults to 0, omitted second index defaults to the size of the list
print squares[0:2] # items from position 0 (included) to 2 (excluded)
print squares[:3] # items from the beginning to position 3 (excluded print squares[-3:] # slicing returns a new list
print squares[:]
# Modification & appending: mutable type
# the item in position 0
cubes = [1, 8, 27, 65, 125] # something’s wrong here, the cube of 4 is 64, not 65! cubes[3] = 6
print cubes
# append() method:
cubes.append(216) # add the cube of 6
cubes.append(7 ** 3) # and the cube of 7 print cubes
# len()
print len(cubes)
""" Nesting """
a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
print x
print x[0]
print x[0][1]
""" Loop: while, if, for """
# Fibonacci series
# a = 0
# b = 1
#while (b<10) {
# print (b)
# c=a; a=b; b=b+c }
a, b = 0,1 # multiple assignment: variables a and b simultaneously get new values
while b<10:
# standard comparison operators the same as in C: < (less than), > (greater than), == (equal to),
# <= (less than or equal to), >= (greater than or equal to) and != (not equal to).
# The body of the loop must be indented by the same amount.
print b
a, b = b, a+b
# expressions on the right-hand side evaluated first before any of the assignments take place
# right-hand side expressions are evaluated from the left to the right.
# The condition may also be a string or list value
# anything with a non-zero length is true, empty sequences are false;
# like in C, any non-zero integer value is true; zero is false.
#x = 42
#if (x < 0) {
# x=0
# print ("Negative changed to zero")
#} else if (x == 0) {
# print ("Zero")
#} else if (x == 1) {
# print ("Single")
#} else {
# print ("More") }
# elif is short for “else if”, useful to avoid excessive indentation.
x = 42
if x < 0:
x=0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
# Pascal: always iterating over an arithmetic progression of numbers
# C: giving the user the ability to define both the iteration step and halting condition
# Python: iterates over the items of any sequence (a list or a string),
# in the order that they appear in the sequence
# Measure some strings:
#words = c("cat", "window", "defenestrate")
#for (w in words) {
# print (list (w, nchar(w))) } / print (w); print (nchar(w)) }
words = ['cat', 'window', 'defenestrate' ]
for w in words:
print w, len(w)
# range(): iterate over a sequence of numbers
print range(10)
print range(5, 10)
print range(0, 10, 3)
for x in range(-10, -100, -30):
print x
""" Functions """
# create a function that writes the Fibonacci series to an arbitrary boundary n:
def fib(n):
result=[]
a, b = 0,1
while b < n:
result.append(b)
a, b = b, a+b
return result
# Store the result into a variable.
fib_200 = fib(200)
print fib_200
""" vectors and matrices """
# numpy: fundamental package for scientific computing, already included in the Anaconda distribution.
# start import first.
import numpy as np
# vector
x = np.array([1,2,3])
x
print x
# matrix
y = np.array([[2,3],[4,5]])
print y
# a range of numbers in a vector
np.arange(10)
## array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) start from 0
#lists commands for MATLAB, R, and Python: http://mathesaurus.sourceforge.net/matlab-python-xref.pdf
|
34b6045d7ed6a81051d3f57bdbdb177e9d64383d | sch0nik/python-project-lvl1 | /brain_games/games/even.py | 592 | 3.90625 | 4 | """Главный элемент игры чет-нечет."""
from random import randint
RULES_OF_THE_GAME = 'Answer "yes" if the number is even, otherwise answer "no".'
def generate_game_values():
"""
Сама игра.
Функция придумывает число, показывает пользователю,
и спрашивает ответ.
Returns:
Возвращает вопрос и верный результат.
"""
number = randint(0, 1000)
return (
str(number),
'yes' if number % 2 == 0 else 'no',
)
|
4ebca1ef89f7c234477f3b809e8be7d3bef6799b | Aliciaalexandriachew/python_practice | /P1/src/futval.py | 548 | 3.890625 | 4 | '''
Created on 20 Jul 2020
@author: Alicia
'''
'''
Study Unit 1 Activity 14:
'''
def main():
print("Calculate your future worth through compound interest:")
principal = int(input("Enter the amount of money in dollars: $"))
apr = float(input("Enter bank annual interest rate as decimal number: "))
n = int(input("Enter the number of years: "))
for i in range(n):
principal = principal * (1 + apr)
print("The compounded interest for" , n , "years is $" , principal)
main()
|
5d2022720a315bfa4d5034ddf71065460396bb50 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2424/60619/243144.py | 273 | 3.671875 | 4 | t = int(input())
for index in range(t):
length = int(input())
numbers = input().split(" ")
exist = False
for n in numbers:
if numbers.count(n)%2 == 1:
print(n)
exist = True
break
if not exist:
print(0) |
46ce73a607f6a177c3dbb306d4247dbfd5573551 | dalexach/holbertonschool-machine_learning | /supervised_learning/0x06-keras/0-sequential.py | 1,332 | 3.703125 | 4 | #!/usr/bin/env python3
"""
Building a model with Keras
"""
import tensorflow.keras as K
def build_model(nx, layers, activations, lambtha, keep_prob):
"""
Function that that builds a neural network with the Keras library
Arguments:
- nx is the number of input features to the network
- layers is a list containing the number of nodes in each layer
of the network
- activations is a list containing the activation functions used for
each layer of the network
- lambtha is the L2 regularization parameter
- keep_prob is the probability that a node will be kept for dropout
Returns:
The keras model
"""
model = K.Sequential()
regularizer = K.regularizers.l2(lambtha)
model.add(K.layers.Dense(layers[0], input_shape=(nx,),
activation=activations[0],
kernel_regularizer=regularizer,
name='dense'))
for layer in range(1, len(layers)):
dname = 'dense_' + str(layer)
model.add(K.layers.Dropout(1 - keep_prob))
model.add(K.layers.Dense(layers[layer],
activation=activations[layer],
kernel_regularizer=regularizer,
name=dname))
return model
|
b592eb6d84a9c8b4009b9fe1febbf4be581bd90f | BrandonNay/distributed-systems | /genetic-algorithms/src/population.py | 2,260 | 3.546875 | 4 | # Population Class | Genetic Algorithm
from random import randint
from random import choice
class Population:
class Member:
def __init__(self, lifespan=50, write_dna=True):
self.lifespan = lifespan
self.fitness = 0
self.directions = ["U", "D", "L", "R"]
if write_dna:
self.DNA = [choice(self.directions) for x in range(self.lifespan)]
else:
self.DNA = []
def __eq__(self, other):
return self.fitness == other
def __ne__(self, other):
return self.fitness != other
def __lt__(self, other):
return self.fitness < other
def __gt__(self, other):
return self.fitness > other
def get_fitness(self, feedback):
pass
def mutate(self, mutation_rate):
for i in range(len(self.DNA)):
chance = randint(0, 100)/100
if chance < mutation_rate:
self.DNA[i] = choice(self.directions)
def __init__(self, spawn, pop_size=10, mutation_rate=0.1):
self.spawn = spawn # (x, y) tuple, np format
self.population_size = pop_size
self.mutation_rate = mutation_rate
self.members = [self.Member() for x in range(self.population_size)]
def batch_fitness(self):
for x in self.members:
x.get_fitness() # TODO
def batch_mutate(self):
for x in self.members:
x.mutate(self.mutation_rate)
def crossover(self):
new_pop = []
parents = self.selection()
for x in range(self.population_size//2):
p1 = choice(parents)
p2 = choice(parents)
child1 = self.Member(lifespan=p1.lifespan, write_dna=False)
child2 = self.Member(lifespan=p1.lifespan, write_dna=False)
pos = randint(0, p1.lifespan) # crossover point
child1.DNA = p1.DNA[:pos] + p2.DNA[pos:]
child2.DNA = p2.DNA[:pos] + p1.DNA[pos:]
new_pop.append(child1)
new_pop.append(child2)
self.members = new_pop
def selection(self):
self.members.sort(reverse=True)
return self.members[0:self.population_size//2]
|
d867d0d88bc1eafefff32c27db6ace861a320f5e | elephantscale/emlp-labs-macys | /recommendations/code/knn-recommender/src/utils.py | 2,242 | 3.53125 | 4 | import numpy as np
import pandas as pd
from fuzzywuzzy import fuzz
def fuzzy_matching(mapper, fav_movie, verbose=True):
"""
return the closest match via fuzzy ratio. If no match found, return None
Parameters
----------
mapper: dict, map movie title name to index of the movie in data
fav_movie: str, name of user input movie
verbose: bool, print log if True
Return
------
index of the closest match
"""
match_tuple = []
# get match
for title, idx in mapper.items():
ratio = fuzz.ratio(title.lower(), fav_movie.lower())
if ratio >= 60:
match_tuple.append((title, idx, ratio))
# sort
match_tuple = sorted(match_tuple, key=lambda x: x[2])[::-1]
if not match_tuple:
print('Oops! No match is found')
return
if verbose:
print('Found possible matches in our database: {0}\n'.format([x[0] for x in match_tuple]))
return match_tuple[0][1]
def make_recommendation(model_knn, data, mapper, fav_movie, n_recommendations):
"""
return top n similar movie recommendations based on user's input movie
Parameters
----------
model_knn: sklearn model, knn model
data: movie-user matrix
mapper: dict, map movie title name to index of the movie in data
fav_movie: str, name of user input movie
n_recommendations: int, top n recommendations
Return
------
list of top n similar movie recommendations
"""
# fit
model_knn.fit(data)
# get input movie index
print('You have input movie:', fav_movie)
idx = fuzzy_matching(mapper, fav_movie, verbose=True)
# inference
distances, indices = model_knn.kneighbors(data[idx], n_neighbors=n_recommendations+1)
# get list of raw idx of recommendations
raw_recommends = \
sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1]
# get reverse mapper
reverse_mapper = {v: k for k, v in mapper.items()}
# print recommendations
print('Recommendations for {}:'.format(fav_movie))
for i, (idx, dist) in enumerate(raw_recommends):
print('{0}: {1}, with distance of {2}'.format(i+1, reverse_mapper[idx], dist))
|
6ae970c3b68ad461f4fe03fa9544bf06c9540860 | campbellmarianna/Rest-API-with-Flask-Course | /section-2-python-refresher/passing_functions.py | 546 | 4.15625 | 4 | def methodception(another):
return another()
def add_two_numbers():
return 35 + 77
# print(methodception(add_two_numbers))
# print(methodception(lambda: 35 + 77)) # a lambda function is an anonymous function - always one line
my_list = [13, 56, 77, 484]
def not_thirteen(x):
return x != 13
# filter this list using this function - basicly all of the numbers that were not 13
print(list(filter(not_thirteen, my_list))) # method that allows you keep only some values, takes in an iterator
print([x for x in my_list if x != 13])
|
9cdfa0d8ab4c04d3632cba11be364ff7743257a3 | tgtn007/DSAinPython | /Projects/project1_UnscrambleCSProblems/Task4.py | 1,406 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
listOfAllCallers = set()
for callers in calls:
listOfAllCallers.add(callers[0])
# Removing the numbers which received calls.
for callers in calls:
if callers[1] in listOfAllCallers:
listOfAllCallers.remove(callers[1])
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
# Removing numbers that sent or received texts
for texters in texts:
if texters[0] in listOfAllCallers:
listOfAllCallers.remove(texters[0])
if texters[1] in listOfAllCallers:
listOfAllCallers.remove(texters[1])
listOfAllCallers = list(listOfAllCallers)
listOfAllCallers = sorted(listOfAllCallers)
print("These numbers could be telemarketers: ")
for caller in listOfAllCallers:
print(caller)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
|
893f4ab88dd20603cb9115498c9e46ab1d81061d | sandeep24789/Python | /Python/demo2.py | 148 | 4 | 4 | a=int(input("enter the number"))
if(a>10):
print("true")
print(a)
elif(a<8):
print("else if false")
print(a)
else:
print("end")
|
b253242888ac240d778687a0694ba12e7087c4e1 | mitsurukikkawa/Python | /DeepQNetwork/qlearning-ab.py | 2,482 | 3.921875 | 4 | '''
環境の状態は、'A'または'B'からなる長さ8の文字列で表され、
その文字列にはある法則により得点がつけられる。
プレイヤーはその法則についての知識を予め持たないが、
文字列中の任意の1文字を選んで'A'または'B'に置き換えることができ、
その結果、その操作による得点の変化量を報酬として受け取る。
https://zaburo-ch.github.io/post/q-learning/
'''
import numpy as np
import matplotlib.pyplot as plt
STR_LEN = 8
ALPHA = 0.1
GAMMA = 0.99
EPS = 0.1
def int_to_state(n):
ret = ""
for i in range(STR_LEN):
if (n >> i) & 1:
ret += "B"
else:
ret += "A"
return ret
def score(s):
point_dict = {"A": 1, "BB": 1, "AB": 2, "ABB": 3, "BBA": 3, "BBBB": 4}
ret = 0
for i in range(STR_LEN):
for j in range(i, STR_LEN):
if s[i:j+1] in point_dict:
ret += point_dict[s[i:j+1]]
return ret
def do_action(s, a):
current_score = score(s)
if a == 0:
next_s = s
elif 1 <= a <= STR_LEN:
next_s = s[:a-1] + "A" + s[a:]
else:
next_s = s[:a-STR_LEN-1] + "B" + s[a-STR_LEN:]
reward = score(next_s) - current_score
return next_s, reward
def QLearning(n_rounds, t_max):
# init
s0 = "A" * STR_LEN
A = range(STR_LEN*2+1)
Q = {}
for i in range(2**STR_LEN):
Q[int_to_state(i)] = np.random.random(len(A))
score_history = []
# learn
for i in range(n_rounds):
s = s0
for t in range(t_max):
# select action
if np.random.random() < EPS:
a = Q[s].argmax()
else:
a = np.random.choice(A)
# do action
next_s, reward = do_action(s, a)
# update Q, and change s
Q[s][a] += ALPHA * (reward + GAMMA*Q[next_s].max() - Q[s][a])
s = next_s
print("round {0:4d}: {1} = {2:2d}".format(i, s, score(s)),)
# test
s = s0
for t in range(t_max):
a = Q[s].argmax()
s, _ = do_action(s, a)
score_history.append(score(s))
print("test result: {0} = {1}".format(s, score_history[i]))
# visualize
plt.plot(score_history)
plt.show()
if __name__ == '__main__':
np.random.seed(123)
QLearning(1000, 20)
|
d398fade4929ed636bb4a78c7515eb376147e0ab | ferreret/python-bootcamp-udemy | /36-challenges/ex130.py | 636 | 4.375 | 4 | '''
three_odd_numbers([1,2,3,4,5]) # True
three_odd_numbers([0,-2,4,1,9,12,4,1,0]) # True
three_odd_numbers([5,2,1]) # False
three_odd_numbers([1,2,3,3,2]) # False
'''
def three_odd_numbers(numbers):
len_numbers = len(numbers)
for cursor in range(2, len_numbers):
sum_test = numbers[cursor - 2] + numbers[cursor - 1] + numbers[cursor]
if sum_test % 2 == 1:
return True
return False
print(three_odd_numbers([1, 2, 3, 4, 5])) # True
print(three_odd_numbers([0, -2, 4, 1, 9, 12, 4, 1, 0])) # True
print(three_odd_numbers([5, 2, 1])) # False
print(three_odd_numbers([1, 2, 3, 3, 2])) # False
|
18fa511636b3030d52d0b8c5977a16172c63a2d2 | eric496/leetcode.py | /hash_table/974.subarray_sums_divisible_by_K.py | 758 | 3.734375 | 4 | """
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.
Example 1:
Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Note:
1 <= A.length <= 30000
-10000 <= A[i] <= 10000
2 <= K <= 10000
"""
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
res = accsum = 0
mod_d = {0: 1}
for n in A:
accsum += n
if accsum % K in mod_d:
res += mod_d[accsum % K]
mod_d[accsum % K] += 1
else:
mod_d[accsum % K] = 1
return res
|
7e2514db4fddaf2e035f709a8f290c75101d192a | Plasmoxy/MaturitaInformatika2019 | /python/noob/pocet_9.py | 147 | 3.515625 | 4 |
x = int(input("Zadajte prir. c. : "))
c = 0
while x > 1:
if x % 10 == 9:
c += 1
x //= 10
print(f"Pocet cislic 9 v cisle je {c}") |
1f48e4b35006edee4231595aa8fb26e4f18f65a0 | FrenchBear/Python | /Learning/130_Fluent_Python/fp2-utf8/bloccode/example 6-12.py | 352 | 3.90625 | 4 | # Example 6-12. A simple class to illustrate the danger of a mutable default
class HauntedBus:
"""A bus model haunted by ghost passengers"""
def __init__(self, passengers=[]):
self.passengers = passengers
def pick(self, name):
self.passengers.append(name)
def drop(self, name):
self.passengers.remove(name)
|
9f2ef944ebf7ed8fd6f377d68e2825e3b659bd54 | edu-athensoft/stem1401python_student | /py200913d_python2m4/day09_201108/global_scope_2.py | 236 | 3.546875 | 4 | """
global scope
global variable - A variable which is defined and takes effect in global scope
"""
x = 10
def foo():
"""
x does not change here
:return:
"""
print("x inside:", x+1)
foo()
print("x outside:", x) |
62a90aa794b1901327a1500d1ba8d995e85db44a | weilian1977/openmv-project | /openmv/6-10_find_outliers.py | 7,582 | 3.578125 | 4 | # Untitled - By: 黄惠泽 - 周四 6月 7 2018
import sensor, image, time
## Red Threshold in LAB color space for finding the largest blobs
red_threshold_LAB =(51, 75, 19, 84, -7, 70)
## Red Threshold in RGB color space for get_pixels() finding the right color
red_threshold_RGB= (200,256,0,160,0,180)
## Global variables for finding the largest blob
most_pixels = 0
largest_blob = 0
# Lists stores coordinates on x, y axis of two sets of points on each edge respectively
list1=[]
list2=[]
list3=[]
list4=[]
## Threshold for black line
rgb_line = (0,0 ,0)
##################################################################################################################################
## Define a function given the coordinates (x, y) of sample points and returns a, b of best fitting regression line using least squares
##################################################################################################################################
def calcAB(x,y):
if x is not None and y is not None:
n = len(x)
sumX,sumY,sumXY,sumXX =0,0,0,0
for i in range(0,n):
sumX += x[i]
sumY += y[i]
sumXX += x[i]*x[i]
sumXY += x[i]*y[i]
if (n*sumXX -sumX*sumX)!= 0:
a = (n*sumXY -sumX*sumY)/(n*sumXX -sumX*sumX)
b = (sumXX*sumY - sumX*sumXY)/(n*sumXX-sumX*sumX)
else:
a=0
b=0
return a,b
############################
## Remove Outliers Module ##
############################
##function of finding median##
def find_median(lst):
q2=0
n=len(lst)
lst=sorted(lst)
if n!=0:
if n%2==0:
q2=(lst[int(n/2)]+lst[int(n/2-1)])/2
if n%2==1:
q2=lst[int((n-1)/2)]
return q2
else:
return q2
## Find quartiles ##
def find_quartile(lst):
lst1=[]
lst2=[]
q1=0
q3=0
n=len(lst)
lst=sorted(lst)
if n%2==0:
lst1=lst[0:int(n/2)]
lst2=lst[int(n/2):int(n)]
else:
lst1=lst[0:int((n-1)/2)]
lst2=lst[int((n-1)/2+1):int(n)]
q1=find_median(lst1)
q3=find_median(lst2)
return q1,q3
## Remove outliers ##
def remove_outliers(lst1,lst2,m,n):
q1=0
q3=0
IQR=0
mini=0
maxi=0
i=0
lst_dis=[]
for i in range(len(lst_dis)):
lst_dis.append(abs(lst2[i]-(m*lst1[i]+n)))
q1,q3=find_quartile(lst_dis)
IQR=q3-q1
mini=q1-0.1*IQR
maxi=q3+0.1*IQR
if len(lst_dis)!=0 and len(lst_dis)<len(lst2):
while i<len(lst_dis):
if lst_dis[i]<mini or lst_dis[i]>maxi:
lst2.pop(i)
lst1.pop(i)
i -= 1
i +=1
return lst1,lst2
else:
return lst1,lst2
######################################################################################
## Define a function combining find_largest_blob module and find_sets_of_points module
######################################################################################
def find_redLines():
blobs = img.find_blobs([red_threshold_LAB], area_threshold=150)
if blobs:
most_pixels = 0
largest_blob = 0
for i in range(len(blobs)):
if blobs[i].pixels() > most_pixels:
most_pixels = blobs[i].pixels()
largest_blob = i
img.draw_rectangle(blobs[largest_blob].rect(),color=(0,0,0))
img.draw_cross(blobs[largest_blob].cx(),blobs[largest_blob].cy())
#for y in range(240):
#pixels1 = img.get_pixel(160,y)
#if pixels1[0]>red_threshold_RGB[0] and pixels1[0]<red_threshold_RGB[1] and pixels1[1]>red_threshold_RGB[2] and pixels1[1]<red_threshold_RGB[3] and pixels1[2]>red_threshold_RGB[4] and pixels1[2]<red_threshold_RGB[5]:
#list1.append(160)
#list2.append(y)
#break;
## Find pixels from above edge of rectangle
for x in range(0,320,20):
a,b = calcAB(list1,list2)
for y in range(blobs[largest_blob].y(),blobs[largest_blob].y()+blobs[largest_blob].h()):
pixels1 = img.get_pixel(x,y)
if pixels1[0]>red_threshold_RGB[0] and pixels1[0]<red_threshold_RGB[1] and pixels1[1]>red_threshold_RGB[2] and pixels1[1]<red_threshold_RGB[3] and pixels1[2]>red_threshold_RGB[4] and pixels1[2]<red_threshold_RGB[5]:
#if abs(y-(a*x+b))<20:
list1.append(x)
list2.append(y)
img.draw_cross(x, y)
break;
## Find pixels from below edge of rectangle
lst=range(blobs[largest_blob].y(),blobs[largest_blob].y()+blobs[largest_blob].h())
lst1=[i for i in reversed(lst)]
#for y in lst1:
#pixels1 = img.get_pixel(10,y)
#if pixels1[0]>red_threshold_RGB[0] and pixels1[0]<red_threshold_RGB[1] and pixels1[1]>red_threshold_RGB[2] and pixels1[1]<red_threshold_RGB[3] and pixels1[2]>red_threshold_RGB[4] and pixels1[2]<red_threshold_RGB[5]:
#list3.append(10)
#list4.append(y)
for x in range(0,320,20):
a,b = calcAB(list3,list4)
for y in lst1:
pixels1 = img.get_pixel(x,y)
if pixels1[0]>red_threshold_RGB[0] and pixels1[0]<red_threshold_RGB[1] and pixels1[1]>red_threshold_RGB[2] and pixels1[1]<red_threshold_RGB[3] and pixels1[2]>red_threshold_RGB[4] and pixels1[2]<red_threshold_RGB[5]:
#if abs(y-(a*x+b))<20:
list3.append(x)
list4.append(y)
img.draw_cross(x, y)
break;
return list1, list2, list3, list4, red_threshold_RGB
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
clock = time.clock()
while(True):
clock.tick()
img = sensor.snapshot()
img = img.lens_corr(1.8) # for 2.8mm lens...
list1,list2,list3,list4,present_threshold=find_redLines()
## Calculate the slope and intercept a, b for the first line and print it in the serial terminal
a,b=calcAB(list1,list2)
## Take two points on the line and draw it on the image
line_tuple = (20, int(a*20+b), 300, int(a*300+b))
img.draw_line(line_tuple, color=rgb_line)
print("line1_before: y = %10.3fx + %10.3f" %(a,b))
print("y1_before:",list2)
list1,list2=remove_outliers(list1,list2,a,b)
a,b=calcAB(list1,list2)
print("line1_after: y = %10.3fx + %10.3f" %(a,b))
print("y1_after:",list2)
## Take two points on the line and draw it on the image
line_tuple = (20, int(a*20+b), 300, int(a*300+b))
img.draw_line(line_tuple, color=(0,0,255))
## Calculate the slope and intercept c, d for the second line and print it in the serial terminal
c,d=calcAB(list3,list4)
## Take two points on the line and draw it on the image
line_tuple = (20, int(c*20+d), 300, int(c*300+d))
img.draw_line(line_tuple, color=rgb_line)
print("line2_before: y = %10.3fx + %10.3f" %(c,d))
print("x1",list3)
print("y2_before:",list4)
list3,list4=remove_outliers(list3,list4,c,d)
c,d=calcAB(list3,list4)
print("line2_after: y = %10.3fx + %10.3f" %(c,d))
print("y2_after:",list4)
## Take two points on the line and draw it on the image
line_tuple = (20, int(c*20+d), 300, int(c*300+d))
#img.draw_line(line_tuple, color=(0,0,255))
## Clear the list ##
list1.clear()
list2.clear()
list3.clear()
list4.clear()
print("fps:",clock.fps())
|
62be4fa6944fe2bc709a4b6346d0bf58259d4814 | HalfMoonFatty/Interview-Questions | /680. Valid Palindrome II.py | 872 | 4.03125 | 4 | '''
Problem:
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
'''
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
def isValid(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
for i in range(len(s)/2):
if s[i] != s[len(s)-i-1]:
j = len(s)-i-1
return isValid(s, i+1, j) or isValid(s, i, j-1)
return True
|
9842673e1c18352b51157ed3aa4a9e706874966d | wiput1999/Python101 | /7 Extra 4/P.55 Part IV/9.py | 100 | 3.65625 | 4 | def leadingdigit(n):
t = str(n)
return t[0]
a = int(input("num : "))
print(leadingdigit(a)) |
bf05cc91e97097ef50442498af34b60411a58c92 | shivan-s/AutomateTheBoringStuff | /Chapter9/selectiveCopy.py | 1,192 | 3.640625 | 4 | #! python3
# selectiveCopy.py Program walks through folder tree and searches files ending with .pdf or .jpg into a new folder
# using ./SelectiveCopy/americanFiles as a test
import os, shutil
#function to copy
def copyFormat(folder,fileFormat):
folder = os.path.abspath(folder)
print('\nFOLDER to copy...\n %s\n' % folder)
print(f'Searching for format: \'{fileFormat}\'\n')
print('FILES to copy:')
newLocation = folder + '_new'
if not os.path.exists(newLocation):
os.mkdir(newLocation)
# walk the tree
for folderName, subfolders, filenames in os.walk(folder):
for filename in filenames:
if filename.endswith(fileFormat):
fileToCopy = folderName + '\\' + filename
print('filename: %s' % fileToCopy)
shutil.copy(fileToCopy, newLocation + '\\' + filename)
print('\nFILES copied to...\n%s\n' % newLocation)
def main():
# select file formats
fileFormat = '.txt'
path_ = r'Chapter9\SelectiveCopy\americanFiles'
pathToCopy = os.path.join(os.getcwd(), path_)
print(pathToCopy)
copyFormat(pathToCopy, fileFormat)
if __name__ == '__main__':
main() |
74dcea2607f6d7d8f093ddc6a2e3e2058db2d628 | IlosvayAron/script-languages | /Lesson9/homework/own_solution/pages.py | 692 | 4.03125 | 4 | #!/usr/bin/env python3
def printable_pages(pages: list) -> list:
lst = pages.split(',')
res = []
for num in lst:
if '-' not in num:
res.append(int(num))
else:
interval = num.split('-')
lower = interval[0]
upper = interval[-1]
for i in range(int(lower), int(upper)+1):
res.append(i)
return res
def main():
print("Minta az inputra: 1-4,7,9,11-15")
text = input('Add meg a nyomtatandó oldalakat: ')
print("Nyomtatandó oldalak:", printable_pages(text))
##############################################################################
if __name__ == "__main__":
main() |
6f6a0783512c5d2bee6e71e35459609bcc53d5bc | Wh1t3Fox/hackthissite | /programming/11.reverse_ascii/reverse.py | 255 | 3.546875 | 4 | #!/usr/bin/env python
import sys
if __name__ == '__main__':
string = '30,32,23,31,5,5,'
shift = -30
string = string.split(string[-1])
string.remove('')
output = ''.join([chr(int(c) - int(shift)) for c in string])
print output
|
61144b8c72a71c7b83ecaab4fd2c16c7610e8780 | goodsoul/learningpython | /03_absoult_value.py | 138 | 4.34375 | 4 | # print absolute value of an integer:
number=float(input('Please input a number'))
if number>=0:
print(number)
else:
print(-number) |
ea8abd8fcf8dd1ec8fb0cc4358f90756e1604482 | rometsch/sheep | /chprm.py | 1,529 | 3.515625 | 4 | #!/usr/bin/env python3
# Replace a parameter value in a text based config file.
# The only assumption is that the parameter name and the value
# are separated by whitespaces and followed by whitespaces or newlines.
import re
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("infile", help="config file to change parameter in")
parser.add_argument("param", help="parameter to be changed")
parser.add_argument("value", help="new value")
parser.add_argument("-o", help="output file path")
args = parser.parse_args()
change_param(args.infile, args.param, args.value,
outfile_path = args.o)
def change_param(infile_path, param, value, outfile_path=None):
outfile_path = outfile_path if outfile_path is not None else infile_path
ptrn = re.compile(r"\A([ \t]*{}[ \t]+)([\S]+(?=\s))".format(param))
NreplTot = 0
with open(infile_path, 'r') as infile:
outlines = []
for line in infile:
out, Nrepl = re.subn(ptrn, r"\g<1>{}".format(value), line)
outlines.append( out )
NreplTot += Nrepl
if NreplTot > 1:
raise AssertionError("Replaced {} instead of 1 occurances of parameter '{}'".format(Nrepl, param))
if NreplTot == 0:
raise AssertionError("Could not find parameter '{}' in '{}'".format(param, infile_path))
with open(outfile_path, 'w') as outfile:
outfile.write("".join(outlines))
if __name__=="__main__":
main()
|
1523aa56dfd7a16abca579587fe462d0e5b499b6 | Napster56/Sandbox | /factorial_recursively.py | 727 | 4.28125 | 4 | """
Function that calculates the factorial of n and prints the result.
"""
def main():
n = factorial(1)
print(n) # print result for first function
# n = factorial_2(0)
# print(n) # prints result for second function
def factorial(n):
""" Recursive factorial. """
if n == 1 or n == 0: # n >= 0, factorial of a negative number is undefined
return 1 # base case
# else: redundant because return stops the function
return n * factorial(n - 1) # recursive case
# as a for loop
# def factorial_2(n):
# for i in range(n):
# if n == 1 or n == 0:
# return 1
# return n * (n - 1)
main()
|
976190cc72fa7e453d4190434bce3eb75fb49a71 | duylamasd/basic-algorithms | /prim-mst.py | 2,770 | 3.8125 | 4 | import sys
MAX_INT = sys.maxsize
class Graph:
def __init__(self, num_of_vertices):
self.num_of_vertices = num_of_vertices
self.adjecency_matrix = []
def add_dist(self, distances):
self.adjecency_matrix.append(distances)
def min_key(self, key, mst_set):
"""
A utility function to find the vertex
with minimum key value, from the set of vertices
not yet included in MST
"""
min = MAX_INT
min_idx = 0
for v in range(self.num_of_vertices):
if (not mst_set[v]) and key[v] < min:
min = key[v]
min_idx = v
return min_idx
def print_mst(self, parent):
"""
A utility function to print the constructed MST stored in parent
"""
print "edge", "weight"
for i in range(1, self.num_of_vertices):
print parent[i], i, self.adjecency_matrix[i][parent[i]]
def prim_mst(self):
"""
Construct and print MST for a graph represented using adjecency matrix representation
"""
# Key values used to pick minimum weight edge in cut
key = [MAX_INT] * self.num_of_vertices
# Always include first vertex in MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
# Array to store constructed MST
parent = [MAX_INT] * self.num_of_vertices
# First node is always root of MST
parent[0] = -1
# Represent set of vertices not yet included in MST
mst_set = [False] * self.num_of_vertices
for _ in range(self.num_of_vertices - 1):
# Pick the minimum ket vertex from the
# set of vertices not yet included in MST
u = self.min_key(key, mst_set)
# Add the picked vertex to the MST set
mst_set[u] = True
# Update key value and parent index
# of the adjacent vertices of the picked vertex.
# Consider only those vertices which are not
# yet included in MST
for v in range(self.num_of_vertices):
# graph[u][v] is non zero only for adjecent vertices of m
# mst_set[v] is False for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[v]
if self.adjecency_matrix[u][v] and (not mst_set[v]) and self.adjecency_matrix[u][v] < key[v]:
parent[v] = u
key[v] = self.adjecency_matrix[u][v]
self.print_mst(parent)
# Test
g = Graph(5)
g.add_dist([0, 2, 0, 6, 0])
g.add_dist([2, 0, 3, 8, 5])
g.add_dist([0, 3, 0, 0, 7])
g.add_dist([6, 8, 0, 0, 9])
g.add_dist([0, 5, 7, 9, 0])
g.prim_mst()
|
4cc2333fbd702019a2700e771e1a734bcdf97db6 | MachFour/info1110 | /week2/T14B/intro-things.py | 2,024 | 4.46875 | 4 |
############################
# Some introductory things #
############################
#
# Datatypes:
# These should be familiar! What is the type of each variable?
count = 10
name = "Alexander the Great"
ratio = 2.3
cost = count*ratio # what datatype is the product of these two variables?
# A new datatype: Boolean! It takes only two values, True and False.
success = True
finished_yet = False
# Variable names:
# We want to have some basic rules for how we choose variable names:
# - generally stick to lower case letters
# - can't start a variable name with a number
# - replace spaces in words by underscores: '_'
# - variables named in all uppercase are constants (don't change during the
# program's execution), e.g. MAX_CAPACITY = 1000
# - can't (don't) use a name that already means something in python, e.g.
# print, True, class, if
# Have a look at the lab sheet and decide whether the variables there are
# good variable names or not.
# Further reading on python's variable naming conventions:
# https://www.python.org/dev/peps/pep-0008/
#
# Some style points:
#
# 1. Use comments to explain things about your code that are not obvious
# For example:
radius = 10 # centimetres
area = radius*3.1415*3.1415 # multiply by pi squared
# 2. Try to pick variable names that describe the purpose of the variable
# We can improve on the previous example:
radius_cm = 10 # now the variable name describes the unit too!
PI = 3.1415 # I used capitals for PI since it's a constant
area_cm_squared = radius_cm*PI*PI
# 3. Don't 'reuse' variables'
# The following is not very good style:
age = input("What is your age? ")
age = int(age) # this changes age from a string to an int - not good!
# Here is a better way:
age_input = input("What is your age? ") # use a more specific variable name
age = int(age_input) # this one is 'age' because we want to use it as an int
# PEP 8 also has information on good style (in Python)
# https://www.python.org/dev/peps/pep-0008/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.