text stringlengths 37 1.41M |
|---|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(f"name:{self.name}")
def drink(self):
print(f"name:{self.name} 我在喝")
xiao = Person("xiao", 10)
hong = Person("hong", 15)
print(xiao.name)
print(xiao.eat())
|
import json
class Pokemon(object):
def __init__ (self,id,name,type,base_hp,base_atk,base_def ):
self.id=id
self.name=name
self.type=type
self.base_hp = base_hp
self.base_atk=base_atk
self.base_def=base_def
def welcome():
print "Welcome to the demo\n"
test = True
while test:
x = raw_input("Please choose the pokemon number:\n")
if x == "1":
print "Your pokemon descriptions:\n"
print "ID = %d"% (p1.id)
print "Name = %s"% (p1.name)
print "Type = %s"% (p1.type)
print "Base Hp = %d"%(p1.base_hp)
print "Base Attack = %d"% (p1.base_atk)
print "Base Defense = %d"% (p1.base_def)
print_out_pokemon()
test = False
elif x == "2":
print "Your pokemon descriptions:\n"
print "ID = %d"% (p2.id)
print "Name = %s"% (p2.name)
print "Type = %s"% (p2.type)
print "Base Hp = %d"%(p2.base_hp)
print "Base Attack = %d"% (p2.base_atk)
print "Base Defense = %d"% (p2.base_def)
print_out_pokemon()
test = False
else:
print "Invalid input.\n"
def print_out_pokemon():
print "You chose your first pokemon.\n"
print "The other player will play the remaining pokemon.\n"
print "Player 1 will attack first\n."
def text1():
ask = raw_input("Do you want to attack?(Y/N)\n")
if ask == "Y" :
p2.base_hp = p2.base_hp - p1.base_atk
elif ask == "N" :
print "You didnt attack"
def text2():
ask = raw_input("Do you want to attack?(Y/N)\n")
if ask == "Y" :
p1.base_hp = p1.base_hp - p2.base_atk
elif ask == "N" :
print "You didnt attack\n"
def endgame():
if p1.base_hp == 0 | p1.base_hp <0:
print "Game Over, Player 2 wins.\n"
elif p2.base_hp == 0 | p2.base_hp <0:
print "Game Over, Player 1 wins.\n"
print "Player 1 hp: %d\n" %(p1.base_hp)
print "Player 2 hp: %d\n"%(p2.base_hp)
p1 = Pokemon(1,"Ivysaur","grass",250,60,50 )
p2 = Pokemon(2,"Chameleon","fire",200,60,45 )
welcome()
turn = 1
while p1.base_hp > 0 | p2.base_hp >0:
if turn == 1:
print "Its player 1's turn.\n"
text1()
turn = 2
if turn == 2:
print "Its player 2's turn.\n"
text2()
turn = 1
endgame() |
from math import copysign
class Piece():
def __init__(self,color,direction):
self.color = color.lower()
self.direction = direction
def king(self):
self.color = self.color.upper()
self.direction = 0
def __repr__(self):
return self.color
class CheckerBoard():
def __init__(self,size=8):
self.board = [['_' for _ in range(size)] for _ in range(size)]
self.populate()
def populate(self):
'''
Populates the board with initial conditions.
'''
for i in range(3):
for j in range(i%2,len(self.board[i]),2):
self.board[i][j%len(self.board[i])] = Piece('r',1)
for i in range(3):
for j in range(i-1%2,len(self.board[i]),2):
self.board[i-3][j%len(self.board[i])] = Piece('b',-1)
def move(self,x,y,nx,ny):
'''
Moves a piece. Returns True if move succesful, otherwise False.
Valid move checks: - If there is a piece in the cell,
return False
- If move is not a diagonal, move in the correct direction,
return False
- If there is a piece in the new cell,
- If it is a team piece,
return False
- If it is an enemy piece,
- If the cell behind it is filled
return False
- otherwise,
return True and captured piece
'''
# Cell will contain a string if not a piece.
if not isinstance(self.board[x][y],Piece):
print(f'No piece in the cell.')
return False, None
# Any move has to be +/- 1 in the column and + or - 1 in the row,
# depending on it's movement direction, unless it has been kinged
# (kinged represended by setting direction to zero)
######## Doing this part wrong ###########
#if not (abs(x-nx) == 1 and y-ny == copysign(1, self.board[x][y].direction)):
# return False, None
# If there is a piece in the new cell
if isinstance(self.board[nx][ny],Piece):
if self.board[nx][ny].color == self.board[x][y].color:
return False, None
else:
# Get the cell behind the new cell
behind_nx = x + (nx - x)*2
behind_ny = y + (ny - y)*2
if isinstance(self.board[behind_nx][behind_ny], Piece):
return False, None
else:
captured = self.board[nx][ny]
self.board[nx][ny] = '_'
self.board[behind_nx][behind_ny] = self.board[x][y]
self.board[x][y] = '_'
return True, captured
self.board[nx][ny] = self.board[x][y]
self.board[x][y] = '_'
return True, None
def win_condition(self):
'''
Checks if there are any win conditions. Returns player color
that won. Returns None if no player has a winning condition.
Win Conditions: - Opponent has no valid moves.
- Opponent has no pieces left.
Maybe implement draws.
Draw conditions: - Both players concede to draw.
'''
return
def play(self,players=['r','b'],starting_player=0):
'''
Runs the main play loop.
Loop Steps: - Print board
- Get user move.
- Attempt to perform move.
- If invalid,
return to top of loop.
(- If can still move,
return to top of loop.)
- Otherwise,
change player.
'''
curr_player = starting_player
while not self.win_condition():
print(f'----------------------------------------------\n{self}')
print(f'It is player {players[curr_player]} turn.')
command = input('Enter a piece\'s address and the address to move it to.\n')
x,y,nx,ny = map(int,command.split(' '))
result,captured = self.move(x,y,nx,ny)
if not result:
print(f'Invalid Move. Retry.')
continue
elif captured:
print(f'Captured a {captured} piece. It remains your turn.')
continue
# Switch player.
curr_player ^= 1
def __repr__(self):
'''
Prints the checkers board.
'''
result = ' ' + ' '.join([str(i) for i in range(len(self.board))]) + '\n'
for i,row in enumerate(self.board):
result += f'{i} '
for j,elem in enumerate(row):
result += elem.__str__() + '|'
result = result[:-1] + '\n'
return result
if __name__ == '__main__':
checkers = CheckerBoard()
checkers.play() |
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
def circle_2D():
# CIRCLE APPROXIMATION FUNCTION
plt.figure(1,figsize=(13,12))
for count in range(1,8):
hit=0
N=10**count
plt.subplot(3,3,count)
randomx = np.random.uniform(-1,1,size=N)
randomy = np.random.uniform(-1,1,size=N)
plt.axis([-1,1,-1,1])
powersum = np.power(randomx,2)+np.power(randomy,2) #condition for any point to be inside the circle
hit=np.count_nonzero(powersum<=1) #Number of points inside the circle
pi = 4.0*hit/N #Estimating pi by equating area probabilty with empirical probabilty
print('for n = %i, approx pi = %f' %(N,pi))
#Points inside the circle
circlex = randomx[np.nonzero(powersum<=1)]
circley = randomy[np.nonzero(powersum<=1)]
#Points outside the circle
outx = randomx[np.nonzero(powersum>1)]
outy = randomy[np.nonzero(powersum>1)]
plt.plot(circlex,circley,'bo')
plt.plot(outx,outy,'ro')
plt.title(r'N: $10^%i$ pi : %f' %(count,pi))
#plt.show()
def sphere_3D():
#SPHERE APPROXIMATION FUNCTION
for count in range(1,8):
plt.figure(count+1)
hit=0
N=10**count
ax=plt.axes(projection='3d')
randomx = np.random.uniform(-1,1,size=N)
randomy = np.random.uniform(-1,1,size=N)
randomz = np.random.uniform(-1,1,size=N)
powersum = np.power(randomx,2)+np.power(randomy,2)+np.power(randomz,2) #condition for any point to be inside the sphere
hit=np.count_nonzero(powersum<=1) #Number of points inside the sphere
pi = 6.0*hit/N #Estimating pi by equating volume probabilty with empirical probabilty
print('for n = %i, approx pi = %f' %(N,pi))
#Points inside the sphere
spherex = randomx[np.nonzero(powersum<=1)]
spherey = randomy[np.nonzero(powersum<=1)]
spherez = randomz[np.nonzero(powersum<=1)]
#Points outside the sphere
outx = randomx[np.nonzero(powersum>1)]
outy = randomy[np.nonzero(powersum>1)]
outz = randomz[np.nonzero(powersum>1)]
ax.scatter3D(spherex,spherey,spherez,c='b',marker='o')
ax.scatter3D(outx,outy,outz,c='r',marker='o')
plt.title(r'N: $10^%i$ pi : %f' %(count,pi))
plt.show()
if __name__=='__main__':
# MAIN FUNCTION
print('\n')
print('Printing pi values for Part A: Circle (2D)')
circle_2D()
print('\n')
print('Printing pi values for Part B: Sphere (3D)')
sphere_3D()
|
"""Creates a body object to be used in the simulator."""
import numpy as np
from constants import G
class body:
"""
Initializes a body.
Given a body's mass, radius, position, and velocity, create an object to be
used in the simulator.
"""
def __init__(self, name, mass, radius, xy, velocity, color):
"""Init the body."""
self.name = name
self.mass = mass # kg (str)
self.radius = radius # m (float)
self.xs = [xy[0]] # m (floats)
self.ys = [xy[1]] # m (floats)
self.velocity = velocity # [x,y] [m/s, m/s] (floats)
self.acceleration = [0, 0] # [x,y] [m s-2, m s-2] (floats)
self.color = color # plot color (str)
self.hostNode = None # Useful for gridding stuff later
self.fname = name + '.txt'
def isEqual(self, otherBody):
"""Check if two bodies are actually the same."""
if self.name == otherBody.name:
return True
return False
def aGrav(self, otherBody):
"""Calculate the grav. accel. on a body due to a different body."""
# Zero this out elsewhere and add on.
#self.acceleration = [0,0]
if self.name != otherBody.name:
# Update gravitational acceleration (a = f/m) -> self.m cancels
# take x or y projections with x/y hats
x = (self.xs[-1] - otherBody.xs[-1])
y = (self.ys[-1] - otherBody.ys[-1])
d = (np.sqrt(x**2 + y**2))
xhat = x/d
yhat = y/d
self.acceleration[0] += xhat * G * otherBody.mass * d**-2
self.acceleration[1] += yhat * G * otherBody.mass * d**-2
def positionAndVelocityUpdater(self, dt):
"""Update a body's position and velocity over a timestep."""
self.velocity[0] += self.acceleration[0] * dt # x component
self.velocity[1] += self.acceleration[1] * dt # y component
self.xs.append(self.xs[-1]
+ self.velocity[0] * dt
+ 0.5*self.acceleration[0] * (dt**2)
)
self.ys.append(self.ys[-1]
+ self.velocity[1] * dt
+ 0.5*self.acceleration[1] * (dt**2)
)
# Now write this position change to the body's file.
# Maybe change this to a DF and pickle it?
g = open(self.fname, 'a')
outstr = str(self.xs[-1]) + " " + str(self.ys[-1]) + '\n'
g.write(outstr)
g.close()
def hill_radius(self, otherBody):
"""Calculate the Hill Radius of a body.
From Wiki: An astronomical body's Hill sphere is the region in which it
dominates the attraction of satellites. The outer shell of that region
constitutes a zero-velocity surface.
Note that this is set up for circular orbits, which is probably a bad
assumption for this orbits, but finding a real eccentricity would be
brutal.
"""
e = 0
a = np.sqrt((self.xs[-1] - otherBody.xs[-1])**2
+ (self.ys[-1] - otherBody.ys[-1])**2)
r_hill = a * (1 - e) * (otherBody.mass / (3*self.mass))**(1/3)
return r_hill
|
# Executer python dans Sublime Text : Ctrl+B
# Pour i de 0 à x (x exclu)
for i in range(x):
# int to string
str(i)
# string to int
int(s)
# tableau
tableau = []
tableau.append(x)
# join tableau (fonctionne qu'avec tableau de string)
','.join(tableau)
#Récupérer un charactère d'un string
word[x]
#Récupérer une partie d'un string
word[x:y] # x inclu, y exclu
# Récupérer les x derniers caractères
word[-x:]
# Split une chaîne de caractère
word.split(' ')
# Dictionnaire
dictionnaire = {}
dictionnaire['test'] = 2
# Sortir la liste des clés d'un dictionnaire ordonnées en fonction de leur valeur
sorted(dictionnaire, key=dictionnaire.get)
# lowercase
word.lower()
# Position d'une lettre dans l'alphabet
import string
string.ascii_lowercase.index(char) + 1
# Pour les dessins utiliser turtle
import turtle
turtle.ht()
turtle.down()
turtle.setworldcoordinates(-1, -1, 2000, 2000)
turtle.goto(x, y)
|
import math
def round_down(numb, decimals=0):
multiplier = numb ** decimals;
return math.floor(numb*multiplier)/multiplier
def get_fuel_module(modcnt):
return round_down(modcnt/3)-2
def find_last_fuel_value(fval):
fr=fval
ft = 0
while fr > 0 :
fr = get_fuel_module(fr)
if fr > 0:
ft = ft + fr
return ft
# Calculate the values and print the output
santa_fuel=0
santa_neg_fuel = 0
f = open("day1 input.txt")
for r in f:
santa_fuel = santa_fuel + get_fuel_module(int(r))
santa_neg_fuel = santa_neg_fuel + find_last_fuel_value(int(r))
print("Santa's fuel is {}".format(int(santa_fuel)))
print("Santa's Recursive Fuel is {}".format(int(santa_neg_fuel))) |
# coding:UTF-8
import sys
s = sys.stdin.readline()
for i in range(0,len(s)):
print(s[i],end="")
if (s[i] == "@"):
print("【跳1行】\n1",end="")
if (s[i] == "$"):
print("【跳2行】\n1\n2",end="")
if (s[i] == "#"):
print("【跳3行】\n1\n2\n3",end="")
if (s[i] == "!"):
print("【跳4行】\n1\n2\n3\n4",end="")
if (s[i] == "%"):
print("【跳5行】\n1\n2\n3\n4\n5",end="") |
# coding:UTF-8
import sys
year = sys.stdin.readline()
while (year != ""):
year = year.replace("\r", "").replace("\n", "")
year = int(year)
if (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
print("閏年")
else:
print("平年")
year = sys.stdin.readline() |
#def faktorial(n):
# if(n == 1):
# return n
# else:
# return n * faktorial(n-1)
#print('vysledek', faktorial(4))
#print(faktorial(9))
#print(input())
#print("dfjdskl")
#def foo():
# return 666
#def goo():
# return foo() + 1
#print(goo())
#while(input() == 'a'): #cyklus
# print("zapsali jste a, pokracujeme")
# 0 1 2 3 4 5 6
#nasList = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
#print(nasList[6])
nasList = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for i in range(0, 7):
print('index:', i)
print(nasList[i])
|
#First Day of Python
#Simple Print
print('Hello, Day 1 of python')
#Print by varibales
data = 'This line is stored in a varibale'
print(data)
#arthematic operations
x = 10
y = 20
a = y + x
print(a)
x = 10
y = 20
b = y - x
print(b)
x = 10
y = 20
c = y / x
print(c)
x = 10
y = 20
d = y * x
print(d)
#CHECK TYPE OF VARIABLE
print(type(d))
print(type(c))
#RELATIONAL
x = 30
y = 20
z = y == x
print(z)
#LOGICAL
x = 30
y = 10
z = x > y
print(z) #It will return either true or false
#INPUT FROM USER
Q1 = input('what is your name?')
print(Q1)
maths = int(input("Enter your marks in math: "))
computer = int(input('Enter your marks in computer: '))
total = maths + computer
print('Total marks: ', total)
#Simple if
x = 10
if x > 10:
print('This is inside the loob')
print('This is outside the loop')
#if else
x = 15
if x > 15:
print('x > 15 is true')
else:
print('x > 15 is not true')
#if else if
x = 15
if x > 15:
print('x > 15 is true')
elif x < 15:
print('x < 15 is true')
else:
print('all of them are false')
# Loops
#while loop
i = 1
while i<10:
print(i)
i = i + 1
#for loop
for i in range (0,10):
print(i)
#for loop with 2 incriment
for i in range (0,10,2):
print(i)
|
#!/usr/bin/env python3
"""
Challenge:
Have the function AlphabetSoup(str) take the str string parameter
being passed and return the string with the letters in alphabetical
order (ie. hello becomes ehllo). Assume numbers and punctuation
symbols will not be included in the string.
Sample Test Cases:
Case 1:
Input:"coderbyte"
Output:"bcdeeorty"
Case 2:
Input:"hooplah"
Output:"ahhloop"
"""
def alphabetSoup(str):
return ''.join(sorted(str))
if __name__ == '__main__':
print(alphabetSoup(input('Text:> ')))
|
import cv2
from image_prepro import binary_threshold, resize_image
#画像の輪郭検出
def detect_contour(path, min_size):
contoured = cv2.imread(path)
forcrop = cv2.imread(path)
# make binary image 画像の2値か
katagami = binary_threshold(path)
katagami = cv2.bitwise_not(katagami)
# detect contour
im2, contours, hierarchy = cv2.findContours(katagami, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
crops = []
# draw contour
for c in contours:
if cv2.contourArea(c) < min_size:
continue
# rectangle area
x, y, w, h = cv2.boundingRect(c)
x, y, w, h = padding_position(x, y, w, h, 5)
# crop the image
cropped = forcrop[y:(y + h), x:(x + w)]
cropped = resize_image(cropped, (210, 210))
crops.append(cropped)
# draw contour
cv2.drawContours(contoured, c, -1, (0, 0, 255), 3) # contour
cv2.rectangle(contoured, (x, y), (x + w, y + h), (0, 255, 0), 3) #rectangle contour
return contoured, crops
def padding_position(x, y, w, h, p):
return x - p, y - p, w + p * 2, h + p * 2
|
# Imports
import random, math
# Generates an array of random points on a two dimensional plane
def random_points(pointsNum):
a = []
for i in range(0, pointsNum):
a.append(Point(random.random(), random.random()))
return a
# Base class for a point
class Point:
def __init__(self, x, y):
self.X = x
self.Y = y
# Calculate distance between two points
def distance(self, otherPoint):
return math.sqrt(pow((self.X - otherPoint.X), 2)
+ pow((self.Y - otherPoint.Y), 2))
def print(self):
print("Point (X,Y): " + str(self.X) + ", " + str(self.Y) + "\n")
# Base class for a binary tree
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data),
if self.right:
self.right.PrintTree()
# Base class for a queu that will hold points and their distance to the query and be ordered by distance
class DQueue:
def __init__(self, maxLength):
self.data = []
self.maxLength = maxLength
# Returns number of elements currently in the DQueue
def length(self):
return len(self.data)
# Insert DQueue element ([point, distance]) based on distance
def insert(self, point, distance):
index = 0
if self.length() > 0:
while self.data[index][1] < distance:
index += 1
self.data.insert(index, [point, distance])
# Shave off excess elements
del self.data[self.maxLength:]
# Peek the distance of the last element - the one furthest away based on distance
def peek_distance(self):
return self.data[self.length()-1][1];
|
#to split the cases binary to make recursion less times
def myPow(x,n):
if n == 0:
return 1
elif n < 0:
return 1 / myPow(x, -n)
elif (n % 2) == 1:
return x*myPow(x, n - 1)
else:
return myPow(x*x, n/2)
print(myPow(3,2)) |
## calculate the linear regression coef for
# a single column in a dataframe
# input df: pandas Dataframe
# column_in: the column name that we want to caluate the linear regression
class LinearReg:
"""
for linear regression
"""
def single_linear_reg(self,df,column_in):
"""
linear regression for one column
x: 0: length(y)
y: y
"""
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn import linear_model
import numpy as np
X_in1 = pd.DataFrame(df,columns=[column_in])
X = pd.DataFrame(X_in1,columns=[column_in]).dropna()
# how many rows in the dataframe and make it as x
rows=X.shape[0]
x=np.array(range(rows)).reshape(-1,1)
y = X.values
y = y/max(y)
# regression
regr = linear_model.LinearRegression()
regr.fit(x,y)
slope = round(regr.coef_.item(),3)
inter = round(regr.intercept_.item(),2)
return slope,inter
if __name__=='__main__':
import pandas as pd
d = {'col1': [1, 2,50], 'col2': [3, 4,2]}
df = pd.DataFrame(data=d)
t1 = LinearReg()
slope, inter = t1.single_linear_reg(df,"col1")
print("slope "+ str(slope))
print("intercept "+ str(inter))
|
import csv
## list write to csv
def write_to_csv(myfile,data,colnames):
with open(myfile, 'wb') as f:
wr = csv.writer(f, lineterminator='\n')
wr.writerow(colnames)
for a1 in data:
wr.writerow(a1)
|
def candidate(arr):
li=[]
for i in arr:
li.append(arr[i])
max_value = max(li)
name=[]
for i in arr:
if arr[i]==max_value:
name.append(i)
print(name)
small=name[0]
for i in range(0, len(name)):
if len(small)>len(name[i]):
small=name[i]
print(small)
dic = {"abhi":3,"rahul":5,"rajiv":1,"priyanka":5,"rishu":5,"chandan":5,"rani":5}
candidate(dic)
|
import loader
def remove_newline(s):
return s[:s.count(s)-2]
def reverse(s):
return reduce((lambda x, y: y + x), s)
def replace_e_3(s):
return s.replace('e', '3')
def replace_i_1(s):
return s.replace('i', '1')
def replace_i_exc(s):
return s.replace('i', '!')
def main():
lines = loader.read_lines_from("words.txt", 10, 100)
for line in lines:
for line2 in lines:
print remove_newline(line) + remove_newline(line2)
print line
print reverse(line)
print replace_e_3(line)
print replace_i_1(line)
print replace_i_exc(line)
if __name__ == "__main__":
main()
|
import random
number = random.randint(1,10)
guess = 0
while not guess == number:
guess = int(input("\nguess a number between 1 and 10: "))
if guess < number:
print("Your guess is too low")
elif guess > number:
print("your guess is too high")
elif guess == number:
print("you guessed right!")
play_More = input("\nwould you like to ply again? y/n ")
if play_More == "y" or play_More == "Y":
number = random.randint(1,10)
print("bye bye!") |
"""
title: random_salary
author: Cameron
date: 2019-06-12 09:52
"""
import random
name = input("Enter your name")
salary = int(input(">>> Enter your salary"))
raise_per = random.randint(0,100)
raise_amount = salary + ((salary / 100) * raise_per)
print(str(name) + " your current salary is $" + str(salary) + ".")
print("Your raise is " + str(raise_per) + "% of $" + str(salary) + ".")
print(str(name) + ", your new salary is " + str(raise_amount))
|
Partidos_a_elegir = print("Ingrese un partido entre MAS o MNR")
partido1 = "MAS"
partido2 = "MNR"
print(partido1, partido2)
voto = input("Seleccione un partido: ")
if voto == partido1 or voto == partido2 :
print(voto)
else :
print("Voto Invalido") |
estatura = float(input("Ingrese su estatura: "))
peso = int(input("Ingrese su peso: "))
edad = int(input("Ingrese su edad: "))
imc = peso / estatura**2
if imc < 22.0 and edad < 45:
print(f"Su IMC es: {imc}, su condición de riesgo es bajo")
elif imc < 22.0 and edad >= 45:
print(f"Su IMC es: {imc}, su condición de riesgo es medio")
elif imc >= 22.0 and edad < 45:
print (f"Su IMC es: {imc}, su condición de riesgo es medio")
elif imc >= 22.0 and edad >= 45:
print (f"Su IMC es: {imc}, su condición de riesgo es alta") |
def largo_cadena(lista):
cont=0
for i in lista:
cont+=1
print("La cadena tiene %d caracteres" %cont)
string = input("Ingrese su cadena de carcteres: ")
largo_cadena(string) |
num=int(input("Introduce el número: "))
def tablaM(numI):
for i in range (1,11):
print(numI, "x", i," = ",i*numI)
for j in range (1,11):
print("La tabla del: ",j)
tablaM(j)
|
num1 = int(input("Número 1: "))
num2 = int(input("Número 2: "))
num3 = int(input("Número 3: "))
def numM(num1,num2,num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num1 and num2 > num3:
return num2
elif num3 > num1 and num3 > num2:
print(num3)
else:
return ("Los números son iguales.")
print(numM(num1,num2,num3)) |
import collections
class Node(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.children = collections.defaultdict(Node)
# If there is a word, there should not be None.
self.word = None
# Count every node frequency.
self.count = 0
class Trie(object):
"""
Trie: prefix tree
"""
def __init__(self):
self.root = Node()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
current = self.root
for letter in word:
# create a child, count + 1
current = current.children[letter]
current.count += 1
current.word = word
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
current = self.root
for letter in word:
# choose the letter in children
current = current.children.get(letter)
if current == None:
return False
return current.word == word
def showTrie(self, node):
if node.children == {}:
print(node.word)
return
elif node.word != None:
print(node.word)
for letter in node.children.keys():
self.showTrie(node.children.get(letter))
def startWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
Print the word with "prefix" in the trie.
:type prefix: str
:rtype: bool
"""
current = self.root
for letter in prefix:
current = current.children.get(letter)
if current == None:
return False
self.showTrie(current)
return True
def delete(self, word):
"""
Delete a word from the trie, returns if the word is deleted successfully.
:type prefix: str
:rtype: bool
"""
mission = False
if self.search(word):
mission = True
current = self.root
for letter in word:
wNode = current.children.get(letter)
# delete a node count, if the number of current node is 0, delete it
wNode.count -= 1
if wNode.count == 0:
# current is Node object, but current.children is dict object
# del current will not change [global variable t], though they own the same memory address
current.children.pop(letter)
break
current = wNode
return mission
def deleteTrie(self):
"""
Delete a trie object.
"""
nodes = self.root.children
for k in list(nodes.keys()):
if k is not None:
nodes.pop(k)
del self.root
# if __name__ == "__main__":
# t = Trie()
# t.insert('apple')
# t.insert('apply')
# t.insert('application')
# t.insert('adapt')
# t.insert('add')
# t.insert('addams')
# t.insert('addict')
# t.insert('go')
# t.insert('god')
# t.insert('good')
# t.insert('great')
# t.insert('ground')
# t.insert('gradient')
# print(t.startWith('ad'))
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
if 'Bob' in d:
ans = d.get('Tracy')
print(ans) |
#Program to multiply
m = [2,4,5,8,9]
n = 1
for i in m:
n = i*n
i+=1
print(n)
#Write a Python program to flatten a shallow list
import itertools
original_list = [[2,4,3],[1,5,6], [9], [7,9,0]]
merged_list = list(itertools.chain(*original_list))
print(merged_list) |
#Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself
m = 'restart'
n = ''
for i in m:
if i in n and i == m[0]:
i = '$'
n += i
else:
n += i
print(n)
|
# Program to find the larger num
m = [2,5,4,8,6]
n = 0
for i in m:
if (i>n):
n = i
print(n)
#Write a Python program to sort a list of nested dictionaries.
new_list = [{'key': {'subkey': 1}}, {'key': {'subkey': 10}}, {'key': {'subkey': 5}}]
print("Original List: ")
print(new_list)
new_list.sort(key=lambda e: e['key']['subkey'], reverse=True)
print("Sorted List: ")
print(new_list) |
bicycles = ['trek', 'cannondate', 'redline', 'specialized']
print(bicycles)
# 访问列表
print(bicycles[0])
# 添加列表元素
bicycles.append("first")
print(bicycles)
bicycles.insert(0, "zero")
print(bicycles)
# 修改列表元素
bicycles[1] = "second"
print(bicycles)
# 删除列表元素
del bicycles[-1]
print(bicycles)
# 使用pop()获取被删除的末尾元素
poped_bicycles = bicycles.pop()
print(poped_bicycles)
print(bicycles)
# 使用索引可以弹出任何位置处的元素
first_owned = bicycles.pop(0)
print(first_owned)
# 使用remove删除元素
print(bicycles)
bicycles.remove("redline")
print(bicycles)
name = "123"
#使用sort永久性排序
cars=['bmw','audi','toyoto','subaru']
#cars.sort()
print(cars)
#sorted进行临时排序
print(sorted(cars))
print(cars)
#reverse对列表元素反转
cars.reverse()
print(cars)
print("*****************操作列表***********************")
#for循环列表
print("*******for循环列表*******")
magicians=["alice","devid","caroline"]
for magician in magicians:
print(magician)
for magician in magicians:
print(magician.title()+", that was a great trick")
print("I cannot wait to see your next trick,"+magician.title()+".\n")
print("Thank you,everyone.That was a great magic show")
print(magician)
print("*******range生成列表*******")
for value in range(1,5):
print (value)
#1,2,3,4
numbers=list(range(1,6))
print(numbers)
#从2开始数,每次加2,直到达到或超过11
even_numbers=list(range(2,11,2))
print(even_numbers)
squares=[]
for value in range(1,11):
square=value**2
squares.append(square)
print(squares)
#列表解析
squares_list=[value**2 for value in range(1,11)]
print(squares_list)
values=[v for v in range(1,21)]
print (values)
#数到数字20
for value in range(1,20):
print (value)
#计算1到1000000的总和
values=list(range(1,1000001))
print(min(values))
print(max(values))
print(sum(values))
for value in range(1,21,2):
print (value)
values=[value for value in range(3,30,3)]
print (values)
values=[value**3 for value in range(1,11)]
print (values)
print("************列表切片***************")
player=["jack","stark","bucky","rogers","lion"]
#切片里的都是索引,从索引为1到索引为3,不包括索引为3
print(player[1:3])
print(player[1:4])
#输出从第二个索引一直到最后,都是从左到右
print(player[2:])
print(player[-3:])
print(player[-3:-2])
#遍历切片
for p in player[:3]:
print(p.title())
#利用切片复制列表
player_copy=player[:]
print("player_copy:")
print(player_copy)
#字符串也能用切片
str_title="the first three items in the list are"
print(str_title[1:3])
print("*******元组*********")
dimensions=(200,50)
print (dimensions[0])
for dimension in dimensions:
print (dimension)
|
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
question="What language did you first learn to speak?"
self.my_survey=AnonymousSurvey(question)
self.responses=["English","Spanish","Mandarin"]
def test_store_single_response(self):
self.my_survey.store_response(self.responses[0])
self.assertIn("English",self.my_survey.responses)
def test_store_three_response(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response,self.my_survey.responses)
unittest.main() |
class coche(): #establecemos las propiedades clase coche, su estado,propiedades y comportamiento
def __init__(self): #estado inicial o punto de partida de las propiedades, se denomina metodo constructor
self.largochasis=250
self.anchochasis=120
self.__ruedas=4 ##utilizamos __ para encapsular la propiedad y asi no puede ser modificada desde afuera
self.enmarcha=False
###tiene 4 propiedades####
def arrancar(self,arrancamos):
self.enmarcha=arrancamos
if (self.enmarcha):
return "el coche esta en marcha" #usamos def method ya que cuando usamos la clase tenemos q emplear defs y no def defuncion
else:
return "el coche esta parado" #comportamiento, tiene 2 comportamientos
def estado(self):
print("el coche tiene ", self.__ruedas,"ruedas.Un ancho de ", self.anchochasis,"y un largo de ",self.largochasis)
micoche=coche() #creamos el objeto, instaciamos o ejemplarizamos la clase
print(micoche.arrancar(True))
micoche.estado()
print(".....a continuacion creamos el segudo objeto.....")
micoche2=coche() #creamos segundo objeto
print(micoche2.arrancar(False))
micoche2.ruedas=2
micoche2.estado()
|
def decimal_to_roman(decimal):
roman_number = ''
num = 0
decimal_number = str(decimal) [::-1]
longitud = len(decimal_number)
u =''
d =''
c =''
m =''
num = int(decimal_number [0])
if (num != 4 or num != 9):
while (num > 0):
if (num >= 5):
u += "V"
num -= 5
else:
u += "I"
num -= 1
if decimal_number[0] == '4':
u = 'IV'
if decimal_number[0] == '9':
u = 'IX'
if longitud >= 2:
num = int(decimal_number [1])
if (num != 4 or num != 9):
while (num > 0):
if (num >= 5):
d += "L"
num -= 5
else:
d += "X"
num -= 1
if decimal_number[1] == '4' :
d = 'XL'
if decimal_number[1] == '9' :
d = 'XC'
if longitud >= 3:
num = int(decimal_number [2])
if (num != 4 or num != 9):
while (num > 0):
if (num >= 5):
c += "D"
num -= 5
else:
c += "C"
num -= 1
if decimal_number[2] == '4':
c = 'CD'
if decimal_number[2] == '9':
c = 'CM'
if longitud >= 4:
num = int(decimal_number[3])
if (num < 4):
while (num > 0):
m += "M"
num -= 1
roman_number = m + c + d + u
return (roman_number) |
import unittest
from decimal_numbers import decimal_to_roman
class TestDecimalNumbers(unittest.TestCase):
def test_decimal_1_to_roman(self):
roman_number = decimal_to_roman(1)
self.assertEqual(roman_number, 'I')
def test_decimal_2_to_roman(self):
roman_number = decimal_to_roman(2)
self.assertEqual(roman_number, 'II')
def test_decimal_3_to_roman(self):
roman_number = decimal_to_roman(3)
self.assertEqual(roman_number, 'III')
def test_decimal_4_to_roman(self):
roman_number = decimal_to_roman(4)
self.assertEqual(roman_number, 'IV')
def test_decimal_5_to_roman(self):
roman_number = decimal_to_roman(5)
self.assertEqual(roman_number, 'V')
def test_decimal_6_to_roman(self):
roman_number = decimal_to_roman(6)
self.assertEqual(roman_number, 'VI')
def test_decimal_7_to_roman(self):
roman_number = decimal_to_roman(7)
self.assertEqual(roman_number, 'VII')
def test_decimal_8_to_roman(self):
roman_number = decimal_to_roman(8)
self.assertEqual(roman_number, 'VIII')
def test_decimal_9_to_roman(self):
roman_number = decimal_to_roman(9)
self.assertEqual(roman_number, 'IX')
def test_decimal_15_to_roman(self):
roman_number = decimal_to_roman(15)
self.assertEqual(roman_number, 'XV')
def test_decimal_24_to_roman(self):
roman_number = decimal_to_roman(24)
self.assertEqual(roman_number, 'XXIV')
def test_decimal_43_to_roman(self):
roman_number = decimal_to_roman(43)
self.assertEqual(roman_number, 'XLIII')
def test_decimal_58_to_roman(self):
roman_number = decimal_to_roman(58)
self.assertEqual(roman_number, 'LVIII')
def test_decimal_72_to_roman(self):
roman_number = decimal_to_roman(72)
self.assertEqual(roman_number, 'LXXII')
def test_decimal_87_to_roman(self):
roman_number = decimal_to_roman(87)
self.assertEqual(roman_number, 'LXXXVII')
def test_decimal_91_to_roman(self):
roman_number = decimal_to_roman(91)
self.assertEqual(roman_number, 'XCI')
def test_decimal_99_to_roman(self):
roman_number = decimal_to_roman(99)
self.assertEqual(roman_number, 'XCIX')
def test_decimal_101_to_roman(self):
roman_number = decimal_to_roman(101)
self.assertEqual(roman_number, 'CI')
def test_decimal_149_to_roman(self):
roman_number = decimal_to_roman(294)
self.assertEqual(roman_number, 'CCXCIV')
def test_decimal_478_to_roman(self):
roman_number = decimal_to_roman(501)
self.assertEqual(roman_number, 'DI')
def test_decimal_693_to_roman(self):
roman_number = decimal_to_roman(632)
self.assertEqual(roman_number, 'DCXXXII')
def test_decimal_954_to_roman(self):
roman_number = decimal_to_roman(904)
self.assertEqual(roman_number, 'CMIV')
def test_decimal_999_to_roman(self):
roman_number = decimal_to_roman(999)
self.assertEqual(roman_number, 'CMXCIX')
def test_decimal_1000_to_roman(self):
roman_number = decimal_to_roman(1000)
self.assertEqual(roman_number, 'M')
def test_decimal_1954_to_roman(self):
roman_number = decimal_to_roman(1649)
self.assertEqual(roman_number, 'MDCIL')
def test_decimal_3999_to_roman(self):
roman_number = decimal_to_roman(2554)
self.assertEqual(roman_number, 'MMDLIV')
if __name__ == '__main__':
unittest.main()
|
import unittest
from count_letters import count_letters
class TestLetterCounter(unittest.TestCase):
def test_count_(self):
result = count_letters('hello world')
self.assertEqual(result, {
' ': 1,
'e': 1,
'd': 1,
'h': 1,
'l': 3,
'o': 2,
'r': 1,
'w': 1,
})
def test_count_2(self):
result = count_letters('hola como estas?')
self.assertEqual(result, {
' ': 2,
'e': 1,
'h': 1,
'o': 3,
'l': 1,
'a': 2,
'c': 1,
'm': 1,
's': 2,
't': 1,
'?': 1,
})
def test_count_3(self):
result = count_letters('Esta funcion, funciona')
self.assertEqual(result, {
'E': 1,
's': 1,
't': 1,
'a': 2,
' ': 2,
'f': 2,
'u': 2,
'n': 4,
'c': 2,
'i': 2,
'o': 2,
',': 1,
})
def test_count_4(self):
result = count_letters('Esto es un test')
self.assertEqual(result, {
'E': 1,
's': 3,
't': 3,
'o': 1,
' ': 3,
'e': 2,
'u': 1,
'n': 1
})
if __name__ == '__main__':
unittest.main() |
class NotAListException(Exception):
pass
class NotAllNumberInListException(Exception):
pass
def find_max(list_of_numbers):
if not isinstance(list_of_numbers, list):
raise NotAListException('argument is not a list')
if not list_of_numbers:
return None
else :
max_number = list_of_numbers[0]
for x in list_of_numbers:
if not isinstance(x, int):
raise NotAllNumberInListException('{} is not a number'.format(x))
if max_number < float (x) :
max_number = float (x)
return max_number
|
# 递归函数:以一个函数在内部调用本身
# def fact(n):
# if n==1:
# return 1
# return n*fact(n-1)
# print(fact(1000))
# 递归函数的优点是 定义简单,逻辑清晰,所有的递归函数都可以写成循环的方式,但是循环的逻辑不如递归清晰
# 使用递归函数需要注意防止栈溢出。在计算机中函数调用是通过栈stack这种数据结构实现的,
# 每当进入一个函数调用,栈就会增加一层栈帧,返回栈就会减少一层栈帧。
# 由于栈的大小不是无限的,所以递归调用的次数过多,会导致栈溢出。
# 解决递归调用栈溢出的方法是通过尾递归优化,事实上尾递归和循环效果是一样的,所以把循环看成是一种特殊的尾递归函数也是可以的。
# 尾递归是指,在函数返回的时候调用自身本身,并且return语句不能包含表达式。
# 这样编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况。
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num-1, num*product)
# print(fact(5))
# 尾递归调用时,如果做了优化,栈不会增长,因此,无论多少次调用也不会导致栈溢出
# 遗憾的是,大多数编程语言没有对尾递归做优化,python解释器也没有做优化,所以,即使把上面的fact(n)函数改成尾递归方式,也会导致栈溢出
# 使用递归函数的有点是逻辑简单清晰,缺点是过深的调用会导致栈溢出
# 针对尾递归优化的语言可以通过尾递归防止栈溢出。尾递归事实上和循环等价,没有循环语句的编程语言只能通过尾递归实现循环
# python标准的解释器没有针对尾递归做优化,任何递归函数都存在栈溢出问题
# 汉诺塔的移动可以调用递归函数非常简单的实现
def move(n, a, b, c):
if n == 1:
print(a,'->',c)
else:
move(n-1, a, c, b)
move(1, a, b, c)
move(n-1, b, a, c)
a='A'
b='B'
c='C'
print(move(3, a, b, c)) |
#!/bin/python
def palindrome(number):
if str(number) == str(number)[::-1]:
return True
return False
def triple(number):
for k in range(100,1001):
if number % k == 0:
if len(str(number/k)) < 3:
return False
elif len(str(number/k)) == 3:
print k
print number/k
return True
a = int(input())
for i in range(a):
b = int(input()) -1
q = True
while q:
if palindrome(b):
if triple(b):
print b
q = False
else:
b-=1
else:
b -= 1 |
def fact(number):
if number == 1:
return 1
return number*fact(number-1)
a = int(input())
for i in range(a):
n,m = list(map(int,raw_input().split()))
print(fact(n+m)//(fact(n)*fact(m))%(10**9+7)) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = [(1,4),(5,1),(2,3)]
b = sorted(a, key=lambda x:(x[0] > x[1] and x[0] or x[1]))
print b
|
# loop
# 'C'
# i = 1
# n = 5
# while(i <= n)
# {
# printf("%d", i);
# i++;
# }
# while stat :
# while <expr>
# <body>
# use indentation to indicate the body belongs to the while
# leader:
# suite
i = 1
n = 5
while i <= n :
print(i, end = " ")
i += 1
print()
i = 1
n = 5
while i <= n :
print(i, end = " ")
i += 1
print()
# not ok in 3.x
"""
i = 1
n = 5
while i <= n :
print(i, end = " ")# tab
i += 1 # 4 spaces
print()
"""
"""
i = 1
n = 5
while i <= n :
print(i, end = " ")
i += 1 # cannot increase indentation unless the earlier
# statement is a leader
print()
"""
i = 1
n = 5
while i <= n :
j = 1
while j <= i :
print(j, end = " ")
j += 1
i += 1
print()
|
n = input("enter a number : ")
n = int(n)
s = 0
i = 0
while n :
s += n % 10
n = int(n / 10)
i += 1
print(s)
print(i)
|
statedict = {
('Karnataka', 'Bangalore'): ['PES Uni', 'PES South']
} #sample starter dict
while True:
print(statedict)
print("1. Add key")
print("2. Modify key")
print("3. Remove key")
print("4. Print Dict")
inp = int(input("Enter: "))
if inp == 1:
statecit = tuple(input("Enter state <space> city").split(" "))
places = input("Enter places of interest with spaces: ").split(" ")
print(places)
statedict[statecit] = places
if inp == 2:
statecit = tuple(input("Enter state <space> city to find: ").split(" "))
if statecit in statedict:
print(statedict[statecit])
statedict[statecit] = input("Enter modification with spaces: ").split(" ")
else:
print("not found. ")
if inp == 3:
statecit = tuple(input("Enter state <space> city to remove: ").split(" "))
if statecit in statedict:
statedict.pop(statecit)
print("removed. ")
else:
print("not found. ")
if inp == 4:
print(statedict)
|
wicket = []
while True:
print("1. Wicket")
print("2. Game Over")
print("3. Exit")
i = input()
if i=='1':
run = int(input("partnership run:"))
wicket.append(run)
elif i=='2':
print("Highest partnership: ", max(wicket))
break
else:
break
|
dic1={"k1":"v1", "k2":"v2","k3":"v3", "k4":"v4"}
list1=["l1", "l2", "l3"]
def fun(li,dic):
li1 = tuple(dic.values())
## dic1 = dict(zip(tuple((dic.keys())),li))
dic1 = dict(zip(dic,li))
return li1,dic1
(li,dic) = fun(list1,dic1)
print('li=',li)
print('dic=',dic)
|
import time
import asyncio
async def is_prime(x):
return not any(x//i == x/i for i in range(x-1,1,-1))
async def highest_prime_below(x):
print("最大的素数低于:%d"%x)
for y in range(x-1,0,-1):
if await is_prime(y):
print("最大的素数 %d在 %d"%(x,y))
return y
await asyncio.sleep(0.0001)
return None
async def main():
t0 = time.time()
await asyncio.wait([
highest_prime_below(900000),
highest_prime_below(910000),
highest_prime_below(91000)
])
t1 = time.time()
print("Took %.2f ms" %(1000*(t1-t0)))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# if __name__ == "__main__":
#
# main() |
# coding: utf-8
# 测试多线程中join的功能
import threading, time
def doWaiting():
print( 'start waiting1: ' + time.strftime('%H:%M:%S') )
time.sleep(3)
print( 'stop waiting1: ' + time.strftime('%H:%M:%S') )
def doWaiting1():
print( 'start waiting2: ' + time.strftime('%H:%M:%S') )
time.sleep(8)
print( 'stop waiting2: ', time.strftime('%H:%M:%S') )
tsk = []
thread1 = threading.Thread(target=doWaiting)
thread1.start()
tsk.append(thread1)
thread2 = threading.Thread(target=doWaiting1)
thread2.start()
tsk.append(thread2)
print('start join: ' + time.strftime('%H:%M:%S'))
for tt in tsk:
tt.join(5)
print('end join: ' + time.strftime('%H:%M:%S') )
|
import math
import os
import random
import re
import sys
# Complete the findDigits function below.
def findDigits(n):
c=0
for d in str(n):
try:
if(n%int(d)==0):
c=c+1
except ZeroDivisionError:
continue
return c
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = findDigits(n)
fptr.write(str(result) + '\n')
fptr.close() |
import re
file = input('Enter name of file:')
handle = open(file)
count = 1
for line in handle:
parts = line.split()
print(str(count) + ". **", parts[0], "** | ", end="")
count = count + 1
for x in range(len(parts)):
if x > 0:
print(parts[x]," ", end="")
print(" \n", end="")
#print(str(count) + ". " + line, end="")
#print("_"*len(line)
|
#循环式交互求平均值
def main():
total=0.0
count=0
moredata="yes"
while moredata[0] == "y":
x=float(input("Enter a number>>"))
total=total+x
count=count+1
moredata=input("Do you have more numbers (yes or no)")
print("\nThe average of the numbers is",total/count)
main()
|
import math
import graphics
def main():
a= float(input("input a:"))
b = float(input("input b:"))
c = float(input("input c:"))
discRoot=math.sqrt(b*b-4*a*c)
root1=(-b+discRoot)/(2*a)
root1=(-b-discRoot)/(2*a)
print()
print("a=",a,"b=",b)
def square():
a=float(input("input a :"))
b=float(input("input b :"))
c=float(input("input c :"))
s=(a+b+c)/2
A=math.sqrt(s * (s - a ) * (s - b) * (s - c))
print("square is ",A)
def graphicsTest():
win=graphics.GrapWin()
graphicsTest()
|
def main():
n=int(input("How many numbers do you have?"))
total = 0.0
for i in range(n):
x=int(input("Enter a number >>"))
total=total+x
print("\nThe avgrage of the numbers is ",total/n)
main()
|
from graphics import *
def main():
win=GraphWin("温度转换")
win.setCoords(0.0,0.0,3.0,4.0)
Text(Point(1,3),"摄氏度:").draw(win)
Text(Point(1,1),"华氏度:").draw(win)
inputText=Entry(Point(2.25,3),5)
inputText.setText("0.0")
inputText.draw(win)
outputText=Text(Point(2.25,1),"")
outputText.draw(win)
button=Text(Point(1.5,2.0),"转换")
button.draw(win)
Rectangle(Point(1,1.5),Point(2,2.5)).draw(win)
win.getMouse()
celsius=float(inputText.getText())
f=9.0/5.0*celsius+32
outputText.setText(round(f,2))
button.setText("quit")
win.getMouse()
win.close()
main()
|
#!/usr/bin/python
from random import shuffle
class Card(object):
def __init__(self, identifier, name=None):
self.identifier = identifier
self.name = name
def __str__(self):
return self.name if self.name else self.identifier
class Pile(object):
def __init__(self):
self.cards = []
def __iter__(self):
return iter(self.cards)
def get(self, identifier):
"""Returns a specific card from the pile
"""
for i in range(len(self.cards)):
if self.cards[i].identifier == identifier:
card = self.cards[i]
del self.cards[i]
return card
return None
def get_top(self):
"""Returns the card on the top of the pile
"""
return self.cards.pop()
def shuffle(self):
"""
shuffle the cards
"""
shuffle(self.cards)
def show(self):
#print it in reverse (first one printed is top of pile)
for c in reversed(self.cards):
print(c)
def add(self, card):
"""Adds a card to the top of the pile (will be drawn next)
"""
self.cards.append(card)
def extend(self, pile):
"""Adds multiple cards to pile in the given order
"""
self.cards.extend(pile)
pile.empty()
def size(self):
return len(self.cards)
def empty(self):
self.cards = []
def deal(self, players, num):
"""Deals num cards to each player in players
"""
for _ in range(num):
for p in players:
p.draw(self)
if self.size() == 0:
return
def has(self, ident):
"""Checks to see if a card is inside the pile
"""
return any(ident == c.identifier for c in self.cards)
def remove(self, ident):
"""Remove a specific card from the pile if it exists
"""
for c in self.cards:
if ident == c.identifier:
self.cards.remove(c)
return True
return False
class Suit(object):
def __init__(self, identifier, name, rank):
self.identifier = identifier
self.name = name
self.rank = rank
#in a normal deck (e.g. poker) suits are all ranked the same
suits = {
'diamonds' : Suit('D', 'Diamonds', 1),
'clubs' : Suit('C', 'Clubs', 1),
'hearts' : Suit('H', 'Hearts', 1),
'spades' : Suit('S', 'Spades', 1),
}
class Value(object):
def __init__(self, identifier, name, rank):
self.identifier = identifier
self.name = name
self.rank = rank
values = {
'2' : Value('2', 'Two', 2),
'3' : Value('3', 'Three', 3),
'4' : Value('4', 'Four', 4),
'5' : Value('5', 'Five', 5),
'6' : Value('6', 'Six', 6),
'7' : Value('7', 'Seven', 7),
'8' : Value('8', 'Eight', 8),
'9' : Value('9', 'Nine', 9),
'10': Value('10', 'Ten', 10),
'J' : Value('J', 'Jack', 11),
'Q' : Value('Q', 'Queen', 12),
'K' : Value('K', 'King', 13),
'A' : Value('A', 'Ace', 14),
}
class PlayingCard(Card):
def __init__(self, suit, value):
identifier = suit.identifier + value.identifier
Card.__init__(self, identifier, value.name + ' of ' + suit.name)
self.suit = suit
self.value = value
def __lt__(self, other):
return self.get_rank() < other.get_rank()
def __eq__(self, other):
return self.get_rank() == other.get_rank()
def get_rank(self):
"""Calculated value taking into account suit and rank
"""
return self.suit.rank * 1000 + self.value.rank
class StandardDeck(Pile):
def __init__(self):
Pile.__init__(self)
self.cards = []
#dictionary value ordering is not preserved!!
for s in suits.values():
for v in values.values():
self.add(PlayingCard(s, v))
self.shuffle()
class Player(object):
def __init__(self, name):
self.name = name
self.hand = Pile()
def draw(self, pile, num=1):
"""Given a pile, the player draws num cards from the top of the pile.
"""
for _ in range(num):
self.hand.add(pile.get_top())
def add(self, card):
"""Given a card, the player adds it to their hand.
"""
self.hand.add(card)
def take(self, pile):
"""Given a pile, the player takes it and ands the whole pile to their
hand.
"""
for card in pile:
self.add(card)
pile.empty()
|
'''
enumerate
'''
lista = ['a', 'b', 'c', 'd', 'e']
for element in lista:
print(element)
print('---')
for i, element in enumerate(lista):
print(i, element)
print('----')
for i, element in enumerate(lista):
print(i, lista[i])
|
'''
tworzenie slownika z rownolicznych list
'''
litery = ['a', 'b', 'c']
cyfry = [1, 2, 3]
print(dict(zip(litery, cyfry)))
|
def longest_word(w1, w2, w3):
if len(w1) > len(w2) and len(w1) >= len(w3):
return w1
elif
pass
|
myItems = ['a', 'b', 'c', 'd']
def permutationsR(items):
""" yields all permutations of a set """
if len(items) == 0:
yield []
for i in range(len(items)):
for remainder in permutationsR(items[:i] + items[i+1:]):
yield [items[i]] + remainder
def permutationsR2(items):
if len(items) == 0:
yield []
for item in items:
for remainder in permutationsR2([otherItems for otherItems in items if item not in otherItems]):
yield [item] + remainder
def permutationsI(items):
a = items[:]
N = len(a)
p = [n for n in range(N + 1)]
i = 1
yield a
while i < N:
p[i] -= 1
j = (i % 2) * p[i]
a[j], a[i] = a[i], a[j]
yield a
i = 1
while p[i] == 0:
p[i] = i
i += 1
def permutationsI2(items):
a = items[:]
N = len(a)
p = [0 for n in range(N)]
i = 1
yield a
while i < N:
if p[i] < i:
j = (i % 2) * p[i]
a[j], a[i] = a[i], a[j]
yield a
p[i] += 1
i = 1
else:
p[i] = 0
i += 1
from timeit import timeit
t1 = timeit("for x in permutationsR(['a', 'b', 'c', 'd', 'e', 'f']): pass", setup="from __main__ import permutationsR", number=500)
t2 = timeit("for x in permutationsI(['a', 'b', 'c', 'd', 'e', 'f']): pass", setup="from __main__ import permutationsI", number=500)
t3 = timeit("for x in permutationsI2(['a', 'b', 'c', 'd', 'e', 'f']): pass", setup="from __main__ import permutationsI2", number=500)
t4 = timeit("for x in permutationsI2(['a', 'b', 'c', 'd', 'e', 'f', 'g']): pass", setup="from __main__ import permutationsI2", number=500)
t5 = timeit("for x in permutationsR2(['a', 'b', 'c', 'd', 'e', 'f']): pass", setup="from __main__ import permutationsR2", number=500)
print("Recursive method: %0.6f" % t1)
print("Recursive method list comprehension: %0.6f" % t5)
print("Iterative countdown: %0.6f" % t2)
print("Iterative counting: %0.6f" % t3)
print("Longer Iterative counting: %0.6f" % (t4 / t3))
"""
print('recursive:')
for x in permutationsR(['a', 'b', 'c']):
print(x)
print('recursive list comprehension:')
for x in permutationsR2(['a', 'b', 'c']):
print(x)
print('countdown:')
for x in permutationsI(['a', 'b', 'c']):
print(x)
print('counting:')
for x in permutationsI2(['a', 'b', 'c']):
print(x)
""" |
import random
prizes = [0,0,0,5,10,25,100]
cash = 100
def lottery_number_game():
global cash
while cash >= 10:
cmd = input('[P]lay or [Q]uit: ')
if cmd == 'P' or cmd == 'p' or cmd == 'play' or cmd == 'Play':
lottery_numbers = generate_lottery_numbers()
num_set = buy_ticket()
drawing_result(lottery_numbers, num_set)
elif cmd == 'Q' or cmd == 'q' or cmd == 'Quit' or cmd == 'quit':
print('Thanks for playing!\n')
break
else:
print('Unrecognized command.\n')
print('You finished with ${} remaining.'.format(cash))
def generate_lottery_numbers():
lottery_numbers = set()
while len(lottery_numbers) < 6:
lottery_numbers.add(random.randint(1,20))
return lottery_numbers
def buy_ticket():
global cash
cash -= 10
num_set = set()
while len(num_set) < 6:
nums = input('Enter {} numbers between 0 and 20: '.format(6-len(num_set)))
nums = nums.replace(',', ' ')
nums_list = nums.split()
if len(nums_list) > 6-len(num_set):
print('You entered too many numbers, please try again.\n')
continue
try:
num_set = num_set.union(convert_to_set(nums_list))
except ValueError:
continue
return num_set
def drawing_result(lottery_numbers, num_set):
global cash
matching_set = num_set.intersection(lottery_numbers)
result = len(matching_set)
print('The lottery numbers are: {}'.format(lottery_numbers))
print('Your numbers are: {}'.format(num_set))
print('Your matching numbers: {}'.format(matching_set))
if result <= 2:
print('Better luck next time! You got {} matches and won {} dollars.\nYou have {} dollars remaining.\n'.
format(result, prizes[result], cash))
elif result > 2 or result < 6:
cash += prizes[result]
print('Congratulations! You got {} matches and won {} dollars.\nYou have {} dollars remaining.\n'.
format(result, prizes[result], cash))
else:
cash += prizes[result]
print('Jackpot! You got {} matches and won {} dollars.\nYou have {} dollars remaining.\n'.
format(result, prizes[result], cash))
def convert_to_set(s):
ret_set = set()
for n in s:
try:
int(n)
except ValueError:
print('Invalid input. {} not an integer. Please try again.\n'.format(n))
raise
n = int(n)
if n < 0 or n > 20:
print('Value {} out of bounds. Please try again.\n'.format(n))
raise ValueError()
ret_set.add(n)
return ret_set
lottery_number_game()
|
'''
Created on Sep 25, 2014
Mini-project # 1: Rock-paper-scissors-lizard-Spock
Python MOOC @ Coursera
@author: nirav.chotai
The key idea of this program is to equate the strings
"rock", "paper", "scissors", "lizard", "Spock" to numbers
as follows:
0 - rock
1 - Spock
2 - paper
3 - lizard
4 - scissors
'''
import random
def name_to_number(name):
if name == "rock":
return 0
elif name == "Spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
return 4
else:
print "Wrong choice!"
def number_to_name(number):
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print "Wrong choice!"
def rpsls(player_choice):
# print a blank line to separate consecutive games
print " "
# print out the message for the player's choice
print "Player chooses", player_choice
# convert the player's choice to player_number using the function name_to_number()
player_number = name_to_number(player_choice)
# compute random guess for comp_number using random.randrange()
comp_number = random.randrange(0, 5)
# convert comp_number to comp_choice using the function number_to_name()
comp_choice = number_to_name(comp_number)
# print out the message for computer's choice
print "Computer chooses", comp_choice
# compute difference of comp_number and player_number modulo five
score = (player_number - comp_number) % 5
# use if/elif/else to determine winner, print winner message
if score == 1 or score == 2:
print "Player wins!"
elif score == 3 or score == 4:
print "Computer wins!"
else:
print "Player and computer tie!"
# testing
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors") |
#Spencer Zahn - Python Daily Exercise 1- 020818
# 1. Write a statement that concatenates at least two variables (you can have more than 2 for this practice).
x = "Hi"
y = " how are you?"
print (x + y) |
import math
# 1)
def f (x, y, z):
return x + y + z
y = f(1, 2, 3)
print y
# 2)
def square (x):
return x * x
def sqrt (x):
return math.sqrt(x)
def pythagoras (a, b):
return sqrt(square(a) + square(b))
print square(5)
# 3)
"""
1) Haz una funcion que reciba tres parámetros,
y regrese la suma
2) Haz las siguientes funciones:
'square': Regresa el cuadrado de un número
'sqrt': Calcula la raíz de un número
(Tienes que googlear esto :v)
'pythagoras': Recibe la longitud de dos catetos de un triángulo
y regresa la hipotenusa
(usa las funciones square y sqrt que definiste antes)
3) Haz el ejercicio anterior (que haga exactamente
lo mismo), pero sin usar ciclos
(HINT: Usa funciones) ((funciones recursivas))
""" |
import numpy as np
import pandas as pd
from .movies import get_movie_id, get_movie_name
def pairsimilarity(feature_matrix):
"""Compute pairwise similarity between objects.
If $x_1$ and $x_2$ are objects,
Similarity is defined as follow :
$similarity(x_1, x_2) = \sum_{i=1}^n x_{1i} x_{2i}$
where $x_{1i}$ and $x_{2i}$ are 0-1 values.
Args:
feature_matrix (NumPy array or Pandas DataFrame)
Returns:
NumPy array or Pandas DataFrame : pairwise similarity
"""
return feature_matrix.dot(feature_matrix.T)
def get_most_similar_by_id(similarity, index, top=10):
"""Get most similar items to a given item.
Args:
similarity (NumPy array)
index (array like)
top (int, optional). Default to 10
Returns:
Movie id
"""
assert top >= 0, "top needs to be a non-negative value"
top = min(top,len(similarity))
# Sort by best similarity
best = similarity[index].argsort()[:,::-1]
best_without_duplicate = []
# A movie is obviously similar to itself
# Delete its id, if present
# To keep a top 10 for instance
for i in range(best.shape[0]):
mask = (best[i] != index[i])
best_without_duplicate.append(best[i,mask])
return np.array(best_without_duplicate)[:,:top]
def get_most_similar_movies(movies, similarity, requested_movies, top=10):
"""Get most similar movies to a given movie by names.
Args:
movies (Pandas DataFrame)
similarity (NumPy array)
requested_movies (list of names or id) : if strings are provided, the function will
perform a look up to find corresponding id. Otherwise, integers must be provided.
year (int, optional). Default to None.
top (int, optional). Default to 10
Returns:
Movie id
"""
assert top >= 0, "top needs to be a non-negative value"
all_int = all(isinstance(x, (int, np.integer)) for x in requested_movies)
all_str = all(isinstance(x, str) for x in requested_movies)
assert (all_int and not all_str) or (not all_int and all_str), "movie should be all name or all id"
top = min(top,similarity.shape[0])
index = []
if all_str:
index = np.concatenate([
get_movie_id(movies, name)
for name in requested_movies
])
else:
index = requested_movies
most_similar_movies = get_most_similar_by_id(similarity, index, top=top)
film_ranks = np.arange(1,top+1)
recommended_movies = pd.DataFrame(index=index, data=most_similar_movies, columns=film_ranks)
recommended_movies = recommended_movies.applymap(
lambda x : (x, get_movie_name(movies, x))
)
return pd.concat([movies.iloc[index][["title", "year"]], recommended_movies], axis=1)
|
#!/usr/bin/env python
'''
Meep meep!
To help test whether your puzzle submissions fit the guidelines, try this simple test puzzle. Your solution must follow the guidelines like any other puzzle. Write a program that takes as input a single argument on the command line. Normally this argument must be the name of a text file; however, for this puzzle your program should ignore the argument given. Instead, your program must print to standard out the string "Meep meep!" (without the double quotes and with exact capitalization) followed by a single newline (not zero or two).
Input specifications
The input file will contain ASCII text that is going to be completely ignored by your program. In fact, do not even bother opening up the file, it will just complicate things. The input file format is as follows:
<Lots of ASCII characters that do not matter>
Example input file:
Just ignore me, I am not important.
Output specifications
The output should be the string "Meep meep!" (without the double quotes, using exact capitalization) followed by a single newline (don't forget this part!).
Example output (newline after string):
Meep meep!
'''
print "Meep meep!"
|
''' Robert Ramsay 2011 Google Code Jam
Blue and Orange are friendly robots. An evil computer mastermind has locked
them up in separate hallways to test them, and then possibly give them cake.
Each hallway contains 100 buttons labeled with the positive integers {1, 2, ...,
100}. Button k is always k meters from the start of the hallway, and the
robots both begin at button 1. Over the period of one second, a robot can walk
one meter in either direction, or it can press the button at its position, or
it can stay at its position and not press the button. To complete the test,
the robots need to push a certain sequence of buttons in a certain order. Both
robots know the full sequence in advance. How fast can they complete it?
For example, let's consider the following button sequence:
O 2, B 1, B 2, O 4
Here, O 2 means button 2 in Orange's hallway, B 1 means button 1 in Blue's
hallway, and so on. The robots can push this sequence of buttons in 6 seconds
using the strategy shown below:
Time | Orange | Blue
-----+------------------+-----------------
1 | Move to button 2 | Stay at button 1
2 | Push button 2 | Stay at button 1
3 | Move to button 3 | Push button 1
4 | Move to button 4 | Move to button 2
5 | Stay at button 4 | Push button 2
6 | Push button 4 | Stay at button 2
Note that Blue has to wait until Orange has completely finished pushing O 2
before it can start pushing B 1.
Input
The first line of the input gives the number of test cases, T. T test cases
follow.
Each test case consists of a single line beginning with a positive integer N,
representing the number of buttons that need to be pressed. This is followed by
N terms of the form "Ri Pi" where Ri is a robot color (always 'O' or 'B'), and
Pi is a button position.
Output
For each test case, output one line containing "Case #x: y", where x is the
case number (starting from 1) and y is the minimum number of seconds required
for the robots to push the given buttons, in order.
Limits
1 <= Pi <= 100 for all i.
Small dataset
1 <= T <= 20.
1 <= N <= 10.
Large dataset
1 <= T <= 100.
1 <= N <= 100.
Sample
Input
3
4 O 2 B 1 B 2 O 4
3 O 5 O 8 B 100
2 B 2 B 1
Output
Case #1: 6
Case #2: 100
Case #3: 4
'''
def trust(commands):
color = [None]
orange = [1]
blue = [1]
times = [0]
for i in range(0, len(commands), 2):
delta = 0
if commands[i] == 'O':
orange.append(int(commands[i+1]))
delta = abs(orange[-1] - orange[-2])
for t, c in zip(times[-1:0:-1],color[-1:0:-1]):
if c == 'O':
break
delta -= t
color.append('O')
else:
blue.append(int(commands[i+1]))
delta = abs(blue[-1] - blue[-2])
for t, c in zip(times[-1:0:-1],color[-1:0:-1]):
if c == 'B':
break
delta -= t
color.append('B')
times.append(max(delta+1, 1))
return sum(times)
if __name__ == '__main__':
import sys
with open(sys.argv[1], 'rt') as cheat_codes:
cheat_codes.next()
count = 1
for line in cheat_codes:
test_case = line.strip().split(' ')
x = test_case.pop(0)
print "Case #%d: %d" % (count, trust(test_case))
count += 1
|
#!/usr/bin/python
"""
Robert Ramsay <robert.alan.ramsay@gmail.com>
Packing your Dropbox
When you're working with petabytes of data, you have to store files wherever they can fit. All of us here at Dropbox are always searching for more ways to efficiently pack data into smaller and more manageable chunks. The fun begins when you bend the rules a little bit and visualize it in two dimensions.
You'll be given a list of rectangular "files" that you'll need to pack into as small a "Dropbox" as possible. The dimensions of each file will be specified by a tuple (width, height), both of which will be integers. The output of your function should be the area of the smallest rectangular Dropbox that can enclose all of them without any overlap. Files can be rotated 90(deg) if it helps. Bonus points if you can draw pictures of the winning configurations along the way. While drawing pictures, any files sharing dimensions should be considered identical/interchangeable.
Input
Your program must read a small integer N (1 <= N <= 100) from stdin representing the maximum number of files to consider, followed by the width and height of each file, one per line.
Output
Output should be simply be the area of the smallest containing Dropbox. If you want to print pretty pictures, send that to stderr. Only the output on stdout will be judged.
Sample Input
3
8 8
4 3
3 4
Sample Output
88
"""
#from __future__ import print_function
import sys
class DropBox:
w = 0
h = 0
x = 0
y = 0
def __init__(self,vector=None, w=0, h=0):
if vector:
self.w, self.h = vector
else:
self.w = w
self.h = h
def rotate(self):
t = self.w
self.w = self.h
self.h = t
def align(self):
if self.w > self.h:
self.rotate()
return self.h
#free space = (lowest left x, lowest left y, width, height)
def fit(size, free, box):
x, y, w, h = free
box.x = x
box.y = y
if h < box.h and w < box.w:
# Our box will not fit inside the current freespace.
size = (size[0]+box.w-w, size[1]+box.h-h)
x += box.w
w = 0
h = box.h
elif w < box.w:
size = (size[0] + box.w - w, size[1])
w = box.w
y += box.h
h -= box.h
elif h < box.h:
x += box.w
w -= box.w
else:
box.rotate()
if w < box.w:
size = (size[0] + box.w - w, size[1])
w = box.w
y += box.h
h -= box.h
else:
x += box.w
w -= box.w
free = (x, y, w, h)
return size, free
def pretty(boxes,w,h):
'''Pretty print the list of boxes'''
print >> sys.stderr, str(w) + 'x' + str(h) + ':'
graph = [[' ' for l in range(h+1)] for m in range(w+1)]
for box in boxes:
try:
# Vertices
graph[box.x][box.y] = '+'
graph[box.x+box.w][box.y] = '+'
graph[box.x][box.y+box.h] = '+'
graph[box.x+box.w][box.y+box.h] = '+'
# Edges
for x in range(box.x+1, box.x+box.w):
graph[x][box.y] = '|'
graph[x][box.y+box.h] = '|'
for y in range(box.y+1, box.y+box.h):
graph[box.x][y] = '-'
graph[box.x+box.w][y] = '-'
except Exception as e:
print >> sys.stderr, "Box (", box.x, box.y, box.w, box.h, ") is outside bounds (", w, h,")"
raise e
print >> sys.stderr, '\n'.join([''.join(row) for row in graph])
def pack(boxes):
#Align all the boxes and sort them by height lagest to smallest
boxes.sort(key=lambda box: box.align(), reverse=True)
size = (0, 0)
#free = (left, lower, width, height)
free = (0, 0, 0, 0)
for box in boxes:
size, free = fit(size, free, box)
pretty(boxes, size[0], size[1])
return size[0]*size[1]
class DropNode:
left = None # Left Edge is the parent.
vertex = None # We can store at most one Box
right = None # Right Edge is the child.
direction = [1,0] # direction is the identity ray
def __init__(self,vertex=None, left=None, right=None):
self.vertex = vertex
self.left = left
if self.left:
self.left.right = self
self.right = right
if self.right:
w = self.right.width()
h = self.right.height()
if self.vertex.w > self.vertex.h:
# An increase in width costs less than an increase in height
# if width is already greater.
self.direction = [0,1]
if w < h:
self.right.rotate()
else:
self.direction = [0,1]
if h < w:
self.right.rotate()
self.right.left = self
def rotate(self):
self.direction.reverse()
if self.vertex:
self.vertex.rotate()
if self.right:
self.right.rotate()
def width(self):
w = 0
if self.vertex is not None:
w = self.vertex.w
if self.right is not None:
if self.direction[0]:
w += self.right.width()
return w
def height(self):
h = 0
if self.vertex is not None:
h = self.vertex.h
if self.right is not None:
if self.direction[1]:
h += self.right.height()
return h
def packtree(node, boxes):
'''This is a recursive pack algorithm, similar to a binary search
tree.'''
if node is None:
node = DropNode()
if not boxes: # Stack empty.
while node.left:
node = node.left
return node # Return root
if node is None: #RootNode
print >> sys.stderr, "root node", boxes[-1]
return packtree(DropNode(boxes.pop(0)), boxes)
if node.vertex is None: # Not sure if I agree with this.
print >> sys.stderr, "curious"
node.vertex = boxes.pop()
return packtree(node, boxes)
# Make comparisons simpler
left = (max(boxes[0].w, boxes[0].h), min(boxes[0].w, boxes[0].h))
w = node.width()
h = node.height()
right = (max(w, h), min(w, h))
print >> sys.stderr, "left", left, "right", right,
if left[0] > right[0]:
print >> sys.stderr, "insert left"
if node.left:
return packtree(node.left, boxes)
else:
return packtree(DropNode(boxes.pop(0),None,node), boxes)
#if left[0] < right[1]:
# print >> sys.stderr, "insert right"
# if node.right:
# return packtree(node.right, boxes)
# else:
# return packtree(DropNode(boxes.pop(0),node),boxes)
print >> sys.stderr, "insert middle"
return packtree(DropNode(boxes.pop(0), node.left, node), boxes)
def prettytree(tree):
'''Pretty print the list of boxes'''
w = tree.width()
h = tree.height()
print >> sys.stderr, str(w) + 'x' + str(h) + ':'
graph = [[' ' for l in range(h+1)] for m in range(w+1)]
vx = 0
vy = 0
i = 0
node = tree
while node.right:
i += 1
print >> sys.stderr, '.',
if node.vertex is None:
print >> sys.stderr, "Empty Vertex"
node = node.right
continue
try:
vw = tree.vertex.w
vh = tree.vertex.h
# Vertices
graph[vx][vy] = '+'
graph[vx+vw][vy] = '+'
graph[vx][vy+vh] = '+'
graph[vx+vw][vy+vh] = '+'
# Edges
for x in range(vx+1, vx+vw):
graph[x][vy] = '|'
graph[x][vy+vh] = '|'
for y in range(vy+1, vy+vh):
graph[vx][y] = '-'
graph[vx+vw][y] = '-'
vx += tree.direction[0]*vw
vy += tree.direction[1]*vh
except Exception as e:
raise e
node = node.right
print >> sys.stderr
print >> sys.stderr, '\n'.join([''.join(row) for row in graph])
if __name__ == '__main__':
import sys
inp = input() #Number of boxes
try:
boxcount = int(inp)
if boxcount < 1 or boxcount > 100:
raise
except:
sys.exit("Box count must be between 1 and 100 (inclusive)")
boxes = []
for i in range(boxcount):
inp = raw_input('') #Box: width height
box = DropBox()
try:
w, h = inp.split(" ")
box.w = int(w)
box.h = int(h)
except:
sys.exit("Box definition should be integers seperated "\
"by whitespace")
boxes.append(box)
print(pack(boxes))
sys.exit()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print "Hello!"
loop = 1
choice = 0
while loop == 1:
print "We have several operations : "
print "Option 1 - plus"
print "Option 2 - minus"
print "Option 3 - multiply"
print "Option 4 - divide"
print "Option 5 - exit"
choice = input("Please, select operation ")
if choice == 1:
print "You chosen +"
num1 = input("Please input the first number ")
num2 = input("Please input the second number ")
print num1, " + ", num2, " = ", num1 + num2
if choice == 2:
print "You chosen -"
num1 = input("Please input the first number ")
num2 = input("Please input the second number ")
print num1, " - ", num2, " = ", num1 - num2
if choice == 3:
print "You chosen *"
num1 = input("Please input the first number ")
num2 = input("Please input the second number ")
print num1, " * ", num2, " = ", num1 * num2
if choice == 4:
print "You chosen /"
num1 = input("Please input the first number ")
num2 = input("Please input the second number ")
print num1, " / ", num2, " = ", num1 / num2
if choice == 5:
loop == 0
print "See you soon!"
|
# name saurav adhikari
# roll no 734
# class of 2021
# section B
p=int(input("Enter the principal amount(Rs):"))
n=int(input("Enter the no of times interest is compounded per year : "))
t=int(input("enter the no. of years : "))
r=float(input("Enter the annual interest(%) : "))
finalvalue= p*(1+(r/n))**(n*t)
print("The final amount after",t,"years is Rs.",finalvalue)
|
import random
import math
import sys
def rabinMiller(n):
s = n-1
t = 0
while s&1 == 0:
s = s/2
t +=1
k = 0
while k<1:
a = random.randrange(2,n-1)
print a
#a^s is computationally infeasible. we need a more intelligent approach
#v = (a**s)%n
#python's core math module can do modular exponentiation
v = pow(a,s,n) #where values are (num,exp,mod)
if v != 1:
i=0
while v != (n-1):
if i == t-1:
return False
else:
i = i+1
v = (v**2)%n
k+=2
return True
if __name__=="__main__":
# # print generateLargePrime(1024)
# p= generateLargePrime(128)
# q= generateLargePrime(128)
print rabinMiller(29)
print rabinMiller(221)
|
s=dict()
def intialise(key):
global s
for i in xrange(256):
s[i]=i
j=0
for i in xrange(256):
j= j + s[i]+ord(key[i%len(key)])
j=j%256
s[i],s[j]=s[j],s[i]
def encryption(text):
i,j=0,0
global s
for i in xrange(len(text)):
j = (j + s[i])%256
s[i],s[j]=s[j],s[i]
z = s[(s[i] + s[j])%256]
print (chr(ord(text[i])^z),"")
if __name__ == "__main__":
key=raw_input("Enter the key:")
plaintext=raw_input("Enter the plaintext:")
intialise(key)
print "CipherText"
encryption(plaintext)
|
print("Advent Of Code - Day 2")
PUZZLEINPUT = open('input.txt').read().strip().split(',')
data = [int(i) for i in PUZZLEINPUT]
#Create the 1202 program
data[1] = 12
data[2] = 2
for x in range(0, len(data), 4):
opcode = data[x]
x1, x2, destination = data[x + 1], data[x + 2], data[x + 3]
if opcode == 1:
data[destination] = data[x1]+data[x2]
elif opcode == 2:
data[destination] = data[x1]*data[x2]
elif opcode == 99:
## Terminate if opcode 99 is found
break
print(f'Part 1: {data[0]}')
original_data = [int(i) for i in PUZZLEINPUT]
for noun in range(0,100):
for verb in range(0,100):
current_data = [int(i) for i in original_data]
#Create the new 1202 program
current_data[1] = noun
current_data[2] = verb
for pointer in range(0, len(current_data), 4):
opcode = current_data[pointer]
x1, x2, destination = current_data[pointer + 1], current_data[pointer + 2], current_data[pointer + 3]
if opcode == 1:
current_data[destination] = current_data[x1]+current_data[x2]
elif opcode == 2:
current_data[destination] = current_data[x1]*current_data[x2]
elif opcode == 99:
## Terminate if opcode 99 is found
break
if current_data[0] == 19690720:
print(f'Part 2: {100 * noun + verb}') |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 18:43:18 2019
@author: Kartik
"""
A=[6,5,4,3,2,1]
K=4
def CyclicRotation(A,K):
if l>0:
l=len(A)
for i in range(K):
temp=A[l-1]
print(temp)
for j in range(l-1):
A[l-j-1]=A[l-j-2]
A[0]=temp
print(A)
CyclicRotation(A,K) |
import math
import csv
with open('data.csv', newline='')as f:
reader=csv.reader(f)
fileData=list(reader)
data=fileData[0]
def mean(data):
n=len(data)
total=0
for x in data:
total+=int(x)
mean=total/n
return mean
squaredList=[]
for number in data:
a=int(number)-mean(data)
a=a**2
squaredList.append(a)
sum=0
for i in squaredList:
sum=sum+int(i)
n=len(data)
result=sum/n-1
standardDeviation=math.sqrt(result)
print(standardDeviation) |
class siswa:
#class variabel
jumlah_siswa = 0
#konstruktor
def __init__(self, nama, kelas, kejurusan, sekolah, nilai):
self.nama = nama
self.kelas = kelas
self.kejurusan = kejurusan
self.sekolah = sekolah
self.nilai = nilai
siswa.jumlah_siswa += 1
#methode
def viewSiswa(self):
print("=================")
print("Data Siswa")
print("Nama : ", self.nama)
print("Kelas : ", self.kelas)
print("Sekolah : ", self.sekolah)
print("=================")
def viewNilai(self):
print("Data Nilai dan Jurusan")
print("Nama : ", self.nama)
print("Kejurusan : ", self.kejurusan)
for nilai in self.nilai:
print("Nilai : ", nilai)
print("=================")
def viewKeterangan(self):
print("Keterangan")
print("Nama : ", self.nama)
print("Kelas : ", self.kelas)
rata = sum(self.nilai)/len(self.nilai)
print("Rata-rata : ", rata)
if rata >= 75 :
keterangan = "LULUS."
else:
keterangan = "TIDAK LULUS."
print("Keterangan : ", keterangan)
#instansiasi objek
siswa1 = siswa("Lilian", "XI-3", "IPA", "SMA 1", [75, 80, 86, 78])
siswa2 = siswa("Anya", "XI-2", "IPA", "SMA 3", [88, 70, 80, 68])
siswa3 = siswa("Damian", "XI-5", "IPS", "SMA 2", [95, 80, 74, 78])
#pemanggilan objek siswa 1
siswa1.viewSiswa()
siswa1.viewNilai()
siswa1.viewKeterangan()
print("Jumlah siswa : ", siswa.jumlah_siswa)
print("=================")
#pemanggilan objek siswa 2
siswa2.viewSiswa()
siswa2.viewNilai()
siswa2.viewKeterangan()
print("Jumlah siswa : ", siswa.jumlah_siswa)
print("=================")
#pemanggilan objek siswa 3
siswa3.viewSiswa()
siswa3.viewNilai()
siswa3.viewKeterangan()
print("Jumlah siswa : ", siswa.jumlah_siswa)
print("=================") |
import threading
from time import sleep, time
mutex = threading.Semaphore()
emptyPot = threading.Semaphore(0)
fullPot = threading.Semaphore(0)
pot = []
M = 10
runtimes = [0 for i in range(3)]
def cook():
servings = 0
for i in range(3):
emptyPot.acquire()
# Fill up the pot
for i in range(M):
pot.append(i)
fullPot.release()
servings += 1
print('-'*16)
print("Served : ", servings)
def savage(index):
food = -1
startTime = time()
for i in range(10):
mutex.acquire()
if len(pot) == 0:
emptyPot.release()
fullPot.acquire()
food = pot.pop()
mutex.release()
print("Eating : ", food)
sleep(0.2)
runtimes[index] = time() - startTime
chef = threading.Thread(target=cook)
savages = []
savages.append(threading.Thread(target=savage, args=(0,)))
savages.append(threading.Thread(target=savage, args=(1,)))
savages.append(threading.Thread(target=savage, args=(2,)))
print("Cooking")
chef.start()
print("Eating")
startTime = time()
for s in savages:
s.start()
for s in savages:
s.join()
print("Total runtime:", time() - startTime)
print(runtimes)
chef.join() |
#命令模式:将一个请求封装成一个对象,从而让你使用不同的请求将客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。
from abc import ABCMeta,abstractmethod
class Command(metaclass=ABCMeta):
@abstractmethod
def execute(self):
pass
class CommandImpl(Command):
def __init__(self,reveiver):
self.__receiver = receiver
def execute(self):
self.__receiver.doSomething()
class Receiver:
def doSomething(self):
print("do something")
class Invoker:
def __init__(self):
self.__command = None
def setCommand(self,command):
self.__command = command
def action(self):
if self.__command is not None:
self.__command.execute()
#命令模式有命令,接受者,调度者,用户。
#优点是对命令的发送者和接受者进行解耦,使得调用方不用关心具体的行动执行者如何执行,只需要发送正确的命令
#可以很方便的增加新命令
#缺点是在一些系统中可能会有很多命令,而每一个命令都需要一个具体的类去封装,容易使命令的类急剧膨胀
|
# Задание1. Разобрать код.
# 1. Ответить на вопрос: "Что тут происходит?"
# 2 .Что такое raise_for_status()
# 3. for цикл в питоне
# 4. как добавить третий запрос на 'http://localhost:5002/basic_auth'
import requests
from requests.exceptions import HTTPError
from requests.auth import HTTPBasicAuth
# sending hhtp requests one by one in cycle
for url in ['http://localhost:5002/', 'http://localhost:5002/fail500',
# uncomment below to: 1) without authorization catch 401 error
#'http://localhost:5002/basic_auth'
]:
# try to send request
try:
# if 200ok print 'Success!' message#
print(f"\nSending GET request to {url}")
response = requests.get(url)
# 2) with authorization
responseWithToken = requests.get('http://localhost:5002/basic_auth',
auth = HTTPBasicAuth('sergii', 'hello'))
# method raises an exception if a request is unsuccessful (with http errors)
response.raise_for_status()
# 2) with authorization
responseWithToken.raise_for_status()
# if catch HTTP errors (400+, 500+) print error code and description
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
# if catch any exception errors print error text
except Exception as err:
print(f'Other error occurred: {err}')
else:
print('Success!')
# 2) with authorization
print(f"\nSending GET request to http://localhost:5002/basic_auth:\n" + responseWithToken.text)
|
# Задание1. Разобрать код.
# 1. Ответить на вопрос: "Что тут происходит?"
# 2 .Что такое raise_for_status()
# 3. for цикл в питоне
# 4. как добавить третий запрос на 'http://localhost:5002/basic_auth'
import requests # импортируем библиотеку requests
from requests.exceptions import HTTPError # из библиотеки requests.exceptions импортируем HTTPError
for url in ['http://localhost:5002/', 'http://localhost:5002/fail500','http://localhost:5002/basic_auth']: # в цикле перебираются урлы
try: # обработка исключений. Здесь в блоке мы выполняем инструкцию, которая может породить исключение.
print(f"\nSending GET request to {url}") # информационный вывод об отправке реквеста на итерируемый урл
response = requests.get(url) # создается переменная с результатом вызова состояния
response.raise_for_status() # вызов исключения, если запрос был неудачным.
# HTTPError будет вызываться для определенных кодов состояния. Если код состояния указывает на успешный запрос, программа продолжит работу без возникновения этого исключения.
except HTTPError as http_err: # обработка исключений. Здесь в блоке мы перехватываем исключения.
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
else:
print('Success!') # если никаких исключений/ ошибок в итерируемой урле не возникло, выводится сообщение об успешном результате.
|
def pot( n, m ):
if m == 0 :
return 1
elif m == 1 :
return n
else:
return pot( n, m-1 ) * n
n = int( input( "Ingrese base para calcular potencia: " ) )
m = int( input( "Ingrese exponente para calcular potencia: " ) )
numero_pot = pot( n, m )
print( "La potencia " + repr( n ) + " elevado a la " + repr( m ) + " es " + repr( numero_pot ) )
|
"""
Name: Zackery Vering
Project: Lab 3E
Date: 7 Sept 2018
"""
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1)+fibonacci(n-2)
i = 0
x = 0
y = 1
current = 0
for i in xrange(100):
current = x + y
x = y
y = current
print(current)
i = 0
while(True):
for i in xrange(100):
print(fibonacci(i))
break |
"""
Name: Zackery Vering
Project: Lab 4A
Date: 10 Sept 2018
Instructions
Create a fully functional calculator using BOTH functions and lambdas.
Create a user menu as well as a "screen" where the numbers and
operations take place. The calculator needs to have the following
functionality:
Addition
Subtraction
Division
Multiplication
Power
At least two math algorithms (One can be your Fibonacci)
Requirments
Adhere to PEP8
Functionality requirments above
Utilize user input and proper validation
Utilize proper formatting
Utilize proper and clean statements and loop
Additional
More than two numbers
Continuous operations (5 + 5 + 2 - 1 / 2 for example)
Additional operations
Additonal math algorithms
"""
import time
import Tkinter
import tkMessageBox
from math import sqrt
from PIL import JpegPresets
top = Tkinter.Tk()
top.title("Calculator")
top.grid(baseWidth=10, widthInc=10, baseHeight=10, heightInc=10)
#define variables
user_choice = 0
result = 0
label4 = Tkinter.Label()
#define functions
def addition():
global result
result = int(first_num.get()) + int(second_num.get())
label4 = Tkinter.Label(top, text="{}".format(result))
label4.grid(column=1, row=6)
def subtraction():
global result
result = int(first_num.get()) - int(second_num.get())
label4 = Tkinter.Label(top, text="{}".format(result))
label4.grid(column=1, row=6)
def division():
global result
result = float(first_num.get()) / float(second_num.get())
label4 = Tkinter.Label(top, text="{}".format(result))
label4.grid(column=1, row=6)
def multiplication():
global result
result = int(first_num.get()) * int(second_num.get())
label4 = Tkinter.Label(top, text="{}".format(result))
label4.grid(column=1, row=6)
def power():
global result
result = int(first_num.get()) ** int(second_num.get())
label4 = Tkinter.Label(top, text="{}".format(result))
label4.grid(column=1, row=6)
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1)+fibonacci(n-2)
def fib():
global result
result= str('')
for i in range(int(first_num.get())):
if (result == ''):
result = str(fibonacci(i))
else:
result = result + ',' + str(fibonacci(i))
label4 = Tkinter.Label(top, text="{}".format(result))
label4.grid(column=1, row=6)
def pythagoras():
global result
result = sqrt((int(first_num.get())**2) + (int(second_num.get()**2)))
label4 = Tkinter.Label(top, text="{}".format(result))
label4.grid(column=1, row=6)
def surprise():
picture = Tkinter.Tk()
picture.title("Surprise!")
top.grid(baseWidth=10, widthInc=10, baseHeight=10, heightInc=10)
#photo = Tkinter.PhotoImage(file="CerberusRE2.jpg")
#doge = Tkinter.Button(picture, image=photo, command=quit)
#doge.grid(column=1, row=0)
doge_label = Tkinter.Label(picture, text="This is temp text. Still working on this.")
doge_label.grid(column=1, row=1)
picture.mainloop()
label1 = Tkinter.Label(top, text="First Number")
label1.grid(column=0, row=0)
first_num = Tkinter.Entry(top)
first_num.grid(column=1, row=0)
label2 = Tkinter.Label(top, text="Second Number")
label2.grid(column=0, row=1)
second_num = Tkinter.Entry(top)
second_num.grid(column=1, row=1)
add = Tkinter.Button(top, text="Addition", width=12, command=addition)
sub = Tkinter.Button(top, text="Subtraction", width=12, command=subtraction)
div = Tkinter.Button(top, text="Division", width=12, command=division)
mul = Tkinter.Button(top, text="Multiplication", width=12, command=multiplication)
pwr = Tkinter.Button(top, text="Power", width=12, command=power)
pyt = Tkinter.Button(top, text="Pythagoras", width=12, command=pythagoras)
fib = Tkinter.Button(top, text="Fibonacci", width=12, command=fib)
sur = Tkinter.Button(top, text="Something Else", width=12, command=surprise)
qit = Tkinter.Button(top, text="Quit", width=12, command=quit)
add.grid(column=0, row=2)
sub.grid(column=1, row=2)
div.grid(column=2, row=2)
mul.grid(column=0, row=3)
pwr.grid(column=1, row=3)
pyt.grid(column=2, row=3)
fib.grid(column=0, row=4)
sur.grid(column=1, row=4)
qit.grid(column=1, row=5)
label3 = Tkinter.Label(top, text="Result")
label3.grid(column=0, row=6)
label4 = Tkinter.Label(top, text="{}".format(result))
label4.grid(column=1, row=6)
top.mainloop() |
"""Name: Zackery Vering
Project: Python2 lab2e
Date: 5 Sept 2018"""
print "==================================="
user_string = raw_input("Input a sentence.\n")
print "There are {} words in your sentence.\n".format(len(user_string.split(" ")))
print "There are {} upper case letters in your sentence.\n".format(sum(1 for c in user_string if c.isupper))
print "There are {} lower case letters in your sentence.\n".format(sum(1 for d in user_string if d.islower)) |
#!/usr/local/bin/python2.6
"""
Purpose
-------
Takes an input binary file of a well know format, extracts the data and
saves it in a simple but required CSV format.
Program Flow
------------
Input:
A file name with the full location,
i.e. C:\Users\schiefej\Desktop\binary_filename.bin
Output:
Writes data to an output CSV file in the format per line of:
YYYYMMDD,latitude,longitude,value
where YYYY is the year in four digits, MM is the month in two digits
and DD is the day in two digits.
Notes/Lessons Learned
---------------------
None
--------
"""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
# The __future__ print function is used to ensure an easier path to
# Python 3 if and when the upgrade is needed.
from __future__ import print_function
# built-ins
import argparse
import cProfile
import datetime
import gzip
import logging
import os
import pstats
import StringIO
import sys
import time
# external
import gpcp_parsers
#------------------------------------------------------------------------------
# Functions
#------------------------------------------------------------------------------
def get_args():
"""
Purpose
Get the command line arguments and provide help if the -h option is
selected.
Returns
A tuple in a format similar to:
Namespace(input_file='C:/Users/schiefej/Desktop/gpcp_v2.2psg.1987',
output_file='C:/Users/schiefej/Desktop/out_1987',
input_prefix='',
output_prefix='',
years='[]')
or
Namespace(input_file='',
output_file='',
input_prefix='gpcp_v2.2psg.',
output_prefix='gpcp_out_',
years='(1987,2011)')
"""
gpcp_url = "http://precip.gsfc.nasa.gov/"
description = "Please see " + gpcp_url + " for a full description of " + \
"the data set."
epilog = "Special thanks to clawtros/Adam Benzan and Carbon Chick for " + \
"their initial program that solved the hard problem."
parser = argparse.ArgumentParser(description=description,
epilog=epilog)
parser.add_argument('-z',
'--gzip',
action='store_true',
help="Set this flag if the input files are " + \
"zipped using gzip and end with .gz.")
parser.add_argument('-s',
'--single_file',
action='store_true',
help="Set this flag if running the program for " + \
"only a single (one) file. Specify the file " + \
"using the -i option.")
parser.add_argument('-i',
'--input_file',
default="",
help="The full path of the input file, i.e.: " + \
"C:/Users/schiefej/Desktop/gpcp_v2.2psg.1987" + \
" if no year(s) is(are) provided this is " + \
"required. If this switch is used, -s must " + \
"also be set.")
parser.add_argument('-o',
'--output_file',
default="",
help="The full path of the input file, i.e.: " + \
"C:/Users/schiefej/Desktop/out_1987.csv")
parser.add_argument('-p',
'--input_prefix',
default="./gpcp_1dd_v1.2_p1d.",
help="The path to the input file(s) and " + \
"the appropriate prefix such as: " + \
"'./gpcp_v2.2_psg.' or " + \
"'C:/Users/schiefej/binary_files/gpcp_file_'" + \
"The default is the current directory plus " + \
"the prefix for the new format files: " + \
"'./gpcp_1dd_v1.2_p1d.'")
parser.add_argument('-op',
'--output_prefix',
default="./gpcp_out_",
help="The path to the output file(s) and " + \
"the appropriate prefix such as: " + \
"'./gpcp_out_' or " + \
"'C:/Users/schiefej/binary_files/gpcp_out_'")
current_year = datetime.datetime.now().year
parser.add_argument('-y',
'--years',
default=str(current_year),
help="Years of the requested data, i.e. 2012" + \
" or 1987,2011. The MUST be no spaces in " + \
"the string, ie. 1999,2000 is okay but " + \
"1999, 2000 is not." + \
"This is a optional value but if it is " + \
"provided, prefixes must be provided. If " + \
"it is provided, an input file must be provided.")
current_month = datetime.datetime.now().month
parser.add_argument('-m',
'--months',
default=str(current_month),
help="Months of the requested data, i.e. 10 " + \
"or 1,2,3,4,5,6,7,8,9,10,11,12 for an " + \
"entire year. There MUST be no spaces in " + \
"the string; see the year argument for " + \
"applicable examples but using month numbers.")
format_help = ("This switch determines which parser to use. " +
"0 decodes MONTHLY GPCP (v2.2) binary file into CSV " +
"output. Tags the data by month and pre-pends a list of " +
"grid box lat/lons in the same order as the precip data " +
"itself. Format originally designed by Adler, et al." +
"1 decodes MONTHLY GPCP (v2.2) binary data into CSV with " +
"a date/lat/lon value for each precip value in the file. " +
"One line per value. 2 decodes DAILY GPCP (v1.2) binary " +
"file into same csv format as 1 above.")
parser.add_argument('-f',
'--format',
default='2',
help=format_help)
return parser.parse_args()
#------------------------------------------------------------------------------
def check_args(args):
""" Checks the validity of the inputs from the command lines.
Input:
A tuple of arguments from the command line
Output:
Returns a tuple with the verified/checked values. Exits if values
are not correct with the appropriate error message.
"""
# get the known arguments from args
zipped = args.gzip
single_file = args.single_file
input_file = args.input_file
output_file = args.output_file
input_prefix = args.input_prefix
output_prefix = args.output_prefix
years = args.years
months = args.months
format_opt = args.format
if single_file:
# check for input_file and output_file
if input_file != "" and output_file != "":
format_opt = int(format_opt)
return (zipped,
input_file,
output_file,
format_opt)
else:
err_message = "For a single file, a input and output file " + \
"must be specified with the appropriate options."
error_help_then_exit(err_message)
else: # multi_file options
format_opt = int(format_opt)
if not(0 <= format_opt <= 2):
err_message = "Please enter an appropriate format option with " + \
"-f as in: "
error_help_then_exit(err_message)
years_list = []
if "," in years:
years_list = years.split(",")
else:
years_list.append(years)
for year in years_list:
if not(1970 <= int(year) <= int(datetime.datetime.now().year)):
err_message = "Please enter a year from 1970 to current."
error_help_then_exit(err_message)
if format_opt != 0:
months_list = []
if "," in months:
months_list = months.split(",")
else:
months_list.append(months)
for month in months_list:
if not(1 <= int(month) <= 12):
err_message = "Please enter a month from 1 to " + \
"12 inclusive."
error_help_then_exit(err_message)
else:
months_list = None
return (zipped,
input_prefix,
output_prefix,
years_list,
months_list,
format_opt)
#------------------------------------------------------------------------------
def error_help_then_exit(message):
""" Prints the given message, then has the help for the program print
out and then exits.
"""
print(message)
os.system("python -B gpcp_to_csv.py -h")
sys.exit()
#------------------------------------------------------------------------------
def unzip(filename):
""" Unzips a gzip file for use. If the file ends with .gz it decompresses
the file to the filename minus the .gz file extension. If the file does
not end with .gz it adds _unzipped at the end of the file name.
Input:
The file name of a compressed file. The file must be compressed using
gzip.
Returns:
The file name of the uncompressed file.
"""
if filename.endswith(".gz"):
return_filename = filename[:-3]
else:
return_filename = filename + "_unzipped"
try:
z_content = gzip.open(filename, 'rb')
print("\nExtracting data from: ", filename)
with open(return_filename, 'wb') as uncompressed:
uncompressed.write(z_content.read())
except IOError, error:
print("\nIOError from unzip: ", error)
raise
else:
return return_filename
#------------------------------------------------------------------------------
def process_file(input_filename, output_filename, format_opt, zipped):
""" Extracts the data from the input file and saves it in CSV format in
the output file in the format specified by the format option. If the file
is zipped it is decompressed first.
"""
if zipped:
try:
input_file = unzip(input_filename)
except IOError:
err_message = "Skipping file: " + input_filename + "\n"
print(err_message)
return 0
else:
input_file = input_filename
if format_opt == 0:
parser = gpcp_parsers.GpcpParserOriginal(input_file)
elif format_opt == 1:
parser = gpcp_parsers.GpcpParserOriginalOneLine(input_file)
elif format_opt == 2:
parser = gpcp_parsers.GpcpParserNewOneLine(input_file)
else:
err_message = "An incorrect format was entered please enter a " + \
"valid option of 0, 1, or 2."
error_help_then_exit(err_message)
if parser.has_data():
with open(output_filename, 'w') as out_file:
print("Writing CSV value to ", output_filename)
parser.write_csv(out_file)
if zipped:
os.remove(input_file)
return 1
#------------------------------------------------------------------------------
# Main
#------------------------------------------------------------------------------
def main():
""" The 'main' function used to run the file/modules as a stand alone
application.
"""
# get the arguments, parse and then check them
the_args = check_args(get_args())
# set some variables for program readability
num_of_args = len(the_args)
num_of_singlefile_args = 4 # this will change with changes to check_args
num_of_multifile_args = 6 # ditto for this number
# for single file
if num_of_args == num_of_singlefile_args:
zipped, input_file, output_file, format_opt = the_args
print("\nStarting process to reformat GPCP binary data to CSV.")
if not(output_file.endswith(".csv")):
output_file = output_file + ".csv"
process_file(input_file, output_file, format_opt, zipped)
print("\nProcess complete.\n")
# for multiple files
elif num_of_args == num_of_multifile_args:
(zipped,
input_prefix,
output_prefix,
years,
months,
format_opt) = the_args
files_dict = {}
for year in years:
if format_opt != 2:
if zipped:
in_file = input_prefix + year + ".gz"
else:
in_file = input_prefix + year
out_file = output_prefix + year + ".csv"
files_dict[in_file] = out_file
else:
for month in months:
month = month.zfill(2)
if zipped:
in_file = input_prefix + year + month + ".gz"
else:
in_file = input_prefix + year + month
out_file = output_prefix + year + month + ".csv"
files_dict[in_file] = out_file
print("\nStarting process to reformat GPCP binary data to CSV.")
for input_file, output_file in sorted(files_dict.iteritems()):
process_file(input_file, output_file, format_opt, zipped)
print("\nProcess complete.\n")
# there was an error, the program should never get here
else:
print("There was a significant error not caught elsewhere. " + \
"Try again, if it happens again then submit a bug report.")
def profile_main():
"""
Purpose
Used from if __name__ == ... to profile the program from the command
line and locate the bottlenecks
Profiles the main() function and logs the result to a file. This file
is simply text and can be viewed using a simple text editor. At a
later time it might be beneficial to create a html or
reStructured text file for easier reading.
Got idea and code from:
http://code.google.com/appengine/kb/commontasks.html#profiling
Input
Same as main(), defined in previous function.
Output
A text file name profile_filename_timestamp.log containing a full
profile of calls and timing.
"""
# get and format the time stamp for the file name
today = str(datetime.date.fromtimestamp(time.time()))
now = str(int(time.time() * 100))[6:] # for a unique file name
# define the file name
file_name = (os.path.basename(__file__))[:-3]
profile_log_name = "profile_" + file_name + "_" + \
today + "_" + now + ".log"
# begin logging
logging.basicConfig(filename=profile_log_name, level=logging.DEBUG)
# start profiling
profiler = cProfile.Profile()
profiler = profiler.runctx("main()", globals(), locals())
stream = StringIO.StringIO()
stats = pstats.Stats(profiler, stream=stream)
stats.sort_stats("time")
# Or cumulative
stats.print_stats(160) # 80 = how many to print
# The rest is optional.
# stats.print_callees()
# stats.print_callers()
logging.info("Profile data:\n%s", stream.getvalue())
#------------------------------------------------------------------------------
# Name
#------------------------------------------------------------------------------
if __name__ == '__main__':
main()
# profile_main()
|
class CleanPhoneNumber(object):
def __init__(self, phone_number):
self.phone_number = phone_number
def sanitize_phone_number(self):
phone_number = self.phone_number
phone = list(phone_number)
prefix = phone[0]
length = len(phone_number)
if prefix == '+' and length == 13:
phone[0] = ''
return "".join(phone)
if prefix == '0' and length == 10:
phone[0] = '254'
return "".join(phone)
elif prefix == '2' and length == 12:
return str(phone_number)
elif length < 10:
return ''
else:
return ''
|
class Node:
def __init__(self, val, left = None, right = None):
self.value = val;
self.left = left;
self.right = right;
def contains(rootNode, searchValue):
if not rootNode:
return False
if rootNode.value == searchValue:
return True
if rootNode.value > searchValue:
return contains(rootNode.left, searchValue)
else:
return contains(rootNode.right, searchValue)
root = Node(15, Node(11), Node(22, Node(13), Node(25)))
print(contains(root, 11)) |
# Create string with 'Facebook'
# Create counter variable
# Check if input is empty, return
# iterate over characters of given word
# if char in given word == char in facebook, add counter
# if len == facebook, true, else: false
def fbInString(input):
fb = "facebook"
counter = 0
if not input:
return False
else:
for i in range(len(input)):
if input[i] == fb[counter]:
counter += 1
if counter == len(fb):
return True
return False
if __name__ == '__main__':
print(fbInString("ffffaaccccebbok"))
print(fbInString("is instagram owned by facebook?"))
print(fbInString("ffffaacccebbooook"))
print(fbInString(""))
|
__author__ = "ZiXing"
age_of_oldboy = 56
type = True
while type:
you_guess = int(input("guess age:"))
if age_of_oldboy == you_guess:
print("Yes !")
type = False
elif age_of_oldboy > you_guess:
print("you guess is small")
else:
print("You guess is old")
|
b = []
for i in range(2, 101):
for j in range(2, i):
if i % j == 0:
break
else:
print i
for a in range (0,100):
b.append(a)
elements = []
#then use the range function to do 0 to 5 counts
for i in range(0,6):
print "Adding %d to the list."%i
#append is a function that lists understand
elements.append(i)
c = 2
a,b = c,c
print a,b |
import cv2;
import numpy as np;
import matplotlib.pyplot as plt
import operator
# Read image
image = cv2.imread("white_test_2.jpg")
# cropping image
#third_x = int(im_in)
third_y = int(image.shape[0]/2)
width = int(image.shape[1])
height = int(image.shape[0])
print(third_y)
print(width)
cropped_image = image[third_y:height,0:width]
def select_rgb_white_yellow(image):
# white color mask
#lower = np.uint8([220, 220, 20])
#upper = np.uint8([255, 255, 255])
lower = np.uint8([200, 200, 200])
upper = np.uint8([255, 255, 255])
mask = cv2.inRange(image, lower, upper)
masked = cv2.bitwise_and(image, image, mask = mask)
return masked
cv2.imshow("masked",select_rgb_white_yellow(cropped_image))
cv2.waitKey(0)
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 8 11:42:46 2019
@author: computer
"""
for i in range(1,6):
print("*"*i)
for j in range(4,0,-1):
print("*"*j)
******************************************
# Enter Number to print pattern
num = int(input("Enter Number to print Pattern: "))
# Prints the upper half of the pattern
for i in range(1,num+1):
print("*" * i)
# Prints the lower half of the pattern
for i in range(num-1,0,-1):
print("*" * i) |
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 11:42:18 2019
@author: computer
"""
import numpy as np
Num=input("Enter space separated no.").split()
Num = np.array(Num)
Num=Num.reshape(3,3)
print(Num)
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 10 10:45:43 2019
@author: computer
"""
with open("new.txt", "rt") as file1:
with open("copy.txt","wt") as file2:
for line in file1:
file2.write(line)
content = file1.readline()
print(content)
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 11 10:44:55 2019
@author: computer
"""
import re
while True:
li1=input("enter no").split(">")
if not li1:
break
for val in li1:
if re.findall(r'[+-.]?[0-9]\.[0-9]*',val):
print("True")
else:
print("False") |
# -*- coding: utf-8 -*-
"""
Created on Fri May 17 13:04:53 2019
@author: computer
"""
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
img = Image.open("Sample1.jpg","rt")
draw = ImageDraw.Draw(img)
selectFont = ImageFont.truetype("FontName.ttf", size = 60)
draw.text( (x,y), text, (r,g,b), font=selectFont
# (x,y) is the starting position for the draw object
# text is the text to be entered
# (r,g,b) represents the color eg (255,0,0) is Red
# font is used to specify the Font object
img.save( 'certi.pdf', "PDF", resolution=100.0)
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 13:07:39 2019
@author: computer
"""
newstr="RESTART"
l=newstr.find('R')
a=newstr[:l+1]
b=newstr[l+1:]
print(a+b.replace('R','$'))
**************************************************88
input_string = input("Enter your String :")
replaced_char = input("Enter Character which you want to replace :")
replacement_char = input("Enter Character using which you want to replace :")
# First occurence of replaced character
first_occurence = input_string.find(replaced_char)
# Replace replaced character with replacement character from input string
print (input_string[:first_occurence+1] + input_string[first_occurence+1:].replace(replaced_char, replacement_char,1))
|
#@result Submitted a few seconds ago • Score: 20.00 Status: Accepted Test Case #0: 0s Test Case #1: 0s Test Case #2: 0s Test Case #3: 0s Test Case #4: 0.01s Test Case #5: 0s
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import namedtuple
stu_num = int(raw_input())
Student = namedtuple('Student', raw_input())
sum = 0.0
for i in range(stu_num):
stu = Student(*(raw_input().split()))
sum += int(stu.MARKS)
print sum / stu_num |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
queue = [root]
min_depth = -1
while len(queue):
min_depth += 1
for i in range(len(queue)):
current = queue.pop(0)
if current:
if None == current.left and None == current.right:
return min_depth + 1
queue.append(current.left)
queue.append(current.right)
return min_depth
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
dummy = ListNode(-1)
dummy.next = head
current = dummy
dummy0 = ListNode(-1)
less = dummy0
dummy1 = ListNode(-1)
greater = dummy1
while current.next:
if current.next.val < x:
less.next = current.next
less = less.next
else:
greater.next = current.next
greater = greater.next
current = current.next
less.next = dummy1.next
greater.next = None
return dummy0.next
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.helper(root, - sys.maxint, sys.maxint)
def helper(self, root, minimum, maximum):
return None == root or (root.val > minimum and root.val < maximum and self.helper(root.left, minimum, root.val) and self.helper(root.right, root.val, maximum)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.