text
stringlengths 37
1.41M
|
---|
# The Riddler Classic 2020-03-20: SET
# https://fivethirtyeight.com/features/how-many-sets-of-cards-can-you-find/
# Monte-Carlo simulation
import random
import itertools
class card:
def __init__(self, number, shape, color, shading):
self.number = number
self.shape = shape
self.color = color
self.shading = shading
def is_set(card1, card2, card3):
#determine whether 3 cards form a set
number_flag = False
shape_flag = False
color_flag = False
shading_flag = False
#check all number different
if (card1.number != card2.number and card1.number != card3.number
and card2.number != card3.number):
number_flag = True
#check all number the same
elif (card1.number == card2.number and card1.number == card3.number):
number_flag = True
#check all shape different
if (card1.shape != card2.shape and card1.shape != card3.shape
and card2.shape != card3.shape):
shape_flag = True
#check all shape the same
elif (card1.shape == card2.shape and card1.shape == card3.shape):
shape_flag = True
#check all color different
if (card1.color != card2.color and card1.color != card3.color
and card2.color != card3.color):
color_flag = True
#check all color the same
elif (card1.color == card2.color and card1.color == card3.color):
color_flag = True
#check all shading different
if (card1.shading != card2.shading and card1.shading != card3.shading
and card2.shading != card3.shading):
shading_flag = True
#check all shading the same
elif (card1.shading == card2.shading and card1.shading == card3.shading):
shading_flag = True
if (number_flag and shape_flag and color_flag and shading_flag):
return True
else:
return False
#attributes
numbers = [1, 2, 3]
shapes = ["oval", "diamond", "squiggle"]
colors = ["r", "g", "p"]
shadings = ["solid", "shaded", "outlined"]
#create the deck
deck = []
for i1 in numbers:
for i2 in shapes:
for i3 in colors:
for i4 in shadings:
deck.append(card(i1, i2, i3, i4))
Nsim = 100000 #number of simulations
count = 0
for N in range(Nsim):
#sample a random board of 12
board = random.sample(deck, 12)
#generate all 12 choose 3 combinations from the board
combos = list(itertools.combinations(board, 3))
#check whether any of the combinations is a set
for c in combos:
if card.is_set(c[0], c[1], c[2]):
count += 1
break
print(count/Nsim)
|
#The Riddler Express 2018-11-02: Rigged Coin Flip
#Monte-Carlo simulation
import random
Nsim = 1000000 #number of simulations
#----------------------------------------------------
#Methods for coin flips and comparing flip results
def coin_flip():
#Outputs the result of a single coin flip
return bool(random.getrandbits(1))
def flip_coins(x):
#Outputs the result of x coin flips
return [coin_flip() for i in range(x)]
def match_template(flips, template):
#Determine whether a flip sequence matches a template
x = len(win_template)
return all([flips[i] == template[i] for i in range(x)])
#----------------------------------------------------
#Game with 1/3 win chance
count = 0
for n in range(Nsim):
winner_found = False
#if this is flipped, A wins the game:
win_template = [True, True]
#if this is flipped, replay the game:
reset_template = [False, False]
x = len(win_template)
while (not winner_found):
flips = flip_coins(x)
#determine whether game ends
if (not match_template(flips, reset_template)):
winner_found = True
#determine whether A wins
if (match_template(flips, win_template)):
count += 1
print('Win proportion for game with 1/3 win chance:')
print(count/Nsim)
#----------------------------------------------------
#Game with 1/4 win chance
count = 0
for n in range(Nsim):
#if this is flipped, A wins the game:
win_template = [True, True]
x = len(win_template)
flips = flip_coins(x)
#determine whether A wins
if (match_template(flips, win_template)):
count += 1
print('Win proportion for game with 1/4 win chance:')
print(count/Nsim)
#----------------------------------------------------
#Game with 1/5 win chance
count = 0
for n in range(Nsim):
winner_found = False
#if this is flipped, A wins the game:
win_template = [True, True, True]
#if this is flipped, replay the game:
reset_templates = [[False, False, False],
[False, False, True],
[False, True, False]]
x = len(win_template)
while (not winner_found):
flips = flip_coins(x)
#determine whether game ends
if (not any([match_template(flips, t) for t in reset_templates])):
winner_found = True
#determine whether A wins
if (match_template(flips, win_template)):
count += 1
print('Win proportion for game with 1/5 win chance:')
print(count/Nsim)
|
#The Riddler Classic 2018-10-26: Organisational Obsession
#Monte-Carlo simulation
import random
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def draw(n, deck):
#This function returns a random hand of size n drawn from a deck
return random.sample(deck, n)
def same_colour(s1, s2):
#This function returns whether two suits are of the same colour
if (s1 == 'Clubs' and s2 == 'Spades'):
return True
elif (s1 == 'Spades' and s2 == 'Clubs'):
return True
elif (s1 == 'Hearts' and s2 == 'Diamonds'):
return True
elif (s1 == 'Diamonds' and s2 == 'Hearts'):
return True
return False
def is_organised(hand):
#This function determines whether a hand is organised
#use a dictionary to count how many of each suit are in the hand
suits = {'Clubs', 'Spades', 'Diamonds', 'Hearts'}
count_suits = dict()
for s in suits:
count_suits[s] = sum([c.suit == s for c in hand])
#go through the cards
i = 0
while (i < len(hand)):
#count sequentially all cards of the same suit
current_suit = hand[i].suit
j = i
while (j < len(hand) and hand[j].suit == current_suit):
j += 1
#if all the cards counted sequentially of the same suit
#are not all the cards of the same suit in the hand
if (j - i < count_suits[current_suit]):
return False
#reached end of the hand
if (j >= len(hand)):
return True
#if the next suit is of the same colour
if (same_colour(current_suit, hand[j].suit)):
#if there are two different colours in the hand
if ((count_suits['Clubs'] > 0 or count_suits['Spades'] > 0) and
(count_suits['Hearts'] > 0 or count_suits['Diamonds'] > 0)):
return False
i = j
return True
def get_moves(hand):
#This function returns a list of all the possible moves that can be made
#for a given hand
n = len(hand)
moves = []
for i in range(1, n + 1): #loop through block sizes
for j in range(n - i + 1): #loop through each block of that size
for k in range(n - i + 1): #loop through each position where that block can be placed
temp_hand = list.copy(hand)
#extract the block
block = temp_hand[j:(j + i)]
for c in block:
temp_hand.remove(c)
#move the block to the new position
move = temp_hand[0:k] + block + temp_hand[k:len(hand)]
#add to list of moves
moves.append(move)
return moves
def is_sortable(hand):
#This function returns whether a hand can be sorted
moves = get_moves(hand)
for m in moves:
if (is_organised(m)):
return True
return False
def print_cards(hand):
#This function prints the cards in a hand, useful for debugging
s = ''
for c in hand:
s += c.suit[0] + str(c.rank) + ','
print(s)
#------------------------------------------------------------------------
#Unit tests
suits1 = ['Clubs', 'Diamonds', 'Spades', 'Hearts']
suits2 = ['Clubs', 'Spades', 'Diamonds', 'Hearts']
deck1 = [Card(r, s) for s in suits1 for r in range(1, 14)]
deck2 = [Card(r, s) for s in suits2 for r in range(1, 14)]
deck3 = [Card(r, suits1[0]) for r in range(1, 7)]
deck4 = [Card(r, suits1[0]) for s in suits2[0:2] for r in range(1, 4)]
deck5 = [Card(r, suits1[0]) for s in suits2[2:4] for r in range(1, 4)]
hand1 = [Card(5, 'Diamonds'), Card(6, 'Hearts'), Card(3, 'Diamonds'),
Card(5, 'Hearts'), Card(2, 'Hearts'), Card(10, 'Hearts')]
hand2 = [Card(2, 'Spades'), Card(3, 'Clubs'), Card(5, 'Spades'),
Card(13, 'Clubs'), Card(1, 'Clubs'), Card(4, 'Clubs')]
hand3 = [Card(5, 'Diamonds'), Card(3, 'Diamonds'), Card(6, 'Hearts'),
Card(5, 'Hearts'), Card(2, 'Hearts'), Card(10, 'Hearts')]
assert is_organised(deck1) == True, "Unit test fail"
assert is_organised(deck2) == False, "Unit test fail"
assert is_organised(deck3) == True, "Unit test fail"
assert is_organised(deck4) == True, "Unit test fail"
assert is_organised(deck5) == True, "Unit test fail"
assert is_sortable(hand1) == True, "Unit test fail"
assert is_sortable(hand2) == True, "Unit test fail"
assert is_organised(hand3) == True, "Unit test fail"
#------------------------------------------------------------------------
#Main script
Nsim = 100000 #Number of simulations
count = 0
n = 6 #Hand size
for N in range(Nsim):
#draw cards
hand = draw(n, deck1)
#determine if sortable
if is_sortable(hand):
count += 1
#compute empirical probability
print(count/Nsim)
|
#The Riddler Classic 2016-11-18: The Lonesome King
#analytical computation and monte carlo simulation
import random
import math
#function returning the binomial coefficient, ie. n choose k
def binomcoeff(n, k):
return int(math.factorial(n)/math.factorial(k)/math.factorial(n - k))
#======================================================
#Simulation for the distribution of subjects chosen
N = 1 #Number of simulations
n = 6 #starting number of subjects
dist = [0]*n #initialise list to store frequency
for x in range(0, N):
subjects = [0]*n #binary list for subjects
for i in range(0, n):
#a subject is made 1 if it is chosen
subjects[random.randint(0, n - 1)] = 1
#the sum of the list gives the number of subjects chosen
#increment the frequency
dist[sum(subjects) - 1] += 1
##print empirical distribution
#print('1 chosen ... ' + str(n) + ' chosen')
#print([x/N for x in dist])
##print analytical distribution
#print([binomcoeff(n, i)*f(n, i)/(n**n) for i in range(1, n + 1)])
#======================================================
#Analytical probability for eventually 1 subject remaining
#function for number of ways to write a sequence n elements long where each of i elements must be used at least once
def f(n, i):
x = i**n
for j in range(i - 1, 0, -1):
x -= binomcoeff(i, j)*f(n, j)
return x
#function for probability that i subjects are chosen from n
def pr_cho(n, i):
return binomcoeff(n, i)*f(n, i)/(n**n)
#function for probability that eventually 1 subject remains from n starting
def pr_1rem(n):
dict_pr1rem = dict() #store previous values in dictionary
dict_pr1rem[2] = 0.5 #initial trivial value
for x in range(3, n + 1):
#compute probability of eventually 1 remaining for each starting number of subjects
p = pr_cho(x, x - 1)
for i in range(1, x - 1):
p += pr_cho(x, i)*dict_pr1rem[x - i]
#store in dictionary
dict_pr1rem[x] = p
return dict_pr1rem[n]
n = 8 #number of starting subjects
print(pr_1rem(n))
#========================================================
#Simulation for probability of eventually 1 subject remaining
N = 100000 #number of simulations
n = 8 #number of starting subjects
count = 0 #store number of times there are 1 subject remaining
for x in range(0, N):
num_subjects = n #starting number of subjects
while num_subjects > 1:
subjects = [0]*num_subjects
#randomly choose subjects
for i in range(0, num_subjects):
subjects[random.randint(0, num_subjects - 1)] = 1
#reduce number of subjects based on number chosen
num_subjects = num_subjects - sum(subjects)
if num_subjects == 1:
count += 1
print(count/N)
|
# The Riddler Classic 2020-09-18: Guess My Word
# https://fivethirtyeight.com/features/can-you-break-a-very-expensive-centrifuge/
# Monte-Carlo simulation and comparison with theoretical expectations
import math
import random
def expected_guesses(n):
#recursive function for expected number of guesses
if (n == 0):
return 0
elif (n == 1):
return 1
n1 = math.floor((n - 1)/2)
n2 = math.ceil((n - 1)/2)
return 1 + expected_guesses(n1)*n1/n + expected_guesses(n2)*n2/n
Nsim = 1000000 #number of simulations
n = 267751 #number of possible words to guess
t = [0]*Nsim
for N in range(Nsim):
c = 0 #count number of guesses
#random index of word to guess
x = random.randint(1, n)
lb = 1 #lower bound on index of word
ub = n #upper bound on index of word
m = n #number of elements between lb and ub (inclusive)
g = math.ceil(m/2) #initial guess
c += 1
while(g != x):
if (x < g): #before guess
ub = g - 1
elif (x > g): #after guess
lb = g + 1
#number of elements between lb and ub (inclusive)
m = ub - lb + 1
#binary search guess
g = lb + math.ceil(m/2) - 1
c += 1
t[N] = c
print('Simulation:')
print(sum(t)/Nsim)
print('Theoretical:')
print(expected_guesses(n))
|
"""
Authors: Sasha Friedrich
Amelia Sheppard
Date: 4/1/18
Description:
"""
import numpy as np
import csv
from util import * # data extraction functions
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
def lineplot(x, y, label):
"""
Make a line plot.
Parameters
--------------------
x -- list of doubles, x values
y -- list of doubles, y values
label -- string, label for legend
"""
xx = range(len(x))
plt.plot(xx, y, linestyle='-', linewidth=2, label=label)
plt.xticks(xx, x)
plt.show()
def plot_histogram(X, y, Xname, yname, bins=None) :
"""
Author: Prof. Wu
Plots histogram of values in X grouped by y.
Parameters
--------------------
X -- numpy array of shape (n,), feature values
y -- numpy array of shape (n,), target classes
Xname -- string, name of feature
yname -- string, name of target
"""
# set up data for plotting
targets = sorted(set(y))
data = []; labels = []
for target in targets :
features = [X[i] for i in xrange(len(y)) if y[i] == target]
data.append(features)
labels.append('%s = %s' % (yname, target))
# set up histogram bins
if bins==None:
features = set(X)
nfeatures = len(features)
test_range = range(int(math.floor(min(features))), int(math.ceil(max(features)))+1)
if nfeatures < 10 and sorted(features) == test_range:
bins = test_range + [test_range[-1] + 1] # add last bin
align = 'left'
else :
bins = 10
align = 'mid'
else:
align = 'left'
# plot
plt.figure()
n, bins, patches = plt.hist(data, bins=bins, align=align, alpha=0.5, label=labels)
plt.xlabel(Xname)
plt.ylabel('Frequency')
plt.legend() #plt.legend(loc='upper left')
plt.show()
def plot_scatter(X, y, Xnames, yname):
"""
Author: Prof. Wu
Plots scatter plot of values in X grouped by y.
Parameters
--------------------
X -- numpy array of shape (n,2), feature values
y -- numpy array of shape (n,), target classes
Xnames -- tuple of strings, names of features
yname -- string, name of target
"""
# plot
targets = sorted(set(y))
plt.figure()
for target in targets :
### ========== TODO : START ========== ###
xData=[]
yData=[]
for index in range(len(y)):
if y[index] == target:
xData.append(X[0][index])
yData.append(X[1][index])
plt.plot(xData,yData, '.', label = "survival = " + str(target))
### ========== TODO : END ========== ###
plt.autoscale(enable=True)
plt.xlabel(Xnames[0])
plt.ylabel(Xnames[1])
plt.legend()
plt.show()
def countWords(X, testWords):
""" counts the number of occurrences of particular words
Parameters
-----------
X - list of comments (strings), length n
Returns
-------
y - list of counts of occurences of words, length n
"""
y = []
for string in X:
testWordCount = 0
words = extract_words(string)
for testWord in testWords:
for word in words:
if testWord == word:
testWordCount+=1
y.append(testWordCount)
return y
def extract_words(input_string):
"""
Processes the input_string, separating it into "words" based on the presence
of spaces, and separating punctuation marks into their own words.
Parameters
--------------------
input_string -- string of characters
Returns
--------------------
words -- list of lowercase "words"
"""
for c in punctuation:
input_string = input_string.replace(c, ' ' + c + ' ')
return input_string.lower().split()
def extract_words_nolower(input_string):
"""
Processes the input_string, separating it into "words" based on the presence
of spaces, and separating punctuation marks into their own words.
Parameters
--------------------
input_string -- string of characters
Returns
--------------------
words -- list of lowercase "words"
"""
for c in punctuation:
input_string = input_string.replace(c, ' ' + c + ' ')
return input_string.split()
def split_comments(X):
"""
Parameters
--------------------
X -- list of comments
Return
--------------------
new_X -- list of comments where each comment is a list of words
"""
new_X = []
for comment in X:
new_X.append(extract_words_nolower(comment))
return new_X
def visualize_capitalization(X, y):
"""
Parameters
--------------------
X -- list of comments (list of comments)
y -- list of associated labels (toxic vs nontoxic)
Make a histogram of capitalization percentages for toxic vs nontoxic comments.
"""
#capitalizaiton percentage
cap_per = []
for comment in X:
stripped_comment = comment.replace(" ", "")
cap_count = 0
uppers = [l for l in stripped_comment if l.isupper()]
percentage = 1.0*len(uppers)/len(stripped_comment)
cap_per.append(percentage)
plot_histogram(cap_per, y, "Capitalization Percentage", "Toxicity")
def visualize_comment_length(X, y):
"""
Parameters
--------------------
X -- list of comments (list of comments)
y -- list of associated labels (toxic vs nontoxic)
Make a histogram of comment length for toxic vs nontoxic comments.
"""
#comment length
comment_length = []
for comment in X:
comment_length.append(len(comment))
plot_histogram(comment_length, y, "Comment Length", "Toxicity")
def main():
raw_data = load('../data/features_subsample.csv')
x,y=extract(raw_data) # x is list of comments, y is associated labels
swear_words = ['shit', 'fuck', 'damn', 'bitch', 'crap', 'piss', 'ass', 'asshole', 'bastard']
# swear_counts = np.asarray(countWords(x, swear_words))
# assert len(swear_counts) == len(y)
# plot_histogram(swear_counts, np.asarray(y), 'number of swear words', 'toxicity', bins = [0, 1, 2, 3, 4, 5,6,7])
sex_words = ['dick', 'suck', 'pussy', 'cunt', 'penis', 'balls', 'testicles', 'pubic', 'genitals', 'sex', 'fuck','sex']
counts = np.asarray(countWords(x, sex_words+swear_words))
plot_histogram(counts, np.asarray(y), 'number of swear/sex-related words', 'toxicity', bins = [0, 1, 2, 3, 4, 5,6,7])
if __name__ == "__main__":
main()
|
# In this lecture we'll cover the usage of the with statement.
# The with statement allows to close a file without using the close method.
# The with statement defines a block, which will close the file once left.
# In the block defined the variable file can be used
with open("18_Text_File.txt", 'a') as file:
file.write ("Line 4 \n")
#OTHER POSSIBILITY:
f = open('test.txt', 'w') # creiamo il file object
with f:
f.write('contenuto del file')
f.closed
# The file will be closed automatically.
#IT IS IMPORTANT FOR EXCEPTIONS!!!!
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
变量可以指向函数,函数名其实就是指向函数的变量
'''
# print abs(-111)
'''
高阶函数:能够接收函数作为参数的函数
demo:接收abs函数作为参数,定义一个函数,接收x,y,f三个参数,其中x.y是普通的数,f是函数
'''
def add(x,y,f):
return f(x)+f(y)
print add(-1,-22,abs)
|
age = int(input('enter your age\n'))
if age <=0:
print("invalid input for age.")
elif age <=1:
print("you are an infant.")
elif age <=12:
print("you're just a kid.")
elif age <=19:
print("you're a teenager.")
elif age <=45:
print("you are adult now.")
elif age <=59:
print("you're middle-aged.")
elif age <=120:
print("you're old.")
else:
print("you're too old to alive.")
|
names = ['john Doe','jane Doe','johny truk']
#change the first name in the last
names[0] = 'foo bar'
print ( 'names now :', names)
#Append some more names
names.append('Molly Mormon')
names.append('Joe bloggs')
print('Names finally:', names)
print('last names in the list: %s' % names[-1])
#you can join lists using str.join() method
joined_names = '\n'.join(names)
print('\nList of names:')
print(joined_names)
|
"""
https://www.hackerrank.com/challenges/grading/problem
"""
import math
def is_grade_enough(grade):
if rounded(grade) < 40:
return(False)
return(True)
def rounded(grade):
if next_multiple_of_five(grade) - grade < 3:
return(next_multiple_of_five(grade))
return(grade)
def next_multiple_of_five(grade):
if grade % 5 == 0:
return(grade)
next_multiple = math.ceil(grade/5)*5
return(next_multiple)
students_number = int(input().strip())
for i in range(students_number):
grade = int(input().strip())
if is_grade_enough(grade):
grade = rounded(grade)
print(grade)
|
import sys
class board:
def __init__(self, pieces):
self.pieces = pieces
def add_piece(self, piece):
self.pieces.append(piece)
def get_piece_on_coordinate(self, x, y):
"""
:param x: x value of coordinate
:param y: y value of coordinate
:return: piece on coordinate if no piece exists on this coordinate returns False
"""
for piece in self.pieces:
if piece.x == x and piece.y == y:
return piece
return False
def get_black_bishop_coordinates(self):
"""
:return: list which includes black bishop coordinates as tuple
"""
bishop_coordinates = []
for piece in self.pieces:
if piece.is_black and piece.acronym == "f":
bishop_coordinates.append((piece.x, piece.y))
return bishop_coordinates
def get_white_bishop_coordinates(self):
"""
:return: list which includes white bishop coordinates as tuple
"""
bishop_coordinates = []
for piece in self.pieces:
if not piece.is_black and piece.acronym == "f":
bishop_coordinates.append((piece.x, piece.y))
return bishop_coordinates
def is_any_piece_between(self, c1, c2):
"""
Since bishop cannot jump over other pieces to attack, we must sure whether any
piece exists between bishop and piece which is attacked by bishop
:param c1: coordinate of piece as tuple
:param c2: coordinate of bishop as tuple
:return: True if any other piece exists between them, False otherwise
"""
slope = (c2[1] - c1[1]) / (c2[0] - c1[0])
if slope == 1:
if c2[1] > c1[1]:
max_y = c2[1]
for i in range(1, max_y - c1[1]):
coordinate = (c1[0] + i, c1[1] + i)
if self.get_piece_on_coordinate(coordinate[0], coordinate[1]):
return True
else:
max_y = c1[1]
for i in range(1, max_y - c2[1]):
coordinate = (c2[0] + i, c2[1] + i)
if self.get_piece_on_coordinate(coordinate[0], coordinate[1]):
return True
elif slope == -1:
if c1[1] > c2[1]:
max_y = c1[1]
for i in range(1, max_y - c2[1]):
coordinate = (c1[0] + i, c1[1] - i)
if self.get_piece_on_coordinate(coordinate[0], coordinate[1]):
return True
else:
max_y = c2[1]
for i in range(1, max_y - c1[1]):
coordinate = (c2[0] + i, c2[1] - i)
if self.get_piece_on_coordinate(coordinate[0], coordinate[1]):
return True
return False
def calculate_score(self):
"""
:return: white's score and black's score
"""
white_score = 139.0
black_score = 139.0
white_bishops = self.get_white_bishop_coordinates()
black_bishops = self.get_black_bishop_coordinates()
for piece in self.pieces:
if piece.is_black:
if piece.acronym != "a":
attack_positions = piece.knight_attack_positions()
for pos in attack_positions:
i = self.get_piece_on_coordinate(pos[0], pos[1])
if i and i.acronym == "a" and not i.is_black:
black_score -= (piece.score / 2)
if piece.acronym != "f":
bishop_coordinate = piece.is_aligned_with_bishop(white_bishops)
if bishop_coordinate:
if not self.is_any_piece_between((piece.x, piece.y), bishop_coordinate):
black_score -= (piece.score / 2)
else:
if piece.acronym != "a":
attack_positions = piece.knight_attack_positions()
for pos in attack_positions:
i = self.get_piece_on_coordinate(pos[0], pos[1])
if i and i.acronym == "a" and i.is_black:
white_score -= (piece.score / 2)
if piece.acronym != "f":
bishop_coordinate = piece.is_aligned_with_bishop(black_bishops)
if bishop_coordinate:
if not self.is_any_piece_between((piece.x, piece.y), bishop_coordinate):
white_score -= (piece.score / 2)
return white_score, black_score
class piece:
"""
All pieces have a acronym, coordinate(x,y) and are belong to white or black.
"""
is_black = None
acronym = ""
x = 0
y = 0
def __init__(self, acr, x, y, is_black):
self.acronym = acr
self.x = x
self.y = y
self.is_black = is_black
def knight_attack_positions(self):
"""
:return: list of coordinate which are attackable positions by knight according to piece coordinate
"""
x = self.x
y = self.y
positions = [(x - 1, y - 2), (x - 2, y - 1),
(x + 1, y - 2), (x + 2, y - 1),
(x - 2, y + 1), (x - 1, y + 2),
(x + 1, y + 2), (x + 2, y + 1)]
for (i, j) in positions:
if i < 1 or i > 8 or j < 1 or j > 8:
positions = list(filter(lambda x: x[0] != i or x[1] != j, positions))
return positions
def is_aligned_with_bishop(self, bishop_coordinates):
"""
Since bishop can move crosswise only, slope of piece to bishop must be 1 or -1 to be aligned.
:param bishop_coordinates: list of coordinate tuples
:return: True if they are aligned, False otherwise
"""
bishop_coordinate1 = bishop_coordinates[0]
bishop_coordinate2 = bishop_coordinates[1]
if (bishop_coordinate1[0] - self.x) == 0:
return False
if (bishop_coordinate2[0] - self.x) == 0:
return False
slope1 = (bishop_coordinate1[1] - self.y) / (bishop_coordinate1[0] - self.x)
slope2 = (bishop_coordinate2[1] - self.y) / (bishop_coordinate2[0] - self.x)
if slope1 == 1 or slope1 == -1:
return bishop_coordinate1
elif slope2 == 1 or slope2 == -1:
return bishop_coordinate2
else:
return False
class p(piece):
"""
For "piyon" piece
"""
def __init__(self, acr, x, y, is_black):
self.score = 1.0
super().__init__(acr, x, y, is_black)
class a(piece):
"""
For "at" piece
"""
def __init__(self, acr, x, y, is_black):
self.score = 3.0
super().__init__(acr, x, y, is_black)
class f(piece):
"""
For "fil" piece
"""
def __init__(self, acr, x, y, is_black):
self.score = 3.0
super().__init__(acr, x, y, is_black)
class k(piece):
"""
For "kale" piece
"""
def __init__(self, acr, x, y, is_black):
self.score = 5.0
super().__init__(acr, x, y, is_black)
class v(piece):
"""
For "vezir" piece
"""
def __init__(self, acr, x, y, is_black):
self.score = 9.0
super().__init__(acr, x, y, is_black)
class s(piece):
"""
For "şah" piece
"""
def __init__(self, acr, x, y, is_black):
self.score = 100.0
super().__init__(acr, x, y, is_black)
def main():
"""
reads input file
create board and then adds all pieces to board.
:param input_path: string of input file's name
:return: -
"""
input_path = sys.argv[-1]
pieces = []
global board
board = board(pieces)
row_number = 8
with open(input_path, 'r') as data:
rows = data.readlines()
for row in rows:
row = row.split()
col_number = 1
for item in row:
if item == "xx":
pass
else:
if item == "ks":
new_piece = k("k", col_number, row_number, True)
elif item == "as":
new_piece = a("a", col_number, row_number, True)
elif item == "fs":
new_piece = f("f", col_number, row_number, True)
elif item == "vs":
new_piece = v("v", col_number, row_number, True)
elif item == "ss":
new_piece = s("s", col_number, row_number, True)
elif item == "ps":
new_piece = p("p", col_number, row_number, True)
elif item == "kb":
new_piece = k("k", col_number, row_number, False)
elif item == "ab":
new_piece = a("a", col_number, row_number, False)
elif item == "fb":
new_piece = f("f", col_number, row_number, False)
elif item == "vb":
new_piece = v("v", col_number, row_number, False)
elif item == "sb":
new_piece = s("s", col_number, row_number, False)
elif item == "pb":
new_piece = p("p", col_number, row_number, False)
board.add_piece(new_piece)
col_number = col_number + 1
row_number = row_number - 1
scores = board.calculate_score()
white_score = scores[0]
black_score = scores[1]
print("White's score is", white_score)
print("Black's score is", black_score)
return
if __name__ == '__main__':
main()
|
power = eval(input('Enter power : '))
number = 2**power
lastDigits = number%100
print('Power =',power)
print('Number =',number)
print('Last Two Digits =',lastDigits)
|
weightInKilograms = eval(input('Enter weight : '))
weightInPounds = weightInKilograms*2.2
print('There are',weightInPounds,'pounds in',weightInKilograms,'kilograms.')
|
fib1 = 1
fib2 = 1
fib = fib1+fib2
numberOfFib = eval(input('Enter Number of Elements In The Sequence : '))
print(fib1,fib2,fib,sep=',',end='')
for i in range(numberOfFib-3):
fib1 = fib2
fib2 = fib
fib = fib1+fib2
print(',',fib,sep='',end='')
# What is a user enters a number less than 3?
|
# Imagine we wanted to to display a --- a^n, where n is an real numbers.
# Ofcouse a*a*a*a*a*...*a would be tedious and combusome.
import math
for i in range(1,21):
print(i, pow(i,2),sep=' --- ')
|
exponent = eval(input('Enter power : '))
answer = pow(2,exponent)
digit = answer%10
print('Power =',exponent)
print('Number =',answer)
print('Last Digit =',digit)
|
def rozciagniecie(plansza, x, y):
list_of_x = range(-1,2)
list_of_y = range(-1,2)
for row in list_of_y:
for col in list_of_x:
ix = col
iy = row
while plansza[y][x] == ".":
x += ix
y += iy
return x, y
|
#Number game - Guess a number between 0 to 10
print("Guess a number between 0 to 10")
guess=0
high = 10
low =0
while(high >low):
guess +=1
guess = (high+low)/2
print("Is the number",guess)
while True:
answer = input("If the answer is right enter \n"
"Y for Yes\n"
"N for No")
if answer == 'Y' or answer =='y':
print("Our guess is right")
break
else:
high_or_low = input("Is the number high or low than my guess press \n"
"H if it is high\n"
"L if it is Low")
if(high_or_low == 'H' or high_or_low == 'h'):
guess = guess - 1
|
import string
START = 32
END = 126
def palindrome(input):
input = str(input)
input = input.lower()
input = input.replace(' ','')
if input == input[::-1]:
exclude = set(string.punctuation)
return ''.join(c for c in input if c not in exclude)
return None
def main():
DATA = ('Murder for a jar of red rum','12321','nope','abcbA',3443,'what','Never odd or even','Rats live on no evil star')
for input in DATA:
result = palindrome(input)
if result:
print(input," --> ",result)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
print("***** Cuanto sera este numero en minutos y hora *****")
num = int(input("Ingrese el numero:"))
print ("Horas:%d - Minutos:%d" % (num/60,num%60))
|
#!/usr/bin/env python
print("***** Una imagen vale mas que mil palabras *****")
word = input("Ingrese la palabra:")
print("Mil Veces: ")
print("%s "%(word) * 1000)
|
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __str__(self):
return f"{self.data}"
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_val(self, x):
'''Append value x at the end of the list'''
if not isinstance(x, Node):
x = Node(x)
if self.head is None:
self.head = x
else:
self.tail.next = x
self.tail = x
def __str__(self):
to_print = ""
curr = self.head
while curr is not None:
to_print += f"{curr.data}->"
curr = curr.next
if to_print:
return f"[{to_print[:-2]}]"
return "[]"
def add_to_start(self, x):
'''Add x to the start of the list' making it the head'''
if not isinstance(x, Node):
x = Node(x)
if self.head is None:
self.head = x
self.tail = x
else:
old_val = self.head
self.head = x
self.head.next = old_val
def search_val(self, x):
'''Return the indices where x was found'''
pass
def remove_val_by_index(self, x):
'''remove and return the value at the index x provided as parameter'''
pass
def length(self):
'''return the length of the list represented by the number of nodes'''
pass
def reverse_list_recur(self, current, previous):
'''Reverse the sequence of the node pointers in the linked list'''
pass
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node6 = Node(6)
my_list = SinglyLinkedList()
print(my_list)
my_list.append_val(node1)
my_list.append_val(node2)
my_list.append_val(node3)
my_list.append_val(node4)
my_list.append_val(node5)
my_list.append_val(node6)
print(my_list)
node7 = Node(10)
my_list.add_to_start(node7)
print(my_list)
|
# ## 1. Load MNIST Database
from keras.datasets import mnist
( x_train, y_train),( x_test, y_test ) = mnist.load_data()
# ## 2. Normalize the data
# rescale [ 0, 255] -> [ 0, 1 ]
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# 3. Encode categorical integer labels using a one-hot code
from keras.utils import np_utils
# print first ten (integer-valued) training labels
print('Integer-valued labels:')
print(y_train[:10])
print('\n\n\n')
# one-hot encode the labels
y_train = np_utils.to_categorical( y_train, 10 )
y_test = np_utils.to_categorical( y_test, 10 )
# print first ten (one-hot) training labels
print('One-hot labels:')
print(y_train[:10])
from keras.models import Sequential
from keras.layers import Dense, Flatten, Activation, Dropout
model = Sequential()
# turn the matrix to vector
model.add( Flatten( input_shape = x_train.shape[ 1: ] ) )
# two hidden layers
model.add( Dense( 512 , activation = 'relu' ) )
model.add( Dropout( 0.2 ) )
model.add( Dense( 512 , activation = 'relu' ) )
model.add( Dropout( 0.2 ))
# output layer
model.add( Dense( 10 ) )
model.add( Activation('softmax' ) )
model.summary()
# ## 5. Compile the model
model.compile( loss = 'categorical_crossentropy', optimizer = 'rmsprop', metircs = ['accuracy'])
# 6. Evaluate the model
score = model.evaluate( x_test, y_test, verbose = 0)
accuracy = 100 * score[ 1 ]
print( 'Test accuracy: %.4f%%' % accuracy )
# 7. Train the model
#
# Validation set: certain numbers of datas splited from the training set, used to evaluate the model after each epoch, in order not to be overfitting
from keras.callbacks import ModelCheckpoint
checkpointer = ModelCheckpoint( filepath = 'mnist.model.best.hdf5',
verbose = 1, save_best_only = True)
hist = model.fit( x_train, y_train, batch_size = 128, epochs=10,
validation_split = 0.2, callbacks = [checkpointer],
verbose = 1, shuffle = True)
# 8. Load the model with the best classification accuracy on the validation set
model.load_weights('mnist.model.best.hdf5')
# 9. Calculate the classification accuracy on the test set
score = model.evaluate( x_test, y_test, verbose=0)
accuracy = 100 * score[ 1 ]
print('Test accuracy: %.4f%%' %accuracy )
|
def pisano_numbers(n, m):
previous, current = 0, 1
pisano_numbers = [previous, current]
for i in range(6 * m):
previous, current = current, (previous + current) % m
pisano_numbers.append(current)
if previous == 0 and current == 1:
pisano_numbers = pisano_numbers[0:-2]
return pisano_numbers
break
n = int(input())
fibonacci_mod_10 = pisano_numbers(n, 10)
fibonacci_mod_10_sum = sum(fibonacci_mod_10)
fibonacci_mod_10_len = len(fibonacci_mod_10)
if n < fibonacci_mod_10_len:
print(sum(fibonacci_mod_10[:n + 1]) % 10)
else:
f = n // fibonacci_mod_10_len
n = n % fibonacci_mod_10_len
print((fibonacci_mod_10_sum + sum(fibonacci_mod_10[:n + 1])) % 10)
|
# Spencer Nettles
# CS246
# Calculator program will take exations and solve them
import math
# Finds Magnitude of Vector
def magVector():
Vx = float(input("Vx = "))
Vy = float(input("Vy = "))
mag = math.sqrt((Vx * Vx) + (Vy * Vy))
print("Magnitude of the vector = ", mag)
# Finds the angle the vector is at
def angleVector():
Vx = float(input("Vx = "))
Vy = float(input("Vy = "))
ang = math.atan(math.radians(Vy/Vx))
print("Angle of the vector = ", ang)
# Finds the x compnent of the vector
def findVx():
mag = float(input("Magnitude = "))
ang = float(input("Angle = "))
Vx = mag * math.cos(math.radians(ang))
print("Vx = ", Vx)
# Finds the y compnent of the vetor
def findVy():
mag = float(input("Magnitude = "))
ang = float(input("Angle = "))
Vy = mag * math.sin(math.radians(ang))
print("Vy = ", Vy)
# Finds the x compnent of the vector
# if the angle is on the y axis
def findVxYAxis():
mag = float(input("Magnitude = "))
ang = float(input("Angle = "))
Vx = mag * math.sin(math.radians(ang))
print("Vx from y axis = ", Vx)
# Finds the y compnent of the vector
# if the angle is on the y axis
def findVyYAxis():
mag = float(input("Magnitude = "))
ang = float(input("Angle = "))
Vy = mag * math.cos(math.radians(ang))
print("Vy from y axis = ", Vy)
def main():
print("Select One:")
print("1. Magnitude of vector")
print("2. Angle of Vector")
print("3. Find Vx")
print("4. Find Vy")
print("5. Find Vx from y axis")
print("6. Find Vy from y axis")
print("q. Quit")
choice = input()
while choice != "q":
if choice == "1":
magVector()
elif choice == "2":
angleVector()
elif choice == "3":
findVx()
elif choice == "4":
findVy()
elif choice == "5":
findVxYAxis()
elif choice == "6":
findVyYAxis()
choice = input()
if __name__ == "__main__":
main()
|
'''
密碼重設程式
password = 'a123456'
讓使用者重複輸入密碼
最多輸入3次
如果正確,就印出 "登入成功!"
如果不正確,就印出 "密碼錯誤! 還有__次機會!"
'''
password = 'a123456'
number = 0
left_chance = 3-number #剩於機會
while left_chance > 0:
user_pwd = input('請輸入密碼(最多3次): ')
number += 1
left_chance = 3 - number
if user_pwd == password:
print('登入成功')
break #逃出迴圈
else:
print('密碼錯誤!' )
if left_chance > 0:
print('還有', left_chance, '次機會')
else:
print('沒機會了,你要鎖帳號了啦! ')
|
https://www.hackerrank.com/challenges/find-angle/problem
Find Angle MBC
from math import *
ab, bc = [int(input()) for _ in range(2)]
print(str(int(degrees(atan2(ab,bc)) + 0.5))+'°')
|
ERROR: type should be string, got "https://www.hackerrank.com/challenges/write-a-function/problem\nWrite a function\n\ndef is_leap(year):\n leap = False\n \ndef is_leap(y):\n return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)\n \n return leap\n \n" |
https://www.hackerrank.com/challenges/merge-the-tools/problem
Merge the Tools!
def merge_the_tools(string, k):
for i in range(0, len(string), k):
output = ''
unique_letters = set()
for letter in string[i:i + k]:
if letter not in unique_letters:
output += letter
unique_letters.add(letter)
else:
pass
print(output)
|
ERROR: type should be string, got "https://www.hackerrank.com/challenges/swap-nodes-algo/problem\nSwap Nodes [Algo]\n\nimport os\nimport sys\nsys.setrecursionlimit(15000)\n\ntree = []\n\nclass Node:\n\n def __init__(self, value=None):\n self.value = value\n self.right = None\n self.left = None\n\n def __repr__(self):\n return \"Node:- {} Right - {} Left {}\".format(self.value, self.right, self.left)\n\ndef swap(root, l, q):\n if l % q == 0:\n root.left, root.right = root.right, root.left\n if root.left:\n swap(root.left, l + 1, q)\n if root.right:\n swap(root.right, l + 1, q)\n\n\ndef inorder(roots, inter_result):\n if roots:\n inorder(roots.left, inter_result)\n inter_result.append(roots.value)\n inorder(roots.right, inter_result)\n\n#\n# Complete the swapNodes function below.\n#\n\ndef swapNodes(indexes, queries):\n initial_root = Node(1)\n tree = [initial_root]\n for i in range(0, len(indexes)):\n root = tree.pop(0)\n left = indexes[i][0]\n right = indexes[i][1]\n if left != -1:\n root.left = Node(left)\n tree.append(root.left)\n\n if right != -1:\n root.right = Node(right)\n tree.append(root.right)\n result = []\n for query in queries:\n inter_result = []\n swap(initial_root, 1, query)\n inorder(initial_root, inter_result)\n result.append(inter_result)\n return result\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n indexes = []\n\n for _ in range(n):\n indexes.append(list(map(int, input().rstrip().split())))\n\n queries_count = int(input())\n\n queries = []\n\n for _ in range(queries_count):\n queries_item = int(input())\n queries.append(queries_item)\n\n result = swapNodes(indexes, queries)\n\n fptr.write('\\n'.join([' '.join(map(str, x)) for x in result]))\n fptr.write('\\n')\n\n fptr.close()\n \n" |
https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/problem
Binary Search Tree : Lowest Common Ancestor
# Enter your code here. Read input from STDIN. Print output to STDOUT
'''
class Node:
def __init__(self,info):
self.info = info
self.left = None
self.right = None
// this is a node of the tree , which contains info as data, left , right
'''
def lca(root, v1, v2):
#Enter your code here
smaller = min(v1, v2)
larger = max(v1, v2)
if smaller <= root.info and larger >= root.info:
# this means root is the lca since they are on different
# sides of the tree
return root
elif larger < root.info:
# both on left side, call recursively on left child
return lca(root.left, v1, v2)
else: # smaller > root.info
return lca(root.right, v1, v2)
|
https://www.hackerrank.com/challenges/any-or-all/problem
Any or All
n, l = int(input()), input().split()
a, b = [int(x) > 0 for x in l], [x == x[::-1] for x in l]
print(all(a) and any(b))
|
https://www.hackerrank.com/challenges/py-set-difference-operation/problem
Set .difference() Operation
n = int(input())
e_set = set(map(int, input().split()))
m = int(input())
f_set = set(map(int, input().split()))
print(len(e_set.difference(f_set)))
|
https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem
Insert a node at a specific position in a linked list
# Complete the insertNodeAtPosition function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def insertNodeAtPosition(head, data, position):
node = SinglyLinkedListNode(data)
if position == 0:
node.next = head
head = node
else:
# if not inserting at head, loop until the next node at the insert position
cur_node = head
next_node_pos = 1
while next_node_pos < position:
cur_node = cur_node.next
next_node_pos += 1
# once reach here, next_node_pos = position, so insert after the cur_node
node.next = cur_node.next
cur_node.next = node
return head
|
https://www.hackerrank.com/challenges/find-a-string/problem
Find a string
def count_substring(string, sub_string):
return (sum([1
for i in range(0, len(string) - len(sub_string) + 1)
if (string[i:(len(sub_string)+i)] == sub_string)]))
|
# task_1 - leap year and list of all leap years from 0 to 2018 and count their amount
def is_leap(year):
if year%4==0 and year%100!=0 or year%400==0:
return True
return False
years = [n for n in range(2019)]
leap_years_list = []
for year in years:
if is_leap(year):
print( year, 'is leap')
# task_2 - 2 lists: list1 = [0...100000] / 3, list2 = [0...100000] / 7 + find all not douplicated elements which are in both lists
list1 = [n for n in range (100000) if n%3==0]
list2 = [n for n in range (100000) if n%7==0]
list3 = set(list1).union(set(list2))
print(list3)
# task_3 - there is a list with not ordered nums, find second highest num in the list
list = [1, 5, 8, 2, 4, 9, 10, 3, 6, 7]
list.sort(reverse=True)
print('the second highest num in', list, 'is', list[1])
# task_4 - python = {2: 'Ivan', 17: 'Artem', 18: 'Sergey', 21: 'Antuan', 34: 'Anton', 35: 'Sergey', 37: 'Stepan', 43: 'Artem', 44: 'Antuan', 51: 'Sergey', 60: 'Antuan',
# 61: 'Sergey', 62: 'Stepan', 78: 'Artem', 79: 'Stepan', 82: 'Ivan', 90: 'Antuan', 94: 'Antuan', 95: 'Ivan'}
# js = {0: 'Antuan', 7: 'Sergey', 10: 'Anton', 16: 'Ivan', 17: 'Ivan', 23: 'Ivan', 33: 'Ivan',34: 'Antuan', 39: 'Ivan', 45: 'Artem', 47: 'Stepan', 58: 'Stepan',
# 66: 'Stepan', 67: 'Sergey', 71: 'Sergey', 73: 'Antuan', 87: 'Stepan', 94: 'Antuan', 96: 'Stepan'}
# find students who study both lang and one only
python = {2: 'Ivan', 17: 'Artem', 18: 'Sergey', 21: 'Antuan', 34: 'Anton', 35: 'Sergey', 37: 'Stepan', 43: 'Artem', 44: 'Antuan', 51: 'Sergey', 60: 'Antuan',
61: 'Sergey', 62: 'Stepan', 78: 'Artem', 79: 'Stepan', 82: 'Ivan', 90: 'Antuan', 94: 'Antuan', 95: 'Ivan'}
js = {0: 'Antuan', 7: 'Sergey', 10: 'Anton', 16: 'Ivan', 17: 'Ivan', 23: 'Ivan', 33: 'Ivan',34: 'Antuan', 39: 'Ivan', 45: 'Artem', 47: 'Stepan', 58: 'Stepan',
66: 'Stepan', 67: 'Sergey', 71: 'Sergey', 73: 'Antuan', 87: 'Stepan', 94: 'Antuan', 96: 'Stepan'}
#variant_1
both_courses = {x:python[x] for x in python if x in js}
print(both_courses)
#variant_2
intersection = dict(python.items() & js.items())
print(intersection)
# task_5 generators
# variant_1
def square_nums(nums):
for i in nums:
yield (i*i)
square_result = square_nums([1, 2, 3, 4, 5])
for n in square_result:
print (n)
#variant_2
square_result = (i*i for i in [1,2, 3, 4, 5])
print (square_result)
for n in square_result:
print (n)
|
# -- coding: utf-8 --
def add(a, b):
print "ADDING %d + %d" %(a, b)
return a + b
def substract(a, b):
print "SUBSTRACTING %d + %d" %(a, b)
return a - b
print "Let's do some math with just fuctions!"
age = add(30, 5)
height = substract(78, 4)
print "Age : %d, Height : %d" % (age, height)
|
#coding: gbk
#===========================================Core Function===========================================
#SelectionSort
def SelectionSort(A):
for i in range(0 , len(A) - 1): #For all A element
min = i #Record the minimum's cursor.Init by i self
for j in range(i + 1,len(A)): #For the remaining elements
if A[j] < A[min]: #if there is a smaller one than current min
min = j #Update it
A[i],A[min] = A[min],A[i] #Exchange the current i th element with the minimum element
#Invariant: A[0 ... j-1] keeps in order when 'for' begin
#Begin: j = 1 . A[0] is in order
#Keep: when quit from 'while': We get the i: key >= A[i] but key < A[i+1] and A[i+1] have copied to A[i+2]
# So we put key in A[i+1]. right after a[i]. which makes A[0 ... j-1] keeps invariant next time
#Final: When Sort ends. final j = len(A) which makes a[0...j-1] = A. i.e : A is sorted!
#Analysis:
# Worst Average Best Comment
#Compare: n(n+1)/2 - 1 +n-1 =
#Exchage: n(n-1)/2 nԪ1+...+n-1
#Time: O(n^2) O(n^2)
#Space: O(1) O(1) O(1)
#Stabiliry: True
#Feature: ֻʵǰα֮ǰԪء
#Comment: ҪĽԵĸȡҪıȽϴ=+Сn-1
# ÿһαȽʧܵ+nnԪزýбȽ-11
#===========================================Core Function===========================================
#===========================================Core Function===========================================
#InsertionSort
def InsertionSort(A):
for j in range(1,len(A)): #For all element in A
key = A[j] #Fetch the key
i = j - 1 #Begin from the element ahead of A[j]
while i >= 0 and key < A[i]: #while key is still small. A[i] is bigger
A[i+1] = A[i] #Put A[i] to A[i+1]
i = i -1 # i go ahead
A[i+1] = key #Boundary check: i = -1 . valid
#Invariant: A[0 ... j-1] keeps in order when 'for' begin
#Begin: j = 1 . A[0] is in order
#Keep: when quit from 'while': We get the i: key >= A[i] but key < A[i+1] and A[i+1] have copied to A[i+2]
# So we put key in A[i+1]. right after a[i]. which makes A[0 ... j-1] keeps invariant next time
#Final: When Sort ends. final j = len(A) which makes a[0...j-1] = A. i.e : A is sorted!
#Analysis:
# Worst Average Best Comment
#Compare: n(n+1)/2 - 1 +n-1 =
#Exchage: n(n-1)/2 nԪ1+...+n-1
#Time: O(n^2) O(n^2)
#Space: O(1) O(1) O(1)
#Stabiliry: True
#Feature: ֻʵǰα֮ǰԪء
#Comment: ҪĽԵĸȡҪıȽϴ=+Сn-1
# ÿһαȽʧܵ+nnԪزýбȽ-1
#===========================================Core Function===========================================
#===========================================Core Function===========================================
#MergeSort
def MergeSort(A):
pass
def Merge(A,p,q,r):
n1 = q - p + 1 #Array 1: p ... q
n2 = r - q #Array 1:
#Invariant: A[0 ... j-1] keeps in order when 'for' begin
#Begin: j = 1 . A[0] is in order
#Keep: when quit from 'while': We get the i: key >= A[i] but key < A[i+1] and A[i+1] have copied to A[i+2]
# So we put key in A[i+1]. right after a[i]. which makes A[0 ... j-1] keeps invariant next time
#Final: When Sort ends. final j = len(A) which makes a[0...j-1] = A. i.e : A is sorted!
#Analysis:
# Worst Average Best Comment
#Compare: n(n+1)/2 - 1 +n-1 =
#Exchage: n(n-1)/2 nԪ1+...+n-1
#Time: O(n^2) O(n^2)
#Space: O(1) O(1) O(1)
#Stabiliry: True
#Feature: ֻʵǰα֮ǰԪء
#Comment: ҪĽԵĸȡҪıȽϴ=+Сn-1
# ÿһαȽʧܵ+nnԪزýбȽ-1
#===========================================Core Function===========================================
|
raio = float(input("Digite o raio em cm: "))
area = 3.14 * (raio**2)
print("A área do círculo de raio " + str(raio) + "cm vale: " + str(area) + "cm2")
|
nA = int(input("A: "))
nB = int(input("B: "))
print("Resultado: " + str(nA + nB))
|
from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry("300x400+0+0")
root.resizable(0,0)
root.title("TIC TAC TOE")
#################################################################
i=1
data = StringVar()
data.set("Player 1")
x=0
p1=0
p2=0
p3=0
p4=0
p5=0
p6=0
p7=0
p8=0
p9=0
#############################################################
def btn1clicked():
global i
global p1
if (btn1 ["text"] == " ") and (i==1) :
btn1["text"] = "X"
i=2
p1 = 1
player()
win()
tie()
else:
if(btn1["text"]==" ")and(i==2):
btn1["text"] = "O"
i=1
p1 = 2
player()
win2()
tie()
def btn2clicked():
global i
global p2
if (btn2 ["text"] == " ") and (i==1) :
btn2["text"] = "X"
i=2
p2 = 1
player()
win()
tie()
else:
if(btn2["text"]==" ")and(i==2):
btn2["text"] = "O"
i=1
p2 = 2
player()
win2()
tie()
def btn3clicked():
global i
global p3
if (btn3 ["text"] == " ") and (i==1) :
btn3["text"] = "X"
i=2
p3 = 1
player()
win()
tie()
else:
if(btn3["text"]==" ")and(i==2):
btn3["text"] = "O"
i=1
p3 = 2
player()
win2()
tie()
def btn4clicked():
global i
global p4
if (btn4 ["text"] == " ") and (i==1) :
btn4["text"] = "X"
i=2
p4 = 1
player()
win()
tie()
else:
if(btn4["text"]==" ")and(i==2):
btn4["text"] = "O"
i=1
p4 = 2
player()
win2()
tie()
def btn5clicked():
global i
global p5
if (btn5 ["text"] == " ") and (i==1) :
btn5["text"] = "X"
i=2
p5 = 1
player()
win()
tie()
else:
if(btn5["text"]==" ")and(i==2):
btn5["text"] = "O"
i=1
p5 = 2
player()
win2()
tie()
def btn6clicked():
global i
global p6
if (btn6 ["text"] == " ") and (i==1) :
btn6["text"] = "X"
i=2
p6 = 1
player()
win()
tie()
else:
if(btn6["text"]==" ")and(i==2):
btn6["text"] = "O"
i=1
p6 = 2
player()
win2()
tie()
def btn7clicked():
global i
global p7
if (btn7 ["text"] == " ") and (i==1) :
btn7["text"] = "X"
i=2
p7 = 1
player()
win()
tie()
else:
if(btn7["text"]==" ")and(i==2):
btn7["text"] = "O"
i=1
p7 = 2
player()
win2()
tie()
def btn8clicked():
global i
global p8
if (btn8 ["text"] == " ") and (i==1) :
btn8["text"] = "X"
i=2
p8 = 1
player()
win()
tie()
else:
if(btn8["text"]==" ")and(i==2):
btn8["text"] = "O"
i=1
p8 = 2
player()
win2()
def btn9clicked():
global i
global p9
if (btn9 ["text"] == " ") and (i==1) :
btn9["text"] = "X"
i=2
p9 = 1
player()
win()
tie()
else:
if(btn9["text"]==" ")and(i==2):
btn9["text"] = "O"
i=1
p9 = 2
player()
win2()
tie()
def player():
global i
global data
global x
if((i == 1)):
data.set("Player 1")
x=x+1
else:
if((i==2)and (x<8)):
data.set("Player 2")
x=x+1
else:
data.set(" ")
def tie():
global p1
global p2
global p3
global p4
global p5
global p6
global p7
global p8
global p9
global i
if((p1!=0)and(p2!=0)and(p3!=0)and(p4!=0)and(p5!=0)and(p6!=0)and(p7!=0)and(p8!=0)and(p9!=0)):
messagebox.showinfo("Tie","It's a tie")
i=1
player()
reset()
clear()
def win():
global p1
global p2
global p3
global p4
global p5
global p6
global p7
global p8
global p9
global i
if(((p1==1)and(p2==1)and(p3==1))or((p4==1)and(p5==1)and(p6==1))or((p7==1)and(p8==1)and(p9==1))or((p1==1)and(p4==1)and(p7==1))or((p2==1)and(p5==1)and(p8==1))or((p3==1)and(p6==1)and(p9==1))or((p1==1)and(p5==1)and(p9==1))or((p3==1)and(p5==1)and(p7==1))):
#print("win 1")
messagebox.showinfo("Win","Player 1 wins")
clear()
i=1
player()
reset()
def win2():
global p1
global p2
global p3
global p4
global p5
global p6
global p7
global p8
global p9
global i
if(((p1==2)and(p2==2)and(p3==2))or((p4==2)and(p5==2)and(p6==2))or((p7==2)and(p8==2)and(p9==2))or((p1==2)and(p4==2)and(p7==2))or((p2==2)and(p5==2)and(p8==2))or((p3==2)and(p6==2)and(p9==2))or((p1==2)and(p5==2)and(p9==2))or((p3==2)and(p5==2)and(p7==2))):
messagebox.showinfo("Win","Player 2 wins")
clear()
i=2
player()
reset()
def clear():
btn1["text"]=" "
btn2["text"]=" "
btn3["text"]=" "
btn4["text"]=" "
btn5["text"]=" "
btn6["text"]=" "
btn7["text"]=" "
btn8["text"]=" "
btn9["text"]=" "
def reset():
global p1
global p2
global p3
global p4
global p5
global p6
global p7
global p8
global p9
global x
x=0
p1=0
p2=0
p3=0
p4=0
p5=0
p6=0
p7=0
p8=0
p9=0
#############################################################
btnrow1 = Frame(root)
btnrow1.pack(expand = TRUE, fill = "both")
btnrow2 = Frame(root)
btnrow2.pack(expand = TRUE, fill = "both")
btnrow3 = Frame(root)
btnrow3.pack(expand = TRUE, fill = "both")
btnrow4 = Frame(root)
btnrow4.pack(expand = TRUE, fill = "both")
btn1 = Button(btnrow1, text=" ", font= ("Verdana",10),command=btn1clicked)
btn1.pack(side = LEFT,expand=TRUE,fill="both")
btn2 = Button(btnrow1, text=" ", font= ("Verdana",10),command=btn2clicked)
btn2.pack(side = LEFT,expand=TRUE,fill="both")
btn3 = Button(btnrow1, text=" ", font= ("Verdana",10),command=btn3clicked)
btn3.pack(side = LEFT,expand=TRUE,fill="both")
btn4 = Button(btnrow2, text=" ", font= ("Verdana",10),command=btn4clicked)
btn4.pack(side = LEFT,expand=TRUE,fill="both")
btn5 = Button(btnrow2, text=" ", font= ("Verdana",10),command=btn5clicked)
btn5.pack(side = LEFT,expand=TRUE,fill="both")
btn6 = Button(btnrow2, text=" ", font= ("Verdana",10),command=btn6clicked)
btn6.pack(side = LEFT,expand=TRUE,fill="both")
btn7 = Button(btnrow3, text=" ", font= ("Verdana",10),command=btn7clicked)
btn7.pack(side = LEFT,expand=TRUE,fill="both")
btn8 = Button(btnrow3, text=" ", font= ("Verdana",10),command=btn8clicked)
btn8.pack(side = LEFT,expand=TRUE,fill="both")
btn9 = Button(btnrow3, text=" ", font= ("Verdana",10),command=btn9clicked)
btn9.pack(side = LEFT,expand=TRUE,fill="both")
lbl = Label(btnrow4, text = "Label", anchor=N, font = ("Verdana",18,"bold"),textvariable = data)
lbl.pack(expand=TRUE , fill="both")
root.mainloop()
|
#!/usr/bin/env python
# coding: latin-1
# Autor: kevin
# Date: 20160331
# Version: 1.0
#Thanks for origin Autor's Ingmar Stape
# This module is designed to control two motors with a L298N H-Bridge
# Use this module by creating an instance of the class. To do so call the Init function, then command as desired, e.g.
# import L298NHBridge
# HBridge = L298NHBridge.L298NHBridge()
# HBridge.Init()
# Import the libraries the class needs
import RPi.GPIO as io
import time
class HBridge(object):
def __init__(self, left_pin1, left_pin2, right_pin1, right_pin2, leftpwm_pin, rightpwm_pin):
io.setmode(io.BCM)
# Constant values
self.PWM_MAX = 100
# Here we configure the GPIO settings for the left and right motors spinning direction.
# It defines the four GPIO pins used as input on the L298 H-Bridge to set the motor mode (forward, reverse and stopp).
self.leftmotor_in1_pin = left_pin1
self.leftmotor_in2_pin = left_pin2
self.rightmotor_in1_pin = right_pin1
self.rightmotor_in2_pin = right_pin2
self.leftmotorpwm_pin = leftpwm_pin
self.rightmotorpwm_pin = rightpwm_pin
self.SetupGPIO()
self.leftmotorpwm = io.PWM(self.leftmotorpwm_pin,100)
self.rightmotorpwm = io.PWM(self.rightmotorpwm_pin,100)
self.InitPWM()
# Disable warning from GPIO
io.setwarnings(False)
def SetupGPIO(self):
io.setup(self.rightmotor_in1_pin, io.OUT)
io.setup(self.rightmotor_in2_pin, io.OUT)
io.setup(self.leftmotor_in1_pin, io.OUT)
io.setup(self.leftmotor_in2_pin, io.OUT)
io.setup(self.leftmotorpwm_pin, io.OUT)
io.setup(self.rightmotorpwm_pin, io.OUT)
def InitPWM(self):
# Here we configure the GPIO settings for the left and right motors spinning speed.
# It defines the two GPIO pins used as input on the L298 H-Bridge to set the motor speed with a PWM signal.
self.leftmotorpwm.start(0)
self.leftmotorpwm.ChangeDutyCycle(0)
self.rightmotorpwm.start(0)
self.rightmotorpwm.ChangeDutyCycle(0)
def resetMotorGPIO(self):
io.output(self.leftmotor_in1_pin, False)
io.output(self.leftmotor_in2_pin, False)
io.output(self.rightmotor_in1_pin, False)
io.output(self.rightmotor_in2_pin, False)
# setMotorMode()
# Sets the mode for the L298 H-Bridge which motor is in which mode.
# This is a short explanation for a better understanding:
# motor -> which motor is selected left motor or right motor
# mode -> mode explains what action should be performed by the H-Bridge
# setMotorMode(leftmotor, reverse) -> The left motor is called by a function and set into reverse mode
# setMotorMode(rightmotor, stopp) -> The right motor is called by a function and set into stopp mode
def setMotorMode(self, motor, mode):
if motor == "leftmotor":
if mode == "reverse":
io.output(self.leftmotor_in1_pin, True)
io.output(self.leftmotor_in2_pin, False)
elif mode == "forward":
io.output(self.leftmotor_in1_pin, False)
io.output(self.leftmotor_in2_pin, True)
else:
io.output(self.leftmotor_in1_pin, False)
io.output(self.leftmotor_in2_pin, False)
elif motor == "rightmotor":
if mode == "reverse":
io.output(self.rightmotor_in1_pin, False)
io.output(self.rightmotor_in2_pin, True)
elif mode == "forward":
io.output(self.rightmotor_in1_pin, True)
io.output(self.rightmotor_in2_pin, False)
else:
io.output(self.rightmotor_in1_pin, False)
io.output(self.rightmotor_in2_pin, False)
else:
self.resetMotorGPIO()
# SetMotorLeft(power)
# Sets the drive level for the left motor, from +1 (max) to -1 (min).
# This is a short explanation for a better understanding:
# SetMotorLeft(0) -> left motor is stopped
# SetMotorLeft(0.75) -> left motor moving forward at 75% power
# SetMotorLeft(-0.5) -> left motor moving reverse at 50% power
# SetMotorLeft(1) -> left motor moving forward at 100% power
def setMotorLeft(self, power):
if power < 0:
# Reverse mode for the left motor
self.setMotorMode("leftmotor", "reverse")
pwm = -int(self.PWM_MAX * power)
if pwm > self.PWM_MAX:
pwm = self.PWM_MAX
elif power > 0:
# Forward mode for the left motor
self.setMotorMode("leftmotor", "forward")
pwm = int(self.PWM_MAX * power)
if pwm > self.PWM_MAX:
pwm = self.PWM_MAX
else:
# Stopp mode for the left motor
self.setMotorMode("leftmotor", "stopp")
pwm = 0
# print "SetMotorLeft", pwm
self.leftmotorpwm.ChangeDutyCycle(pwm)
# SetMotorRight(power)
# Sets the drive level for the right motor, from +1 (max) to -1 (min).
# This is a short explanation for a better understanding:
# SetMotorRight(0) -> right motor is stopped
# SetMotorRight(0.75) -> right motor moving forward at 75% power
# SetMotorRight(-0.5) -> right motor moving reverse at 50% power
# SetMotorRight(1) -> right motor moving forward at 100% power
def setMotorRight(self, power):
if power < 0:
# Reverse mode for the right motor
self.setMotorMode("rightmotor", "reverse")
pwm = -int(self.PWM_MAX * power)
if pwm > self.PWM_MAX:
pwm = self.PWM_MAX
elif power > 0:
# Forward mode for the right motor
self.setMotorMode("rightmotor", "forward")
pwm = int(self.PWM_MAX * power)
if pwm > self.PWM_MAX:
pwm = self.PWM_MAX
else:
# Stopp mode for the right motor
self.setMotorMode("rightmotor", "stopp")
pwm = 0
#print "SetMotorRight", pwm
self.rightmotorpwm.ChangeDutyCycle(pwm)
# Program will clean up all GPIO settings and terminates
def exit(self):
self.resetMotorGPIO()
io.cleanup()
|
"""
Author : Gurpreet Singh
Date : 17 jan 2020
Purpose : To understand how to access the varible of one process to another using "Queue"
######################
Queue : FIFO (First in First out)
Two Method :
put : enqueue
get : dequeue
###############
Create Queue varible :
q = muliiprocessing.Queue()
"""
import time
import multiprocessing
def calc_square(numbers,q):
for i in numbers:
q.put(i*i) #Put the element in the End of queue
if __name__ == "__main__":
arr = [2, 5, 8, 9]
q = multiprocessing.Queue()
p1 = multiprocessing.Process(target=calc_square, args=(arr,q))
p1.start()
p1.join()
# when queue is empty it return "true" and condition valus
while q.empty() is False:
print(q.empty())
print(q.get())
"""
Difference bw Multiprocessing Queue and "Queue Module"
###################
import multiprocessing
q = muliprocessing.Queue()
{
Lives in shared memory
used to share data between processes
}
################
import queue
q = queue.Queue()
{
lives in in-process memeory
used to share data between thereads
}
"""
|
"""
Author : Gurpreet singh
Date 20 jan 2020
############# Basic cmd
[np.fxn : generic fxn]
1. check the type of numpy dimension : ndim
ex. a.ndim
2. itemsize : tell about the size of each elements
ex. a.itemsize
3. a.dtype : Tells about the type of datatype/ or used to initialize array with specific datatype
ex. [ dtype = np.int32 , dtype = np.float64, dtype = complex]
4. a.size : tells about the total no of elements
5. a.shape : tells about the no. of rows and coloums in array
6. np.zeros(shape) : initialize array with zeros with shape specified.
ex. one_matrix = np.ones((3,4)) #initialize with ones
7. np.arange() : similar to range in list
# arange fxn :, but returns an ndarray rather than a list.
8. np.linspace(1,5,20) : Returns `num` evenly spaced samples, calculated over the interval [`start`, `stop`].
9. a.reshape() : reshape to any dimensions
10. a.ravel() : flaten array : make any dimensional to one-dimensional array
##### Mathematical fxn
11. a.min() : returns minimum no in array
12. a.max() :
13. a.sum() : adding all the elements in the array
14. a.sum(axis=0) adding all the element in columns wise
15. a.sum(axis=1) adding all the element in row wise
16. np.sqrt() : calculate square root of each elements
17. np.std() : calculate standard devaiation
18. a.dot(b) : Matrix production of two array a and b
"""
import numpy as np
########## n dimensional numpy array
a = np.array([5,6,7]) #one dimensional numpy
print(a,type(a))
print("Value at Zero index : ",a[0])
# Two dimesinal array
a = np.array([ [1,2], [3,4], [5,6] ])
print(a,type(a))
print(f"#### {a.ndim} : Type of dimensional : ")
print(f"#### size of each item/elements :{a.itemsize} ")
print(f"#### Type of datatype :{a.dtype} ")
# Initialize array with specific data-type :
a = np.array([ [1,2], [3,4],[5,9] ], dtype=np.float64)
print(f"#### Type of datatype :{a.dtype} and itemsize : {a.itemsize} ")
print(a)
print(f"#### Total no of elements :{a.size} ")
print(f"#### No. of rows and coloums (row,colums) :{a.shape} ")
#initialize array with zero : 3 row and 4 coloms
zero_matrix = np.zeros((3,4))
print(zero_matrix,zero_matrix.dtype)
# initialize with one : aloong with changed datatype
one_matrix = np.ones((3,4),dtype=np.int32)
print(one_matrix,one_matrix.dtype)
# arange fxn :, but returns an ndarray rather than a list.
rang = np.arange(1,5,2)
print("arange fxn : ",rang)
#Generate linearly numbers bw specified numbers :
# Returns `num` evenly spaced samples, calculated over the interval [`start`, `stop`].
linear_sep = np.linspace(1,5,20)
# generate 10 numbers evenly spaced bw 1, 5
print(linear_sep)
# Reshape
print(f"### Befor Reshape : {a.shape}\n {a}" )
reshp = a.reshape(2,3)
print(f"### After Reshape of array :\n {reshp}")
reshp = a.reshape(6,1)
print(f" Six row one colums : {reshp}")
# flaten array : convert n-dimensinal to one-dimensional
# returns a new array : You have to caputre that array using varible
print(f"Flaten array a : {a.ravel()}")
#### Mathematical fxn
print(f"Minimum no in array : {a.min()}")
print(f"Maximum no in array : {a.max()}")
print(f"Addtion of all the elements in array : {a.sum()}")
# axis 0 : means column wise
# axis 1 : means row wise
print(a)
print(f"Addtion of elements :Column wise : {a.sum(axis=0)}")
print(f"Addtion of elements :Row wise : {a.sum(axis=1)}")
print(f"Square root : {np.sqrt(a)}")
print(f"Standard devation : {np.std(a)}")
a = np.array([ [ 1,2], [3,4] ])
b = np.array([ [ 5,6], [7,8] ])
print(a,"\n",b)
print(f"Addtion : {a+b}")
print(f"Subtraction : {a-b}")
print(f"Multiplication : {a*b}")
### Matrix production :
print(f"Matrix Production : \n{a.dot(b)}")
|
#骰子
from random import randint
class Die():
'''扔骰子的简单尝试'''
def __init__(self, sides):
self.sides = sides
def roll_die(self, times):
i = 0
while i < times:
print(randint(1, self.sides))
i += 1
num_one = Die(6)
num_one.roll_die(8)
|
# computes the gcd. taken from snappea
from functools import total_ordering
import re
def gcd(a, b):
a = abs(a)
b = abs(b)
if a == 0:
if b == 0: raise ValueError("gcd(0,0) undefined.")
else: return b
while 1:
b = b % a
if (b == 0): return a
a = a % b
if (a == 0): return b
# returns (gcd, a, b) where ap + bq = gcd. taken from snappea
def euclidean_algorithm(m, n):
# Given two long integers m and n, use the Euclidean algorithm to
# find integers a and b such that a*m + b*n = g.c.d.(m,n).
#
# Recall the Euclidean algorithm is to keep subtracting the
# smaller of {m, n} from the larger until one of them reaches
# zero. At that point the other will equal the g.c.d.
#
# As the algorithm progresses, we'll use the coefficients
# mm, mn, nm, and nn to express the current values of m and n
# in terms of the original values:
#
# current m = mm*(original m) + mn*(original n)
# current n = nm*(original m) + nn*(original n)
# Begin with a quick error check.
if m == 0 and n == 0 : raise ValueError("gcd(0,0) undefined.")
# Initially we have
#
# current m = 1 (original m) + 0 (original n)
# current n = 0 (original m) + 1 (original n)
mm = nn = 1
mn = nm = 0
# It will be convenient to work with nonnegative m and n.
if m < 0:
m = - m
mm = -1
if n < 0:
n = - n
nn = -1
while 1:
# If m is zero, then n is the g.c.d. and we're done.
if m == 0:
return(n, nm, nn)
# Let n = n % m, and adjust the coefficients nm and nn accordingly.
quotient = n // m
nm = nm - quotient * mm
nn = nn - quotient * mn
n = n - quotient * m
# If n is zero, then m is the g.c.d. and we're done.
if n == 0:
return(m, mm, mn)
# Let m = m % n, and adjust the coefficients mm and mn accordingly.
quotient = m // n
mm = mm - quotient * nm
mn = mn - quotient * nn
m = m - quotient * n
# We never reach this point.
# computes the lcm of the given list of numbers:
def lcm( a ):
cur_lcm = a[0]
for n in a[1 : ]:
cur_lcm = n * cur_lcm // gcd(n, cur_lcm)
return abs(cur_lcm)
# computes the continued fraction expansion of the given
# number p/q which must satisfy 0 < a/b < 1, a, b > 0
def positive_continued_fraction_expansion(a, b):
if not (0 < a < b): raise ValueError("must have 0 < a < b")
expansion = []
while a > 0:
# b = q a + r
q = b//a
r = b % a
expansion.append(q)
b, a = a, r
return expansion
# A fraction class
from types import *
@total_ordering
class frac:
# the fraction is stored as self.t/self.b where
# t and b are coprime and b > 0
#
# standard arithmatic and compareson ops implemented.
# can add, etc. fracs and integers
def __init__(self, p, q):
if (not isinstance(p, int)) or (not isinstance(q, int)):
raise TypeError
g = gcd(p, q)
if q == 0:
self.t, self.b = 1, 0
if q < 0:
self.t, self.b = -p//g, -q//g
else:
self.t, self.b = p//g, q//g
def copy(self):
return frac(self.t, self.b)
def __repr__(self):
if self.b == 1: return "%i" % self.t
return "%i/%i" % (self.t, self.b)
def __abs__(self):
return frac(abs(self.t), abs(self.b) )
def __add__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
return frac(self.t*o.b + self.b*o.t, self.b*o.b)
def __radd__(self, o):
return self.__add__(o)
def __sub__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
return frac(self.t*o.b - self.b*o.t, self.b*o.b)
def __rsub__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
return frac(o.t*self.b - o.b*self.t, self.b*o.b)
def __mul__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
return frac(self.t*o.t , self.b*o.b)
def __rmul__(self, o):
return self.__mul__(o)
def __truediv__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac): raise TypeError
if o == 0: raise ZeroDivisionError
try:
p, q = self.t*o.b , self.b*o.t
return frac( p, q )
except OverflowError:
gt = gcd(self.t, o.t)
gb = gcd(self.b, o.b)
return frac( (self.t//gt)*(o.b//gb) , (self.b//gb)*(o.t//gt))
def __neg__(self):
return frac(-self.t, self.b)
def __bool__(self):
return self.t != 0
def __eq__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac):
raise TypeError
return self.t*o.b == self.b*o.t
def __lt__(self, o):
if isinstance(o, int):
o = frac(o, 1)
if not isinstance(o, frac):
raise TypeError
return self.t*o.b < self.b*o.t
def string_to_frac(s):
data = re.match("([+-]{0,1}\d+)/([+-]{0,1}\d+)$", s)
if not data:
data = re.match("[+-]{0,1}\d+$", s)
if data:
return frac(int(s), 1)
else:
raise ValueError("need something of form a/b, a and b integers")
p, q = map(int, data.groups())
return frac(p, q)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/1/24 22:29
@annotation = ''
"""
import numpy as np
import pandas as pd
"""
自定义函数 有点像map
"""
s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
def add3(x):
return x + 3
if False:
print s1.apply(add3)
"""
applymap()
pandas series 即 DataFrame 新列
apply() 针对每一列
"""
df = pd.DataFrame({
'a': [1, 2, 3],
'b': [10, 20, 30],
'c': [5, 10, 15]
})
def add_one(x):
return x + 1
def get_second_max(column):
return column.sort_values(ascending=False).iloc[1]
if False:
print df.applymap(add_one)
print df.apply(np.max)
print df.apply(get_second_max)
grades_df = pd.DataFrame(
data={'exam1': [43, 81, 78, 75, 89, 70, 91, 65, 98, 87],
'exam2': [24, 63, 56, 56, 67, 51, 79, 46, 72, 60]},
index=['Andre', 'Barry', 'Chris', 'Dan', 'Emilio',
'Fred', 'Greta', 'Humbert', 'Ivan', 'James']
)
def std_cloumn():
print grades_df.mean(axis=0) == grades_df.mean(axis='index')
return (grades_df - grades_df.mean(axis='index')) / grades_df.std()
def std_row():
print grades_df.mean(axis=1) == grades_df.mean(axis='columns')
return (grades_df.sub(grades_df.mean(axis=1), axis=0)).div(grades_df.std(axis=1), axis=0)
"""
DataFrame Series 按照列相加 没有对应的列名columns就NaN
Series 的index 对应 DataFrame的列名
"""
if False:
s = pd.Series([1, 2, 3, 4], index=['b', 'a', 'c', 'd'])
df = pd.DataFrame({
'a': [10, 20, 30, 40],
'b': [50, 60, 70, 80],
'c': [90, 100, 110, 120],
'd': [130, 140, 150, 160]
})
print df
print '' # Create a blank line between outputs
print df + s
if False:
s = pd.Series([1, 2, 3, 4])
df = pd.DataFrame({
'a': [10, 20, 30, 40],
'b': [50, 60, 70, 80],
'c': [90, 100, 110, 120],
'd': [130, 140, 150, 160]
})
print df
print '' # Create a blank line between outputs
print df + s
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/6/18 14:27
@annotation = ''
"""
"""
文字信息 转化为数字
"""
"""
Dealing with categorical features in Python
● scikit-learn: OneHotEncoder()
● pandas: get_dummies()
"""
"""
In [3]: df_origin = pd.get_dummies(df)
In [4]: print(df_origin.head())
mpg displ hp weight accel size origin_Asia origin_Europe \
0 18.0 250.0 88 3139 14.5 15.0 0 0
1 9.0 304.0 193 4732 18.5 20.0 0 0
2 36.1 91.0 60 1800 16.4 10.0 1 0
3 18.5 250.0 98 3525 19.0 15.0 0 0
4 34.3 97.0 78 2188 15.8 10.0 0 1
"""
"""
Using the mean of the non-missing entries
In [1]: from sklearn.preprocessing import Imputer
In [2]: imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
In [3]: imp.fit(X)
In [4]: X = imp.transform(X)
"""
"""
Why scale your data?
● Many models use some form of distance to inform them
● Features on larger scales can unduly influence the model
● Example: k-NN uses distance explicitly when making predictions
● We want features to be on a similar scale
● Normalizing (or scaling and centering)
Ways to normalize your data
● Standardization: Subtract the mean and divide by variance
● All features are centered around zero and have variance one
● Can also subtract the minimum and divide by the range
● Minimum zero and maximum one
● Can also normalize so the data ranges from -1 to +1
● See scikit-learn docs for further details
"""
"""
In [2]: from sklearn.preprocessing import scale
In [3]: X_scaled = scale(X)
In [4]: np.mean(X), np.std(X)
Out[4]: (8.13421922452, 16.7265339794)
In [5]: np.mean(X_scaled), np.std(X_scaled)
Out[5]: (2.54662653149e-15, 1.0)
"""
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/1/24 21:54
@annotation = ''
"""
import numpy as np
# Subway ridership for 5 stations on 10 different days
ridership = np.array([
[0, 0, 2, 5, 0],
[1478, 3877, 3674, 2328, 2539],
[1613, 4088, 3991, 6461, 2691],
[1560, 3392, 3826, 4787, 2613],
[1608, 4802, 3932, 4477, 2705],
[1576, 3933, 3909, 4979, 2685],
[95, 229, 255, 496, 201],
[2, 0, 1, 27, 0],
[1438, 3785, 3589, 4174, 2215],
[1342, 4043, 4009, 4665, 3033]
])
# Change False to True for each block of code to see what it does
# Accessing elements
if False:
# print ridership[1, 3] == ridership[1][3]
# print ridership[1:3, 3:5]
print ridership[1, :]
# 按序取行列
print ridership[[1, 5, 7, 2]][:, [3, 1, 2, 0]]
# Vectorized operations on rows or columns
if False:
print ridership[0,]
print ridership[1, ...]
print ridership[..., 0]
print ridership[:, 1]
# Vectorized operations on entire arrays
if False:
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
print a + b
a = np.array([1, 2, 3])
b = np.array([1, 1, 1])
print a > b
def mean_riders_for_max_station(ridership):
max_station = ridership[0, :].argmax()
print max_station
mean_for_max = ridership[:, max_station].mean()
overall_mean = ridership.mean()
return (overall_mean, mean_for_max)
"""
轴 竖0
"""
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print a.shape
if False:
print a
print a.sum()
print a.sum(axis=0)
print a.sum(axis=1)
if True:
# 列
print a[:, 0]
print a[:, -1]
# 行
print a[0, :]
print a[-1, :]
print a[-1, 1]
print a[0, 1]
print a[0]
print a[0][1]
print(a[:2, :])
if False:
print np.mean(a[0])
print a[2]
print np.square(a)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/1/24 20:55
@annotation = ''
"""
import pandas as pd
a = pd.Series([1, 2, 3, 4])
# Accessing elements and slicing
if False:
for country_life_expectancy in a:
print 'Examining life expectancy {}'.format(country_life_expectancy) # Pandas functions
# if False:
# print a[0]
# print a[3:6]
# print a.mean()
# print a.std()
# print a.max()
# print a.sum()
if False:
a = pd.Series([1, 2, 3, 4])
c = pd.Series([1, 2, 3, 4], index=["a", "b", "c", "d"])
b = pd.Series([1, 2, 1, 2])
print a.values
print a.index
print a + b
print a * 2
print a >= 3
print a[a >= 3]
if False:
d = pd.Series({
"a": 1,
"b": 2,
})
print d
# def variable_correlation(variable1, variable2):
# both_above = (variable1 > variable1.mean()) & (variable2 > variable2.mean())
# both_below = (variable1 < variable1.mean()) & (variable2 < variable2.mean())
#
# num_same_direction = (both_above | both_below).sum()
# num_different_direction = len(variable1) - num_same_direction
#
# return (num_same_direction, num_different_direction)
# print variable_correlation(life_expectancy, gdp)
"""
"""
entries_and_exits = pd.DataFrame({
'ENTRIESn': [3144312, 3144335, 3144353, 3144424, 3144594,
3144808, 3144895, 3144905, 3144941, 3145094],
'EXITSn': [1088151, 1088159, 1088177, 1088231, 1088275,
1088317, 1088328, 1088331, 1088420, 1088753]
})
def get_hourly_entries_and_exits(entries_and_exits):
print (entries_and_exits - entries_and_exits.shift(1)).dropna()
# get_hourly_entries_and_exits(entries_and_exits)
|
"""
OOP implementation
"""
import reprlib
import itertools
import typing as typ
from treasure_hunt.utils import list_to_str
class SearchForTreasurePath:
"""
Object-oriented implementation of treasure search
"""
__slots__ = ('_treasure_map', '_curr_row', '_curr_col')
def __init__(self, treasure_map: typ.Tuple[typ.Tuple[int, ...], ...],
curr_i: int = 1, curr_j: int = 1):
"""
Create new :class:`SearchForTreasurePath`
:param treasure_map: treasure map input
"""
self.treasure_map = treasure_map
self._curr_row = curr_i
self._curr_col = curr_j
@property
def treasure_map(self):
return self._treasure_map
@treasure_map.setter
def treasure_map(self, treasure_map: typ.Tuple[typ.Tuple[int, ...], ...]) -> None:
"""
Set treasure map for the class
:param treasure_map: treasure map input
:return:
:raise ValueError: if treasure map format is not valid
"""
if not treasure_map:
raise ValueError('Got empty value')
if not isinstance(treasure_map, (list, tuple)):
raise ValueError(f'Treasure map should be list or tuple instance, '
f'got {type(treasure_map)} instead')
if not all(isinstance(row, (list, tuple))
and len(row) == len(treasure_map)
for row in treasure_map):
raise ValueError(f'The treasure map should be 2D array '
f'{len(treasure_map)}x{len(treasure_map)}')
self._treasure_map = treasure_map
def _get_next_row_and_col_nums(self) -> typ.Tuple[int, int]:
"""
Get next path cell containing the next clue
:return: next row and next column address
"""
return divmod(self.treasure_map[self._curr_row - 1][self._curr_col - 1], 10)
def __call__(self) -> typ.List[int]:
"""
Implementation of treasure search
:return: treasure path
:raise ValueError: if loops found in the treasure map input
"""
res = list()
max_loop_count = len(self._treasure_map) * len(self._treasure_map)
for i in itertools.count():
if i > max_loop_count:
raise ValueError('Loop found in the treasure map input')
res.append(self._curr_row * 10 + self._curr_col)
next_row, next_col = self._get_next_row_and_col_nums()
if (self._curr_row, self._curr_col) == (next_row, next_col):
break
self._curr_row, self._curr_col = next_row, next_col
return res
def __repr__(self):
return '<SearchForTreasurePath {}>'.format(reprlib.repr(self.treasure_map))
def find_treasure(treasure_map: typ.Tuple[typ.Tuple[int, ...], ...]) -> str:
"""
Find the treasure path
:param treasure_map: treasure map input
:return: treasure path
"""
treasure_path = SearchForTreasurePath(treasure_map)()
return list_to_str(treasure_path)
|
def factorial(n):
if n < 0:
print("Factorials do not exist below zero")
return -1
elif (n == 0) or (n == 1):
return 1
elif n > 1:
product=1
for x in range(2, n+1):
product=product*x
return product
|
'''Faça um programa que leia algo pelo teclado e mostre
na tela o seu tipo primitivo e todas as informações
possíveis sobre ele.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO04\033[m iniciado.')
print('=' * 50)
info = input('Digite \033[4malgo\033[m: ')
print(info.isalnum())
print(info.isalpha())
print(info.isdecimal())
print(info.islower())
print(info.isnumeric())
print(info.isupper())
print(info.istitle())
print('=' * 50)
print('Fim do programa.')
|
'''Faça um programa que leia um número inteiro e diga
se ele é ou não um número primo.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO52\033[m iniciado.')
print('=' * 50)
num = int(input('Digite um número: '))
aux = 0
for cont in range(1, (num + 1)):
# num % cont
if (num % cont == 0):
aux += 1
#esquema de contagem de quantas vezes o número foi múltiplo de alguém
if aux > 2:
print('\033[35m{}\033[m não é um número primo.'.format(num))
else:
print('\033[35m{}\033[m é um número primo.'.format(num))
print('=' * 50)
print('Fim do programa.')
|
'''Refaça o DESAFIO09, mostrando a tabuada de um número
que o usuário escolher, só que agora utilizando um
laço for.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO49\033[m iniciado.')
print('=' * 50)
num = int(input('Digite um número: '))
print('_' * 50)
print(f'\033[1mTabuada do {num}\033[m')
for i in range(1, 11):
print('\033[36m{}\033[m x {} = \033[36m{}\033[m'.format(i, num, (i * num)))
print('=' * 50)
print('Fim do programa.')
|
'''Faça um programa que leia a largura e a altura de uma parede
em metros, calcule a sua área e a quantidade de tinta
necessária para pintá-la, sabendo que cada litro de tinta
pinta uma área de 2m².'''
print('=' * 50)
print(('' * 10), 'Programa \033[1;4mDESAFIO11\033[m iniciado.')
print('=' * 50)
largura = float(input('Digite a \033[4mlargura\033[m da parede: '))
altura = float(input('Digite a \033[4maltura\033[m da parede: '))
area = largura * altura
tinta = area * 0.5
print('_' * 50)
print('A parede tem \033[31m{}\033[m\033[33mm²\033[m. '
'Serão necessários \033[31m{}\033[m \033[33mlitros\033[m '
'de tinta para pintar a parede.'.format(area, tinta))
print('=' * 50)
print('Fim do programa.')
|
'''Faça um programa que mostre a tabuada de vários
números, um de cada vez, para cada valor digitado pelo
usuário. O programa será interrompido quando o número
solicitado for negativo.'''
print('=' * 50)
print('Programa \033[4mDESAFIO67\033[m iniciado. Digite um \033[31mnúmero negativo\033[m para \033[31msair\033[m.')
print('=' * 50)
resposta = str(input('Você quer ver a tabuada de algum número? \033[31m[S/N]\033[m\n')).upper()
while resposta == 'S':
num = 1
while num > 0:
print('_' * 50)
print('\033[4;31mDigite um número negativo para sair.\033[m')
num = int(input('Digite um número: '))
if num < 0:
break
else:
print(f'Tabuada do \033[36m{num}\033[m.')
for cont in range(1,11):
print(f'\033[36m{cont} x {num}\033[m = \033[33m{cont * num}\033[m')
print('_' * 50)
resposta = str(input('Você deseja continuar?\033[31m[S/N]\033[m\n')).upper()
print('=' * 50)
print('Programa encerrado.')
|
'''
Crie um programa que leia nome e duas notas de vários
alunos e guarde tudo em uma lista composta. No final,
mostre um boletim contendo a média de cada um e permita
que o usuário possa mostrar as notas de cada aluno
individualmente.
'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO89\033[m iniciado.')
print('=' * 50)
lista_notas = list()
lista_tudo = list()
lista_tudo2 = list()
resposta = 'S'
cont = 0
while resposta == 'S':
nome = str(input('Digite o nome do aluno: '))
nota1 = float(input('Digite a nota 1: '))
nota2 = float(input('Digite a nota 2: '))
cont += 1
lista_notas.append(nota1)
lista_notas.append(nota2)
lista_tudo.append(nome)
lista_tudo.append(lista_notas[:])
lista_tudo2.append(lista_tudo[:])
lista_notas.clear()
lista_tudo.clear()
resposta = str(input('Deseja continuar? [S/N]\n')).upper()
n1 = 0
n2 = 1
print('NOME', (' ' * 36), 'N1 N2 | MEDIA')
while n1 < cont:
aux1 = lista_tudo2[n1][0]
aux2 = len(aux1)
aux3 = lista_tudo2[n1][1][0]
aux4 = lista_tudo2[n1][1][1]
media = (aux3 + aux4) / 2
print(f'{lista_tudo2[n1][0]}', ('_' * (40 - aux2)), lista_tudo2[n1][1][0], '+', lista_tudo2[n1][1][1], '=', media)
n1 += 1
print('=' * 50)
print('Fim do programa.')
|
'''Crie um programa que tenha uma tupla única com nomes
de produtos e seus respectivos preços na sequência. No
final, mostre uma listagem de preços, organizando os
dados em forma tabular.'''
print('=' * 50)
print(' ' * 10, 'Programa \033[1;4mDESAFIO76\033[m iniciado.')
print('=' * 50)
print('Lista de itens:')
#Lista com nomes e preços
produtos = ('Batata', 50.00, 'Morango', 20.00, 'Pêssego', 35.00, 'Refrigerante', 5.00, 'Esfihas', 0.50)
aux = 40 - len(produtos)
#print(produtos, '-' * aux)
#PRODUTO.................R$ 10.00
#nome + (len(produto) - (qntde de pontos) + R$ produtos[cont]
aux2 = len(produtos)
cont1 = 0
cont2 = 1
while cont1 <= aux2:
print(produtos[cont1], ('.' * (20-len(produtos[cont1]))), f'\033[33mR$ {produtos[cont2]}\033[m')
cont1 += 2
cont2 += 2
if cont1 >= aux2 and cont2 > aux2:
break
print('=' * 50)
print('Fim do programa.')
|
'''Faça um programa que leia uma frase pelo teclado e mostre:
- Quantas vezes aparece a letra "A"
- Em que posição ela aparece a primeira vez
- Em que posição ela aparece a última vez'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO26\033[m iniciado.')
print('=' * 50)
frase = str(input('Digite uma frase: ')).upper()
#utilizei a função upper() para considerar todas as letras como A maiúsculo
cont = frase.count('A')
print('A letra \033[35m"A"\033[m aparece \033[35m',
(frase.count('A')), '\033[mvez(es).' )
print('A primeira letra \033[35m"A"\033[m aparece na '
'posição \033[35m', frase.find('A'), '\033[m')
print('A última letra \033[35m"A"\033[m aparece na '
'posição \033[35m', frase.rfind('A'), '\033[m')
print('=' * 50)
print('Fim do programa.')
|
'''
Faça um programa que leia o nome e peso de várias pessoas,
guardando tudo em uma lista. No final, mostre:
A) quantas pessoas foram cadastradas
B) uma listagem com as pessoas mais pesadas
C) uma listagem com as pessoas mais leves
'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO84\033[m iniciado.')
print('=' * 50)
lista_tudo = list()
lista_pesadas = list()
lista_leves = list()
cont = 0
resposta = 'S'
while resposta == 'S':
lista_tudo.append(str(input('Nome: ')))
lista_tudo.append(float(input('Peso: ')))
if cont == 0:
lista_pesadas.append(lista_tudo[0])
lista_pesadas.append(lista_tudo[1])
lista_leves.append(lista_tudo[0])
lista_leves.append(lista_tudo[1])
lista_tudo.clear()
else:
if lista_tudo[1] == lista_pesadas[1]:
lista_pesadas.append(lista_tudo[0])
lista_pesadas.append(lista_tudo[1])
lista_tudo.clear()
elif lista_tudo[1] > lista_pesadas[1]:
lista_pesadas.clear()
lista_pesadas.append(lista_tudo[0])
lista_pesadas.append(lista_tudo[1])
lista_tudo.clear()
elif lista_tudo[1] == lista_leves[1]:
lista_leves.append(lista_tudo[0])
lista_leves.append(lista_tudo[1])
lista_tudo.clear()
elif lista_tudo[1] < lista_leves[1]:
lista_leves.clear()
lista_leves.append(lista_tudo[0])
lista_leves.append(lista_tudo[1])
lista_tudo.clear()
cont += 1
resposta = str(input('Deseja continuar [S/N]:\n')).upper()
print('_' * 50)
print(f'Quantidade de pessoas cadastradas: \033[33m{cont}\033[m')
print(f'Lista das pessoas mais pesadas: \033[31m{lista_pesadas}\033[m')
print(f'Lista das pessoas mais leves: \033[32m{lista_leves}\033[m')
print('=' * 50)
print('Fim do programa.')
|
'''Faça um programa que leia o peso de cinco pessoas.
No final, mostre qual foi o maior e o menor peso lidos.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO55\033[m iniciado.')
print('=' * 50)
print('Digite o peso de 5 pessoas:')
for cont in range(1, 6):
peso = float(input('Peso da pessoa {} = '.format(cont)))
if cont == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print('_' * 50)
print('O maior peso é: \033[1;31m{:.2f}\033[m'.format(maior))
print('O menor peso é: \033[1;32m{:.2f}\033[m'.format(menor))
# INSERIR CONDICIONAIS DENTRO DO LAÇO. INSERIR EXCEÇÃO.
print('=' * 50)
print('Fim do programa.')
|
'''Escreva um programa que pergunte o salário de um funcionário
e calcule o valor do seu aumento.
Para salários superiores a R$ 1.250,00, calcule um aumento
de 10%.
Para os inferiores ou iguais, o aumento é de 15%.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO34\033[m iniciado.')
print('=' * 50)
salario = float(input('Digite o salário: '))
if salario > 1250:
salario = salario + (salario * 0.10)
print('Você recebeu um \033[1;32maumento de 10%!\033[m '
'Seu novo salário é: \033[4;33mR$ {:.2f}.\033[m'
.format(salario))
else:
salario = salario + (salario * 0.15)
print('Você recebeu um \033[1;32maumento de 15%!\033[m '
'Seu novo salário é: \033[4;33mR$ {:.2f}\033[m.'
.format(salario))
print('=' * 50)
print('Fim do programa.')
|
'''Escreva um programa que leia dois números inteiros e
compare-os, mostrando na tela alguma destas mensagens:
- O primeiro valor é maior
- O segundo valor é maior
- Não existe valor maior, os dois são iguais'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO38\033[m iniciado.')
print('=' * 50)
print('Digite dois números \033[1minteiros\033[m:')
n1 = int(input('Primeiro - '))
n2 = int(input('Segundo - '))
print('_' * 50)
if n1 > n2:
print('O \033[4mprimeiro\033[m é maior.')
elif n1 < n2:
print('O \033[4msegundo\033[m é maior.')
else:
print('Não existe valor maior, os dois são \033[4miguais\033[m.')
print('=' * 50)
print('Fim do programa.')
|
# Exercise 1.
# Using a while loop create a program that prints the values of your favorite movie stars.
# have a number in front of the printed name.
movie_stars = ["Eddie Murphy", "Ryan Reynolds", "Julia Robers"]
i = 0
while i < len(movie_stars):
print(f"{i+1}. {movie_stars[i]}")
i += 1
#################################
# Exercise 2.
# Using a for loop, re-do the above exercise.
# (hint) you still need to create a variable that is incrimented.
movie_stars = ["Eddie Murphy", "Ryan Reynolds", "Julia Robers"]
i = 0
for person in movie_stars:
print(f"{i+1}. {person}")
i += 1
#################################
# Exercise 3.
# Create a program that will add the values of a list of numbers, and then print out the results.
# (hint) You will need to create a variable to hold the current value.
# Repeat with several different lists of numbers of different lengths.
num = [5, 5, 5]
num2 = 0
for i in num:
num2 += i
print(num2)
num3 = [1, 100, 60, 30]
num4 = 0
for j in num3:
num4 += j
print(num4)
|
# *
# ***
# *****
# *******
for x in range(0, 4):
for y in range(0, 6-x):
print(" ", end="")
for k in range(0, 2 * x + 1):
print("*", end="")
print("")
|
coins = 0
print(f"You have currently have {coins} coins.")
more_coins = input("Do you want another?\n")
while more_coins == "yes":
coins +=1
print(f"You have {coins} coins.")
more_coins = input("Do you want another?")
else:
print("Bye!")
|
day = int(input("Day (0-6)?"))
if day == 0:
print("It is Sunday")
elif day == 1:
print("It is Monday")
elif day == 2:
print("It is Tuesday")
elif day == 3:
print("It is Wednesday")
elif day == 4:
print("It is Thursday")
elif day == 4:
print("It is Friday")
else:
print("I don't know what day it is")
|
"""
Problem: 238. Product of Array Except Self
Url: https://leetcode.com/problems/product-of-array-except-self/
Author: David Wang
Date: 12/31/2020
"""
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
m_profit = 0
if not prices:
return 0
min_price = prices[0]
for i in range(len(prices) - 1):
if prices[i] < min_price:
min_price = prices[i]
diff = prices[i+1] - min_price
if diff > m_profit:
m_profit = diff
return m_profit
if __name__ == '__main__':
input = [7,1,5,3,6,4]
answer = 5
output = Solution().maxProfit(input)
assert(answer == output)
|
"""
Problem: 63. Unique Paths II
Url: https://leetcode.com/problems/unique-paths-ii/
Author: David Wang
Date: 06/23/2020
"""
from typing import List
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
if len(obstacleGrid) == 0:
return 0
if len(obstacleGrid[0]) == 0:
return 0
paths = [[0] * len(row) for i, row in enumerate(obstacleGrid)]
# Set the origin with a path of 1 if there is no obstacle.
paths[0][0] = 1 if not obstacleGrid[0][0] else 0
# Set a cell in the first row to whatever the cell is left of it unless the
# current position has an obstacle in which we'll have to set the path to 0.
for j in range(1, len(obstacleGrid[0])):
paths[0][j] = paths[0][j-1] if not obstacleGrid[0][j-1] else 0
# Set a cell in the first column to whatever the cell is left of it unless
# the current position has an obstacle in which we'll have to set the path
# to 0.
for i in range(1, len(obstacleGrid)):
paths[i][0] = paths[i-1][0] if not obstacleGrid[i-1][0] else 0
for i, row in enumerate(obstacleGrid):
for j, val in enumerate(row):
if obstacleGrid[i][j] == 1:
paths[i][j] = 0
continue
# Check if top space above current position is not an obstacle.
if i > 0 and j > 0 and not obstacleGrid[i-1][j]:
paths[i][j] += paths[i-1][j]
if i > 0 and j > 0 and not obstacleGrid[i][j-1]:
paths[i][j] += paths[i][j-1]
m = len(obstacleGrid) - 1
n = len(obstacleGrid[0]) - 1
return paths[m][n]
if __name__ == '__main__':
input = [
[0,0,0],
[0,1,0],
[0,0,0]
]
output = Solution().uniquePathsWithObstacles(input)
assert output == 2
input = [[1]]
output = Solution().uniquePathsWithObstacles(input)
assert output == 0
input = [[1,0]]
output = Solution().uniquePathsWithObstacles(input)
assert output == 0
input = [[0, 0], [0, 1]]
output = Solution().uniquePathsWithObstacles(input)
assert output == 0
input = [
[0,1,0,0,0],
[1,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]
]
output = Solution().uniquePathsWithObstacles(input)
assert output == 0
|
# Miller-Rabin algorithm
def fast_int_mod_power(base, exponent, n):
inbase2 = list()
basepowers = list()
while(exponent > 0):
exponent, r = divmod(exponent, 2)
inbase2.append(r)
basepowers.append(base)
base = base * base % n
result = 1
for i in range(len(inbase2)):
#print 'base ** (2 **', i, ') = ', basepowers[i]
if inbase2[i] == 1:
#print 'result = ', result, ' * ', basepowers[i], ' = ',
result = result * basepowers[i] % n
#print result
return result
def find_max_2(n):
n_1 = n - 1
counter = 0
while n_1 % 2 == 0:
counter += 1
n_1 /= 2
#print 'input n = ', n
#print 'n - 1 = ', n_1, ' * (2 ** ', counter, ')'
return n_1, counter
def find_witness(n):
(d, s) = find_max_2(n)
print 'd = ', d, 's = ', s
for a in range(2, n-2):
temp = fast_int_mod_power(a, d, n)
print a, '**', d, '=', temp, 'mod', n
if temp == 1:
# pass this a
continue
for r in range(s):
temp = fast_int_mod_power(a, 2 ** r * d, n)
print a, '** (', d, '* 2 **', r, ') =', temp, 'mod', n
if temp == n-1:
# Found, also pass this a
break
else:
# End of for loop, not found any r s.t. a ** ( d * 2 ** r ) == n - 1
print a, 'is a witness of', n
print a, '**', d, '=', fast_int_mod_power(a, d, n), 'mod', n
for r in range(s):
print a, '** (', d, '* 2 **', r, ') =', fast_int_mod_power(a, 2 ** r * d, n), 'mod', n
return a
# break will jump here, continue this loop for next a
#print 'Witness not found'
return -1
def prime_test(n):
if n < 2:
return None
if n == 2:
return True
if n > 2 and n % 2 == 0:
return False
w = find_witness(n)
if w > 0:
print n, 'is not a prime number, with at least a witness:', w
return False
else:
print n, 'is a prime number'
return True
if __name__ == '__main__':
while True:
inp = int(raw_input('Please type in a number you want to test\n'))
if inp != 0:
print prime_test(inp)
else:
break
#find_witness(9937)
#find_witness(5619)
#find_witness(65537)
#print fast_int_mod_power(2, 2808, 5619)
|
class Operaciones:
def __init__(self,num1,num2):
self.numero1=num1
self.numero2=num2
def suma(self):
suma=self.numero1 + self.numero2
return suma
def resta(self):
return self.numero1 - self.numero2
def multiplicacion(self):
return self.numero1 * self.numero2
def division(self):
if self.numero2 != 0: return self.numero1 / self.numero2
return 0
def divisionEntera(self):
if self.numero2 != 0: return self.numero1 // self.numero2
return 0
def residuo(self):
return self.numero1 % self.numero2
def exponente(self):
return self.numero1 ** self.numero2
def mostrar(self):
print("operando1={}, operando2={}".format(self.numero1, self.numero2))
print("**Lista De Operaciones Matematicas**")
print((" 1) Suma\n 2) Resta\n 3) Multiplicacin\n 4) Division\n 5) Division entera\n 6) Residuo\n 7)Exponente\n 8)salir"))
opc= "0"
while opc != "8":
opc= input("Escoja una opcion[1...8]: ")
num1= int(input("Esbriba numero 1: "))
num2= int(input("Escriba numero 2: "))
ope= Operaciones(num1,num2)
if opc == "1":
print("{}+{}={}".format(ope.numero1,ope.numero2,ope.suma()))
elif opc == "2":
print("{}-{}={}".format(ope.numero1,ope.numero2,ope.resta()))
elif opc == "3":
print("{}*{}={}".format(ope.numero1,ope.numero2,ope.multiplicacion()))
elif opc == "4":
print("{}/{}={}".format(ope.numero1,ope.numero2,ope.division()))
elif opc == "5":
print("{}/{}={}".format(ope.numero1,ope.numero2,ope.divisionEntera()))
elif opc == "6":
print("{}%{}={}".format(ope.numero1,ope.numero2,ope.residuo()))
elif opc == "7":
print("{}**{}={}".format(ope.numero1,ope.numero2,ope.exponente()))
print("Muchas Gracias!!")
# operacion=Operaciones(10,20)
# x=operacion.suma()
# #print(operacion.suma())
# #print(operacion.division())
# y=operacion.resta()
# z=x ** y
# print(z)
# operacion.mostrar()
|
from collections import namedtuple
NIVEL = int(input("Ingrese el nivel de dificultad deseado - 1 a 5-")) # El usuario debe ingresar el nivel que quiere jugar
while NIVEL > 5 or NIVEL < 1: # Hasta que el usuario no ingrese un nivel dentro del rango estipulado, el programa se lo sigue solicitando
NIVEL = ((int(input("Debe ingresar un valor entre 1 y 5"))))
TAMANNO_LETRA = 20
FPS_inicial = NIVEL
TIEMPO_MAX = 61
ANCHO = 1000
ALTO = 600
COLOR_LETRAS = (0,255,0)
COLOR_FONDO = (176,156,231)
COLOR_TEXTO = (217,255,255)
COLOR_TIEMPO_FINAL = (200,20,10)
Punto = namedtuple('Punto','x y')
|
#!/usr/bin/env python3
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# pylint: disable=no-else-return
# pylint: disable=consider-using-enumerate
"""
Trie datastruktur
"""
from node import Node
class Trie:
"""
Trie datastruktur
"""
def __init__(self):
"""init"""
self.root = Node()
def add(self, list_word):
"""add word"""
current = self.root
if len(list_word.split()) == 2:
split_word = list_word.split()
word = split_word[0].lower()
frequency = split_word[1]
else:
word = list_word.lower()
frequency = False
for i in range(len(word)):
letter = word[i]
if letter in current.children:
current = current.children[letter]
else:
new_node = Node(letter)
current.add_child(letter, new_node)
current = current.children[letter]
current.set_complete()
if frequency:
current.set_frequency(frequency)
def search(self, find):
"""Search for word in list"""
current = self.root
found = False
for l in find:
if l in current.children:
current = current.children[l]
else:
return found
if current.is_complete():
found = True
return found
def print_words(self):
"""Print words in list"""
current = self.root.children
word_list = []
for c in current:
words = self._print_words(current[c], word_list)
return words
@staticmethod
def _print_words(node, word_list, word=""):
"""Print words in list"""
word += node.letter
if node.is_complete() and node.has_frequency():
word_list.append(word + ' ' + node.has_frequency())
elif node.is_complete():
word_list.append(word)
if node.children:
for n in node.children:
Trie._print_words(node.children[n], word_list, word)
return word_list
def print_prefix_words(self, prefix):
"""Print words witrh prefix"""
current = self.root
word_list = []
word = ""
for i in range(len(prefix)):
if prefix[i] in current.children:
current = current.children[prefix[i]]
word += current.letter
else:
return
if current.is_complete() and not current.children:
if current.has_frequency():
word_str = word + ' ' + current.has_frequency()
else:
word_str = word
return word_str
else:
current = current.children
for c in current:
word_list = self._print_prefix_words(current[c],\
prefix, word_list)
return word_list
@staticmethod
def _print_prefix_words(node, prefix, word_list, word=""):
"""Print words witrh prefix"""
word += node.letter
if node.is_complete() and node.has_frequency():
word_list.append(prefix + word + ' ' + node.has_frequency())
elif node.is_complete():
word_list.append(prefix + word)
if node.children:
for n in node.children:
Trie._print_prefix_words(node.children[n], prefix,\
word_list, word)
return word_list
|
#!/usr/bin/env python3
"""
Unittest file for Phone
"""
import unittest
from hand import Hand
from deck import Deck
from card import Card
class Testwar(unittest.TestCase):
"""Submodule for unittests, derives from unittest.TestCase"""
def setUp(self):
""" Create object for all tests """
self.hand = Hand("Player 1")
self.deck = Deck()
self.card = Card("Hearts", 9)
def tearDown(self):
""" Remove dependencies after test """
self.hand = None
self.deck = None
self.card = None
def test_player_name(self):
"""Test for player name"""
self.assertEqual(self.hand.get_player(), "Player 1")
def test_empty_hand(self):
"""Test for empty hand"""
self.assertEqual(self.hand.get_hand(), "Need to split the deck first")
def test_set_hand(self):
"""Test for setting hand"""
self.hand.set_hand(["Queen of hearts", "7 of Diamonds"])
self.assertEqual(self.hand.get_hand(), \
["Queen of hearts", "7 of Diamonds"])
def test_deck_size(self):
"""Test for 52 unshuffled card objects"""
self.assertEqual(len(self.deck.get_deck()), 52)
def test_reshuffle_deck(self):
"""Test to re-shuffle 52 card objects"""
self.deck.shuffle_deck()
self.assertEqual(len(self.deck.get_deck()), 52)
def test_random_deck(self):
"""Test to see if shuffled deck is random"""
deck_before = self.deck.get_deck()
self.deck.shuffle_deck()
self.assertFalse(self.deck.get_deck() == deck_before)
def test_card_suit(self):
"""Test for card suit"""
self.assertEqual(self.card.get_suit(), "Hearts")
def test_card_value(self):
"""Test for card value"""
self.assertEqual(self.card.get_value(), 9)
if __name__ == '__main__':
unittest.main(verbosity=3)
|
# Pandas Getting Started
# Import Pandas
import pandas
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)
print()
# Pandas as pd
import pandas as pd
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pd.DataFrame(mydataset)
print(myvar)
print()
# Checking Pandas Version
print(pd.__version__)
|
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
def f3(x):
"""discus function"""
sum = 0.0
sum += (x[0]**2)*(10**6)
for i in range(2, len(x)+1):
sum += x[i-1]**2
return sum
#Function 3
X = np.linspace(-100, 100, 100) # points from 0..10 in the x axis
Y = np.linspace(-100, 100, 100) # points from 0..10 in the y axis
X, Y = np.meshgrid(X, Y) # create meshgrid
Z = f3([X, Y]) # Calculate Z
# Plot the 3D surface for first function from project
fig = plt.figure()
ax = fig.gca(projection='3d') # set the 3d axes
ax.plot_surface(X, Y, Z,
rstride=3,
cstride=3,
alpha=0.3,
cmap='hot')
plt.show()
|
print ("Citlali Gonzalez")
def superpower(a,b):
m=0
for m in range(b):
m= m+1
s= pow(a,m)
return s
a = int(input("Give me the number: "))
b = int(input("Give me the power: "))
sp = superpower(a,b)
print(sp)
|
##Nama: Gilang Anggi Wisnu Brata
##Kelas: A
##NIM:L200170011
#####=====No.1==============######
class Pesan(object):
"""hai"""
def __init__(self,sebuahString):
self.teks= sebuahString
def cetakIni(self):
print(self.teks)
def cetakPakaiHurufKapital(self):
print(str.upper(self.teks))
def cetakPakaiHurufKecil(self):
print(str.lower(self.teks))
def jumKar(self):
return len(self.teks)
def cetakJumlahKarakterku(self):
print("kalimat mempunyai",len(self.teks),"karakter.")
def perbarui(self,stringBaru):
self.teks=stringBaru
#####=====No.1(a)==============######
def apakahTerkandung(self,kata):
self.kata=kata
if self.kata in self.teks:
return True
else:
return False
#####=====No.1(b)==============######
def hitungKonsonan(self):
x=self.teks
vokal="AUIEOauieo"
jml=0
for a in x:
if a.lower() not in vokal:
jml +=1
return jml
#####=====No.1(c)==============######
def hitungVokal(self):
x=self.teks
vokal="AUIEOauieo"
jml=0
for a in x:
if a.lower() in vokal:
jml +=1
return jml
#####====No.2=====#########
class Manusia(object):
keadaan="lapar"
def __init__(self,nama):
self.nama=nama
def ucapkanSalam(self):
print("Salam, namaku", self.nama)
def makan(self,s):
print("Saya baru saja makan", s)
self.keadaan="kenyang"
def olahraga(self,k):
print("Saya baru saja latihan", k)
self.keaddan="lapar"
def mengalikanDenganDua(self,n):
return n*2
p1=Manusia("Fatimah")
p1.ucapkanSalam
class Mahasiswa(Manusia):
"""Class Mahasiswa yang dibangun dari class Manusia"""
def __init__(self,nama,NIM,kota,us):
"""Metode inisialisasi ini menutupimetode inisiasi di class Manusia."""
self.nama=nama
self.NIM=NIM
self.kotaTinggal=kota
self.uangsaku=us
def __str__(self):
s=self.nama+", NIM"+str(self.NIM)\
+". Tinggal di" +self.kotaTinggal \
+". Uang saku Rp."+str(self.uangsaku)\
+" tiap bulannya."
return s
def ambilNama(self):
return self.nama
def ambilNIM(self):
return self.NIM
def ambilUangSaku(self):
return self.uangsaku
def makan(self,s):
"""Metode ini menutupi makan -nya class Manusia. Mahasiswa kalau makan sambil belajar"""
print("Saya baru saja makan",s,"sambil belajar.")
self.keadaan="Kenyang"
#####======No.2(a)===================
def ambilKotaTinggal(self):
return self.kotaTinggal
#####======No.2(b)===================
def perbaruiKotaTinggal(self,x):
self.kotaTinggal=x
#####======No.2(c)===================
def tambahUangSaku(self,y):
self.y=y
self.uangsaku=self.uangsaku+self.y
#####======No.3 ada dibawah setelah no.7===================
#####======No.4===================
listKuliah=[]
def ambilKuliah(self,mk):
self.mk_baru = mk
self.listKuliah.append(self.mk_baru)
#####======No.5 ===================
def hapuskuliah(self,hapus):
self.hapus= hapus
self.listKuliah.remove(self.hapus)
#####======No.6 ===================
class SiswaSMA(Manusia):
"""Class SiswaSMA yang dibangun dari class Manusia"""
def __init__(self,umur,id_siswa,asal):
"""Metode inisialisasi ini menutupimetode inisiasi di class Manusia."""
self.umur=umur
self.id=id_siswa
self.sekolah=asal
def __str__(self):
a="ID Siswa :"+str(self.id)+'\n'+"Umur Siswa :"+str(self.umur)+'\n'+"Asal Sekolah :" +self.sekolah
print (a)
def tampilkanumur(self):
return self.umur
def asalSekolah(self):
return self.sekolah
def idSiswa(self):
return self.id
#####======No.7===================
class MhsTIF(Mahasiswa):
"""Class MhsTIF yang dibangun dari class Mahasiswa"""
def katakanPy(self):
print ("python is cool. ")
#####====beri keterangan no.7==========
# a.NIM ==>Mahasiswa
# a.ambilKotaTinggal ==>Mahasiswa
# a.ambilkuliah ==>Mahasiswa
# a.ambilNIM ==>Mahasiswa
# a.ambilNama ==>Mahasiswa
# a.ambilUangSaku ==>Mahasiswa
# a.hapusKuliah ==>Mahasiswa
# a.katakanPy ==>MhsTIF
# a.keadaan ==>Manusia
# a.kotaTinggal ==>Mahasiswa
# a.listKuliah ==>Mahasiswa
# a.makan ==>Manusia
# a.mengalikanDenganDua ==>Manusia
# a.nama ==>Manusia
# a.olahraga ==>Manusia
# a.perbaruiKotaTinggal ==>Mahasiswa
# a.tambahUangSaku ==>Mahasiswa
# a.uangsaku ==>Mahasiswa
# a.ucapkanSalam ==>Manusia
#####======No.3===================
a=input("masukan nama : ")
b=input("masukan NIM : ")
c=input("masukan kota asal : ")
d= input("jumlah uang saku : ")
##instance
m1=Mahasiswa("Gilang Anggi Wisnu Brata","L200170011","Ngawi",10000000)
m2=Mahasiswa("Bandi","D2001800323","Solo",650000)
m3=Mahasiswa("Parjo","D2001*00625","Karanganyar",400000)
mb=Mahasiswa(a,b,c,d)
a= MhsTIF("Doni",2327,"Klaten",350000)
|
import json
with open('country_list.json') as json_file:
data = json.load(json_file)
def display(dc):
print(dc['country'])
print("Total number of registered cases: ", end = "")
print(dc['cases'])
print("Total number of deaths: ", end = "")
print(dc['deaths'])
def query_by_country_name(name):
for i in data:
if(i['country'] == name):
display(i)
query_by_country_name('Brazil')
query_by_country_name('China')
query_by_country_name('USA')
|
"""
This module is used to provide data structures that describe the possible
outcomes of a test execution.
"""
from typing import Optional
import datetime
class TestOutcome(object):
"""
Describes the outcome of a test execution.
"""
def __init__(self,
passed: bool,
duration: datetime.timedelta,
distance_to_goal: Optional[float]
) -> None:
"""
Constructs a new test outcome.
Parameters:
duration: the wall-clock time taken to execute the test.
"""
self.__passed = passed
self.__duration = duration
self.__distance_to_goal = distance_to_goal
@property
def duration(self) -> datetime.timedelta:
"""
The wall-clock time taken to execute the test.
"""
return self.__duration
@property
def distance_to_goal(self) -> Optional[float]:
"""
The distance to the goal.
"""
return self.__distance_to_goal
@property
def successful(self) -> bool:
"""
A flag indicating whether or not the outcome of the test was determined
to be a success.
"""
return self.__passed
class Collided(TestOutcome):
"""
The robot had a collision during the mission.
"""
def __init__(self,
duration: datetime.timedelta,
distance_to_goal: float
) -> None:
super().__init__(False, duration, distance_to_goal)
class GoalReached(TestOutcome):
"""
The robot reached the goal within the time limit.
"""
def __init__(self,
duration: datetime.timedelta,
distance_to_goal: float
) -> None:
super().__init__(True, duration, distance_to_goal)
class GoalNotReached(TestOutcome):
"""
The robot failed to reach the goal within the time limit.
"""
def __init__(self,
duration: datetime.timedelta,
distance_to_goal: float
) -> None:
super().__init__(False, duration, distance_to_goal)
|
def solve(n,char_str):
checked = []
checking = char_str[0]
for i in char_str:
if i != checking:
if i in checked:
return 'NO'
checked.append(checking)
checking = i
return 'YES'
t = int(input())
for i in range(t):
n = int(input())
char_str = input()
print(solve(n,char_str))
|
def find_max_len(arr):
max_flag = 0 ##Result to return at last
flag = 0 ##To track the number of increasing nature
for i in range(len(arr)-1): ##Going throu the arr
if arr[i] < arr[i+1]: ##Checking if increasing
flag += 1
else:
flag = 0
if max_flag < flag: ##max increasing arr length
max_flag = flag
return max_flag + 1
n = int(input()) ##Taking the input
arr = list(map(int,input().strip().split()))[:n] ##Taking the array
result = find_max_len(arr) ##Getting the result
print(result)
|
def watermelon_prob(noOfwatermelon):
if noOfwatermelon%2 == 0 and noOfwatermelon != 2:
print("Yes")
else:
print("No")
num = int(input())
watermelon_prob(num)
|
import socket
# Takes address as input
addr = input("Enter IP address >>> ")
# Loops over all the ports
for port in range(65536):
# Creates socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
# Connects to socket
result = sock.connect_ex((addr, port))
if result == 0:
print("Port ", port, " is open")
sock.close()
|
import random
from random import choice
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
num_caract = int(input("Número de caracteres: "))
Ler_Arquivo = input('Você deseja ver a senha?')
arquivo = open('key.txt', 'w')
def password():
if (num_caract < 0):
return "Erro: número negativo"
elif (num_caract == 0):
return "Erro: Tem que ter pelo menos 1 caracter."
else:
passwd = ""
while len(passwd) != num_caract:
passwd = passwd + random.choice(char)
if len(passwd) >= num_caract:
arquivo.write(passwd)
arquivo.close()
return "Password: %s" % passwd
password()
def ler():
arquivo = open('key.txt','r')
for linha in arquivo:
print(linha)
arquivo.close()
if Ler_Arquivo == 's':
ler()
|
"""Implement 1D and 2D Peak Finding as described in
https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/
in the first lecture.
Usage:
p = Problem([a, b, c, ....], dims=(x,y) or None for 1D)
p.findPeak() -> (value, position)
"""
import numpy as np
import unittest
class Problem:
def __init__(self, values, dims=None):
if dims is None or type(dims) is not tuple or np.product(dims) != len(values):
self.dims = (len(values),)
else:
self.dims = dims
self.values = np.asarray(values).reshape(self.dims)
def neighbors(self, position):
if len(self.dims) == 1:
left = max(position - 1, 0)
right = min(position + 1, self.dims[0] - 1)
return self.values[left], self.values[right]
if len(self.dims) == 2:
row, column = position[0], position[1]
up = (max(row - 1, 0), column)
down = (min(row + 1, self.dims[0] - 1), column)
left = (row, max(column - 1, 0),)
right = (row, min(column + 1, self.dims[1] - 1))
return self.values[left], self.values[right], self.values[up], self.values[down]
def getMax(self, column):
"""Return the index of the maximum element in the column"""
return np.argmax(self.values[slice(None), column], axis=0)
def isPeak(self, position):
if len(self.dims) == 1:
left = max(position - 1, 0)
right = min(position + 1, self.dims[0] - 1)
return self.values[position] >= self.values[left] and self.values[position] >= self.values[right]
if len(self.dims) == 2:
row, column = position[0], position[1]
up = (max(row - 1, 0), column)
down = (min(row + 1, self.dims[0] - 1), column)
left = (row, max(column - 1, 0),)
right = (row, min(column + 1, self.dims[1] - 1))
return (self.values[position] >= self.values[left] and self.values[position] >= self.values[right] and
self.values[position] >= self.values[up] and self.values[position] >= self.values[down])
def isLeftPeak(self, position):
if len(self.dims) == 1:
left = max(position - 1, 0)
return self.values[position] >= self.values[left]
if len(self.dims) == 2:
row, column = position[0], position[1]
left = (row, max(column - 1, 0),)
return self.values[position] >= self.values[left]
def isRightPeak(self, position):
if len(self.dims) == 1:
right = min(position + 1, self.dims[0] - 1)
return self.values[position] >= self.values[right]
if len(self.dims) == 2:
row, column = position[0], position[1]
right = (row, min(column + 1, self.dims[1] - 1))
return self.values[position] >= self.values[right]
def findPeak(self, start=None, end=None):
if start is None or end is None:
start, end = 0, self.dims[0] - 1
mid = (end - start) // 2
if len(self.dims) == 1:
position = mid
else:
id = self.getMax(mid) # the index ROW of the max element in the mid column
position = id, mid
if not self.isLeftPeak(position):
return self.findPeak(start, mid - 1)
elif not self.isRightPeak(position):
return self.findPeak(mid + 1, end)
else: # its a peak
return self.values[position], position
class TestProblemClass(unittest.TestCase):
def setUp(self):
self.v = [0, 0, 9, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 8, 9,
0, 2, 0, 0, 0, 0, 0,
0, 3, 0, 0, 0, 0, 0,
0, 5, 0, 0, 0, 0, 0,
0, 4, 7, 0, 0, 0, 0
]
def testCorrectMissingDims(self):
self.p = Problem(self.v)
self.assertEqual(self.p.dims, (len(self.v),),
"Missing dims should be completed with a tuple of the length of v")
def testIncorrectDimsType(self):
self.p = Problem(self.v, [2, 3])
self.assertEqual(self.p.dims, (len(self.v),),
"Dims not tuple should be completed with a tuple of the length of v")
def testIncorrectDimsDimensions(self):
self.p = Problem(self.v, (2, 3))
self.assertEqual(self.p.dims, (len(self.v),), "Dims should have the correct dimensions")
def testCorrectDimsDimensions(self):
self.p = Problem(self.v, (7, 7))
self.assertEqual(self.p.dims, (7, 7), "Dims should be correctly stored")
self.assertEqual(self.p.values.shape, (7, 7), "Array should be correctly reshaped")
def testGetCorrectNeighbors2D(self):
self.p = Problem(self.v, (7, 7))
self.assertEqual(self.p.neighbors((3, 1)), (0, 0, 1, 3), "Should return the correct neighbors")
def testGetCorrectNeighbors1D(self):
self.p = Problem(self.v)
self.assertEqual(self.p.neighbors(20), (8, 0), "Should return the correct neighbors")
def testIsPeak1D(self):
self.p = Problem(self.v)
self.assertTrue(self.p.isPeak(20), "Should return position 20 as a 1D peak")
def testIsPeak2D(self):
self.p = Problem(self.v, (7, 7))
self.assertTrue(self.p.isPeak((0, 2)), "Should return position 0,2 as a 2D peak")
def testFindPeak1D(self):
self.p = Problem(self.v)
self.assertEqual(self.p.findPeak(), (0, 24), "Should return position 20 as a 1D peak")
def testFindPeak2D(self):
self.p = Problem(self.v, (7, 7))
self.assertEqual(self.p.findPeak(), (5, (5, 1)), "Should return position 0,2 as a 2D peak")
if __name__ == '__main__':
unittest.main()
|
from Maze import maze
import random
from Maze import bcolors
import time
def game_result(height,width,board):
game = Mazeboards(height,width,board)
game.board_initializer()
while game.exit():
game.next_turn()
return (game.move,game.move_pattern)
class Mazeboards:
# 0 = nothing
# 1 = wall
# 2 = player
# 3 = start
# 4 = end
def __init__(self,height,width,start_height,end_height,board):
self.height = height
self.width = width
self.board = board
self.start = None
self.end = None
self.player = None
self.move = 0
self.previous_move = None
self.move_pattern = []
def board_initializer(self):
""" Initializes the board """
start = random.choice([i for i in range(1,self.height-1)])
end = random.choice([i for i in range(1,self.height-1)])
while end == start:
end = random.choice([i for i in range(1,self.height-1)])
self.start = (start,0)
self.end = (end,self.width)
self.board[end][self.width] = 4
self.player = [start,0]
self.board[start][0] = 3
def printboard(self):
for row in self.board:
for ele in row:
if ele == 1: print(bcolors.WARNING +"▉"+bcolors.ENDC,end="")
elif ele == 0: print(bcolors.OKBLUE +"▉"+bcolors.ENDC,end="")
elif ele == 3: print(bcolors.OKGREEN +"▉"+bcolors.ENDC,end="")
elif ele == 4: print(bcolors.FAIL +"▉"+bcolors.ENDC,end="")
elif ele == 2: print(bcolors.PLAY +"▉"+bcolors.ENDC,end="")
print()
def move_position(self,di,dj):
if self.player[1] == 0 and self.player[0] == self.start[0]:
if di == -1:
return False
if self.board[self.player[0] + di][self.player[1] + dj] == 1:
return False
if self.board[self.player[0] + di][self.player[1] + dj] == 3:
return False
return True
def next_turn(self):
if not self.next_to_exit():
x = random.choice(["up","down","left","right"])
while x == self.previous_move:
x = random.choice(["up","down","left","right"])
if x == "up":
di,dj = (-1,0)
elif x == "left":
di,dj = (0,-1)
elif x == "down":
di,dj = (1,0)
elif x == "right":
di,dj = (0,1)
neighbours = [self.move_position(-1,0),self.move_position(0,-1),self.move_position(1,0),self.move_position(0,1)]
if x == "up" and self.move_position(di,dj):
self.previous_move = "down"
elif x == "down" and self.move_position(di,dj):
self.previous_move = "up"
elif x == "left" and self.move_position(di,dj):
self.previous_move = "right"
elif x == "right" and self.move_position(di,dj):
self.previous_move = "left"
if neighbours.count(False) == 3: self.previous_move = None
else:
di,dj = (0,1)
if self.move_position(di,dj):
self.move_pattern.append(self.didj_to_what(di,dj))
self.move += 1
self.board[self.player[0]][self.player[1]] = 0
self.player[0] += di
self.player[1] += dj
self.board[self.start[0]][0] = 3
self.board[self.player[0]][self.player[1]] = 2
def next_to_exit(self):
if self.player[0] + 0 == self.end[0] and self.player[1] + 1 == self.end[1]:
return True
return False
def exit(self):
if self.player[0] == self.end[0] and self.player[1] == self.end[1]:
return False
return True
def didj_to_what(self,di,dj):
if (di,dj) == (-1,0):
return "up"
elif (di,dj) == (0,-1):
return "left"
elif (di,dj) == (1,0):
return "down"
elif (di,dj) == (0,1):
return "right"
board_init = maze(10,10)
#print(game_result(10,10,board_init))
def put_into_file(height,width,board,n):
gamefile = open("board.txt","w+")
for row in board:
gamefile.write(str(row))
for i in range(n):
number,moves = game_result(height,width,board)
filename = "test"+str(i)+".txt"
file = open(filename,"w+")
file.write(str(number))
file.write("\n")
for m in moves:
file.write(m + "\n")
file.close()
put_into_file(10,10,board_init,3)
|
# A Pulsator is a Black_Hole; it updates as a Black_Hole
# does, but also by growing/shrinking depending on
# whether or not it eats Prey (and removing itself from
# the simulation if its dimension becomes 0), and displays
# as a Black_Hole but with varying dimensions
from prey import Prey
from blackhole import Black_Hole
import model
class Pulsator(Black_Hole):
counter_constant = 30
def __init__(self,pos):
Black_Hole.__init__(self,pos)
self.counter = 30
def update(self):
victims = model.find(lambda x: isinstance(x, Prey) and x in self)
if victims:
for i in victims:
model.remove(i)
w,h = self.get_dimension()
self.set_dimension(w+1, h+1)
self.radius = (1/2)*w
self.counter = Pulsator.counter_constant
else:
#print(self.counter)
self.counter-=1
if self.counter == 0:
w,h = self.get_dimension()
#print("here")
self.set_dimension(w-1, h-1)
self.radius = (1/2)*w
if self.get_dimension() == (0,0):
model.remove(self)
self.counter = Pulsator.counter_constant
|
print("Welcome to the Haiku generator!")
print("Provide the first line of your haiku:")
a = str(raw_input())
print("Provide the second line of your haiku:")
b = str(raw_input())
print("Provide the third line of your haiku:")
c = str(raw_input())
print("What file would you like to write your haiku to?")
myFile = str(raw_input())
print("Done! To view your haiku, type 'cat' and the name of your file at the command line.")
my_File = open((myFile), "a")
my_File.write(a + '\n' + b + '\n' + c + '\n')
my_File.close()
|
import random
import numpy as np
random.seed(1234)
print(random.random())
print(random.uniform(25,50))
#Uniform
unifNumbers = [random.uniform(0,1) for _ in range(1000)]
print(unifNumbers)
#Normal
mu = 0
sigma = 1
print(random.normalvariate(mu, sigma))
mu = 0
sigma = 1
[random.normalvariate(mu, sigma) for _ in range(10000)]
'''
Random Sampling from a Population
From lecture, we know that Simple Random Sampling (SRS) has the following properties:
Start with known list of N* population units, and randomly select *n units from the list
Every unit has equal probability of selection = n/N
All possible samples of size n are equaly likely
Estimates of means, proportions, and totals based on SRS are UNBIASED (meaning they are equal to the population values
on average)
'''
mu = 0
sigma = 1
Population = [random.normalvariate(mu, sigma) for _ in range(10000)]
SampleA = random.sample(Population, 500)
SampleB = random.sample(Population, 500)
np.mean(SampleA)
np.std(SampleA)
np.mean(SampleB)
np.std(SampleB)
means = [np.mean(random.sample(Population, 1000)) for _ in range(100)]
np.mean(means)
|
# define functions for poptok here
def num_div35(num):
if num % 3 == 0 and num % 5 == 0:
return True
else:
return False
def num_div3(num):
if num % 3 == 0:
return True
else:
return False
def num_div5(num):
if num % 5 == 0:
return True
else:
return False
# write a function to see if divisible by 3
# write a function to see if divisible by 5
# write a function to see if divisible by 3 and 5
|
def change_string(string, operation):
if operation == "uppercase":
print(string.upper())
elif operation == "lowercase":
print(string.lower())
elif operation == "join":
string = string.split(" ")
print("".join(string))
else:
print("Operation not possible.")
if __name__ == "__main__":
string = input("What words or sentences would you like to change? ")
operation = input("What would you like to do? uppercase, lowercase, join ")
change_string(string,operation)
again = True
while again:
answer = input("Would you like to change another text! y/n")
answer = answer.lower()
if answer == "n":
again = False
print("Bye!")
else:
string = input("What words or sentences would you like to change? ")
operation = input("What would you like to do? uppercase, lowercase, join ")
change_string(string, operation)
|
if __name__ == "__main__":
print("---- Guess the Capital ---")
print("10 Questions to test your geography knowledige.")
import random
import json
with open("capitals.json", "r") as f:
capitals = json.load(f)
f.close()
used = []
questions = 10
question = 0
number = 0
correct_answers = 0
while question!=questions:
while number in used:
number = random.randint(0,len(capitals))
used.append(number)
question += 1
print("Question "+ str(question)+":")
print("What's the capital of " + str(capitals[int(number)]['country'])+"?")
answer = input("Your answer: ")
if answer == capitals[int(number)]['city']:
print("You're right. You earn 1 Point!")
correct_answers +=1
else:
print("I'm sorry, that's wrong. The capital is "+ str(capitals[int(number)]['city']) + ".")
print("Your final score is "+ str(correct_answers)+".")
|
#!/usr/bin/python3
""" JSON Module
"""
import json
def from_json_string(my_str):
"""
Args:
my_str (object): The first parameter.
Returns:
string: JSON string
"""
return json.loads(my_str)
|
#!/usr/bin/python3
"""Same Class Module
"""
def is_same_class(obj, a_class):
"""
Args:
obj (object): The first parameter.
a_class (object): The second parameter.
Returns:
bool: True or False
"""
if type(obj) is a_class:
return True
else:
return False
|
#!/usr/bin/env python
# coding: utf-8
# # Handling Missing Data
#
# In this section, we will study ways to identify and treat missing data. We will:
# - Identify missing data in dataframes
# - Treat (delete or impute) missing values
#
# There are various reasons for missing data, such as, human-errors during data-entry, non availability at the end of the user (e.g. DOB of certain people), etc. Most often, the reasons are simply unknown.
#
# In python, missing data is represented using either of the two objects ```NaN``` (Not a Number) or ```NULL```. We'll not get into the differences between them and how Python stores them internally etc. We'll focus on studying ways to identify and treat missing values in Pandas dataframes.
#
# There are four main methods to identify and treat missing data:
# - ```isnull()```: Indicates presence of missing values, returns a boolean
# - ```notnull()```: Opposite of ```isnull()```, returns a boolean
# - ```dropna()```: Drops the missing values from a data frame and returns the rest
# - ```fillna()```: Fills (or imputes) the missing values by a specified value
#
#
# For this exercise, we will use the **Melbourne house pricing dataset**.
#
# In[1]:
import numpy as np
import pandas as pd
#library to deal with warning
import warnings
warnings.filterwarnings('ignore')
# In[2]:
df = pd.read_csv("melbourne.csv")
df.head()
# In[3]:
df.tail()
# In[4]:
df.shape
# In[5]:
df.keys()
# In[6]:
df.describe() # its give numerical columns and their Aggression funtion
# In[7]:
df.describe(include='all').T
# #### The first few rows contain missing values, represented as NaN.
#
# #### Let's quickly look at the structure of the data frame, types of columns, etc.
# In[8]:
# approx 23k rows, 21 columns
print(df.shape)
print(df.info())
# In[ ]:
# ## Identifying Missing Values
#
# The methods ```isnull()``` and ```notnull()``` are the most common ways of identifying missing values.
#
# While handling missing data, you first need to identify the rows and columns containing missing values, count the number of missing values, and then decide how you want to treat them.
#
# It is important that **you treat missing values in each column separately**, rather than implementing a single solution (e.g. replacing NaNs by the mean of a column) for all columns.
#
# ```isnull()``` returns a boolean (True/False) which can then be used to find the rows or columns containing missing values.
# In[9]:
# isnull()
df.isnull()
# ### Identifying Missing Values in Columns
# Let's first compute the total number of missing values in the data frame. You can calculate the number of missing values in each column by ```df.isnull().sum()```
# In[10]:
# summing up the missing values (column-wise)
df.isnull().sum()
# df.notnull()
# Note that some columns have extremely **large number of missing values**, such as Price, Bedroom2, Bathroom, BuildingArea, YearBuilt etc. In such cases, one should be careful in handling missing values, since if you replace them by arbitrary numbers such as mean, median etc., the entire further analysis may throw `unrealistic or unexpected results.`
#
# The functions ```any()``` and ```all()``` are quite useful to identify rows and columns having missing values:
# - ```any()``` returns ```True``` when at least one value satisfies a condition (equivalent to logical ```or```)
# - ```all()``` returns ```True``` when all the values satisfy a condition (equivalent to logical ```and```)
# In[11]:
# columns having at least one missing value
df.isnull().any()
# above is equivalent to axis=0 (by default, any() operates on columns)
df.isnull().any(axis=0)
# We have identified columns having missing values and have computed the number of missing values in each. Let's do the same for rows.
#
# ### Identifying Missing Values in Rows
#
# The methods ```any()``` and ```all()``` can be used to identify rows having **at least one** and **all** missing values respectively. To specify that the operation should be done on rows, you need to use ```axis=1``` as an argument.
# In[12]:
# rows having at least one missing value
df.isnull().any(axis=1)
# In[13]:
# rows having all missing values
df.isnull().any(axis=1).sum()
# In[14]:
# sum it up to check how many rows have all missing values
df.isnull().all(axis=1).sum()
# Thus, there are no rows having all missing values (we'd remove them if there were any).
#
# Often, you may also want to remove the rows having more than a certain threshold number of missing values. To do that, you need to count the number of missing values in each row using ```sum()```.
# In[15]:
# sum of misisng values in each row
df.isnull().sum(axis=1)
# We have now identified:
# - The number of missing values in columns
# - The number of missing values in rows
#
# Let's now move ahead and treat the missing values.
# ### Treating Missing Values
#
# There are broadly two ways to treat missing values:
# 1. Delete: Delete the missing values
# 2. Impute:
# - Imputing by a simple statistic: Replace the missing values by another value, commonly the mean, median, mode etc.
# - Predictive techniques: Use statistical models such as k-NN, SVM etc. to predict and impute missing values
#
#
# In general, imputation makes assumptions about the missing values and replaces missing values by arbitrary numbers such as mean, median etc. It should be used only when you are reasonably confident about the assumptions.
#
# Otherwise, deletion is often safer and recommended. You may lose some data, but will not make any unreasonable assumptions.
#
# **Caution**: Always have a backup of the original data if you're deleting missing values.
#
# <hr>
# **Additional Stuff for Nerds**
#
# How you treat missing values should ideally depend upon an understnading of why missing values occur. The reasons are classified into categories such as *missing completely at random, missing at random, misisngness that depends on the missing value itself etc.*
#
#
# We'll not discuss *why missing values occur*, though you can read this article if interested: http://www.stat.columbia.edu/~gelman/arm/missing.pdf
# <hr>
# ### Treating Missing Values in Columns
#
# Let's now treat missing values in columns. Let's look at the number of NaNs in each column again, this time as the *percentage of missing values in each column*. Notice that we calculate the number of rows as ```len(df.index)```.
# In[17]:
print(df.isnull().sum())
len(df.index)
# In[18]:
# summing up the missing values (column-wise)
round(100*(df.isnull().sum()/len(df.index)), 2)
# In[19]:
# summing up the missing values (column-wise)
round(100*(df.isnull().sum()/len(df.index)), 0)
# Notice that there are columns having almost `22%, 19%, 26%, 57% etc`. missing values. When dealing with columns, you have two simple choices - either **delete or retain the column.** If you retain the column, you'll have to treat (i.e. delete or impute) the rows having missing values.
#
# If you delete the missing rows, you lose data. If you impute, you introduce bias.
#
# Apart from the number of missing values, the decision to delete or retain a variable depends on various other factors, such as:
# - the analysis task at hand
# - the usefulness of the variable (based on your understanding of the problem)
# - the total size of available data (if you have enough, you can afford to throw away some of it)
# - etc.
#
# For e.g. let's say that we want to build a (linear regression) model to predict the house prices in Melbourne. Now, even though the variable ```Price``` has about 22% missing values, you cannot drop the variable, since that is what you want to predict.
#
# Similarly, you would expect some other variables such as ```Bedroom2```, ```Bathroom```, ```Landsize``` etc. to be important predictors of ```Price```, and thus cannot remove those columns.
#
# There are others such as ```BuildingArea```, which although seem important, have more than 50% missing values. It is impossible to either delete or impute the rows corresponding to such large number of missing values without losing a lot of data or introducing heavy bias.
#
#
#
# Thus, for this exercise, let's remove the columns having more than 30% missing values, i.e. ```BuildingArea```, ```YearBuilt```, ```CouncilArea```.
#
#
# In[20]:
# removing the three columns
df = df.drop('BuildingArea', axis=1)
df = df.drop('YearBuilt', axis=1)
df = df.drop('CouncilArea', axis=1)
round(100*(df.isnull().sum()/len(df.index)), 2)
# We now have columns having maximum 26% missing values (```Landsize```). Next, we need to treat the rows.
# ### Treating Missing Values in Rows
#
# Now, we need to either delete or impute the missing values. First, let's see if there are any rows having a significant number of missing values. If so, we can drop those rows, and then take a decision to delete or impute the rest.
#
# After dropping three columns, we now have 18 columns to work with. Just to inspect rows with missing values, let's have a look at the rows having more than 5 missing values.
# In[21]:
df[df.isnull().sum(axis=1) > 5]
# Notice an interesting pattern - many rows have multiple columns missing. Since each row represents a house, it indicates that there are houses (observations) whose majority data has either not been collected or is unavailable. Such observations are anyway unlikely to contribute to prediction of prices.
#
# Thus we can remove the rows with (say) more than 5 missing values.
# In[22]:
# count the number of rows having > 5 missing values
# use len(df.index)
len(df[df.isnull().sum(axis=1) > 5].index)
# In[23]:
# 4278 rows have more than 5 missing values
# calculate the percentage
100*(len(df[df.isnull().sum(axis=1) > 5].index) / len(df.index))
# Thus, about ` 18% rows have more than 5 missing values.` Let's remove these rows and count the number of missing values remaining.
# In[24]:
# retaining the rows having <= 5 NaNs
df = df[df.isnull().sum(axis=1) <= 5]
# look at the summary again
round(100*(df.isnull().sum()/len(df.index)), 2)
# Notice that now, we have removed most of the rows where multiple columns (```Bedroom2```, ```Bathroom```, ```Landsize```) were missing.
#
# Now, we still have about 21% missing values in the column ```Price``` and 9% in ```Landsize```. Since ```Price``` still contains a lot of missing data (and imputing 21% values of a variable you want to predict will introduce heavy bias), its a bad idea to impute those values.
#
# Thus, let's remove the missing rows in ```Price``` as well. Notice that you can use ```np.isnan(df['column'])``` to filter out the corresonding rows, and use a ```~``` to discard the values satisfying the condition.
# In[25]:
# removing NaN Price rows
df = df[~np.isnan(df['Price'])]
round(100*(df.isnull().sum()/len(df.index)), 2)
# In[26]:
df = df[~np.isnan(df['Price'])]
df
# In[27]:
len(df)
# Now, you have ```Landsize``` as the only variable having a significant number of missing values. Let's give this variable a chance and consider imputing the NaNs.
#
# The decision (whether and how to impute) will depend upon the distribution of the variable. For e.g., if the variable is such that all the observations lie in a short range (say between 800 sq. ft to 820 sq.ft), you can take a call to impute the missing values by something like the mean or median ```Landsize```.
#
# Let's look at the distribution.
# In[28]:
df.dtypes
# In[29]:
df['Landsize'].describe()
# Notice that the minimum is 0, max is 433014, the mean is 558 and median (50%) is 440. There's a significant variation in the 25th and the 75th percentile as well (176 to 651).
#
# Thus, imputing this with mean/median seems quite biased, and so we should remove the NaNs.
# In[30]:
df[~np.isnan(df['Landsize'])]
# In[31]:
len(df[~np.isnan(df['Landsize'])])
# In[32]:
# removing NaNs in Landsize
df = df[~np.isnan(df['Landsize'])]
round(100*(df.isnull().sum()/len(df.index)), 2)
# We have reduced the NaNs significantly now. Only the variables ```Bathroom```, ```Car```, ```Lattitude``` and ```Longitude``` have a small number of missing values (most likely, the same rows will have ```Lattitude``` and ```Longitude``` missing).
#
# Let's first look at ```Lattitude``` and ```Longitude```.
# In[33]:
# rows having Lattitude and Longitude missing
df[np.isnan(df['Lattitude'])]
# As expected, the same rows have ```Lattitude``` and ```Longitude``` missing. Let's look at the summary stats of these.
# In[34]:
df.loc[:, ['Lattitude', 'Longtitude']].describe()
# Notice that the distribution of both ```Lattitude``` and ```Longitude``` is quite narrow.
#
# A good way to estimate the 'spread of data' is to look at the difference between the mean and the median (lower the better), and the variation from 25th to 75th percentile (quite small in this case).
#
# Thus, let's impute the missing values by the mean value of ```Lattitude``` and ```Longitude``` respectively.
# In[35]:
# imputing Lattitude and Longitude by mean values
df.loc[np.isnan(df['Lattitude']), ['Lattitude']] = df['Lattitude'].mean()
df.loc[np.isnan(df['Longtitude']), ['Longtitude']] = df['Longtitude'].mean()
round(100*(df.isnull().sum()/len(df.index)), 2)
# In[36]:
df['Lattitude'].fillna(df['Lattitude'].mean(),inplace=True)
# In[37]:
df['Lattitude'].mean()
# In[38]:
df['Lattitude'].isnull().any()
# We now have ```Bathroom``` and ```Car``` with 0.01% and 0.46% NaNs respectively.
#
# Since these are very small number of rows, it does not really matter whether you delete or impute. However, let's have a look at the distributions.
# In[39]:
df.loc[:, ['Bathroom', 'Car']].describe()
# These two are integer type variables, and thus have values 0, 1, 2 etc. You cannot impute the NaNs by the mean or the median (1.53 bathrooms does not make sense!).
#
# Thus, you need to impute them by the mode - the most common occurring value.
#
#
# In[40]:
# converting to type 'category'
df['Car'] = df['Car'].astype('category')
df['Car'].head()
# In[41]:
df.dtypes
# In[42]:
df['Car'].unique()
# In[43]:
df['Car'].nunique()
# In[44]:
df['Car'].value_counts()
# In[45]:
df['Car'].fillna(2.0,inplace=True)
# In[46]:
# displaying frequencies of each category
df['Car'].isnull().any()
# In[47]:
df['Car'].shape
# The most common value of ```Car``` is 2 (dtype is int), so let's impute the NaNs by that.
# In[48]:
# imputing NaNs by 2.0
df.loc[pd.isnull(df['Car']), ['Car']] = 2
round(100*(df.isnull().sum()/len(df.index)), 2)
# Similarly for ```Bathroom```:
# In[49]:
# converting to type 'category'
df['Bathroom'] = df['Bathroom'].astype('category')
# displaying frequencies of each category
df['Bathroom'].value_counts()
# In[50]:
# imputing NaNs by 1
df.loc[pd.isnull(df['Bathroom']), ['Bathroom']] = 1
round(100*(df.isnull().sum()/len(df.index)), 2)
# We now have a dataframe with no missing values. Let's finally look at how many rows (apart from three columns) we have lost in the process (originally we had 23547):
# In[51]:
df.shape
# In[52]:
# fraction of rows lost
len(df.index)/23547
# Thus, we have lost about 42% observations in cleaning the missing values.
# In[53]:
df.dtypes
# In[54]:
df.groupby(by=['Type']).count()
# In[55]:
df.groupby(by=['Type']).median()
# # Pivot_Table
#
# > Pivot Tables
#
# - Pandas provides a function ‘pivot_table’ to create MS-Excel spreadsheet style pivot tables. It can take following arguments:
# - data: DataFrame object,
# - values: column to aggregate,
# - index: row labels,
# - columns: column labels,
# - Aggfunc: aggregation function to be used on values, default is NumPy.mean
# In[56]:
pd.pivot_table(df, index = ['Type','Bathroom'])
# In[57]:
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[58]:
df['Price'].hist(bins=30)
# In[59]:
df.boxplot('Price')
# In[60]:
df.boxplot('Price', by= 'Type', figsize= (10,10))
# In[61]:
a = pd.pivot_table(df, index = ['Car'], aggfunc= 'mean')
# In[62]:
a.plot(kind='bar')
# In[63]:
a.plot(kind='bar', stacked = True)
|
# Python Regular Expression
# re.search() is used to find the first match for the pattern in the string.
# Syntax: re.search(pattern, string, flags[optional])
import re
s = "my number is 123"
match = re.search(r'\d\d\d', s)
print (match)
print (match.group())
s1 = "python tuts"
match = re.match(r'py', s1)
if match:
print(match.group())
|
N = int(input())
#student_marks = list(input().split() for _ in range(N))
#student_marks.sort(key = value)
student_marks = []
for i in range(N):
name, score = input().split()
a = []
a.append(name)
a.append(score)
student_marks.append(a)
#print(student_marks)
def takeSecond(elem):
return elem[1]
student_marks.sort(key = takeSecond)
print(student_marks)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.