text
stringlengths 37
1.41M
|
---|
#find the union and intersection of two sorted array
#brute force
def find_union_intersection_brute(arr1, arr2):
inter=[]
for i in arr1:
if i in arr2:
inter.append(i)
return inter, arr1+arr2
#ths doesnt handle dups if found in any array
def find_union_intersection(arr1, arr2):
l=0
r=0
inter=[]
union= []
while l<len(arr1) and r<len(arr2):
if arr1[l]==arr2[r]:
inter.append(arr1[l])
union.append(arr1[l])
l+=1
r+=1
elif arr1[l]>arr2[r]:
union.append(arr2[r])
r+=1
else:
union.append(arr1[l])
l+=1
while l < len(arr1):
union.append(arr1[l])
l += 1
while r < len(arr2):
union.append(arr2[r])
r += 1
return inter, union
if __name__ == '__main__':
print(find_union_intersection([1,2,3],[1,2,4]))
|
# iterative solution
#O(N)
def reverse_iterative(array):
size = len(array)
start=0
end=size-1
while start<end:
array[start],array[end] = array[end],array[start]
start+=1
end-=1
return array
# recursive solution
#O(N)
def reverse_recursive(array, start, end):
if start>=end:
return
array[start],array[end] = array[end],array[start]
reverse_recursive(array, start+1, end-1)
print(reverse_iterative([1,2,3,4]))
arr=[1,2,3,4]
reverse_recursive(arr,0,3)
print(arr)
|
import datetime
currentDate = datetime.datetime.now()
while True:
deadline= input ('Plz enter your date of birth (dd/mm/yyyy) ')
try:
deadlineDate= datetime.datetime.strptime(deadline,'%d/%m/%Y')
break
except ValueError:
print ("Invalid input please try again")
print(deadlineDate)
daysLeft = currentDate - deadlineDate
print(daysLeft)
years = ((daysLeft.total_seconds())/(365.242*24*3600))
yearsInt=int(years)
months=(years-yearsInt)*12
monthsInt=int(months)
days=(months-monthsInt)*(365.242/12)
daysInt=int(days)
hours = (days-daysInt)*24
hoursInt=int(hours)
minutes = (hours-hoursInt)*60
minutesInt=int(minutes)
seconds = (minutes-minutesInt)*60
secondsInt =int(seconds)
hoursLived = (yearsInt *24*3600) + hoursInt
print('You are {0:d} years, {1:d} months, {2:d} days, {3:d} hours, {4:d} minutes, '
'{5:d} seconds old.'.format(yearsInt,monthsInt,daysInt,hoursInt,minutesInt,secondsInt))
print('OMG , you are {years} years old so you were born in {date}'.format(years=yearsInt, date=deadlineDate))
print('You lived: {}h in total' .format(hoursLived))
|
#print power of 2
n=0
total=0
while n <= 11 :
print ("Power of 2 is {} " .format(total**2))
total=(n)
n += 1
#for loop
for i in range(1, 11):
print ("Power 2 of is : " +str((i,i**2)))
|
#input a number, calculate grade
#A 90-100%
#B 80-90%
score =int(input("Please enter your score from (0-100):"))
if 90< score <=100:
print("Your score is: A ")
elif 80< score <89:
print("your score is: B")
elif 70< score <79:
print("Your score is: C")
elif 60< score <69:
print("your score is D , keep it up")
elif 0< score <59:
print("your score is F, You failed man")
|
#Inheritance - Is- A relation
#Class Mammals
#Class Man
#Aggregation - Has -A relation
#Aggregation implies a relationahip where the child can exist independently of the parent
#Example: Class(parent) and Student(child).
#Delete the Class and the Students still exists.
#Composition - Has -A relation
#Composition implies a relationship where the child cannot exist independent of the parent.
#Example: House(parent) and Room(child).
#Rooms don't exist separate to a House
#Polymorphism - overriding
#Polymorphism is based on the greek words Poly(many) and morphism (forms)
#We will create a structure that can take or use many forms of objects.
#Sometimes an objects comes in many types or forms.
# If we have a button, there are many different draw outputs
# (round button, check button, square button, button with image)
# but they do share the same logic: onClick().
# We access them using the same method.
# This idea is called Polymorphism.
class MathCal:
def addition(self,a, b):
print("Result of addition is: {}".format(a+b))
def subtraction(self,a , b):
print("Result of subtraction is:{}".format(a-b))
class AdvaCal(MathCal):
def __init__(self):
self.calc1=MathCal()
def subtraction(self,a , b):
self.calc1.subtraction(a, b)
def multiplication(self,a , b):
print("Result of multiplication is: {}".format(a*b))
def division(self,a, b):
print("Result of division is: {}".format(a / b))
cal1=MathCal()
cal1.subtraction(9,6)
cal1.addition(4,2)
cal2=AdvaCal()
cal2.multiplication(5, 5)
cal2.division(5, 5)
del cal2.calc1
#This line is going to fail, because of aggregation
cal2.subtraction(7,8)
|
import pygame
import sys
import numpy
import math
import time
import random
import Controller1
import controllerleft
import test_opponent
#MAIN script for self made robocup simulation. Main idea is that a controlcode scans the field and assigns requests the bots to go to a position,rotation,and action.
# the classes in this script will than have the bots go to this configuration. The controller script must have a function called "update"
# A centralised physics engine still has to be implemented in where each object gets updated
class Ball():
#class Ball
# includes the properties of the ball such as position velocity force mass etc
# function update changes the position depending on the mass and FPS of the program.
# function draw draws the ball
# function getdistance can be called from within another object to get the distance of the ball to that object.
# input "position" is the position of the other object
def __init__(self, width, height):
self.object = "ball" #this is for the physics engine, as the physics engine will see every object as "object" it is necessary to have an object specification
self.xx = int(width/2)
self.yy = int(height/2)
self.radius = 10
self.mass = 10
self.fx = 0
self.fy = 0
self.ax = 0
self.ay = 0
self.vx = 0
self.vy = 0
self.Rr = 0.005
self.Rx = 0
self.Ry = 0
self.bouncefactor = 1
self.hit = False
def update(self,time,height,width):
self.ax = self.fx / self.mass
self.ay = self.fy / self.mass
self.vx = self.vx*(0.5**abs(time))
self.vy = self.vy*(0.5**abs(time))
self.vx += self.ax * time
self.vy += self.ay * time
self.position = [self.position[0] + self.vx, self.position[1] + self.vy]
self.fx = 0
self.fy = 0
if (self.position[0] > width - self.radius) or (self.position[0] < self.radius):
self.vx = -self.vx
if (self.position[1] > height - self.radius) or (self.position[1] < self.radius):
self.vy = -self.vy
def draw(self, screen):
pygame.draw.circle(screen, (0,255,255), (int(self.xx), int(self.yy)), self.radius, 2)
def getdistance(self,position):
difx = self.xx - position[0]
dify = self.yy - position[1]
length = math.sqrt(difx**2 + dify**2)
dirx = difx/length
diry = dify/length
return length, dirx, diry
class Bot():
#Stores the properties of a bot. This class is called from the Team class
# function move updates the position of the bot by finding the direction between the requested position and the
# curent position. Requested position comes from the controller assigned to the team, the Controller is the basic AI for the whole team
# - should be updated to change the movespeed from the requested move speed. Property requested move speed still needs to be implemented.
# Function Rotate rotates the bot towards the requested direction.
def __init__(self):
self.object = "bot"
self.role = 1 #can be used by controller to decide which role the bot has. This for example could be a keeper role for which a different script gets executed.
self.hasBall = False
self.requestPosition = (0,0)
self.pidposition = (0,0)
self.requestAction = (0,0)
self.facing = 0
self.requestfacing = 0
self.movespeed = 1
self.requestmovespeed = 1
self.rotatespeed = 1
self.radius = 20
self.acceleration = 0.1
self.fx = 0
self.fy = 0
self.ax = 0
self.ay = 0
self.vx = 0
self.vy = 0
self.xx = 0
self.yy = 0
self.Rx = 0
self.Ry = 0
self.Rr = 2.5
self.mass = 10
self.kP = 1
self.kI = 0
self.kD = 1
self.kickforce = 0
self.interrorx = 0
self.interrory = 0
self.diferrorx = 0
self.preferrorx = 0
self.diferrory = 0
self.preferrory = 0
self.errorx = 0
self.errory = 0
self.moveforce = 500
self.bouncefactor = 0
def move(self,dt):
self.errorx = numpy.float32(self.requestPosition[0] - self.xx)
self.errory = numpy.float32(self.requestPosition[1] - self.yy)
self.interrorx += self.errorx
self.interrory += self.errory
self.diferrorx = (self.errorx - self.preferrorx)
self.diferrory = (self.errory - self.preferrory)
difx = self.errorx*self.kP + self.kI*self.interrorx + self.kD*self.diferrorx
dify = self.errory*self.kP + self.kI*self.interrory + self.kD*self.diferrory
self.pidposition = (difx,dify)
dist = math.sqrt(difx**2 + dify**2)
if dist > 0:
dirx = difx / abs(dist)
diry = dify / abs(dist)
else:
dirx = 0
diry = 0
self.fx = (self.moveforce * dirx)
self.fy = (self.moveforce * diry)
self.preferrorx = self.errorx
self.preferrory = self.errory
def rotate(self):
if self.requestfacing > self.facing:
self.facing += 0.01*numpy.pi
else:
self.facing -= 0.01*numpy.pi
class Team():
# the Team class is pretty much an envelope for the bots in the team, the class is initialized by assinging a number
# of bots to the team and assinging a controller code. Next to that the bots get assigned a starting position
# - idea? Have the starting position assigned by the controller?
# function Draw_team loops over the bots and updates the position and rotation, than draws the bots.
def __init__(self, number, width, height, controller):
self.bots = [] #array of bots
self.score = 0 #team score -scoring mechanism still needs to be implemented
self.number = number #number of the team
if self.number == 1:
self.side = 1 #left
self.color = (255, 0, 0)
else:
self.side = 2 #right
self.color = (0, 0, 255)
for i in range(3): #append five bots
self.bots.append(Bot())
self.controller = controller(self,width,height)
def draw_team(self,screen,dt,myfont,width):
for i in range(len(self.bots)):
self.bots[i].move(dt)
self.bots[i].rotate()
scoretext = myfont.render(str(self.score),False,(255,255,255))
if self.side == 1:
screen.blit(scoretext,(width/2-50,10))
else:
screen.blit(scoretext,(width/2+50,10))
relpos = (int(numpy.sin(self.bots[i].facing)*20), int(numpy.cos(self.bots[i].facing)*20))
pygame.draw.circle(screen, self.color, (int(self.bots[i].xx), int(self.bots[i].yy)), self.bots[i].radius, 2)
pygame.draw.lines(screen, self.color, False, [(self.bots[i].xx, self.bots[i].yy), (self.bots[i].xx+relpos[0], self.bots[i].yy+relpos[1])])
def draw_field(screen, width, height, goal_width, blue = (100, 100, 255), green = (0, 255, 0 ), white = (255, 255, 255), black = (0, 0, 0 ), pink = (255, 200, 200)):
#function that draws the field
#goal_width = 60
keeper_distance= 100
centre_circle_radius = 20
centre_width = round(width/2)
centre_height = round(height/2)
screen.fill(black)
#center circle
pygame.draw.circle(screen, white, (centre_width,centre_height), centre_circle_radius, 2)
#keeper field
pygame.draw.lines(screen, white, True, [(0, centre_height+keeper_distance), (keeper_distance, centre_height+keeper_distance), (keeper_distance, centre_height-keeper_distance), (0, centre_height-keeper_distance)])
pygame.draw.lines(screen, white, True, [(width, centre_height+keeper_distance), (width-keeper_distance, centre_height+keeper_distance), (width-keeper_distance, centre_height-keeper_distance), (width, centre_height-keeper_distance)])
#goals
pygame.draw.lines(screen, blue, False, [(0,centre_height-goal_width/2), (0,centre_height+goal_width/2)], 8)
pygame.draw.lines(screen, blue, False, [(width-2, centre_height-goal_width/2),(width-2,centre_height+goal_width/2)], 8)
#vertical line centre
pygame.draw.lines(screen, white, False, [(centre_width, 0),(centre_width, height)])
#around the screen
pygame.draw.lines(screen, white, True, [(0,0), (width-2,0), (width-2,height-2), (0,height-2)], 3)
def updatephysics(teams,ball,width,height,dt,screen,goalwidth,cornertime):
objects = []
for team in teams:
for bot in team.bots:
objects.append(bot)
objects.append(ball)
for object in objects:
relftotx = object.xx + object.fx*10
relftoty = object.yy + object.fy*10
object.fy += object.Ry
object.fx += object.Rx
object.ax = object.fx / object.mass
object.ay = object.fy / object.mass
object.vx += object.ax
object.vy += object.ay
object.Rx = -object.Rr * object.vx
object.Ry = -object.Rr * object.vy
object.xx += object.vx * dt
object.yy += object.vy * dt
if object.xx > width-object.radius:
object.xx = width - object.radius
object.vx = -object.vx*object.bouncefactor
if object.xx < object.radius:
object.xx = object.radius
object.vx = -object.vx*object.bouncefactor
if object.yy > height-object.radius:
object.yy = height-object.radius
object.vy = -object.vy*object.bouncefactor
if object.yy < object.radius:
object.yy = object.radius
object.vy = -object.vy*object.bouncefactor
objectdebug = 0
if objectdebug == 1:
relrx = object.xx + object.Rx*10
relry = object.yy + object.Ry*10
relfx = object.xx + object.fx*10
relfy = object.yy + object.fy*10
pygame.draw.lines(screen,(255,0,0),False,[(object.xx,object.yy),(relrx,relry)])
pygame.draw.lines(screen,(0,255,0),False,[(object.xx,object.yy),(relfx,relfy)])
pygame.draw.lines(screen,(0,125,0),False,[(object.xx,object.yy),(relftotx,relftoty)])
if object.object == "bot":
pygame.draw.lines(screen,(0,0,255),False,[(object.xx,object.yy),(object.pidposition[0]+object.xx,object.pidposition[1]+object.yy)])
pygame.draw.lines(screen,(0,0,125),False,[(object.xx,object.yy),object.requestPosition])
if object.object == "bot":
dist,dirx,diry = ball.getdistance((object.xx,object.yy))
if dist <= object.radius + ball.radius:
print("bot hit ball: kickforce = : " + str(object.kickforce) + " dirx: " + str(dirx) + " diry: " + str(diry))
ball.fx += dirx*object.kickforce
ball.fy += diry*object.kickforce
ball.hit = True
difdist = (ball.radius + object.radius) - dist
ball.xx += dirx * difdist
ball.yy += diry * difdist
if object.object == "ball":
object.fx = 0
object.fy = 0
object.hit = False
if abs(height/2 - object.yy) < goalwidth/2:
if object.xx == object.radius:
print("ball in left goal")
teams[1].score += 1
object.xx = width/2
object.yy = height/2
elif object.xx == width-object.radius:
teams[0].score += 1
print("ball in right goal")
object.xx = width/2
object.yy = height/2
for object2 in objects:
if object2.object == "bot" and object.object == "bot":
dist = math.sqrt((object2.xx - object.xx)**2 + (object2.yy - object.yy)**2)
if dist <= object2.radius + object.radius and dist > 0:
print("Collision detected between :" + str(object2.object) + " and " + str(object.object))
difx = object2.xx - object.xx
dify = object2.yy - object.yy
dirx = difx/dist
diry = dify/dist
difdist = (object2.radius + object.radius)-dist
object.xx -= dirx*difdist
object.yy -= diry*difdist
if (ball.xx < ball.radius*3 or ball.xx > width - ball.radius*3) and (ball.yy < ball.radius*3 or ball.yy > height - ball.radius*3):
cornertime += dt
else:
cornertime = 0
if cornertime > 10:
ball.xx = width /2
ball.yy = height /2
ball.vx = 0
ball.vy = 0
ball.ax = 0
ball.ay = 0
ball.fx = 0
ball.fy = 0
return cornertime
def main():
#main loop.
t1 = time.time() #start an FPS timer
red = (255, 0, 0 )
blue = (100, 100, 255)
green = (0, 255, 0 )
white = (255, 255, 255)
black = (0, 0, 0 )
pink = (255, 200, 200)
screen_width = 1280
screen_height = 800
goalwidth = 120
screen = pygame.display.set_mode((screen_width, screen_height))
running = True
pygame.init()
pygame.font.init()
myfont = pygame.font.SysFont('Times New Roman',30)
clock = pygame.time.Clock()
team1 = Team(1, screen_width, screen_height, Controller1.controller)
team2 = Team(2, screen_width, screen_height, controllerleft.controller)
ball = Ball(screen_width, screen_height)
loop = 1
dt = time.time() - t1
cornertime = 0
while running:
t1 = time.time()
clock.tick(1000)
draw_field(screen, screen_width, screen_height, goalwidth)
team1.controller.update(ball,screen_height,screen_width)
team2.controller.update(ball,screen_height,screen_width)
cornertime = updatephysics([team1,team2],ball,screen_width,screen_height,dt,screen,goalwidth,cornertime)
#ball.update(dt,screen_height,screen_width)
team1.draw_team(screen,dt,myfont,screen_width)
team2.draw_team(screen,dt,myfont,screen_width)
ball.draw(screen)
fpstext = myfont.render("FPS = " + str(round(1/dt)),False,(255,255,255))
screen.blit(fpstext,(10,10))
cornertimetext = myfont.render("cornertime = " + str(round(cornertime,1)),False,(255,255,255))
screen.blit(cornertimetext,(10,30))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
#print("FPS = " + str(round(1/dt)))
loop += 1
dt = (time.time() - t1)
main()
|
list_names = list(map(str, input().split("-"))) # split by "-"
short_variation = list(map(lambda name: name[0], list_names)) # get first letter(s) from list of names
output = ''.join(short_variation) # convert list to string
print(output)
|
#Aug 21, 2019
#Michael Zabawa
#Python Assignment 2 for NCSU
from TicTacToeClasses import *
################################################################################
#driving function
def main():
print("\n \nWould you like to play\nTic-Tack_Toe?")
play = input("Type (Y)es or (N)o: ")
play = str.upper(play[0])
while(play == 'Y'):
numPlayer = input("Type (O)ne or (T)wo players: ")
if str.upper(numPlayer[0]) == 'T':
game = TwoPlayerGame()
game.playGame()
elif str.upper(numPlayer[0]) == 'O':
game = OnePlayerGame()
game.playGame()
else:
print("Incorrect Entry \nEnter T or O")
print("\nWold you like to play?")
play = input("Type (Y)es or (N)o: ")
play = str.upper(play[0])
################################################################################
main()
################################################################################
#Generate Game Data
for i in range(100):
game = NoPlayerGame()
game.playGame()
game.printMoveList(True)
import pandas as pd
from sklearn.naive_bayes import MultinomialNB
data = pd.read_csv("gameData.csv")
X = data.iloc[:, 0:9]
y = data.loc[:,'WINNER']
clf = MultinomialNB()
clf.fit(X, y)
MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)
print(clf.predict(X[2:3]))
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(random_state=0, solver='lbfgs',multi_class='multinomial').fit(X, y)
clf.get_params()
|
""" This file contains the different clustering routines.
"""
import numpy as np
from .helpers import compute_correlation_coefficients, normalize_data
def cluster_by_correlation(correlation_matrix):
""" Performs a single renormalization step (clustering neurons into pairs).
The clustering is performed based on correlation. Therefore this function
correlation matrix as an input to compute the clustering.
Returns `[i, j]` where `i` and `j` are both arrays of indices of length
`n//2`. These indicate which neurons should be clustered together. For
example the first cluster is formed by neuron `i[0]` and `j[0]` and the
second one by `i[1]` and `j[1]`.
"""
# these definitions are just for convenience
n = len(correlation_matrix)
n_half = n // 2
# subtract the identity matrix since the diagonal of the correlation matrix
# contains only 1's.
correlation_matrix = correlation_matrix - \
np.identity(len(correlation_matrix))
# we arg sort the negative correlation matrix to get the biggest element
# first. This works because all entries in the correlation matrix range
# from 0 to 1.
#
# `indices` is a sorted list of indices of the most correlated pairs. In
# other words, indices[0] is the index of the largest element of the
# correlation matrix.
indices = np.argsort(-correlation_matrix, axis=None)
# a list of bool's to keep track of the visited neurons
visited_neurons = np.zeros(n, dtype=bool)
most_correlated_pairs = np.zeros((2, n_half), dtype=int)
len_pairs = 0
# only look at the upper triangular elements of the correlation matrix
i, j = np.unravel_index(indices, correlation_matrix.shape)
i_gt_j = i > j
i = i[i_gt_j]
j = j[i_gt_j]
for i, j in zip(i, j):
if not visited_neurons[i] and not visited_neurons[j]:
visited_neurons[i] = True
visited_neurons[j] = True
most_correlated_pairs[:, len_pairs] = [i, j]
len_pairs += 1
if len_pairs >= n_half:
# we are finished after having found n_half pairs
break
return most_correlated_pairs
def cluster_randomly(data_length):
"""Performs one step of random clustering and returns the clustering
indices. `data_length` is the number of neurons in the data.
Returns `[i, j]` where `i` and `j` are both arrays of indices of length
`n//2`. These indicate which neurons should be clustered together. For
example the first cluster is formed by neuron `i[0]` and `j[0]` and the
second one by `i[1]` and `j[1]`.
"""
clustering_pairs = np.zeros((2, data_length//2), dtype=int)
indices = list(range(data_length))
for pair in range(data_length//2):
i = indices.pop(np.random.randint(0, len(indices)))
j = indices.pop(np.random.randint(0, len(indices)))
clustering_pairs[:, pair] = [i, j]
return clustering_pairs
def cluster_pairs(data, strategy='correlation'):
""" Performs a single step of clustering choosing the correct clustering function
"""
if strategy == 'correlation':
corr_coef = compute_correlation_coefficients(data)
return cluster_by_correlation(corr_coef)
elif strategy == 'random':
return cluster_randomly(len(data))
else:
raise Exception('unknown clustering strategy "{}"'.format(strategy))
def apply_clustering(data, clustering_indices, norm=normalize_data):
"""Returns renormalized data using the given clustering."""
num_clusters = np.size(clustering_indices, 1)
rval = np.zeros((num_clusters, np.size(data, 1)))
for i in clustering_indices:
rval += data[i]
return norm(rval)
def cluster_recursive(data,
num_clustering_steps,
clustering_strategy='correlation',
norm=normalize_data):
if num_clustering_steps == 0:
return [np.array([np.arange(len(data))])]
# `clusters` is a matrix where the columns indicate which neurons form a cluster
cluster_matrices = cluster_recursive(
data, num_clustering_steps - 1, clustering_strategy, norm)
clusters = cluster_matrices[-1]
# now we generate the clustered data and compute the most correlated pairs
clustered_data = apply_clustering(data, clusters, norm)
pairs = cluster_pairs(clustered_data, clustering_strategy)
# Here we use the previous `clusters` array and merge them according to `pairs`.
# This was complicated to write but seems to work fine. I admit I don't completely understand
# every aspect of this code.
with np.nditer([pairs, np.arange(len(clusters)), None],
op_axes=[[-1, 0, 1], [0, -1, -1], None]) as itr:
for a, b, out in itr:
out[...] = clusters[b, a]
out = itr.operands[2]
out.shape = (out.shape[0] * out.shape[1], out.shape[2])
cluster_matrices.append(out)
return cluster_matrices
|
for a in(1,2):
for b in (3,5):
if a*b>2:
c=True
print(a*b)
if c:
print("r")
|
#!/usr/bin/env python3
import math
number = 600851475143
# solution 1
def is_prime(n):
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
limit = int(math.sqrt(number))
for i in range(limit, 2, -1):
if is_prime(i) and not number % i:
print(i)
break
|
#!/usr/bin/env python
power = 1000
# solution 1
num = 2**power
s = 0
while num > 0:
s += num % 10
num = num // 10
print(s)
|
import sys
def bubbleSort(arr):
for i in range(0, len(arr)):
for j in range(0, len(arr)-i-1):
if(arr[j] > arr[j+1]):
tmp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = tmp
return arr
def main():
try:
f = open(str(sys.argv[1]),'r')
text = f.readlines()
arr = [int(x) for x in text[0].split(",")]
except:
text = sys.argv[1]
arr = [int(x) for x in text.split(",")]
print("List unsorted: " + str(arr))
arr = bubbleSort(arr)
print("List sorted: " + str(arr))
if __name__ == "__main__":
main()
|
#example 1
def gen_print(n):
num = 0
while num < n:
print(num)
num += 1
(gen_print(5))
#example 2
def gen_print(n):
num = 0
while num < n:
if num%2==0:
print(num)
num+=1
else:
num += 1
(gen_print(5))
|
from Expression import Expression
class Equation:
def __init__(self, lhs, rhs):
self.lhs, self.rhs = lhs, rhs
def __str__(self):
return str(self.lhs) + " = " + str(self.rhs)
def debug_string(self):
return self.lhs.debug_string() + " = " + self.rhs.debug_string()
# ~~~~~~ TESTING ~~~~~~~~
# from Expression import *
#
# three = Constant(3)
# two = Constant(2)
#
# x = Variable('x')
#
#
# three_plus_two_plus_x = Addition(Addition(three, two), x)
#
# equation = Equation(three_plus_two_plus_x, Constant(13))
#
# print(equation)
# ~~~~~~~~~~~~~~~~~~~~~~~~
|
class Greetings:
def __init__(self, name):
self.name = name
def display(self):
print(f'Hello there {self.name}.')
if __name__ == '__main__':
i = input('Enter your name: ')
g = Greetings(i)
g.display()
|
from math import sqrt
import numpy as np
def main():
import pandas as pd
data = pd.read_csv("alldata.csv")
y_arr = data['Price']
x_arr = data['Sentiment']
date_arr = data['Date']
# normalize BTC price
from sklearn.preprocessing import MinMaxScaler
mmscaler = MinMaxScaler(feature_range=(0, 1))
y_arr = mmscaler.fit_transform(y_arr.values.reshape(-1, 1))
x_arr = x_arr.values.reshape(-1, 1)
#print(y_arr)
# select 80% as training data
percent = input('Please enter the percentage you want to set as training data. \n'
'The percentage should be within [5,95]: ')
percent = int(percent)
if percent < 5:
percent = input('Please enter greater than 5 %: ')
percent = int(percent)
if percent > 95:
percent = input('Please enter smaller than 95 %: ')
percent = int(percent)
print("Note that the rest ",100-percent," % will be testing data.")
# since the data is corresponding with date, it has to be in order
# print(len(y_arr), len(x_arr))
index_cut = int(len(y_arr)*(100-percent)/100)
test_x = x_arr[0:index_cut]
train_x = x_arr[index_cut:len(x_arr)]
test_y = y_arr[0:index_cut]
train_y = y_arr[index_cut:len(x_arr)]
test_date = date_arr[0:index_cut]
print("Training data size = ", len(train_y))
print("Testing data size = ", len(test_x))
print("Start process data")
# process data to use [days] day prev [prev-price and this day's sentiment]
day = 2
Xtrain = []
Ytrain = []
for i in range(0, len(train_x)-day):
# price
y = train_y[i]
Ytrain.append(y)
# x = get 2 previous day's price
x = train_y[i+1:i+1+day]
# x = append today's sentiment score from reddit data
x = x.tolist()
x.append(train_x[i].tolist())
Xtrain.append(x)
train_x = np.array(Xtrain)
train_y = np.array(Ytrain)
print("Training input shape: ", train_x.shape)
print("Training output shape: ", train_y.shape)
Xtest = []
Ytest = []
for i in range(0, len(test_x)-day):
# y = train_y[i + 2]
y = test_y[i]
Ytest.append(y)
# x = get 2 previous day's price
x = test_y[i+1:i+1+day]
# x = append today's sentiment score from reddit data
x = x.tolist()
x.append(test_x[i].tolist())
Xtest.append(x)
test_x = np.array(Xtest)
test_y = np.array(Ytest)
#print(test_x.shape)
#print(test_y.shape)
print("Training the model...")
# Model building:
# LSTM Networks with
# 3 layers
# 50 nodes per layers
# loss = Mean Absolute Error
# optimizer = Adam Optimization
import keras
lstm = keras.models.Sequential()
lstm.add(keras.layers.LSTM(50, input_shape=(train_x.shape[1], train_x.shape[2]), return_sequences=True))
lstm.add(keras.layers.LSTM(50))
lstm.add(keras.layers.Dense(1))
lstm.compile(loss='mae', optimizer='adam')
# Model training:
# bagging with
# batch_size = 100
# epochs = 300
re = lstm.fit(train_x, train_y, epochs=300, batch_size=100, validation_data=(test_x, test_y), verbose=0, shuffle=False)
# print(re)
# Model evaluating:
from sklearn.metrics import mean_squared_error
predict_y = lstm.predict(test_x)
err = sqrt(mean_squared_error(test_y, predict_y))
print('raw err: %.3f' % err)
# Price re-convert evaluating:
predict_y = mmscaler.inverse_transform(predict_y.reshape(-1, 1))
test_y = mmscaler.inverse_transform(test_y.reshape(-1, 1))
err = sqrt(mean_squared_error(test_y, predict_y))
print('err: %.3f' % err)
py = np.array(predict_y)
y = np.array(test_y)
test_date = np.array(test_date)
# print("py.shape", py.reshape(-1).shape)
# print("y.shape", y.reshape(-1).shape)
# print("date before", test_date.shape)
# print("date.shape", test_date[day:len(test_date)].shape)
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
date = []
for s in test_date[0:len(test_date)-day]:
s = str(s)
d = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
date.append(d)
date = np.array(date)
print("[May 01, 2018] predicted BTC price (USD) = ", predict_y[0])
# plotting
plt.plot(date.reshape(-1), py.reshape(-1), label="predict_y", color='green')
plt.plot(date[1:-1].reshape(-1), y[1:-1].reshape(-1), label="test_y", color='red')
red_patch = mpatches.Patch(color='red', label='Actual Price')
green_patch = mpatches.Patch(color='green', label='Predicted Price')
plt.legend(handles=[red_patch, green_patch])
plt.ylabel('BTC Prices (USD)')
plt.xlabel('Test dates')
plt.show()
if __name__ == "__main__":
main()
|
# #----------1. define a simple function---------
# # 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()。
# # 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
# # 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
# # 函数内容以冒号起始,并且缩进。
# # return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
# # def 函数名(参数列表):
# # 函数体
#
# def show(stuff):
# print("show stuff: ", stuff)
# stuff = 100
# return type(stuff)
#
#
# List = [99,"99",(99, 100),[99, 100],{99, 100},{"first":99, "second":100}]
#
# for item in List:
# print("----before show----")
# Type = show(item)
# print("----after show(stuff has been changed)----")
# print(item)
# #print("type of stuff: ", Type)
# print("")
#---------------2. mutable & immutable------------
#----2.1 imutable----
def change_int(a):
a = 100
Int = 2
print("before change_int:", Int)
change_int(Int)
print("after change_int:", Int)
def change_str(a):
a = "100"
Str = "2"
print("before change_str:", Str)
change_str(Str)
print("after change_str:", Str)
def change_tuple(a):
a = (3,4)
Tuple = (2,3)
print("before change_tuple:", Tuple)
change_str(Tuple)
print("after change_tuple:", Tuple)
print("-"*50)
#----2.2 mutable----
def change_list(a):
a.append(4)
def change_set(a):
a.add(4)
def change_dict(a):
a["4"] = 4
List = [2,3]
print("before change: ", List)
change_list(List)
print("after change: ", List)
Set = {2,3}
print("before change: ", Set)
change_set(Set)
print("after change: ", Set)
Dict = {"2":2, "3":3}
print("before change: ", Dict)
change_dict(Dict)
print("after change: ", Dict)
# #-----------arguments------------
# #命名参数
# def func1(name, age):
# print("name: ", name)
# print("age: ", age)
#
# #func1(name = 'sun', age = 23)
# func1(age = 23, name='sun')
#
# #缺省参数
# def func2(name, age = 23):
# print("name: ", name)
# print("age: ", age)
#
# func2('sun')
# func2('sun', 23)
# func2(name = 'sun', age = 23)
# func2(age = 23, name = 'sun')
#
# #可变长参数
# def sum(*args, **kwargs):
# print('-'*6)
# sum = 0
# for item in args:
# sum += item
#
# print("args: ", args)
# print("sum = ", sum)
# print("kwargs: ", kwargs)
# print('-'*6)
#
# sum() # args = () , sum = 0
# sum(1,2,3) # sum = 6
# sum(11,22,33,44, name='sun', age = 18) # sum = 110
#
# #拆包
# Tuple = (11,22,33,44)
# Dict = {"name":"sun", "age":23}
#
# def Print(*args, **kwargs):
# print("args: ", args)
# print("kwargs: ", kwargs)
#
# Print(Tuple, Dict) # args(Tuple, Dict) , kwargs{}
# Print(*Tuple, **Dict) # args(Tuple[0], Tuple[1]...) kwargs{Dict[0], Dict[1]...}
# Print(*Dict) # args(dict[0].key, dict[1].key....), kwargs{}
# #Print(**Tuple) #wrong
|
#-----------1. 字符串操作--------
mystr = "hello and world and bitch"
#find("str"), 从左向右找 能找到返回下标,否则返回-1
#rfind("str"),从右向左找 能找到返回下标,否则返回-1
#index("str"),从左向右找 能找到返回下标,否则发生错误
#rindex("str"),从右向左找 能找到返回下标,否则发生错误
#count("str"),统计字符串中含有str的个数
#replace("source", "destination"[, count]),返回字符被替换后的新的字符串,替换count个
#split(sep=None, maxsplit=-1),把字符串根据sep切割返回一个list,maxsplit小于0全部分割,大于0分割maxsplit次,剩余的是一个元素,
#capitalize(),返回新的字符串,把字符串首字母大写
#title(),返回新的字符串,把字符串中所有单词首字母大写
#startswith("str"),判断字符串是否以str开头
#endswith("str"),判断字符串是否以str结尾
#upper(),把字符串的所有字符都改为大写,返回成新的字符串
#lower(), 把字符串的所有字符都改为小写,返回成新的字符串
#center(50),把字符串居中在五十个字符中间
#ljust(50),把字符串左对齐在五十个字符左边
#rjust(50),把字符串右对齐在五十个字符右边
#strip(),默认字符串左右两边的空格全部去掉,作为新字符串返回,如果传入"str",会在左右两边把str中有的字符都删除
#lstrip(), rstrip(),分别删除左右两边的
#partition("str"),把元字符串按照str分为 left,str,right作为tuple返回,某人从左向右找 str
#rpartition("str"), lpartition("str"),分别是从左右两边开始找到str再进行分割
#splitlines(),把字符串按换行切,作为一个新的list返回
#isalpha(),判断字符串是否是纯字母
#isdigit(),判断字符串是否是纯数字
#isalnum(),判断是否是字母数字组合
#isspace(),判断是否是纯空格
#a.join(list),把list中的元素按照a的值连接起来,list = [a,b,c] a = "_" -> a_b_c
|
# #-------1. traverse a list---------
# nums = [11, 22, 33, 44, 55]
# # while
# len = len(nums)
# i = 0
# while i < len:
# print(nums[i], end = " ")
# i += 1
# print("")
#
# # for
# for num in nums:
# print(num, end = " ")
# print("")
# #---------2. for - else---------
# nums = [11, 22, 33]
# #nums = []
# for num in nums:
# print(num)
# break
# else:
# print('--')
#
# #else will be excuted only if [for loop didn't touch break] || [for loop didn't run at all]
# #--------3. Tuple ------------
# #tuple object does not support item assignment
# rdnums = (11, 22, 33)
# print("rdnums: ", rdnums)
#
# #access
# print("rdnums[0]): ", rdnums[0])
# print("rdnums[0:2]): ", rdnums[0:2])
# #rdnums[0] = 100, illegal, tuple's element can not be changed
# rdnums1 = (3.14,)
# print("rdnums1: ", rdnums1)
# print("rdnums + rdnums1 = ", rdnums + rdnums1)
#
# #delete
# del rdnums1
#
# #split
# a,b,c = rdnums
# print("a,b,c = rdnums : ", a, b, c)
#
# #single element
# snum = (11)
# print("type of snum = (11): ", type(snum)) # snum's type is int, use () as a operator
#
# snum = (11,)
# print("type of snum = (11,): ", type(snum)) # snum's type is typle
|
import calendar
import sys
'''name=input("enter your name\n")
for x in range(1,9):
if name.isalpha()==True or ' ' in name:
if len(name)>=3:
pass
break
else:
print("error")
name=input("enter your name\n")
else:
print("error")
name=input("enter your name\n")
age=input("enter your age\n")
while int(age)<15:
print("enter the age ")
age=input("enter your age\n")
mob_no=input("enter your number\n")
while len(mob_no)!=10:
if mob_no.isdecimal()==True:
print("the correct number")
mob_no=input("enter your number\n")
else:
print("invalid")
mob_no=input("enter the number")'''
#calculator
def calculator():
return('{} + {} = '.format(number_1, number_2), number_1 + number_2)
print("choose the number of the operataon you want\n1.addition\n2.subtraction\n3.division\n4.multiplication\n5.square\n6.cube\n7.square root\n8.cube root\n9.calander")
select=int(input("select the number: \n"))
select = 0
while select ==0:
if(int(select==1)):
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))
elif(int(select==2)):
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))
print('{} - {} = '.format(number_1, number_2),number_1 - number_2)
choice = input("1.menu\n2.exit")
if choice == 1:
calculator()
else:
sys.exit("thanks for using")
elif(int(select == 3)):
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))
print('{} / {} = '.format(number_1, number_2), number_1 / number_2)
choice = input("1.menu\n2.exit")
if choice == 1:
calculator()
else:
sys.exit("thanks for using")
elif(int(select==4)):
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))
print('{} * {} = '.format(number_1, number_2),number_1 * number_2)
choice = input("1.menu\n2.exit")
if choice == 1:
calculator()
else:
sys.exit("thanks for using")
elif(int(select==5)):
number_1 = int(input('Enter your number: '))
print('{}² = '.format(number_1),number_1 * number_1)
choice = input("1.menu\n2.exit")
if choice == 1:
calculator()
else:
sys.exit("thanks for using")
elif (int(select == 6)):
number_1 = int(input('Enter your number: '))
print('{}³ = '.format(number_1), number_1 * number_1 *number_1)
choice = input("1.menu\n2.exit")
if choice == 1:
calculator()
else:
sys.exit("thanks for using")
elif (int(select == 7)):
number_1 = int(input('Enter your first number: '))
print('{}½ = '.format(number_1), number_1 **0.5)
choice = input("1.menu\n2.exit")
if choice == 1:
calculator()
else:
sys.exit("thanks for using")
elif(int(select==8)):
number_1=int(input("enter the number you want to cube"))
print('{}**()1/3 = '.format(number_1),number_1**(1/3))
choice = input("1.menu\n2.exit")
if choice == 1:
calculator()
else:
sys.exit("thanks for using")
elif(int(select==9)):
yy=int(input("enter the year"))
mm=int(input("enter the month"))
print(calendar.month(yy , mm))
choice = input("1.menu\n2.exit")
if choice == 1:
calculator()
else:
sys.exit("thanks for using")
else:
print("the number you dial is incorrect please try again")
sys.exit()
calculator()
|
import re
timeStr = "^(?P<hour>[0-2]?[0-3]):(?P<minute>[0-5]?[0-9]):(?P<second>[0-5]?[0-9])$"
#date = "^(?P<month>[0-3]?[0-9])/(?P<day>[0-3]?[0-9])/(?P<year>[0-9]{4})$"
dateStr = "^(?P<year>[0-9]{4})\-(?P<month>[0-3]?[0-9])\-(?P<day>[0-3]?[0-9])$"
date1 = "2009-12-12"
match = re.search(dateStr, date1)
if match:
print "match"
time1 = "11:00:00"
time2 = "23:59:59"
time3 = "24:59:59"
match1 = re.search(timeStr, time1)
match2 = re.search(timeStr, time2)
match3 = re.search(timeStr, time3)
if match1:
print "match1"
if match2:
print "match2"
if match3:
print "match3"
|
def main():
L=[1,3,4.5,"hi"] # تستخدم for loop لطباعه كل عنصر قي سطر في
for item in L:
print(item)
if __name__ == '__main__': main()
|
#Tasks
task1 = {'todo': 'call John for AmI project organization', 'urgent': True}
task2 = {'todo': 'buy a new mouse', 'urgent': True}
task3 = {'todo': 'find a present for Angelina’s birthday', 'urgent': False}
task4 = {'todo': 'organize mega party (last week of April)', 'urgent': False}
task5 = {'todo': 'book summer holidays', 'urgent': False}
task6 = {'todo': 'whatsapp Mary for a coffee', 'urgent': False}
#Final list of dictionaries containing all the urgent tasks
final_task_List = []
#List of all tasks: i'm including all the task into a list to interate on each of them
Task_List = []
Task_List.append(task1)
Task_List.append(task2)
Task_List.append(task3)
Task_List.append(task4)
Task_List.append(task5)
Task_List.append(task6)
for task in Task_List:
if task.get("urgent", True):
final_task_List.append(task)
print(final_task_List)
|
def get_bin_from_user():
bin_string = input('请输入一个二进制数:')
while True:
is_valid_bin = True
for bin_number in bin_string:
if bin_number not in ['0', '1']:
is_valid_bin = False
if is_valid_bin:
return bin_string
else:
bin_string = input('请重新输入一个二进制数:')
def main():
bin_from_user = get_bin_from_user()
dec_from_bin = int(bin_from_user, 2)
print(f'你输入的二进制数{bin_from_user}转换为十进制数为{dec_from_bin}')
if __name__ == '__main__':
main()
|
alphabet = ["a", "b", "c", "d"]
l = len(alphabet)
cypher = 1
def encode(word):
position = 0
res = ""
for char in word:
if char == alphabet[position]:
position += cypher
while position >= l:
position -= l
res += alphabet[position]
else:
position += 1
return res
print(encode("abcd"))
|
"""
Module for currency exchange
This module provides several string parsing functions to implement a
simple currency exchange routine using an online currency service.
The primary function in this module is exchange.
Author: Oscar So (ons4), Jee-In Lee (jl3697)
Date: September 11, 2019
"""
import json
import introcs
#Part A#
def before_space(s):
"""
Returns a copy of s up to, but not including, the first space
Parameter s: the string to slice
Precondition: s has at least one space in it
"""
return s[:s.find(" ")]
def after_space(s):
"""
Returns a copy of s after the first space
Parameter s: the string to slice
Precondition: s has at least one space in it
"""
return s[s.find(" ")+1:]
#Part B#
def first_inside_quotes(s):
"""
Returns the first substring of s between two (double) quotes
Example: If s is 'A "B C" D', this function returns 'B C'
Example: If s is 'A "B C" D "E F" G', this function still returns 'B C'
because it only picks the first such substring.
Parameter s: a string to search
Precondition: s is a string with at least two (double) quote characters
inside.
"""
return s[s.find('"')+1:s.find('"',s.find('"')+1)]
def get_lhs(js):
"""
Returns the lhs value in the response to a currency query
Parameter json: a json string to parse
Precondition: json is the response to a currency query
"""
#unsure how to use first_inside_quotes
y = json.loads(js)
x = first_inside_quotes('"lhs"')
return y[x]
def get_rhs(js):
"""
Returns the rhs value in the response to a currency query
Parameter json: a json string to parse
Precondition: json is the response to a currency query
"""
y = json.loads(js)
x = first_inside_quotes('"rhs"')
return y[x]
def has_error(js):
"""
Returns True if the query has an error; False otherwise.
Parameter json: a json string to parse
Precondition: json is the response to a currency query
"""
y = json.loads(js)
return "invalid" in y["err"]
#Part C#
def currency_response(currency_from, currency_to, amount_from):
"""
Returns: Returns a JSON string that is a response to a currency query.
Parameter currency_from: the currency on hand (the LHS)
Precondition: currency_from is a string with no spaces
Parameter currency_to: the currency to convert to (the RHS)
Precondition: currency_to is a string with no spaces
Parameter amount_from: amount of currency to convert
Precondition: amount_from is a float
"""
return introcs.urlread('http://cs1110.cs.cornell.edu/2019fa/a1?src=' +
currency_from + '&dst=' + currency_to + '&amt=' + str(amount_from))
#Part D#
def is_currency(currency):
"""
Returns: True if code is a valid (3 letter code for a) currency
It returns False otherwise.
Parameter currency: the currency code to verify
Precondition: currency is a string.
"""
return (not (has_error(currency_response(currency, currency, 1.0))))
def exchange(currency_from, currency_to, amount_from):
"""
Returns the amount of currency received in the given exchange.
In this exchange, the user is changing amount_from money in currency
currency_from to the currency currency_to. The value returned
represents the amount in currency currency_to.
The value returned has type float.
Parameter currency_from: the currency on hand (the SRC)
Precondition: currency_from is a string for a valid currency code
Parameter currency_to: the currency to convert to (the DST)
Precondition: currency_to is a string for a valid currency code
Parameter amount_from: amount of currency to convert
Precondition: amount_from is a float
"""
return float(
before_space(get_rhs(
currency_response(currency_from,currency_to,amount_from))))
|
#
'''
Problem
Given: A file containing at most 1000 lines.
Return: A file containing all the even-numbered lines from the original file. Assume 1-based numbering of lines.
Sample Dataset
Bravely bold Sir Robin rode forth from Camelot
Yes, brave Sir Robin turned about
He was not afraid to die, O brave Sir Robin
And gallantly he chickened out
He was not at all afraid to be killed in nasty ways
Bravely talking to his feet
Brave, brave, brave, brave Sir Robin
He beat a very brave retreat
Sample Output
Yes, brave Sir Robin turned about
And gallantly he chickened out
Bravely talking to his feet
He beat a very brave retreat
'''
f = open('rosalind_ini5.txt','r')
count = 1
for i in f:
if count % 2 == 0:
print(i)
count = count + 1
f.close()
|
def print_monthly_savings_accumulation(rm, amount_saved, initial_balance = 0):
bal = initial_balance
# interest = balance * monthly interest rate.
print("Month Interest Amount Balance")
for i in range(12):
mon_int_earn = bal*rm
bal+=amount_saved
bal+=mon_int_earn
print(" "+str(i)+" $"+str(round(mon_int_earn,2))+" $"+str(round(amount_saved,2))+" $"+str(round(bal,2)))
tot_am_sav = amount_saved*12
print
print("Total amount saved: $ "+str(round(tot_am_sav,2)))
print("Total interest earned: $ "+str(round(bal-tot_am_sav,2)))
print("End of year balance: $ "+str(round(bal,2)))
return bal
def interactive_savings_plan():
sg = int(input("Enter your savings goal in dollars: "))
rr = int(input("Enter the expected annual rate of return (i.e. 0.03): "))
y = int(input("Enter time until goal in years: "))
top = sg*rr
mon = y*12
yes = rr+1
bot = yes**mon
sav_am =top/(bot-1)
# some arithmatic problem giving bottom a 0 which is causing error
print("To reach your goal in "+str(y)+" years, you will need to save $"+str(round(sav_am,2))+" per month.")
print
print
bal = 0
for i in range(y):
print("Summary of year "+str(i))
bal = print_monthly_savings_accumulation((rr/12),sav_am,bal)
if __name__ == '__main__':
interactive_savings_plan()
|
def print_rect(ch,width,height):
for i in range(height):
print ch*width
def print_upper_left_triangle(ch,height):
for i in range(height):
print ch*(height-i)
def print_upper_right_triangle(ch, height): #broken
for i in range(height):
print (' '*i)+(ch*(height-i))
def print_lower_left_triangle(ch, height):
for i in range(height+1):
print (ch*i)+(' '*(height-i))
def print_lower_right_triangle(ch, height):
for i in range(height+1):
print (' '*(height-i))+(ch*i)
def print_pyramid(ch, height):
for i in range(height):
print ' '*(height-i-1) + ch*(2*i+1)
def print_diamond(ch, height):
for i in range(height):
print ' '*(height-i-1) + ch*(2*i+1)
for j in reversed(range(height)):
print ' '*(height-j-1) + ch*(2*j+1)
if __name__ == '__main__':
print_rect('*', 7, 5)
print
print_upper_left_triangle('*',7)
print
print_upper_right_triangle('*',4)
print
print_lower_left_triangle('*',5)
print
print_pyramid('*',4)
print
print_diamond('*',4)
|
# a01_four_fours.py - Assignment 1
# your name: Sam Murray
# your email: [email protected]
# Computes the integers 0 through 4 using exactly 4 fours, and a
# creative combination of arithmetic operators.
#
# this statement creates a variable called 'zero' which is the result of the expression 4 + 4 - 4 - 4
zero = 4 + 4 - 4 - 4
# continue to create variables 'one', 'two', 'three', and 'four' below.
one = 4 - 4 + (4//4)
two = (4//4) + (4//4)
three = (4+4+4)//4
four = 4 - ((4-4)//4)
# put all print statements in this section:
print 'zero = ', zero
print 'one = ', one
print 'two = ', two
print 'three = ', three
print 'four = ', four
|
""" Implementation of a Fibonacci generator as a class """
class FibGen:
def fibn(self, n):
a, b = 0, 1
for i in range(n):
a, b = b, a+b
return b
def __getitem__(self, n):
return self.fibn(n)
|
""" Find the value and position of the largest number in a list.
Implemented using range() and len() built-ins.
"""
numlist = (1000,0.22, 34, 4, -12, 13.01, 140.45, 111)
maxnum = numlist[0]
maxpos = 0
for idx in range(len(numlist)):
if numlist[idx] > maxnum:
maxnum = numlist[idx]
maxpos = idx
print(maxnum,"at",maxpos)
|
import decimal
D = decimal.Decimal
amount = D(input("enter amount: "))
print(amount)
for i in map(D,['20', '10', '5', '1', '0.25', '0.1', '0.05', '0.01']):
print(' {} ${:.2f} bill/coin'.format(amount//i, i))
amount = amount % i
|
# coding=UTF-8
from math import exp, sqrt
import sys
h = 0.001
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, ** kwargs)
exit(84)
def f(t, ducks):
"""
Function
:param t:
:param ducks:
:return:
"""
a = ducks
return a * exp(-t) + (4 - 3 * a) * exp(-2 * t) + (2 * a - 4) * exp(-4 * t)
def func_mean_var(ducks):
"""
Question 1
:param ducks:
:return:
"""
mean = 0.0
var = 0.0
for i in range(1, 100000):
t = i * h
res = h * t * f(t, ducks)
t2 = t + h / 2
res2 = h * t2 * f(t2, ducks)
mean += 2 * res + 4 * res2
var += 2 * res * t + 4 * res2 * t2
mean = mean / 6
var = var / 6 - pow(mean, 2)
mean *= 60
var = sqrt(var)
return mean, var
def func_time(ducks):
"""
Calculate times
:param ducks:
:return:
"""
res = 0
i = 1
res50 = None
while True:
t = i * h
res += h * f(t, ducks)
if res > 0.50 and res50 is None:
res50 = t * 60
if res > 0.99:
res99 = t * 60
break
i += 1
return res50, res99
def func_percent(ducks):
"""
Calculate percentage
:param ducks:
:return:
"""
res = 0
i = 1
m1 = None
while True:
t = i * h
res += h * f(t, ducks)
if i >= 1 / h and m1 is None:
m1 = res * 100
if i >= 2 / h:
m2 = res * 100
break
i += 1
return m1, m2
def display_time(seconds):
"""
Display seconds
:param seconds:
:return:
"""
seconds = int(round(seconds))
minutes = seconds // 60
seconds -= 60 * minutes
print("{}m {:02d}s".format(minutes, seconds))
def display(**kw):
"""
Display results
:param kw:
:return:
"""
print("average return time: ", end="")
display_time(kw["mean"] + 0.01)
print("standard deviation: {:0.03f}".format(kw["var"]))
print("time after which 50% of the ducks come back: ", end="")
display_time(kw["t50"])
print("time after which 99% of the ducks come back: ", end="")
display_time(kw["t99"])
print("percentage of ducks back after 1 minute: {:0.01f}%".format(kw["m1"] - 0.05))
print("percentage of ducks back after 2 minutes: {:0.01f}%".format(kw["m2"] - 0.01))
def calculate(ducks):
"""
Compute with duck constant
:param ducks:
:return:
"""
mean, var = func_mean_var(ducks)
t50, t99 = func_time(ducks)
m1, m2 = func_percent(ducks)
display(var=var, mean=mean, t50=t50, t99=t99, m1=m1, m2=m2)
return 0
|
import pygame
pygame.init()
import numpy as np
import matplotlib.pyplot as plt
class Neuron:
def __init__(self):
self.balance = 0.7
self.power = np.random.random()
self.limit = 0.6
self.braking_speed = 0.2
self.acceleration_speed = 0.1
self.input_signal = np.zeros((2, 2))
self.weights = np.random.rand(2, 2) * 3
self.lr = 10
self.History = []
def eval_input_signal(self):
self.power += np.sum(self.input_signal * self.weights)
reward = self.lr * (self.power - self.balance)
delta_w = (self.input_signal * self.weights) * reward
self.weights += delta_w
self.weights = self.weights.clip(0, 1)
def step(self):
delta = self.power - self.balance
if delta > 0:
self.power -= delta * self.braking_speed
else:
self.power -= delta * self.acceleration_speed
self.eval_input_signal()
output_signal = max(self.power - self.limit, 0)
if output_signal > 0:
output_signal = self.power / 4
self.power = 0
self.History.append(self.power)
return output_signal
def color(val):
if val < 0:
val = 0
if val > 1:
val = 1
return tuple([int(val * 255) for _ in range(3)])
def put_input(neuron, Signals, i, j):
if j == 0:
neuron.input_signal[0][0] = 0
else:
neuron.input_signal[0][0] = Signals[i][j - 1]
if i == 0:
neuron.input_signal[0][1] = 0
else:
neuron.input_signal[0][1] = Signals[i - 1][j]
if i == Signals.shape[0] - 1:
neuron.input_signal[1][0] = 0
else:
neuron.input_signal[1][0] = Signals[i + 1][j]
if j == Signals.shape[1] - 1:
neuron.input_signal[1][1] = 0
else:
neuron.input_signal[1][1] = Signals[i][j + 1]
def act(Network):
if np.random.random() < 0.1:
Network[1][1].power += 100
for i in range(len(Network)):
for j in range(len(Network[i])):
neuron = Network[i][j]
put_input(neuron, Signals, i, j)
for i in range(len(Network)):
for j in range(len(Network[i])):
neuron = Network[i][j]
Signals[i][j] = neuron.step()
rect = (j * size + ofs_x, i * size + ofs_y,
size, size)
pygame.draw.rect(sc, color(neuron.power), rect)
if step % 100 == -1:
for x in range(3):
plt.plot(Network[x + 9][12].History)
plt.show()
print(Network[12][12].weights)
FPS = 20000
clock = pygame.time.Clock()
wid, hght = 800, 200
ofs_x, ofs_y = 0, 0
size = 10
sc = pygame.display.set_mode((wid, hght))
Network = [[Neuron() for x in range(ofs_x // size, (wid - ofs_x) // size)]
for y in range(ofs_y // size, (hght - ofs_y) // size)]
Signals = np.zeros((len(Network), len(Network[0])))
for step in range(100000):
sc.fill(pygame.Color('black'))
for i in pygame.event.get():
if i.type == pygame.QUIT:
pygame.quit()
act(Network)
clock.tick(FPS)
pygame.display.update()
|
num1 = 2
num2 = 3
num3 = .25
print(num1 + num2)
print(num1 * num2)
print(num1 - num2)
print(num2 / num1)
print(num1 + num3)
print(num1 * num3)
print(num1 - num3)
print(num2 / num3)
print(num2 % num1)
num1 += 2
print(num1)
num1 *= 2
print(num1)
num1 -= 2
print(num1)
num1 /= 2
print(num1)
|
#!/usr/bin/env python
def ispalindrome(s):
length = len(s)
for i in range(length/2):
if s[i] != s[length - 1 - i]:
return False
return True
|
# # Your code here
with open(r"C:\Users\galfa\Desktop\CODING\Lambda\unit-6\week-1\cs-module-project-hash-tables\applications\histo\robin.txt") as f:
words = f.read()
def histogram(words):
filtered_chars = '":;,.-+=/\\|[]{}()*^&'
filtered_string = ''.join(filter(lambda x : x not in filtered_chars, words))
word_list = filtered_string.split()
largest_word = max(word_list, key=lambda s: (len(s), s))
count = {}
for w in word_list:
word = w.lower()
if count.get(word) is None:
count[word] = 1
else:
count[word] = count[word] + 1
count_sorted = sorted(count.items(), key=lambda x: x[1], reverse=True)
for word, count in count_sorted:
white_space = len(largest_word) - len(word) + 2
print(word + ' ' * white_space + count * '#')
print(histogram(words))
|
# Aloha.py, Python simulation example: a form of slotted ALOHA
# here we will look finite time, finding the probability that there are
# k active nodes at epoch m
# usage: python Aloha.py s p q m k
import random, sys
class node: # one object of this class models one network node
# some class variables
s = int(sys.argv[1]) # number of nodes
p = float(sys.argv[2]) # transmit probability
q = float(sys.argv[3]) # msg creation probability
activeset = [] # which nodes are active now
inactiveset = [] # which nodes are inactive now
r = random.Random(98765) # set seed
def __init__(self): # object constructor
# start this node in inactive mode
node.inactiveset.append(self)
# class methods
def checkgoactive(): # determine which nodes will go active
for n in node.inactiveset:
if node.r.uniform(0,1) < node.q:
node.inactiveset.remove(n)
node.activeset.append(n)
checkgoactive = staticmethod(checkgoactive)
def trysend():
numnodestried = 0 # number of nodes which have tried to send
# during the current epoch
whotried = None # which node tried to send (last)
# determine which nodes try to send
for n in node.activeset:
if node.r.uniform(0,1) < node.p:
whotried = n
numnodestried += 1
# we'll have a successful transmission if and only if exactly one
# node has tried to send
if numnodestried == 1:
node.activeset.remove(whotried)
node.inactiveset.append(whotried)
trysend = staticmethod(trysend)
def reset(): # resets variables after a repetition of the experiment
for n in node.activeset:
node.activeset.remove(n)
node.inactiveset.append(n)
reset = staticmethod(reset)
def main():
m = int(sys.argv[4])
k = int(sys.argv[5])
# set up the s nodes
for i in range(node.s): node()
count = 0
for rep in range(10000):
# run the process for m epochs
for epoch in range(m):
node.checkgoactive()
node.trysend()
if len(node.activeset) == k: count += 1
node.reset()
print ('P(k active at time m) =', count/10000.0)
# technical device to make debugging easier, etc.
if __name__ == '__main__': main()
|
# tic tac toe game
# without design, print x and o.
a1 = "_"
a2 = "_"
a3 = "_"
b1 = "_"
b2 = "_"
b3 = "_"
c1 = "_"
c2 = "_"
c3 = "_"
def grid():
print(" 1 2 3")
print(f"A {a1} {a2} {a3}")
print(f"B {b1} {b2} {b3}")
print(f"C {c1} {c2} {c3}")
def find_loc_user():
loc = input("Choose the location of your X : ")
loc.lower()
loc = str(loc)
if loc == "a1":
a1 = "X"
if loc == "a2":
a2 = "X"
if loc == "a3":
a3 = "X"
if loc == "b1":
b1 = "X"
if loc == "b2":
b2 = "X"
if loc == "b3":
b3 = "X"
if loc == "c1":
c1 = "X"
if loc == "c2":
c2 = "X"
if loc == "c3":
c3 = "X"
print("At the end of the find_loc_user function, a1 is equal to" , a1)
ready = input("Are you ready to play Tic Tac Toe with me ? (say yes): ")
ready.lower()
if ready == "yes":
print("Here is the grid")
grid()
while True:
find_loc_user()
print("After the find_loc_user (outside of it) , a1 is equal to", a1)
grid()
# when I print the grid after having chosen a1, a1 is again equal to _ not X like it was just before
|
# Head ends here
from collections import defaultdict
def next_move(posr, posc, board):
trash = []
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == "d":
if (i,j)==(posr,posc):
print("CLEAN")
return
else:
trash.append((i,j))
mindis = len(board)*2+1
target = ()
for t in trash:
dis = abs(t[0] - posr) + abs(t[1] - posc)
if mindis>dis:
mindis = dis
target = t
if target[0] - posr < 0: print("UP")
elif target[0] - posr > 0: print("DOWN")
elif target[1] - posc < 0: print("LEFT")
elif target[1] - posc > 0: print("RIGHT")
# Tail starts here
if __name__ == "__main__":
pos = [int(i) for i in input().strip().split()]
board = [[j for j in input().strip()] for i in range(5)]
next_move(pos[0], pos[1], board)
|
#!/usr/bin/env python3
"""Find the proportion of non-null values in each column of a CSV."""
import click
import pandas as pd
@click.command()
@click.argument('input-file', default='-', type=click.File('r'))
@click.argument('output-file', default='-', type=click.File('w'))
def null_proportion(input_file, output_file):
input_frame = pd.read_csv(input_file)
null_counts = input_frame.isnull().sum(axis=0) # sum down columns
valid_proportion = (1 - null_counts / len(input_frame))
valid_proportion.to_csv(output_file)
if __name__ == '__main__':
null_proportion()
|
import sys
import heapq
import unittest
class HuffmanData(object):
"""
Description: Object to store every character and its associated Huffman code
"""
def __init__(self, c):
self.c = c
self.code = None
class HuffmanNode(object):
"""
Description: Adds frequency context to huffman data and make it into a binary tree node
"""
def __init__(self, freq, data=None):
self.freq = freq
self.data = data
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def is_internal(self):
"""
Description: Check if its an intermediate node of Huffman tree not associated with a single character (those nodes are at the leaf)
Arguments:
None
Returns:
Boolean indicating internal or not
"""
return self.data is None
def set_code(self, code):
"""
Description: Store given list of chars as string code
Arguments:
code built by traversing tree
Returns:
None
"""
if self.is_internal():
raise ValueError('Cannot set code for internal node')
self.data.code = ''.join(code)
class HuffmanTree(object):
"""
Description: Huffman tree formed by combining Leaf nodes under an internal node
"""
def __init__(self, freq, data=None):
self.root = HuffmanNode(freq, data)
def __lt__(self, other):
return self.root < other.root
def assign_codes(self):
"""
Description: Recurse on this Huffman tree starting from root and assign codes to leaf nodes
Arguments:
None
Returns:
None
"""
self._assign_codes(self.root)
@staticmethod
def _assign_codes(node, code=[]):
"""
Description: Build Huffman code depending on direction of traversal in Binary Huffman Tree
Arguments:
None
Returns:
None
"""
if not node.is_internal():
node.set_code(code)
return
if node.left:
# If you are going left in the tree, append a 0
code.append('0')
HuffmanTree._assign_codes(node.left, code)
code.pop() # Backtrack
if node.right:
# Append 1 if going right
code.append('1')
HuffmanTree._assign_codes(node.right, code)
code.pop() # Backtrack
def get_code_dict(self):
"""
Description: Build dictionary of character to huffman code from a given Huffman tree
Arguments:
None
Returns:
Dictionary of code character to huffman code
"""
code_dict = dict()
self._get_code_dict(self.root, code_dict)
return code_dict
@staticmethod
def _get_code_dict(node, code_dict):
"""
Description: Recursive helper for get_code_dict
Arguments:
None
Returns:
None
"""
if not node.is_internal():
code_dict[node.data.c] = node.data.code
if node.left:
HuffmanTree._get_code_dict(node.left, code_dict)
if node.right:
HuffmanTree._get_code_dict(node.right, code_dict)
def build_freq_dict(data):
"""
Description: Count frequency of occurrence of characters in given string and build map
Arguments:
String data
Returns:
Dictionary of characters and their frequency of occurrence
"""
freq_dict = dict()
for c in data:
freq_dict[c] = freq_dict.get(c, 0) + 1
return freq_dict
def huffman_encoding(data):
if len(data) == 0: # To satisfy int(encoded_data) return 0 with None for tree incase of empty string
return '0', None
freq_dict = build_freq_dict(data)
h = []
for c, freq in freq_dict.items():
heapq.heappush(h, HuffmanTree(freq, HuffmanData(c))) # Push Huffman Trees made of individual character nodes into min heap
while len(h) > 1: # Since you will always have one tree left at the end
tree1 = heapq.heappop(h)
tree2 = heapq.heappop(h)
new_freq = tree1.root.freq + tree2.root.freq
new_tree = HuffmanTree(new_freq)
new_tree.root.left = tree1.root
new_tree.root.right = tree2.root
heapq.heappush(h, new_tree)
final_tree = heapq.heappop(h) # Pop the one tree that's left
if not final_tree.root.is_internal(): # In case of strings with just one character, root will be a HuffmanData node, so convert it to left child of a dummy tree.
new_tree = HuffmanTree(final_tree.root.freq)
new_tree.root.left = final_tree.root
new_tree.root.right = None
final_tree = new_tree
final_tree.assign_codes()
# Build code dict in assign codes
code_dict = final_tree.get_code_dict()
encoded_data = [code_dict[c] for c in data]
return ''.join(encoded_data), final_tree
def huffman_decoding(data, tree):
decoded_data = []
if tree:
curr_node = tree.root
for digit in data:
if digit == '0':
curr_node = curr_node.left
if digit == '1':
curr_node = curr_node.right
if not curr_node.is_internal():
decoded_data.append(curr_node.data.c)
curr_node = tree.root
return ''.join(decoded_data)
class TestHuffmanCoding(unittest.TestCase):
def setUp(self):
print("\n\n****{}****".format(self._testMethodName))
def encode_and_decode(self, a_great_sentence):
print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence)))
print ("The content of the data is: {}\n".format(a_great_sentence))
encoded_data, tree = huffman_encoding(a_great_sentence)
print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2))))
print ("The content of the encoded data is: {}\n".format(encoded_data))
decoded_data = huffman_decoding(encoded_data, tree)
print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data)))
print ("The content of the encoded data is: {}\n".format(decoded_data))
#@unittest.skip('')
def test_case1(self):
self.encode_and_decode("The bird is the word")
# The size of the data is: 57
# The content of the data is: The bird is the word
# The size of the encoded data is: 36
# The content of the encoded data is: 1011111011000111010111110000101111110100100001110110001000111011100001
# The size of the decoded data is: 57
# The content of the encoded data is: The bird is the word
def test_case2_empty_string(self):
self.encode_and_decode('')
# The size of the data is: 37
# The content of the data is
# The size of the encoded data is: 24
# The content of the encoded data is: 0
# The size of the decoded data is: 37
# The content of the encoded data is:
def test_case3_single_char(self):
self.encode_and_decode('a')
# The size of the data is: 38
# The content of the data is: a
# The size of the encoded data is: 24
# The content of the encoded data is: 0
# The size of the decoded data is: 38
# The content of the encoded data is: a
def test_case4_repeated_single_char(self):
self.encode_and_decode('aaaa')
# The size of the data is: 41
# The content of the data is: aaaa
# The size of the encoded data is: 24
# The content of the encoded data is: 0000
# The size of the decoded data is: 41
# The content of the encoded data is: aaaa
if __name__ == "__main__":
unittest.main()
|
import unittest
import random
def _get_min_max(ints, left, right):
"""
Recursive helper to find min and max from left and right halves and to compare the two min/max
Args:
ints(list): list of integers containing one or more integers
left(int): Left index within which to look for min/max
right(int): Right index within which to look for min/max
"""
if right <= left + 1:
# Takes care of 1 and 2 elements- since left and right will be same for 1 elements so
# doesn't matter how you index it. For 1
if ints[left] < ints[right]:
return ints[left], ints[right]
else:
return ints[right], ints[left]
middle = left + (right - left) // 2
left_min, left_max = _get_min_max(ints, left, middle)
right_min, right_max = _get_min_max(ints, middle+1, right)
# Compare min and max of two halves
if left_min < right_min:
min_int = left_min
else:
min_int = right_min
if left_max > right_max:
max_int = left_max
else:
max_int = right_max
return min_int, max_int
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if len(ints) == 0: # Handle special case of zero elements to return None for min/max
return None, None
return _get_min_max(ints, 0, len(ints)-1)
class TestMinMaxUnsortedArr(unittest.TestCase):
def setUp(self):
print("\n\n****{}****".format(self._testMethodName))
def print_pass_fail(self, expected_min, expected_max, ints):
print ("Pass" if ((expected_min, expected_max) == get_min_max(ints)) else "Fail")
def test_case1(self):
## Example Test Case of Ten Integers
l = [i for i in range(0, 10)] # a list containing 0 - 9
random.shuffle(l)
self.print_pass_fail(0, 9, l)
def test_case2(self):
# Empty list
l = [] # a list containing 0 - 9
self.print_pass_fail(None, None, l)
def test_case3(self):
## One element
l = [10] # a list containing 0 - 9
self.print_pass_fail(10, 10, l)
def test_case4(self):
## Two element
l = [10, 8] # a list containing 0 - 9
self.print_pass_fail(8, 10, l)
def test_case5(self):
## Min and Max on same side
l = [10, 0, 3, 4, 5, 5, 2, 2] # a list containing 0 - 9
self.print_pass_fail(0, 10, l)
def test_case6(self):
## All elements are the same
l = [2,2, 2, 2, 2, 2] # a list containing 0 - 9
self.print_pass_fail(2, 2, l)
if __name__ == '__main__':
unittest.main()
"""
Expected Solution-
****test_case1****
Pass
.
****test_case2****
Pass
.
****test_case3****
Pass
.
****test_case4****
Pass
.
****test_case5****
Pass
.
****test_case6****
Pass
.
----------------------------------------------------------------------
Ran 6 tests in 0.001s
OK
"""
|
'''
Örnek 5.5:
100’lük sisteme göre girilen başarı notunu harfli sisteme dönüştüren programı
kodlayalım.
'''
Nt = int (input("0-100 arası not gir.:"))
if Nt>=90 and Nt<=100: #100<=Nt<90
print("AA")
elif Nt>=80 and Nt<90:
print("BA")
elif Nt>=70 and Nt<80:
print("BB")
elif Nt>=60 and Nt<70:
print("CB")
elif Nt>=50 and Nt<60:
print("CC")
else:
print("FF")
|
'''
Örnek 10.3:
Kullanıcının girdiği bir cümleyi listeye dönüştüren ve bu listeden sesli harfleri
çıkaran (sessiz harflerden bir liste oluşturan) programı kodlayalım.
'''
L = [] #boş liste
cumle=input('Bir Cümle Giriniz.:')
L=list(cumle) #listeye dönüştür
print ("Sessiz Harfler Listesi.:")
for k in L:
if k in 'aeıioöuü ':
L.remove(k)
#sesli harfi listeden sil
#döngü sonu
print (L) #listeyi yaz
|
'''
Örnek 20.7: Hilesiz bir madeni para N=10 defa atıldığında 7 kere ‘tura’
gelmesinin olasılığı nedir? Programda ‘tura’ durumunu ‘1’, ‘yazı’ durumunu
‘0’ ile ifade edersek, toplam N atışta bu değerlerin gelme olasılığını inceleyen
programı kodlayalım.
'''
from random import *
from math import *
from statistics import *
import numpy as np
print("Yazı / Tura dağılımı")
#random 0-1 arasında kesirli sayı üretir ve
#round ile de bu sayı yuvarlatılır.
N = 7 #atış sayısı
L = [] #liste
p = 1 #tura durumu
for i in range (N):
para = random()
L.append(round(para))
if para < 0.5:
p = p + 1 #tura gelme sayısı
print (L)
#Histogram şeklinde gösterimi
print ("Tura dağılımı.:" ,"*" * p)
print ("Yazı dağılımı.:" ,"*" *(N-p))
#Varyansı
print ("Varyansı.:" , variance(L))
bK = comb(10,7) #Binom katsayısı: bK
print ("Binom katsayısı", bK)
C = bK * (0.5)**7 * (0.5)**3
print("Binom dağılımı.:", C)
print("Numpy Binom dağılımı.:",
sum(np.random.binomial(10, 0.5, 10000) == 7)/10000)
|
'''
Örnek 23.15:
2012-2020 yılları arasındaki aktif Facebook kullanıcı sayısını gösteren tabloyu
nokta (scatter) ve çizgi (plot) grafikleri ile birlikte gösteriniz
'''
# %%
import numpy as np
import matplotlib.pyplot as plt
yil = np.arange(2012, 2021) #2021 dahil değil
kSay = [1056, 1228, 1393, 1591, 1860, 2129, 2320, 2498, 2797]
plt.scatter (yil, kSay, color='gray') #nokta koy
plt.plot (yil, kSay) #çizgi çiz
#Alternatifi: plt.plot (yil, kSay, '-o')
plt.xlabel('(Yıl)') #x ekseni etiketi
plt.ylabel('(Milyon)') #y ekseni etiketi
plt.title('Facebook aktif kullanıcı sayısı')
plt.show()
# %%
|
'''
Örnek 4.5:
Girilen üç sayı içerisinden en büyük olanı ekranda gösteren programı
kodlayalım.
'''
a = int (input("1.sayı.:"))
b = int (input("2.sayı.:"))
c = int (input("3.sayı.:"))
enb = max (a, max(b,c))
print ("En büyüğü.:",enb)
|
'''
Örnek 9.14: Sezar Şifrelemesi
Konsoldan girilen bir kelimedeki her harfi, o harften sonra 3 harf atlayarak
(gerektiğinde ‘Z’ den ‘A’ ya atlayacak şekilde) şifreleyen ve şifrelenmiş kelimeyi
ekranda gösteren programı kodlayınız.
'''
#Sezar fonksiyonu
def sezar(s):
tKar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
donus = tKar[3:]+tKar[:3]
rotKar = lambda c: donus[tKar.find(c)] if tKar.find(c)>-1 else c
return ''.join( rotKar(c) for c in s )
#Ana program
s=input("Metni giriniz.:")
print(sezar(s.upper()))
|
'''
Örnek 4.4:
Dik kenar uzunlukları kullanıcı tarafından girilen bir dik üçgenin hipotenüsünü,
Pisagor teoremine göre hesaplayan programı kodlayalım.
'''
b = int (input("1.dik kenar.:"))
c = int (input("2.dik kenar.:"))
a = (b**2 + c**2)**0.5
print ("Hipotenüs.:", a)
|
'''
Örnek 14.3: Verilen listeden sayı ile başlayan verileri çeken (alan) programı
kodlayınız.
'''
import re
liste = ["1","22","A1", "333", "A2A"]
regex = r"\d+"
for s in liste:
if re.match(regex,s):
print(s)
|
'''
Örnek 12.3:
Daha önce Örnek 12.2’de verilen Fibonacci serisini hesaplayan programı yield
komutu ile kodlayalım.
'''
def fib(max):
a, b = 0, 1 #a=0; b=1 oldu
while a < max:
yield a #a değerini döndürür
#a değerini test amaçlı yazdıralım
print ("a:",a)
# a = b; b = a + b yer değiştirme işlemini yapalım
a, b = b, a + b
#Ana program
#1000'e kadar ki Fibonacci serisini yazdır
for n in fib(1000):
print("n:", n, end=', ')
|
'''
Örnek 8.6 (OKEK Hesabı):
Rastgele üretilen iki sayının en küçük ortak bölenlerini (OKEK) bulan programı
kodlayalım.
'''
#OKEK(a,b) = a*b / gcd(a,b) ile hesaplanabilir
from random import *
from math import *
#Ana program
a = randint(1,100)
b = randint(1,100)
obeb = gcd(a,b) #obebini al
okek =(a*b)/obeb #okekini al
print (f"a:{a} \nb:{b} \nObeb={obeb}")
print("Okek(", a, ",", b, ")=", okek )
|
'''
Örnek 2.1:
İki sayının toplamını hesaplayan basit matematiksel işlemi yapalım.
'''
A = int (input("1.sayıyı gir:")) #hatalı kullanım: A = input("1.sayıyı gir:")
B = int (input("2.sayıyı gir:"))
T = A + B
print ("Toplam= ", T)
|
'''
Örnek 21.3. (Matrise (1D >> 2D ) Dönüştürme):
“d= [1,2,3,4,5,6,7,8,9,10,11,12]” şeklindeki tek boyutlu diziyi 4*3 lük bir matrise
dönüştüren programı yazınız.
'''
import numpy as np
#Tek boyutlu d dizisi (1-12)
d = np.arange (1, 13)
# d dizisi 4*3 lük matrise dönüştü.
A = d.reshape(4,3)
print (A)
|
'''
Örnek 17.8: JSON formatında veri oluşturup, bu veriden istenilen değerleri
alan programı kodlayalım
'''
import json
#json formatına dönüşebilecek veri
#sözlük yapısına benzer şekilde tasarlanır
veri = '''[
{"plaka" : "01",
"il" : "Adana"
},
{"plaka": "24",
"il" : "Erzincan"
}
]'''
#'.loads' metodu ile veri, JSON formatına dönüştürülür
veriJS = json.loads(veri)
#JSON formatındaki verinin kayıt sayısı
print ("kayıt sayısı.: ", len(veriJS))
#JSON formatındaki veriden belli değerler alınabilir
for i in veriJS:
print ("il adı.: ", i['il'])
print ("plakası.: ", i['plaka'])
|
'''
Örnek 7.2:
4 işlem yapan menülü basit bir hesap makinesi programını kodlayalım.
'''
#Menü fonksiyonu
def menu():
print ("[+]-Toplama\n")
print ("[-]-Çıkarma\n")
print ("[*]-Çarpma\n")
print ("[/]-Bölme\n")
#Hesapla fonksiyonu
def Hesapla (a, b, op):
if (op == '+'): return a+b
if (op == '-'): return a-b
if (op == '*'): return a*b
if (op == '/'): return a/b
#Ana program
while True:
menu ()
a = float (input ("1. sayı.:"))
b = float (input ("2. sayı.:"))
islec = input ("Menüden işlemi seç.:")
sonuc = Hesapla (a, b, islec)
print ("Sonuc= ", sonuc)
cvp = input ("Devam mı[E/H].:")
if cvp.lower()!='e':
break #Eğer cvp ‘e’ değilse programdan çık
|
'''
Örnek 9.1:
Bir stringin içeriğini (belli bir karakterden sonrasını değiştiren) güncelleyen
programı kodlayalım.
'''
ad = 'Galata Saray'
yeniAd= ad[:7 ] + 'Bahçe'
#Alternatifi:
#yeniAd= ad.replace( 'Galata Saray', 'Galata Bahçe')
print ("Adres Güncellendi: ", yeniAd)
|
'''
Örnek 13.7: Soyut sınıf ve metot kavramını bir önceki örnek uygulama
üzerinden açıklayalım.
'''
from abc import *
class Pizza(ABC): #üst soyut sınıf
icerik = ['Peynir', 'Zeytin']
@classmethod #sınıf metodu
@abstractmethod #soyut metot
def getMalzeme(cls):
return cls.icerik
#DiyetPizza sınıfı Pizza sınıfının metotlarına sahip olmalıdır
class DiyetPizza(Pizza): #alt sınıf
@classmethod #sınıf metodu
def getMalzeme(cls):
return ['Mantar'] + cls.icerik
#Ana program da
#Örnek oluşturmadan sınıf metoduna erişebiliriz
print(DiyetPizza.getMalzeme())
|
'''
Örnek 8.8 (Seri toplamı):
f(x) = x + x2 + x3 + x4 + ……… + xn şeklinde verilen serinin toplamını bulan
programı kodlayalım.
'''
from math import *
X = int (input ("X değeri.:"))
Fx = 0 #seri toplam değişkeni
N = int (input ("Seri terim sayısı.:"))
for us in range (1, N+1):
Fx = Fx + pow(X, us)
print ("Toplam.:", Fx) #Seri toplamını (Fx)
|
'''
Örnek 13.6: Soyut sınıf ve @abstractmethod kullanımını Pizza örneği üzerinden
açıklayan programı kodlayalım.
'''
from abc import *
class Pizza(ABC): #üst soyut sınıf
icerik = ['Peynir', 'Zeytin']
@abstractmethod
def getMalzeme(self): #soyut metot
pass #Eşdeğeri: return
#DiyetPizza sınıfı Pizza sınıfının metotlarına sahip olmalıdır
class DiyetPizza(Pizza): #alt sınıf
def getMalzeme(self):
return ['Mantar'] + self.icerik
#Ana program
p = DiyetPizza()
print(p.getMalzeme())
|
'''
Örnek 15.14: String veri tipinde tarih verilerinin tutulduğu bir listeyi tarih-zaman
tipinde farklı saat dilimlerine (“Tokyo”, “İstanbul” gibi) dönüştüren uygulamayı
kodlayınız
'''
import pendulum
tarihList = ["01.01.2020","01.02.2020", "01.03.2020","15.07.2021"]
#bölgesel tarih-saat formatında listele
b = []
t = []
for tarih in tarihList:
x = pendulum.parse(tarih, tz= "Europe/Istanbul", strict=False)
y = pendulum.parse(tarih, tz= "Asia/Tokyo",strict=False)
b.append(x)
t.append(y)
print ("Yıl-Ay-Gün T Saat Formatı")
for ist in b:
print (ist) #Türkiye/istanbul saati
print ("----------------")
for tky in t:
print (tky) #Asya/tokyo saati
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 13 12:40:23 2017
@author: [email protected]
"""
from itertools import product
import pandas as pd
import numpy as np
from pandas import DataFrame
'''
Original problem:
Monty Hall hosts a quiz, in it hidden one prize behind one door.
There are three doors: A,B,C.
You have to choose one door.
Monty then open one door, that is neither your pick nor having the prize.
So there's left two doors now.
Do you switch door? or do you stick? Which is better strategy?
Monty Hall problem taken from A. Downey's book.
'''
class Experiment:
def __init__(self, variables, lists):
"""
variables : list of variable names
lists : each combination of each variable names.
"""
lists = list (product(*lists ))
self.omega = DataFrame(lists)
self.omega["Tally"] = pd.Series(0, index=self.omega.index)
self.omega["Label"] = pd.Series("", index=self.omega.index)
variables.append("Tally")
variables.append("Label")
self.omega.columns = variables
def set(self, expression, value):
self.omega.loc[expression,"Tally"] = value
def __str__(self):
return "%s" % self.omega
def p(self,f):
df_f = self.omega.loc[f]
pf = df_f["Tally"].sum() * 1.0 / self.omega["Tally"].sum()
return pf
def p_given(self,f,g):
omega_g = self.omega.loc[g] # restrict sample down to g
tally_g = omega_g["Tally"].sum()
omega_f = omega_g.loc[f]
tally_f = omega_f["Tally"].sum()
return tally_f * 1.0/ tally_g
def sample(self,num):
prizes = np.random.randint(1,4,num)
doors = np.random.randint(1,4,num) # hundred times.
strategy = np.random.randint(1,3,num) # hundred times.
r = range(num)
for i in r:
p = prizes[i]
d = doors[i]
s = "switch" if strategy[i] == 1 else "stick"
''' tally add 1 '''
self.omega.loc[(self.omega["Prize"]==str(p)) & (self.omega["Door"]==str(d)) & (self.omega["Strategy"]==s), "Tally"] += 1
def assignlabels(self):
for i,r in self.omega.iterrows():
if r["Strategy"] == "stick":
self.omega.loc[i, "Label"] = "Win" if r["Door"] == r["Prize"] else "Lose"
else: #switch
self.omega.loc[i, "Label"] = "Win" if r["Door"] != r["Prize"] else "Lose"
# let's create the sample space. We got two variables "Door" and "Prize" and "Strategy"
# (chosen)Door and Prize is either A,B,C
# Strategy is either "Switch" or "Stick".
# calling the class will expand the sample space by all possibilities.
ex = Experiment(["Prize","Door","Strategy"], [["1","2","3"], ["1","2","3"], ["switch","stick"]] )
ex.assignlabels()
ex.sample(1000)
print ex
# how much probability for "switch" strategy ?
print ex.p_given(ex.omega["Label"] == "Win", ex.omega["Strategy"] == "switch")
# how much probability for "stick" strategy ?
print ex.p_given(ex.omega["Label"] == "Win", ex.omega["Strategy"] == "stick")
|
# Create a class called NumberSet that accepts 2 integers as input, and defines two instance variables: num1 and num2, which hold each of the input integers. Then, create an instance of NumberSet where its num1 is 6 and its num2 is 10. Save this instance to a variable t.
class NumberSet:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
t = NumberSet(6,10)
print(t)
# Create a class called Animal that accepts two numbers as inputs and assigns them respectively to two instance variables: arms and legs. Create an instance method called limbs that, when called, returns the total number of limbs the animal has. To the variable name spider, assign an instance of Animal that has 4 arms and 4 legs. Call the limbs method on the spider instance and save the result to the variable name spidlimbs.
class Animal:
def __init__(self, arms, legs):
self.arms = arms
self.legs = legs
def limbs(self):
return self.arms + self.legs
spider = Animal(4, 4)
spidlimbs = spider.limbs()
print(spidlimbs)
# Create a class called Cereal that accepts three inputs: 2 strings and 1 integer, and assigns them to 3 instance variables in the constructor: name, brand, and fiber. When an instance of Cereal is printed, the user should see the following: “[name] cereal is produced by [brand] and has [fiber integer] grams of fiber in every serving!” To the variable name c1, assign an instance of Cereal whose name is "Corn Flakes", brand is "Kellogg's", and fiber is 2. To the variable name c2, assign an instance of Cereal whose name is "Honey Nut Cheerios", brand is "General Mills", and fiber is 3. Practice printing both!
class Myapp:
def __init__(self, name, brand, fiber):
self.name = name
self.brand = brand
self.fiber = fiber
def __str__(self):
return "{} cereal is produced by {} and has {} grams of fiber in every serving!".format( self.name, self.brand, self.fiber)
c1 = Myapp("Corn Flakes", "Kellogg's", 2)
c2 = Myapp("Honey Nut Cheerios", "General Mills", 3)
print(c2)
|
def square(x):
return x*x
L = [square, abs, lambda x: x+1]
print("****names****")
for f in L:
print(f)
print("****call each of them****")
for f in L:
print(f(-2))
print("****just the first one in the list****")
print(L[0])
print(L[0](3))
# 1. Below, we have provided a list of lists. Use indexing to assign the element ‘horse’ to the variable name idx1.
animals = [['cat', 'dog', 'mouse'], ['horse', 'cow', 'goat'], ['cheetah', 'giraffe', 'rhino']]
idx1 = animals[1][0]
print(idx1)
# 2. Using indexing, retrieve the string ‘willow’ from the list and assign that to the variable plant.
data = ['bagel', 'cream cheese', 'breakfast', 'grits', 'eggs', 'bacon', [34, 9, 73, []], [['willow', 'birch', 'elm'], 'apple', 'peach', 'cherry']]
plant = data[7][0][0]
print(plant)
###########################################################################################
# 2. Below, we have provided a list of lists that contain information about people. Write code to create a new list that contains every person’s last name, and save that list as last_names.
info = [['Tina', 'Turner', 1939, 'singer'], ['Matt', 'Damon', 1970, 'actor'], ['Kristen', 'Wiig', 1973, 'comedian'], ['Michael', 'Phelps', 1985, 'swimmer'], ['Barack', 'Obama', 1961, 'president']]
last_names = []
for listt in info:
last_names.append(listt[1])
print(last_names)
# 3. Below, we have provided a list of lists named L. Use nested iteration to save every string containing “b” into a new list named b_strings.
L = [['apples', 'bananas', 'oranges', 'blueberries', 'lemons'], ['carrots', 'peas', 'cucumbers', 'green beans'], ['root beer', 'smoothies', 'cranberry juice']]
b_strings = list()
for listt in L:
for wordd in listt:
if "b" in wordd:
b_strings.append(wordd)
#############################################################################################################
# When constructing your own nested data, it is a good idea to keep the structure consistent across each level.
# For example, if you have a list of dictionaries, then each dictionary should have the same structure, meaning the same keys and the same type of value associated with a particular key in all the dictionaries.
# The reason for this is because any deviation in the structure that is used will require extra code to handle those special cases.
# The more the structure deviates, the more you will have to use special cases.
# For example, let’s reconsider this nested iteration, but suppose not all the items in the outer list are lists.
# 1_
original = [['dogs', 'puppies'], ['cats', "kittens"]]
copied_version = original[:]
print(copied_version)
print(copied_version is original)
print(copied_version == original)
original[0].append(["canines"])
print(original)
print("-------- Now look at the copied version -----------")
print(copied_version)
# 2_
# 3_
nested1 = [1, 2, ['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']]
for x in nested1:
print("level1: ")
if type(x) is list():
for y in x:
print(" level2: {}".format(y))
else:
print(x)
# @@@@@@@@@@@@@@@@@@@@@@17.6. Deep and Shallow Copies¶@@@@@@@@@@@@@@@@@@@
# Earlier when we discussed cloning and aliasing lists we had mentioned that simply cloning a list using [:] would take care of any issues with having two lists unintentionally connected to each other.
# That was definitely true for making shallow copies (copying a list at the highest level), but as we get into nested data, and nested lists in particular, the rules become a bit more complicated.
# We can have second-level aliasing in these cases, which means we need to make deep copies.
# When you copy a nested list, you do not also get copies of the internal lists.
# This means that if you perform a mutation operation on one of the original sublists, the copied version will also change.
# We can see this happen in the following nested list, which only has two levels.
# 1_original = [['dogs', 'puppies'], ['cats', "kittens"]]
copied_version = original[:]
print(copied_version)
print(copied_version is original)
print(copied_version == original)
original[0].append(["canines"])
print(original)
print("-------- Now look at the copied version -----------")
print(copied_version)
# 2_
original = [['dogs', 'puppies'], ['cats', "kittens"]]
copied_outer_list = []
for inner_list in original:
copied_inner_list = inner_list[:]
copied_outer_list.append(copied_inner_list)
print(copied_outer_list)
original[0].append(["canines"])
print(original)
print("-------- Now look at the copied version -----------")
print(copied_outer_list)
# 3_
original = [['dogs', 'puppies'], ['cats', "kittens"]]
copied_outer_list = []
for inner_list in original:
copied_inner_list = inner_list[:]
copied_outer_list.append(copied_inner_list)
print(copied_outer_list)
original[0].append(["canines"])
print(original)
print("-------- Now look at the copied version -----------")
print(copied_outer_list)
|
class Produto:
def __init__(self, id, nome, descricao, valor):
if id != 0:
self.id = id
else:
raise ValueError('O identificador deve ser diferente de zero')
self.nome = nome
self.descricao = descricao
self. valor = valor
class Endereco:
def __init__(self, rua, cep, cidade):
self.rua = rua
self.cep = cep
self.cidade = cidade
def __str__(self):
return f'{self.rua}, {self.cidade} - {self.cep}'
def __repr__(self):
return f'{self.rua}, {self.cidade} - {self.cep}'
class Cliente:
def __init__(self, nome, cpf, rua, cep, cidade):
self.nome = nome
self.cpf = cpf
self.endereco = Endereco(rua, cep, cidade)
class Compra:
def __init__(self, data, cliente, produtos):
self.data = data
self.cliente = cliente
self.produtos = produtos
def valor_compra(self):
valor = 0
for dict_prod in self.produtos:
valor += dict_prod['produto'].valor * dict_prod['quantidade']
return valor
if __name__ == '__main__':
cad_prod = 'Cadastrar Produto'
cad_compra = 'Cadastrar Compra'
produtos = []
compras = []
while True:
opcao = int(input(
f'escolha uma opção: \n'
f'1 - {cad_prod} \n'
f'2 - {cad_compra} \n'
f'3 - Sair \n'
))
if opcao == 1:
id = int(input('identificador: '))
nome = input('nome: ')
descricao = input('descricao: ')
valor = float(input('valor: '))
prod = Produto(id, nome, descricao, valor)
produtos.append(prod)
print('Produto criado com sucesso!')
elif opcao == 2:
if len(produtos) > 0:
data = input('data: ')
print('dados de endereco do cliente')
rua = input('rua do cliente: ')
cep = input('cep do cliente: ')
cidade = input('cidade do cliente: ')
print('dados pessoais do cliente')
nome = input('nome cliente: ')
cpf = input('cpf: ')
cliente = Cliente(nome, cpf, rua, cep, cidade)
cod_prod = list(map(int, input('identificadores dos produtos: ').split()))
produtos_compra = []
for id in cod_prod:
for item in produtos:
if id == item.id:
num_prod = int(input(f'quantidade de produtos {id}: '))
produtos_compra.append(
{
'produto': item,
'quantidade': num_prod
}
)
c = Compra(data, cliente, produtos_compra)
compras.append(c)
else:
print('Adicione um produto primeiro.')
elif opcao == 3:
break
else:
print('Escolha apenas as opções 1, 2 ou 3')
print('Listando as compras:')
for compra in compras:
print(f'Data da compra: {compra.data}')
print(f'CPF: {compra.cliente.cpf}')
print(f'Nome do comprador: {compra.cliente.nome}')
print(f'Valor total: {compra.valor_compra()}')
|
'''
Copyright:
Mohammad Safeea, 9-Oct-2019
About:
fadingBlinky.py is a microPython script for
ESP8266. It is used to blink the built-in
led (with fading effect) using PWM signal.
'''
from machine import Pin
from machine import PWM
from time import sleep
# Initiate output pin
LedBuiltin=2
p=Pin(LedBuiltin,Pin.OUT)
pwm=PWM(p)
# Initiate some variables
i=1024
delta=256
flag=-1
max=i+delta
min=i-delta
# Control loop
while 1:
i=i+2*flag
if i>max:
flag=-1
if i<min:
flag=1
pwm.duty(i)
sleep(0.01)
|
import turtle
#turtle.shape('turtle')
triangle=turtle.clone()
triangle.shape('triangle')
#triangle.goto(0,100)
#triangle.goto(100,0)
#triangle.goto(0,0)
turtle.shape('turtle')
square=turtle.clone()
square.shape('triangle')
square.goto(0,100)
square.goto(100,0)
square.stamp()
square.goto(0,0)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 09:59:07 2020
@author: Elzette
"""
import numpy as np
def get_neighbours(a):
x = a[0]
y = a[1]
return [[x-1,y-1],[x-1,y],[x-1,y+1],[x,y+1],[x,y-1],[x+1,y-1],[x+1,y],[x+1,y+1]]
def is_in(position):
#This is a cheat
x = int(abs(position[0]//10))
y = int(abs(position[1]//10))
return [x,y]
def social(people):
social = []
grid = [[[] for i in range(120)]for i in range(120)]
for person in people:
pos = is_in(person.position)
grid[pos[0]][pos[1]].append(person)
for person in people:
neigh = get_neighbours(is_in(person.position))
force = np.zeros(2)
for item in neigh:
if item[0] and item[1] <= 120:
for human in grid[item[0]][item[1]]:
force += person.repulsive(human)
social.append(10*force)
return(social)
def total_force(people, obsticles, n):
""" Calculate total force given set of people and boundaries in environment.
For this version, only closest boundary is concedered
return 2*n matrix of x,y force for all people"""
interaction = social(people)
motivationx = [person.motivation[0] for person in people]
motivationy = [person.motivation[1] for person in people]
motivation = np.array([motivationx, motivationy ] )
boundaries = []
for i in range(n):
person = people[i]
if len(obsticles) >= 1:
boundary = np.array([float(0),float(0)])
for item in obsticles:
boundary += np.array(person.boundary(item[0],item[1]))
boundaries.append(boundary)
else: boundaries.append(np.zeros(2))
boundaries = np.array(boundaries)
interaction = np.array(interaction )
motivation = np.array(motivation.transpose())
return interaction+motivation+boundaries
|
# int, float, complex
a=3
b=2.5
c=5+8j
print(a, type(a))
print(b, type(b))
print(c, type(c))
# string
name="aushafy"
print(name, type(name))
# boolean
# also implement typeCasting
isName=bool(name)
print(isName, type(isName))
|
'''
Find the sub array which produces the largest sum
'''
def largestSumOfSubArray(arr):
current_max = None
global_max = None
if len(arr) > 0:
current_max = arr[0]
global_max = arr[0]
for i in range(1, len(arr)):
if current_max < 0:
current_max = arr[i]
else:
current_max = current_max + arr[i]
if global_max < current_max:
global_max = current_max
return global_max
def main():
#arr = [-4, 1, 2, 30, -10, 3, 9, 2, -10]
#arr = [-10, 10]
arr = []
maxSum = largestSumOfSubArray(arr)
print("The largest sum of the subarray in the Array above is: {0}".format(maxSum))
if __name__ == "__main__":
main()
|
# Let us first create the required node and
# then created the linkedListStructure from it
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printNodes(self):
temphead = self.head
index = 0
print("The List of Nodes in the linkedList")
while temphead != None:
print("{0}({1})-->".format(index, temphead.data), end = '')
index = index + 1
temphead = temphead.next
print("None")
# Insert Node at the beginning of the linkedList
def insertAtFront(self, newNode):
newNode.next = self.head
self.head = newNode
# Insert New node at the end of the list
def insertAtEnd(self, newNode):
temphead = self.head
while temphead.next != None:
temphead = temphead.next
temphead.next = newNode
# Insert at a given position in the list
def insertAtPositionN(self, newNode, n):
index = 0
temphead = self.head
while index < n-1:
index = index + 1
temphead = temphead.next
if temphead.next == None:
temphead.next = newNode
break
tempNode = temphead
newNode.next = tempNode.next
tempNode.next = newNode
def deleteData(self, data):
temphead = self.head
# check case if the head itself if the node to
# be deleted
if temphead.data == data:
self.head = temphead.next
while temphead.next != None:
#print("Data is ", temphead.next.data)
if temphead.next.data == data:
temphead.next = temphead.next.next
break
temphead = temphead.next
def getNthNode(self, n):
temphead = self.head
index = 0
firstPointer = temphead
while index < n:
if temphead.next == None:
print("The value {0} is larger than the length of the list")
exit()
index += 1
temphead = temphead.next
while temphead.next != None:
firstPointer = firstPointer.next
temphead = temphead.next
print("The value of the nth Node from the end is {0}".format(firstPointer.data))
def reverseLinkedList(self):
if self.head == None or self.head.next == None:
return
newhead = None
while self.head != None:
temp = self.head
self.head = temp.next
temp.next = newhead
newhead = temp
self.head = newhead
def main():
llist = LinkedList()
llist.head = Node(15)
second = Node(62)
third = Node(83)
fourth = Node(49)
fifth = Node(25)
llist.head.next = second
second.next = third
third.next = fourth
fourth.next = fifth
first = Node(67)
nth = Node(894)
#llist.insertAtFront(first)
#llist.insertAtPositionN(nth, 4)
llist.printNodes()
#llist.deleteData(49)
llist.reverseLinkedList()
llist.printNodes()
#llist.getNthNode(2)
if __name__== "__main__":
main()
|
def update_dictionary(d, key, value): #
if key in d: # проверка наличия ключа в словаре(в случае соответствия проваливаюсь)
d[key].append(value) # добавление элемента в существующие значение по переданному ключу
elif key not in d: # если в наличии ключа нету то праваливаюсь внутр
if 2 * key in d: # проверяю наличие ключа * 2 (проваливаюсь если есть)
d[2 * key].append(value) # добавляю элемент в существующее значение по переданному ключу * 2
else: # если и такого ключа нет
d[2 * key] = [value] # добавляю ключ * 2 и переданное значение в словарь
d = {2: [-1, -2]}
print(update_dictionary(d, 1, -3))
print(d)
#Напишите функцию update_dictionary(d, key, value), которая принимает на вход словарь d и два числа: key и value.
#Если ключ key есть в словаре d, то добавьте значение value в список, который хранится по этому ключу.
#Если ключа key нет в словаре, то нужно добавить значение в список по ключу 2∗key. Если и ключа 2∗key нет, то
#нужно добавить ключ 2∗key в словарь и сопоставить ему список из переданного элемента [value].
#Требуется реализовать только эту функцию, кода вне неё не должно быть.
#Функция не должна вызывать внутри себя функции input и print.
#Пример работы функции:
#d = {}
#print(update_dictionary(d, 1, -1)) # None
#print(d) # {2: [-1]}
#update_dictionary(d, 2, -2)
#print(d) # {2: [-1, -2]}
#update_dictionary(d, 1, -3)
#print(d) # {2: [-1, -2, -3]}
|
'''
В первой строке дано три числа, соответствующие некоторой дате date -- год, месяц и день.
Во второй строке дано одно число days -- число дней.
Вычислите и выведите год, месяц и день даты, которая наступит, когда с момента исходной даты
date пройдет число дней, равное days.
Примечание:
Для решения этой задачи используйте стандартный модуль datetime.
Вам будут полезны класс datetime.date для хранения даты и класс datetime.timedelta для прибавления дней к дате.
Sample Input 1:
2016 4 20
14
Sample Output 1:
2016 5 4
Sample Input 2:
2016 2 20
9
Sample Output 2:
2016 2 29
Sample Input 3:
2015 12 31
1
Sample Output 3:
2016 1 1
'''
from datetime import timedelta, date
start_date = [int(number) for number in input().split()]
up_date = int(input())
start_datetime = date(start_date[0], start_date[1], start_date[2])
up_datetime = timedelta(days=up_date)
finish_date = start_datetime + up_datetime
print(finish_date.year, finish_date.month, finish_date.day)
# import datetime
# start_date = [int(number) for number in input().split()]
# up_date = int(input())
# start_datetime = datetime.date(start_date[0], start_date[1], start_date[2])
# up_datetime = datetime.timedelta(days=up_date)
# finish_date = str(start_datetime + up_datetime)
# finish_date = finish_date.split('-')4
# for element in finish_date:
# print(int(element), end=' ')
|
a = int(input())
b = int(input())
x1 = a
if a == b:
print(a)
elif a % b == 0 or b % a == 0:
if a > b:
print(a)
else:
print(b)
else:
while x1 % b != 0:
x1 += a
if x1 % b == 0:
print(x1)
|
f = float(input())
s = float(input())
o = input("")
if (o == '/' or o == 'mod' or o == '%' or o == 'div' or o == '//') and s == 0:
print("Деление на 0!")
elif o == '+':
print(f + s)
elif o == '-':
print(f - s)
elif o == '*':
print(f * s)
elif o == '/':
print(f / s)
elif o == 'mod' or o == '%':
print(f % s)
elif o == 'pow' or o == '**':
print(f ** s)
elif o == 'div' or o == '//':
print(f // s)
|
'''
Вам дана последовательность строк.
Выведите строки, содержащие "cat" в качестве слова.
Примечание:
Для работы со словами используйте группы символов \b и \B.
Описание этих групп вы можете найти в документации.
Sample Input:
cat
catapult and cat
catcat
concat
Cat
"cat"
!cat?
Sample Output:
cat
catapult and cat
"cat"
!cat?
'''
import sys
import re
for line in sys.stdin:
line = line.rstrip()
pattern = r'\bcat\b'
result = re.findall(pattern, line)
if len(result) > 0:
print(line)
|
import math
for n in range(2, 250, 2):
x=pow(2,-n)
print(n,"\t", math.sqrt(pow(x,2)+1)-1,"\t",x**2/(math.sqrt(pow(x,2)+1)+1))
|
class Car:
def __init__(self, name, company, year, price):
self.price = price
self.name = name
self.company = company
self.year = year
self.owner = None
def print_details(self):
print('name: ' + self.name + '\tyear: ' + str(self.year) + '\tprice: ' + str(self.price))
class Person:
def __init__(self, name, age, money):
self.money = money
self.name = name
self.age = age
self.cars = []
def buy(self, car):
if self.age < 18:
print('You are not old enough.')
elif self.money < car.price:
print('You don\'t have enough money :(')
else:
if car.owner is not None:
car.owner.money += car.price
car.owner.cars.remove(car)
else:
car.company.earnings += car.price
car.company.store.remove(car)
self.money -= car.price
self.cars.append(car)
car.owner = self
def show_cars(self):
print(self.name + ':')
for i in self.cars:
i.print_details()
class Company:
def __init__(self, name):
self.name = name
self.store = []
self.products = []
self.earnings = 0
def add_car_to_products(self, car):
self.products.append(car)
def advance(self):
for i in self.products:
self.store.append(Car(i.name, self, i.year, i.price))
def show_store(self):
print('Store:')
for i in self.store:
i.print_details()
def report_income(self):
print('We have gained about ' + str(self.earnings) + ' =)))')
hyundai = Company('Hyundai')
hyundai.add_car_to_products(Car('Accent', hyundai, 2019, 200))
hyundai.add_car_to_products(Car('Elantra', hyundai, 2021, 300))
for i in range(5):
hyundai.advance()
hyundai.show_store()
p1 = Person('Taha', 20, 500)
p1.buy(hyundai.store[1])
p1.buy(hyundai.store[2])
# اینجا طاها برای ماشین دوم باید پولش کم بیاد و پیغام مناسب براش چاپ بشه
p2 = Person('Amirhossein', 15, 1000)
p2.buy(hyundai.store[0])
# اینجا امیرحسین بابت سن کمش نمیتونه ماشین بخره و باید براش پیغام مناسب چاپ بشه
p3 = Person('Peyman', 40, 2000)
p3.buy(hyundai.store[0])
p3.buy(hyundai.store[0])
p3.buy(hyundai.store[0])
p3.buy(hyundai.store[0])
p3.buy(hyundai.store[0])
p1.show_cars()
p3.show_cars()
p1.buy(p3.cars[0])
p1.buy(p3.cars[0])
p1.show_cars()
p3.show_cars()
# توی 6 خط کد بالا، طاها سعی کرد دو تا از ماشین های پیمان رو بخره، که پولش به یکی ازونا فقط میرسه.
# با استفاده از متود های show_cars میتوانیم تبادل ماشین میان دو نفر را ببینیم.
hyundai.report_income()
|
# If file name does not exist?
# If a path is not valid
# If a key is not valid
#
import os
class ConfigKeyError(Exception):
def __init__(self, this, key):
self.key = key
self.keys = this.keys()
def __str__(self):
return 'key "{}" not found. Availabe keys: ({})'.format(self.key, ', '.join(self.keys))
class ConfigDict(dict):
# fisrt we create a file in the constructor
def __init__(self, filename):
self._filename = filename
# _ is to indicate this is a private var
if not os.path.isfile(self._filename): # is it a file on the path
try:
open(self._filename, 'w').close()
except IOError:
raise IOError('arg to ConfigDict must be a valid pathname')
with open(self._filename, 'r') as fh: # if exist open
print('opening the txt file')
for line in fh:
line = line.rstrip() # line in file new line added
key, value = line.split('=', 1) # max split amount, 1 here on the equal sign
dict.__setitem__(self,key, value) # setting value to key with superclass
def __getitem__(self, key):
if not key in self:
raise ConfigKeyError(self, key)
return dict.__getitem__(self, key)
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
with open(self._filename, 'a') as fh: # here we open the file we created
#for key, val in self.items(): # having loop would update all the previous keys with last given value
print('writing the data')
fh.write('{}={}\n'.format(key, value))
|
import math
class PrimeCounter:
def __init__(self, max_number):
self.max_num = max_number
self.prime_set = []
# self.number_set is a Bool list where all==True and it's length==max. By the end, only Primes will still==True
self.number_set = [True for i in range(self.max_num+1)]
#This takes all numbers from 2 to square route of your max, and looks for their multiples, starting with the lowest
#value, 2. if a number is a multiple, it's value in self.number_set is changed to False. After it finds all that
#number's multiples, it moves on to the next lowest number that still==True.
def prime_sniffer(self):
square_root_max = int(math.sqrt(self.max_num))
for i in range(2, (square_root_max+1)):
if self.number_set[i]:
multiple_of_target = pow(i, 2)
while multiple_of_target <= self.max_num:
self.number_set[multiple_of_target] = False
multiple_of_target += i
#This looks through number_set after only prime numbers == True. If it's a prime, it pulls their index spot into a new
#list, giving us the number of primes found, as well as their values
def list_primes(self):
for i in range(2, len(self.number_set)):
if self.number_set[i]==True:
self.prime_set.append(i)
return f"There are {len(self.prime_set)} prime numbers between 2 and {self.max_num}. They are {self.prime_set}."
if __name__ == '__main__':
max = 100000
x = PrimeCounter(max)
x.prime_sniffer()
print(x.list_primes())
|
def temp_converter():
temp_value= float(raw_input("Please enter the temperature value:"))
conversion = raw_input("Enter F if converting to fahrenheit and C to celsius: ")
n= int(raw_input('Enter the value of n:'))
while(n>0):
n=n-1
if(conversion=='F'):
intermediate = float((1.8*temp_value)+32)
print ("The value is %d Fahrenheit" %(intermediate))
elif (conversion=='C'):
celsius_inter= float((temp_value-32)/1.8)
print ("The value is %2f degree celsius" %(celsius_inter))
else:
print("The selection is invalid")
temp_converter()
|
"""
Exercicio 27 - Escreva um programa que, dada a idade de um nadador, classifique-o em uma das categorias.
Infantil A - Idade (5 a 7)
Infantil B - Idade (8 a 10)
Juvenil A - Idade (11 a 13)
Juvenil B - Idade (14 a 17)
Sênior - Idade (Maiores de 18 anos)
"""
class Nadador:
def __init__(self, idade):
self.idade = idade
def verifica(self):
if 5 <= self.idade <= 7:
print(f'Infantil A idade - {self.idade}')
elif 8 <= self.idade <= 10:
print(f'Infantil B idade - {self.idade}')
elif 11 <= self.idade <= 13:
print(f'Juvenil A idade - {self.idade}')
elif 14 <= self.idade <= 17:
print(f'Juvenil B idade - {self.idade}')
elif self.idade >= 18:
print(f'Sênior idade - {self.idade}')
else:
print('Idade informada não se adequa à tabela existente.')
idade = int(input('Digite sua idade: '))
nadador = Nadador(idade)
nadador.verifica()
|
"""
Exercicio 10
"""
sexo = input("Digite seu sexo M/F: ")
sexo = sexo.upper()
altura = float(input("Digite sua altura: "))
if sexo == 'M':
print(f"peso ideal = {72.7*altura-58}")
elif sexo == 'F':
print(f"Peso ideal = {62.1*altura-44.7}")
else:
print("sexo informado não esta definido.")
|
"""
Exercicio 32 - Escreva um programa que leia o código do produto escolhido do cardápio de uma lanchonete
e a quantidade. O programa deve calcular o valor a ser pago por aquele lanche. Considere que cada execução somente
será calculado um pedido. O cardapio da lanchonete segue o padrão abaixo:
Produto -------- Codigo ------ Preço
Cachorro quente - 100 -------- 1.20
Bauru Simples --- 101 -------- 1.30
Bauru com Ovo --- 102 -------- 1.50
Hamburguer ------ 103 -------- 1.20
Cheeseburguer --- 104 -------- 1.70
Suco ------------ 105 -------- 2.20
Refrigerante ---- 106 -------- 1.00
"""
cardapio = {
100: 1.20,
101: 1.30,
102: 1.50,
103: 1.20,
104: 1.70,
105: 2.20,
106: 1.00
}
def comanda():
valor_final = 0
while True:
try:
codigo = int(input('Codigo do produto: '))
quantidade = int(input('Quantidade: '))
if 100 <= codigo <= 106:
valor_final = valor_final + (quantidade * cardapio.get(codigo))
aux = input('Mais produtos s/n? ')
if aux == 'n':
return valor_final
else:
print('Codigo informado não corresponde a um produto do cardapio.')
except ValueError:
print('Alguma coisa foi informada errada.')
total = comanda()
print(f'{total:.2f}')
|
"""
Exercicio 14
"""
import sys
nota_final = 0
i = 0
while i < 3:
nota = float(input("informe a nota: "))
if 0 <= nota <= 10:
i = i + 1
if i == 1:
nota_final = nota_final + nota * 2
elif i == 2:
nota_final = nota_final + nota * 3
else:
nota_final = nota_final + nota * 5
else:
print("Nota informada não é valida.")
nota_final = nota_final / 10
if 0 <= nota_final <= 2.9:
print(f"aluno em reprovado com nota {nota_final}")
elif 3 <= nota_final <= 4.9:
print(f"aluno em recuperação com nota {nota_final}")
else:
print(f"Aluno aprovado com nota {nota_final}")
|
"""
Exercicio 39 -
"""
salario = float(input("Digite o salario do funcionario: "))
tempo = int(input("Digite o tempo de serviço desse funcionario em ano(s), 0 caso ainda sejam meses: "))
if salario <= 500:
salario = salario * 1.25
elif salario > 500 and salario <= 1000:
salario = salario * 1.20
elif salario > 1000 and salario <= 1500:
salario = salario * 1.15
elif salario > 1500 and salario <= 2000:
salario = salario * 1.10
else:
print('Funcionario não tem direito a reajuste salarial.')
if tempo < 1:
print('Funcionario não tem direito a bonus por tempo')
elif tempo >= 1 and tempo <= 3:
salario = salario + 100
elif tempo >= 4 and tempo <= 6:
salario = salario + 200
elif tempo >= 7 and tempo <= 10:
salario = salario + 300
else:
salario = salario + 500
print(f'Salario final = {salario:.2f}')
|
import time
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%2.2f sec' % \
(te-ts)
return result
return timed
class Timer(object):
def __init__(self):
self.startTimes = {}
self.stopTimes = {}
def start(self, name):
print name + " start"
self.startTimes[name] = time.time()
def stop(self, name):
stopTime = time.time()
print "%s ran - Time Elapsed: %f s" % (name, (stopTime - self.startTimes[name]))
self.stopTimes[name] = stopTime
def startOnce(self, name):
if not self.startTimes.get(name, False):
self.start(name)
def stopOnce(self, name):
if not self.stopTimes.get(name, False):
self.stop(name)
|
#WRITE YOUR CODE IN THIS FILE
#define function
#add parameter
def factorial(x):
y = 1
for i in range (1, x + 1):
y = i * y
return y
#run function
print(factorial(5))
|
from random import choice
import matplotlib.pyplot as plt
class RandomWalk():
""""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
""""初始化随机漫步的属性"""
self.num_points = num_points
# 所有随机漫步都始于(0, 0)
self.x_values = [0]
self.y_values = [0]
def get_step(self):
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
step = direction*distance
return step
def fill_walk(self):
""""计算随机漫步包含的所有点"""
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
if x_step==0 and y_step==0:
continue
x_next = self.x_values[-1] + x_step
y_next = self.y_values[-1] + y_step
self.x_values.append(x_next)
self.y_values.append(y_next)
while True:
rand_walk = RandomWalk(50000)
rand_walk.fill_walk()
point_num = list(range(rand_walk.num_points))
# 设置图像大小
plt.figure(dpi=1080, figsize=(10, 6))
plt.scatter(rand_walk.x_values, rand_walk.y_values, c=point_num,
cmap=plt.cm.Blues,s=1)
# 隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
keep_runing = input("Make anther walk? (y/n) :")
if keep_runing == "n":
break
|
from shape import Shape
from labeling import Labeling
class Square(Shape):
def __init__(self, canvas, name, top_left, bottom_right, color='black'):
super().__init__(name, canvas, color)
self.start = top_left
self.end = bottom_right
# Labelingクラス集約(コンポジション)
self.labeling = Labeling(name, self.start)
def draw(self):
self.canvas.create_rectangle(self.start.x, self.start.y, self.end.x, self.end.y, fill=self.color)
# Labelingクラスのメソッドを呼ぶ
self.labeling.show(self.canvas, 20, -10)
|
x = 8
if x>5:
print("The vaue is greater than 5")
else:
print("The value is smaller")
|
def add(a,b):
m=a+b
print(m)
def prime(i):
fact=0
for j in range(1,i+1):
if i%j==0:
fact=fact+1
if fact==2:
print("true")
else:
print("false")
def prime_factors(n):
for i in range(1,n+1):
if n%i==0:
print(i,end=" ")
|
#TODO: how to do optional arguments?
import os, sys
import Image
import shutil
from directory_walker import DirectoryWalker
def check_image_sizes(images_dir, w, h, out_dir=''):
'''
Checks all the images inside images_dir, and compares their dimensions
to width and height.
If an image is found whose dimensions do not match width or height,
it will be moved to the directory out_dir.
'''
width = int(w)
height = int(h)
print 'Checking %s...' % images_dir
dw = DirectoryWalker(images_dir)
for filename in dw:
file = filename
try:
print filename,
image = Image.open(file)
size = image.size
print size,
if size[0] != width or size[1] != height:
print '*',
image = None
if out_dir:
print 'moving...'
shutil.move(file, out_dir)
print ''
except IOError:
print 'Error opening image. '
if __name__ == '__main__':
src_dir = sys.argv[1]
width = sys.argv[2]
height = sys.argv[3]
out_dir = sys.argv[4]
check_image_sizes(src_dir, width, height, out_dir)
|
from collections import defaultdict
def iterable(obj):
try: iter(obj)
except: return False
return True
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
def group_count(list):
d = defaultdict(int)
for key in list:
d[key] += 1
return d
|
import glob
import cv2
import matplotlib.pyplot as plt
import numpy as np
# utility function to show an image in a separate window
def sh(img, title="img"):
cv2.imshow(title, img)
cv2.waitKey(0)
# utility function for plotting a greyscale image inline
def plotG(img):
plt.imshow(cv2.cvtColor(img, cv2.COLOR_GRAY2RGB))
# utility function for plotting a binary(0,1) image inline
def plotB(img, title="plot"):
plt.figure()
img[img > 0] = 255
img[img <= 0] = 0
plt.imshow(cv2.cvtColor(img, cv2.COLOR_GRAY2RGB))
plt.title(title)
def getBinary(img):
"""
Gives a binary image(consisting of 0 and 1) partitioned at 0
:param img: A image
:return: All elements less than equal to 0 are 0 and all +ve elements are one
"""
img[img > 0] = 1
img[img <= 0] = 0
return img
def count(img):
"""
Gives a count of number of pixels involved
:param img: a binary image
:return: a dictionary x:y. Where x is the pixel value and y is the count of it
"""
unique, counts = np.unique(img, return_counts=True)
return dict(zip(unique, counts))
def hinton(matrix, max_weight=None, ax=None):
"""Draw Hinton diagram for visualizing a weight matrix."""
ax = ax if ax is not None else plt.gca()
if not max_weight:
max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))
ax.patch.set_facecolor('gray')
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(matrix):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax.add_patch(rect)
ax.autoscale_view()
ax.invert_yaxis()
def folderToImages(folderpath):
"""
Returns a list of binary images present in the folderpath. It is thresholded at 127 and getBinary is applied.
:param folderpath: Path of the folder in which images are present
:return: returns a list binary image (@getBinary) present in folder path
"""
images = []
for file in glob.glob(folderpath + "*.jpg"):
ret, thresh = cv2.threshold(cv2.imread(file, 0), 127, 255, cv2.THRESH_BINARY)
getBinary(thresh)
images.append(thresh)
return images
|
'''
Created on 13 May 2016
@author: Sam
'''
# Python 3.5
if __name__ == '__main__':
cipher = input()
newstr = "PER"
days = 0
for eachchar in enumerate(cipher):
if eachchar[1] != newstr[eachchar[0] % 3]:
days += 1
print(days)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.