text stringlengths 37 1.41M |
|---|
def identify():
print("What lies before us?")
lier=input()
if(lier=="a large boulder"):
print("It's time to run!")
else:
print("we will be fine")
identify() |
def box(name):
value=len(name)
print(" -"*value)
print("| " + name + " |")
print(" -"*value)
def lwr(name):
print(name.lower())
def upr(name):
print(name.upper())
def mrd(name):
print(name[::-1])
def repeat(name):
hmt=int(input("How many times do want to repeat: "))
for count in range(0, hmt,1):
lwr(name)
upr(name)
word=input("Please enter a word: ")
print("1) Display in a Box – display the word in an ascii art box")
print("2) Display Lower-case – display the word in lower-case e.g. hello")
print("3) Display Upper-case – display the word in upper-case e.g. HELLO")
print("4) Display Mirrored – display the word with its mirrored word e.g. Hello | olleH ")
print("5) Repeat – ask the user how many times to display the word and then display the word that many times alternating between upper-case and lower-case.")
option = ""
while (option!=0):
option=int(input("Choose a option: "))
if(option==1):
box(word)
elif(option==2):
lwr(word)
elif(option==3):
upr(word)
elif(option==4):
mrd(word)
elif(option==5):
repeat(word)
else:
print("invalid option")
|
number=input("Write a 5 digit-number:\n")
size_number=len(number)
print("1) Display ASCII Triangle - display the number in an ascii art triangle.")
print("2) Display Left Digits Triangle - display digits of the number so that they form a triangle aligned on the left.")
print("3) Display Right Triangle – display the digits of the number so that they form a triangle aligned to the right.")
option=int(input())
#if(option==1):
if(option==2):
for row in range(0, size_number):
for column in range(0, row + 1):
print(number)
print("")
#elif(option==3):
|
print("selamat datang di kelas python")
print("1+1={}".format(1+1))
print("3-1={}".format(3-1))
print("4*2={}".format(4*2))
print("81/9={}".format(81//9))
print("100%3={}".format(100%3))
print("6**1200={}".format(6**1200))
print("1+1={}, dan 2+2={}".format(1+1,2+2))
|
from random import randint
num = randint(0, 100)
count = 0
while count < 8:
guess = int(input("Select a number from 0 to 100"))
count += 1
if guess in list(range(0,101)):
if guess == num:
print("You are correct!")
break
if guess < num:
print("Sorry, your guess is too low")
else:
print("Sorry, your guess is too high")
else:
print("invalid guess, pick a number from 0 to 100")
continue
else:
print("Sorry, no more tries left")
|
weekly_event = int(raw_input()) * 2
goal_number = int(raw_input())
surplus = 0 if goal_number % weekly_event == 0 else 1
print(str(goal_number / weekly_event + surplus))
|
#exercise3 number maths
from __future__ import division
print "I will now count m hens:" # print stmnt
print "hens", 25 + 30 / 6 # expression evaluation
print "roosters", 100 -25 * 3 % 4 # expression evalution
print "now i will count eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # expression evalution
print "is it true 3 + 2 < 5 - 7?"# evaluation of expression
print 3 + 2 < 5 - 7
print "is it greater?", 5 > -2# comparisons
print " is it greater or equal?", 5 >= -2
print "is it less or equal?", 5 <= -2
a = 20
b = 3
d = a / b
print d
|
# exercise 30
people = 30
cars = 40
buses = 150
if cars > people:
print "there are no roads for people to walk!"
elif cars < people:
print "this world is growing too fast!"
else:
print "why cant we know?"
if buses > cars:
print "i love to go by buses!"
elif buses < cars:
print "what happened to all the buses"
else:
print "this is not happening!"
if people < buses:
print "there is place for everyone in the bus"
else:
print "there is no way i can go by bus!"
|
# exercise 31
print "you are going to enter a zoo or a museum? for zoo press 1, for museum press 2"
ans = raw_input("--> ")
if ans == "1":
print "you chose zoo, a tiger is on the loose! what are you going to do?"
print "1) go find the tiger before tiger finds you"
print "2) run for your life!"
zoo = raw_input("--> ")
if zoo == "1":
print "haha! you are dead"
elif zoo == "2":
print "good thinking run.. run.. run.."
else:
print "ok that would be great!"
elif ans == "2":
print " you chose museum, there is egyptian mummy's spirit missing.what are you planning "
print "1) find the spirit!"
print "2) better go back home"
museum = raw_input("--> ")
if museum == "1":
print "no way! have you not heard about the curse!"
elif museum == "2":
print "now thats a nice move!"
else:
print "ok that would be great!"
else:
print "today is good day to stay home and do %r!" % ans
|
# TCP_client_easy.py
# create_connection() 이용한 TCP 클라이언트 프로그램
import socket
# TCP 소켓 생성과 연결
sock = socket.create_connection(("localhost", 2500))
# 메시지 전송
message = "클라이언트 메시지"
print("sending {}".format(message))
sock.sendall(message.encode())
data = sock.recv(1024) #데이터 수신
print("received {}".format(data.decode()))
print("closing socket")
sock.close() |
import sys
filepath='C:\\Users\\himan\\Documents\\Himani-Data\\Git-Working\\practice_python\\Config\\'
def ask():
while True:
try:
x,y = map(int,raw_input("Enter two number to divide ").split())
except ValueError:
print "Incorrect value"
else:
try:
z = x / y
print z
except ZeroDivisionError:
print "Divided by zero"
finally:
print "all Done"
return
def file_fun():
Nfile = filepath + sys.argv[1]
f=open(Nfile,'r')
print " File line by readlines"
for w in f.readlines():
print w.strip()
print f.tell()
print f.seek(0)
for w in f.read():
print w.strip()
f.close()
return
def try_expect():
try:
Nfile=filepath+sys.argv[1]
print Nfile, sys.argv[1]
f = open(Nfile,'r')
except IOError:
print "can't open file"
else:
try:
s=f.readline()
s=int(s.strip())
except EOFError:
print " end of file"
f.close()
return
except ValueError:
print "not a number"
except:
print "just pass for other issue"
raise
else:
print "s squre is ", s**2
finally:
f.close()
return
def ps():
print "This will print phfeonochi serise"
def fib(n):
a,b=1,1
out=[]
for i in range(n):
out.append(a)
a,b=b,a+b
return out
print fib(10)
return
"""Use map to create a function which finds the length of each word in the phrase (broken by spaces) and return the values in a list."""
def word_len():
s1="I am a string seven"
slen= map(lambda x:len(x), (w for w in s1.split()))
print " the length of each word is" , slen
print " the reduce function to get the lowest number"
print reduce(lambda x,y:x if x <y else y, [1,2,45,6,10])
s1=s1.split()
print " The word start with s using filter function " , filter(lambda x:x[0]=='s',s1)
w1=['a','b','c']
w2=['a1','b1','c1']
connector ='-'
print [w11+connector+w22 for (w11, w22) in zip(w1, w2)]
return
if __name__=="__main__":
#try_expect()
#ps()
#word_len()
file_fun() |
# working on it
# import sys
import random
#from Config import Bk_card_value
# Used for card shuffle
# Boolean used to know if hand is in play
playing = False
chip_pool = 100 # Could also make this a raw input.
bet = 1
restart_phrase = "Press 'd' to deal the cards again, or press 'q' to quit"
# Hearts, Diamonds,Clubs,Spades
suits = ('H','D','C','S')
# Possible card ranks
ranking = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')
# Point values dict (Note: Aces can also be 11, check self.ace for details)
card_val = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':10, 'Q':10, 'K':10}
class BJ():
#Now I'll make a card class, it will have some basic ID functions, and then some functions to grab the suit and rank of the card.
# Create a card class
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return self.suit + self.rank
def grab_suit(self):
return self.suit
def grab_rank(self):
return self.rank
def draw(self):
print (self.suit + self.rank)
# Create a hand class
class Hand:
def __init__(self):
self.cards =[]
self.value =0
#Aces can be 1 or 11 so we need to define there
self.ace = False
def __str__(self):
''' Return a string of current hand composition'''
hand_comp =""
for card in self.cards:
card_name=card.__str__()
hand_comp += " " +card_name
return "The hand has %s" %hand_comp
def card_add(self, card):
''' Add another card to the hand'''
self.cards.append(card)
# Check for Aces
if card.rank == 'A':
self.ace = True
self.value += card_val[card.rank]
def calc_val(self):
'''Calculate the value of the hand, make aces an 11 if they don't bust the hand'''
if (self.ace == True and self.value < 12):
return self.value + 10
else:
return self.value
def draw(self, hidden):
if hidden == True and playing == True:
# Don't show first hidden card
starting_card = 1
else:
starting_card = 0
for x in range(starting_card, len(self.cards)):
self.cards[x].draw()
class Deck:
def __init__(self):
''' Create a deck in order '''
self.deck = []
for suit in suits:
for rank in ranking:
self.deck.append(Card(suit, rank))
def shuffle(self):
''' Shuffle the deck, python actually already has a shuffle method in its random lib '''
random.shuffle(self.deck)
def deal(self):
''' Grab the first item in the deck '''
single_card = self.deck.pop()
return single_card
def __str__(self):
deck_comp = ""
for card in self.cards:
deck_comp += " " + deck_comp.__str__()
return "The deck has" + deck_comp
# First Bet
def make_bet():
''' Ask the player for the bet amount and '''
global bet
bet = 0
print ' What amount of chips would you like to bet? (Enter whole integer please) '
# While loop to keep asking for the bet
while bet == 0:
bet_comp = raw_input() # Use bet_comp as a checker
bet_comp = int(bet_comp)
# Check to make sure the bet is within the remaining amount of chips left.
if bet_comp >= 1 and bet_comp <= chip_pool:
bet = bet_comp
else:
print "Invalid bet, you only have " + str(chip_pool) + " remaining"
|
a = "hello"
b = "world"
c = a.upper() + " " + b.upper()
d = c + "!"
print(d)
e = d + " This {} my first type in {} when my age {} {}" #The format() method takes unlimited number of arguments, and are placed into the respective placeholders
f = "was"
g = 23
h = "python"
i = e.format(f,h,f,g)
print(i)
p = "I want to pay {} dollars for {} pieces of the item {}"
price = 20.25
piece = 10
itemNo = 12
q = p.format(price,piece,itemNo)
print(q)
p = "I want to pay {0} dollars for {2} pieces of the item {1}" # we can define index number from format
q = p.format(price,piece,itemNo)
print(q)
|
listOne = ["apple","banana","charry","orange", "kiwi", "melon", "mango"]
print(listOne)
if "melon" in listOne:
print("Yes, melon here in the list")
else:
print("No! melon don't exist here")
print(len(listOne)) #list length
|
import sqlite3
import csv
class Database():
"""This is a simple multi use case database class"""
def __init__(self, useMemory=True):
if useMemory:
self.conn = sqlite3.connect(':memory:')
else:
user_input = input("Name of db?\n")
self.conn = sqlite3.connect(f"{user_input}.db")
self.c = self.conn.cursor()
self.table_name = ""
self.values = []
self.columns = []
print("Database initialized...\n")
def create_table(self, table_name, *args, **kwargs):
"""Takes in a table name and multiple column names then creates a table"""
self.table_name = table_name
string = ["("]
x = 1
for column in args:
if x == len(args):
string.append(f"{column})")
else:
string.append(f"{column}, ")
x += 1
string = "".join(string)
command = f"CREATE TABLE {self.table_name} {string}"
self.c.execute(command)
self.conn.commit()
print("Table created...\n")
def insert_row(self, *args, **kwargs):
"""Takes in a row of values and adds them into the table"""
string = ["("]
for x in range(len(args)):
if x == (len(args) - 1):
string.append("?)")
else:
string.append('?, ')
string = "".join(string)
command = f"INSERT INTO {self.table_name} VALUES {string}"
self.c.execute(command, args)
self.conn.commit()
print("Values added...\n")
def delete_rows(self):
"""Removes all rows from table"""
command = f"DELETE FROM {self.table_name}"
self.c.execute(command)
self.conn.commit()
print("All rows removed...\n")
def fetch_table(self):
"""Retrieves all values within the table"""
self.c.execute("SELECT * FROM " + self.table_name)
values = self.c.fetchall()
self.conn.commit()
print("Values retrieved...\n")
return values
def export_csv(self, file_name):
"""Export table into a csv file with given name."""
self.c.execute("SELECT * FROM "+ self.table_name)
columns = [tuple[0] for tuple in self.c.description]
rows = self.fetch_table()
with open(f'{file_name}.csv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(columns)
for row in rows:
writer.writerow(row)
print("DB exported to csv...\n")
def read_csv(self, file_name):
"""prints out all values in table"""
with open(f'{file_name}.csv', 'r') as f:
reader = csv.reader(f, delimiter="\t")
for row in reader:
if (row):
print(row)
def close(self):
"""closes connection to db"""
self.conn.close()
print("Connection to db closed...\n")
|
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import neighbors, metrics
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd
data = pd.read_csv('car_data.csv')
#print(data.head())
#We define the important labels of the data that will be used
X = data [[
'buying',
'maint',
'safety'
]].values
Y = data[['class']]
#Convert the strings in the data to values with LabelEncoder
le = LabelEncoder()
for i in range(len(X[0])):
X[:,i] = le.fit_transform(X[:,i])
#Convert the strings in the data to values with Mapping
label_mapping = {
'unacc':0,
'acc':1,
'good':2,
'vgood':3,
}
Y['class'] = Y['class'].map(label_mapping)
Y = np.array(Y)
#Creating our KNN model
knn = neighbors.KNeighborsClassifier(n_neighbors=25, weights='uniform')
x_train, x_test, y_train, y_test = train_test_split(X,Y, test_size=0.2)
knn.fit(x_train, y_train)
prediction = knn.predict(x_test)
accuracy = metrics.accuracy_score(y_test, prediction)
#print('Prediction: ', prediction)
#print('Actual: ', y_test)
print('Accuracy: ', accuracy)
# for i in range(10):
# print('Prediction: ', prediction[i])
# print('Actual: ', y_test[i])
|
class stack(object):
def __init__(self):
self.items=[]
def is_empty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
s1=stack()
s1.push(1)
s1.push(2)
s1.push('one')
s1.push('two')
print(s1.is_empty())
print(s1.peek())
|
def pal(a):
if len(a)<1:
return True
else:
if a[0]==a[-1]:
return pal(a[1:-1])
else:
return False
a=str(input("enter the string"))
if pal(a)==True:
print("palindrome")
else:
print("not a palindrome")
|
str=input("enter the string")
vowels=0
for i in str:
if (i=='a'or i=='e'or i=='i'or i=='o'or i=='u'):
vowels=vowels+1
print("no of vowels are:")
print(vowels)
|
import matplotlib.pyplot as plt
from numpy import linspace, pi, cos, sin
import matplotlib.animation as animation
#from matplotlib import style
def table2(n, mod):
"""Trace la table de mutliplication "modulaire" de n modulo mod"""
#tracé du cercle
X1 = linspace(0, 2*pi, 1000)
X = cos(X1)
Y = sin(X1)
plt.plot(X, Y, c='black', linewidth=0.5)
#tracé des points
pas = 2*pi / mod
angle = pi/2
x = []
y = []
for _ in range(mod): #à creuser
x.append(cos(angle))
y.append(sin(angle))
angle -= pas
plt.scatter(x, y, c='black', s = 1)
#tracé de la table de multiplication modulaire
for i in range(mod+1):
q = n*i % mod
x1 = [cos(pi/2 - q*2*pi/mod), x[i%mod]]
y1 = [sin(pi/2 - q*2*pi/mod), y[i%mod]]
plt.plot(x1, y1, c='black', linewidth=0.5)
plt.axis('equal')
plt.title('Table de {} modulo {}'.format(round(n, 2), mod))
plt.show()
i = 360
while i < 500:
table2(i, 300)
plt.pause(0.01)
plt.cla()
i += 0.1
plt.show()
|
from rnn import CharGen
from rnn.train_model import train
train_new_model = True
model_name = 'shakespeare'
if train_new_model: # Create a new neural network model and train it
char_gen = CharGen(name=model_name,
bidirectional=True, # Boolean. Train using a bidirectional LSTM or unidirectional LSTM.
rnn_size=128, # Number of neurons in each layer of your neural network (default 128)
rnn_layers=3, # Number of layers in your neural network (default 3)
embedding_dims=100, # Size of the embedding layer (default 75)
input_length=150 # Number of characters considered for prediction (default 60)
)
train(text_filepath='datasets/shakespeare.txt',
chargen=char_gen,
gen_text_length=500, # Number of characters to be generated default 500)
num_epochs=100, # Number of times entire dataset is passed forward and backward through the neural network
# (default 10)
batch_size=512, # Total number of training examples present in a single batch (default 512)
train_new_model=train_new_model,
dropout=0.2
)
print(char_gen.model.summary())
else: # Continue training an old model
text_filename = 'datasets/shakespeare.txt'
char_gen = CharGen(name=model_name,
weights_filepath='models/shakespeare_weights.hdf5',
vocab_filepath='models/shakespeare_vocabulary.json',
config_filepath='models/shakespeare_config.json')
train(text_filename, char_gen, train_new_model=train_new_model,
num_epochs=50) # change num_epochs to specify number of epochs to continue training
# char_gen = CharGen(weights_filepath='colab_weights.hdf5', # specify correct filename
# vocab_filepath='colab_vocabulary.json', # specify correct filename
# config_filepath='colab_config.json') # specify correct filename
#
# char_gen.generate(gen_text_length=500, prefix='To be or not to be,') |
"""
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
s = 0
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
x_counter = 0
o_counter = 0
for row in board:
for cell in row:
if cell == 'X':
x_counter = x_counter + 1
elif cell == 'O':
o_counter = o_counter + 1
if x_counter <= o_counter:
return 'X'
else:
return 'O'
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
actions = set()
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
actions.add((i,j))
return actions
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
i = action[0]
j = action[1]
new_board = copy.deepcopy(board)
turn = player(board)
if new_board[i][j] != EMPTY:
raise Exception
else:
new_board[i][j] = turn
return new_board
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
#there should be at least 5 filled squares, to obtain a winning position.
if filled_cells_counter(board) <= 4:
return None
#check horizontal win
for row in board:
if row[0] == row[1] == row[2]:
return row[0]
#check vertical win
for i in range(3):
if (board[0][i] != EMPTY and
board[0][i] == board[1][i] and
board[1][i] == board[2][i]):
return board[0][i]
#check diagonal win
if board[0][0] == board[1][1] == board[2][2] or board[0][2] == board[1][1] == board[2][0] :
return board[1][1]
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if winner(board):
return True
for row in board:
if EMPTY in row:
return False
return True
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
w = winner(board)
t = terminal2(board)
if w != None:
if w == X:
return 1
elif w == O:
return -1
if t:
return 0
else:
return None
def minimax(board): #Minimum time: 15.7 seconds
"""
Returns the optimal action for the current player on the board.
"""
if terminal(board):
return None
else:
if player(board) == X:
v,action = max(board)
else:
v,action = min(board)
return action
def max(board):
"""
Returns the optimal move if it's X to play.
"""
opt = None
M = -99999999
utlty = utility(board)
if utlty is not None:
return utlty ,(0,0)
actns = actions(board)
for action in actns :
m, a = min(result(board,action))
if m > M:
M = m
opt = action
return M,opt
def min(board):
"""
Returns the optimal move if it's O to play.
"""
opt = None
M = 99999999
utlty = utility(board)
if utlty is not None:
return utlty ,(0,0)
actns = actions(board)
for action in actns :
m, a = max(result(board,action))
if m < M:
M = m
opt = action
return M,opt
def filled_cells_counter(board):
"""
Returns how many empty cells are on the board.
"""
counter = 0
for row in board:
for cell in row:
if cell is not EMPTY:
counter = counter + 1
return counter
def check_win(board):
"""
Returns the winner of the game, if there is any, version 2.
actually version 1, I made this one first but it was a bit slow because
of the function calls maybe, so I included all of them in one function, which
affected positively the speed of execution, the other function is the one used,
but I decided to keep it anyways.
"""
if filled_cells_counter(board) <= 4:
return None
else:
hrnztl = check_horizontal_pattern(board)
if hrnztl is not None:
return hrnztl
else:
vrtcl = check_vertical_pattern(board)
if vrtcl is not None:
return vrtcl
else:
diag = check_diagonal_pattern(board)
if diag is not None:
return diag
return None
def check_horizontal_pattern(board):
"""
Returns whether there is a horizontal winning pattern or not.
"""
for row in board:
if row[0] == row[1] == row[2]:
return row[0]
return None
def check_vertical_pattern(board):
"""
Returns whether there is a vertical winning pattern or not.
"""
for j in range(3):
counter = 0
cell = None
if board[0][j] != EMPTY:
counter = counter + 1
cell = board[0][j]
else:
continue
for i in range(1,3):
if board[i][j] == cell:
counter = counter + 1
if counter == 3:
return cell
return None
def check_diagonal_pattern(board):
"""
Returns whether there is a diagonal winning pattern or not.
"""
if board[0][0] == board[1][1] == board[2][2] or board[0][2] == board[1][1] == board[2][0] :
return board[1][1]
else:
return None
def terminal2(board):
"""
Returns whether the board is full or not.
"""
for row in board:
if EMPTY in row:
return False
return True
def minimax2(board):#Minimum time: 3.6 seconds
"""
Returns the optimal move for the current player on the board, to complete
the assignement, I thought I had to use the functions given to be implemented
which I did in 'minimax()', but it was taking a bit too long to calculate the first
move when it's the AI to make the first move.
it was taking around 15 seconds, but the average time decreases dramatically move after move.
I used some online resources to optimize the function which led to not using some of the provided functions(to implement).
this function is connected, to max2() and min2().
and the time of the AI's first move as X was reduced from 15 seconds to 4.6 seconds in average.
but I thought of another modification in the code that would make it faster, and it's not the Alpha-beta prunning, but something similar nonetheless.
so I created minimax3(), max3() and min3() to implement the modification.
"""
if terminal(board):
return None
else:
if player(board) == X:
v,action = max2(board)
else:
v,action = min2(board)
return action
def max2(board):
"""
Returns the optimal move if it's X to play.
"""
opt = None
M = -99999999
utlty = utility(board)
if utlty is not None:
return utlty ,(0,0)
for i in range(0, 3):
for j in range(0, 3):
if board[i][j] == EMPTY:
board[i][j] = X
m, a = min2(board)
if m > M:
M = m
opt = (i,j)
board[i][j] = EMPTY
return M,opt
def min2(board):
"""
Returns the optimal move if it's O to play.
"""
opt = None
M = 99999999
utlty = utility(board)
if utlty is not None:
return utlty ,(0,0)
for i in range(0, 3):
for j in range(0, 3):
if board[i][j] == EMPTY:
board[i][j] = O
m, a = max2(board)
if m < M:
M = m
opt = (i,j)
board[i][j] = EMPTY
return M,opt
def minimax3(board):#Minimum time: 0.6 seconds
"""
here I applied the modification talked about in minimax2(), which is something similar to the alpha-beta prunning which is implemented later.
instead of using alpha and beta values, I used the maximum and minimum values.
when the max3() function reaches a position where the utility() function returns 1, it doesn't keep comparing it to other values since it's the largest possible value.
same thing with min3(), except that it returns -1 when reached without comparing it to other values.
after thinking about it, it's pretty much the same thing as the alpha-beta prunning,
except that here we already know what are the possible values and there is no need to wait to check other ones.
and here it's even easier to implement, but it porbably won't work in more complex games.
"""
if terminal(board):
return None
else:
if player(board) == X:
v,action = max3(board)
else:
v,action = min3(board)
return action
def max3(board):
opt = None
M = -99999999
utlty = utility(board)
if utlty is not None:
return utlty ,(0,0)
for i in range(0, 3):
for j in range(0, 3):
if board[i][j] == EMPTY:
board[i][j] = X
m, a = min3(board)
if m == 1:
board[i][j] = EMPTY
return m,(i,j)
if m > M:
M = m
opt = (i,j)
board[i][j] = EMPTY
return M,opt
def min3(board):
opt = None
M = 99999999
utlty = utility(board)
if utlty is not None:
return utlty ,(0,0)
for i in range(0, 3):
for j in range(0, 3):
if board[i][j] == EMPTY:
board[i][j] = O
m, a = max3(board)
if m == -1:
board[i][j] = EMPTY
return m,(i,j)
if m < M:
M = m
opt = (i,j)
board[i][j] = EMPTY
return M,opt
def minimax_alpha_beta_prunning(board):#Minimum time: 0.12 seconds
"""
I included the alpha-beta and the modification I added the previous minimax3().
it didn't change anything I think, the results before and after adding the modification were alike, with average of 1.4 seconds.
"""
if terminal(board):
return None
else:
alpha = -9999999
beta = 9999999
if player(board) == X:
v,action = max_alpha_beta_prunning(board, alpha, beta)
else:
v,action = min_alpha_beta_prunning(board, alpha, beta)
return action
def max_alpha_beta_prunning(board, alpha, beta):
opt = None
M = -99999999
utlty = utility(board)
if utlty is not None:
return utlty ,(0,0)
for i in range(0, 3):
for j in range(0, 3):
if board[i][j] == EMPTY:
board[i][j] = X
m, a = min_alpha_beta_prunning(board,alpha,beta)
if m == 1:
board[i][j] = EMPTY
return m,(i,j)
if m > M:
M = m
opt = (i,j)
board[i][j] = EMPTY
if M >= beta:
return M,(i,j)
if M > alpha:
alpha = M
return M,opt
def min_alpha_beta_prunning(board, alpha, beta):
opt = None
M = 99999999
utlty = utility(board)
if utlty is not None:
return utlty ,(0,0)
for i in range(0, 3):
for j in range(0, 3):
if board[i][j] == EMPTY:
board[i][j] = O
m, a = max_alpha_beta_prunning(board,alpha,beta)
if m == -1:
board[i][j] = EMPTY
return m,(i,j)
if m < M:
M = m
opt = (i,j)
board[i][j] = EMPTY
if M <= alpha:
return M,(i,j)
if M < beta:
beta = M
return M,opt |
def is_palindrome(self, targetString: str) -> bool:
stringArray = []
for character in targetString:
if character.isalnum():
stringArray.append(character.lower())
while len(stringArray) > 1:
if stringArray.pop(0) != stringArray.pop():
return False
return True |
# Your goal for this question is to write a program that accepts
# two lines (x1,x2) and (x3,x4) on the x-axis and returns whether they overlap.
# As an example, (1,5) and (2,6) overlaps but not (1,5) and (6,8).
# Assumptions
# a <= b and a < c
# c <= d and b < d
def isOverlapping (a, b, c, d):
if a==b & b==c:
return True
elif a < c & b >= c:
return True
elif a >= c & a <= d:
return True
elif a < c & b >= c:
return True
elif a >= c & a >= d:
return False
elif a < c & b < c:
return False
|
"""
Create a list called emotions that contains the first word of every line in emotion_words.txt.
"""
f = open("emotion_words.txt","r")
emotions = list()
for line in f:
emotions.append(line.split()[0]) |
"""
Using the file school_prompt.txt, if the character ‘p’ is in a word, then add the word to a list called p_words.
"""
f = open("school_prompt.txt","r")
p_words = []
for line in f:
words = line.split()
for word in words:
if "p" in word:
p_words.append(word) |
import unittest
from flexi.tree import Tree
from flexi.tree import create_sub_tree
class TestTree(unittest.TestCase):
def test_list(self):
root = Tree()
create_sub_tree(root, 'tree').list = [1, 2, 3]
self.assertListEqual(root.tree.list, [1, 2, 3])
def test_get_item(self):
root = Tree()
create_sub_tree(root, 'tree').int = 1
self.assertEqual(root.tree['int'], 1)
def test_recursive_scanning(self):
root = Tree()
create_sub_tree(root, 'tree')
root.tree.int = 1
root.tree.double = 2.0
root.tree.string = 'string'
create_sub_tree(root.tree, 'tree2').list = [1, 2, 3]
def recurse(tree):
for key in tree:
if isinstance(tree[key], Tree):
recurse(tree[key])
recurse(root)
def test_contains(self):
root = Tree()
create_sub_tree(root, 'tree').string = 'string'
self.assertIn('string', root.tree)
def test_representation(self):
root = Tree()
create_sub_tree(create_sub_tree(root, 'a'), 'b').c = 0
self.assertSequenceEqual(str(root), "{'a': {'b': {'c': 0}}}")
def test_equality(self):
root1 = Tree()
create_sub_tree(create_sub_tree(root1, 'a'), 'b').c = 2
root2 = Tree()
create_sub_tree(create_sub_tree(root2, 'a'), 'b').c = 2
self.assertEqual(root1, root2)
root2.a.b.c = 3
self.assertNotEqual(root1, root2)
def test_multiple_sub_tree_creation(self):
root = Tree()
create_sub_tree(root, 'a.b.c.d')
root.a.b.c.d.value = 1
def test_list(self):
root = Tree()
root.list = []
root.list.append(Tree())
root.list.append(Tree())
root.list[0].test = 'test'
root.list[1].test = 'test'
root.list[1].inner_list = []
root.list[1].inner_list.append('test')
self.assertEqual(root.list[1].inner_list[0], 'test')
|
# Algorithmic efficiency - O(V + E)
from collections import deque
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
def breadth_first_search(name):
search_queue = deque()
search_queue += graph[name]
searched = []
while search_queue:
person = search_queue.popleft()
if not person in searched:
if is_seelling_mango(person):
print(f"{person} is selling mango")
return True
else:
search_queue += graph[person]
searched.append(person)
return False
def is_seelling_mango(person):
if person.endswith("m"):
return True
return False
breadth_first_search("you")
|
# lists can contain differing datatypes
myList = ['spam', 2.0, 5, [10, 20]]
#if you read/write to an nonexistant eliment, you get an index error
'spam' in myList # returns true
# negative indicies wrap backwards to end of list
# common way to traverse a list while getting the index
for i in range(len(myList)):
print(myList[i])
# list operations
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c) # [1, 2, 3, 4, 5, 6]
print(a*3) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
# slice operator also works on lists
c[1:3] # [2, 3]
t = ['a', 'b', 'b', 'd', 'e', 'f']
t[1:3] = ['x']*2
print(t)
t.append('g')
t.extend(['j', 'i', 'h'])
print(t)
t.sort()
print(t)
#lists and strings
s = 'spam'
t = list(s)
print(t)
s = 'the quick brown fox'
t = s.split()
print(t)
#split can take an argument for a different dilimeter than ' '
#str.join(list of words) will make a string with tr inbetween elements
print(' '.join(t))
# pop removes the element and returns it
w = t.pop(1)
print(t)
print(w)
# del deletes element. Can be sliced.
del t[1]
|
# Exercise 2 - Pay program which avoids errors.
while True:
try:
hours = float(input("enter hours: "))
rate = float(input("enter rate: "))
break
except:
print('please enter a number.')
pay = hours * rate
print('your pay is : ' + str(pay))
|
"""
Chapter 8, Excercise 6
Write a program which repeatedly reads numbers until the user enters “done”.
Once “done” is entered, print out the total, count, and average of the
numbers. If the user enters anything other than a number, detect their
mistakeusing try and except and print an error message and skip to the next
number.
"""
#get list of values from user
enteredValues = []
userEnteredDone = False
while not userEnteredDone:
userInput = input("Please enter an integer, float, or type 'done' to finish: ")
if (userInput == "done"):
userEnteredDone = True
print(enteredValues)
else:
try:
enteredValues.append(float(userInput))
except:
print("The value you entered was invalid. Please try again.")
minimum = min(enteredValues)
maximum = max(enteredValues)
print("Minimum: " + str(minimum))
print("Maximum: " + str(maximum))
|
# -*- encoding = utf-8 -*-
def swap(arr, i ,j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def insertSort(arr):
for i in range(1, len(arr)):
j = i
while j > 0:
if (arr[j] < arr[j-1]):
swap(arr, j, j -1)
j -= 1
return arr
def insertSort2(arr):
for i in range(1, len(arr)):
temp = arr[i]
j = i
while j > 0:
if (arr[j - 1] > temp):
arr[j] = arr[j - 1]
else:
break
j -= 1
arr[j] = temp
return arr
def bubbleSort(arr):
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if (arr[j] < arr[i]):
swap(arr, i, j)
return arr
def selectSort(arr):
for i in range(len(arr)):
min = i
for j in range(i+1, len(arr)):
if arr[j] < arr[i]:
min = j
swap(arr, i, min)
return arr
if __name__ == '__main__':
arr = [10 , 8, 6, 5, 4, 2,1, 0]
arr = selectSort(arr)
for i in arr:
print(i) |
"""The symbol table stores the locations of each of the symbolic
variable names and the relative scope of those variables.
The tables contains the name of the variable, the type (int, ClassName)
and the kind (field, local)
"""
class SymbolTable:
def __init__(self, global_table=None):
self.global_table = global_table
self.table = {}
self.counts = {'local': 0, 'argument': 0, 'static': 0, 'field': 0}
def define(self, name, type, kind):
index = self.counts[kind]
assert name not in self.table
self.table[name] = (type, kind, index)
self.counts[kind] = index + 1
def var_count(self, kind):
return self.counts[kind]
def __getitem__(self, name):
if name in self.table:
return self.table[name]
elif self.global_table is not None:
return self.global_table[name]
def __contains__(self, name):
g = name in self.global_table if self.global_table is not None else False
return name in self.table or g
def type_of(self, name):
return self[name][0]
def kind_of(self, name):
return self[name][1]
def count_of(self, name):
return self[name][2]
def new_scope(self):
return SymbolTable(self)
def __repr__(self):
return repr(self.table)
|
#LO HICE MEDIANTE UNA LISTA DEBIDO A QUE ES NECESARIO POSEER UNA GRAN CAPACIDAD DE COMPUTO PARA ENCONTRAR NUMEROS PERFECTOS
numerosperfectos = [6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128]
numero = input('ingrese el numero N: ')
if numero.isdigit():
numero = int(numero)
if numero >= 9:
print('El siguiente numero perfecto es demasiado grande, intente con uno menor.')
else:
print(numerosperfectos[0:numero])
|
#! /usr/bin/env python3
"""Find the largest prime factor given a number."""
def get_largest_prime_factor(n):
prime_factor = False
prime_factor_val = None
factors = []
max_factor = n
x = 2
while x < max_factor:
if n % x == 0:
max_factor = int(n / x)
factors.insert(0, x)
factors.insert(0, max_factor)
x += 1
factors.sort()
factors.reverse()
print(len(factors), ' factors: ', factors)
for factor in factors:
composite = False
for x in range(2, factor):
if factor % x == 0:
composite = True
break
if not composite:
print('The largest prime factor for ', n, ' is ', factor)
break
def check_prime(x):
if x in primes:
return primes[x]
else:
current = max(primes.keys())
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-n', dest='num', metavar='int', help='Number to get largest prime factor.', default=4)
(options, args) = parser.parse_args()
get_largest_prime_factor(int(options.num))
|
import pandas as pd
import matplotlib.pyplot as plt
#import matplotlib as plt (Did not work to plot)
#import csv
file = "C:\\Users\\Pedrosky\\Documents\\GitHub\\learning\\Data\\Anacondas\\Panda\\2Dcsv.csv"
df = pd.read_csv(file)
new_df = df.sort_values(["x","y"], ascending=True,)
new_df.plot.scatter(["x"],["y"])
#new_df.plot() (it prints both x and y lines)
#new_df.plot.bar(x='X', stacked=True)
#another example using bars
plt.show()
print ("here's the data sample")
print (new_df.head())
#print (new_df.head())
#print (new_df [::-1])
#s_df.to_csv(r'C:\\Users\\Pedrosky\\Desktop\\Fitbit data\\No data\\Sleep_data_2019pandas.csv')
#PLOT
#https://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html
#https://pandas.pydata.org/pandas-docs/version/0.19/visualization.html
#https://www.shanelynn.ie/python-pandas-read_csv-load-data-from-csv-files/
|
#!/usr/bin/env python
#
# Based on the work of Pravin Paratey (April 15, 2011)
# Joachim Hagege (June 18, 2014)
#
# Code released under BSD license
#
from __future__ import print_function
from math import inf
#DISTANCE_INDEX = 1
class PriorityQueue:
""" This class illustrates a PriorityQueue and its associated functions """
def __init__(self, size=inf, key=None, default=0):
self.heap = []
self.k = size
self.__key = key
self._default = default
def _key(self, obj):
value, key = obj
_key = self.__key
if key is None:
return _key(value) if _key else self._default
return key
def __iter__(self):
for velue, key in self.heap:
yield value
def parent(self, index):
"""
Parent will be at math.floor(index/2). Since integer division
simulates the floor function, we don't explicity use it
"""
return int(index / 2)
def left_child(self, index):
return 2 * index + 1
def right_child(self, index):
return 2 * index + 2
def max_heapify(self, index):
"""
Responsible for maintaining the heap property of the heap.
This function assumes that the subtree located at left and right
child satisfies the max-heap property. But the tree at index
(current node) does not. O(log n)
"""
left_index = self.left_child(index)
right_index = self.right_child(index)
largest = index
#if left_index < len(self.heap) and self.heap[left_index][DISTANCE_INDEX] > self.heap[index][DISTANCE_INDEX]:
if left_index < len(self.heap) and self._item(left_index) > self._item(index):
largest = left_index
#if right_index < len(self.heap) and self.heap[right_index][DISTANCE_INDEX] > self.heap[largest][DISTANCE_INDEX]:
if right_index < len(self.heap) and self._item(right_index) > self._item(largest):
largest = right_index
if largest != index:
self.heap[index], self.heap[largest] = self.heap[largest], self.heap[index]
self.max_heapify(largest)
def build_max_heap(self):
"""
Responsible for building the heap bottom up. It starts with the lowest non-leaf nodes
and calls heapify on them. This function is useful for initialising a heap with an
unordered array. O(n)
We shall note that all the elements after floor(size/2) are leaves.
"""
for i in xrange(len(self.heap)/2, -1, -1):
self.max_heapify(i)
def heap_sort(self):
""" The heap-sort algorithm with a time complexity O(n*log(n))
We run n times the max_heapify (O(log n))
"""
self.build_max_heap()
output = []
for i in xrange(len(self.heap)-1, 0, -1):
self.heap[0], self.heap[i] = self.heap[i], self.heap[0]
output.append(self.heap.pop())
self.max_heapify(0)
output.append(self.heap.pop())
self.heap = output
def _item(self, index):
return self._key(self.heap[index])
def propagate_up(self, index):
""" Compares index with parent and swaps node if larger O(log(n)) """
#while index != 0 and self.heap[self.parent(index)][DISTANCE_INDEX] < self.heap[index][DISTANCE_INDEX]:
while index != 0 and self._item(self.parent(index)) < self._item(index):
self.heap[index], self.heap[self.parent(index)] = self.heap[self.parent(index)], self.heap[index]
index = self.parent(index)
# Here is the whole logic of the Bounded Priority queue.
# Add an element only if size < k and if size == k, only if the element value is less than
def add(self, value, key=None):
obj = value, key
# If number of elements == k and new element < max_elem:
# extract_max and add the new element.
# Else:
# Add the new element.
size = self.size()
# Size == k, The priority queue is at capacity.
if size == self.k:
max_elem = self.max()
# The new element has a lower distance than the biggest one.
# Then we insert, otherwise, don't insert.
#if obj[DISTANCE_INDEX] < max_elem:
if self._key(obj) < max_elem:
self.extract_max()
self.heap_append(obj)
# if size == 0 or 0 < Size < k
else:
self.heap_append(obj)
def heap_append(self, obj):
""" Adds an element in the heap O(ln(n)) """
self.heap.append(obj)
self.propagate_up(len(self.heap) - 1) # Index value is 1 less than length
def max(self):
# The highest distance will always be at the index 0 (heap invariant)
return self.heap[0][1]
def size(self):
return len(self.heap)
def extract_max(self):
"""
Part of the Priority Queue, extracts the element on the top of the heap and
then re-heapifies. O(log n)
"""
max = self.heap[0]
data = self.heap.pop()
if len(self.heap) > 0:
self.heap[0] = data
self.max_heapify(0)
return max
def increment(self, key, value):
""" Increments key by the input value. O(log n) """
for i in xrange(len(self.heap)):
if self.heap[i][0] == key:
self.heap[i] = (value + self.heap[i][1], key)
self.propagate_up(i)
break
|
# loops
# loops are repeated actions (iterations)
# loop wiht a counter (will run a certain number of times)
# n will become whatever you give it,
# the function is expecting a value from anywhere, but only 1 value
# so could have loop_with_counter(5)
# or my_num = 23 n\ loop_with_counter(my_num)
def loop_with_counter(n):
# requires a counter
c = 0
while c < n:
print("hello c is now {}".format(c) )
# increment c
c += 1
return None
count = 10
def loop_with_counter2(count):
# requires a count
c = 0
# counter is set on the counter value
while c < count:
print( "hello c is now {}".format(c) )
# increment c
c += 1
print("all done")
# indefinite loop
def while_loop_indefinite():
# set a condition
run = True
# check the condition
while run == True:
user_choice = input("Enter 'n' to stop loop n\or any other key to stay in the loop: ->")
if user_choice == "n":
print("loop will stop")
run = False
else:
print("you are still in the loop")
def for_in_range_loop():
# this has a bulit in counter
# can be anything but we generally use i or j or k
# can add steps (integer)
# first number, after last number, increment number (steps)
# if you put no step, then it's one
for i in range(3, 20, 5):
print(i)
# double loop
def double_loop():
for i in range(0,5):
for j in range(0,6):
print( "({},{})".format(j,i) , end = "" )
print()
def menu():
my_menu = '''
1: while loop with counter
2: while loop with quit
3: for in range
4: double loop
0: quit
'''
print (my_menu)
choice = int(input("choose your option: -> "))
if choice == 1:
amount = int(input("How many would you like: ->"))
loop_with_counter(amount)
elif choice ==2:
while_loop_indefinite()
elif choice == 3:
for_in_range_loop()
elif choice == 4:
double_loop()
elif choice == 0:
print("Thankyou")
else:
print("Unrecognised entry")
#menu()
# double_loop()
# for_in_range_loop()
# while_loop_indefinite()
# loop_with_counter(6)
#loop_with_counter2(6)
# 5.00
|
#Problem Statement:
#Given an array, rotate the array to the right by k steps, where k is non-negative.
#Example 1:
#Input: [1,2,3,4,5,6,7] and k = 3
#Output: [5,6,7,1,2,3,4]
#Explanation:
#rotate 1 steps to the right: [7,1,2,3,4,5,6]
#rotate 2 steps to the right: [6,7,1,2,3,4,5]
#rotate 3 steps to the right: [5,6,7,1,2,3,4]
#Example 2:
#Input: [-1,-100,3,99] and k = 2
#Output: [3,99,-1,-100]
#Explanation:
#rotate 1 steps to the right: [99,-1,-100,3]
#rotate 2 steps to the right: [3,99,-1,-100]
#Note:
#Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
#Could you do it in-place with O(1) extra space? Level: Easy
#Problem Practice Link: https://leetcode.com/problems/rotate-array/
#Companies Asked in: Amazon, Microsoft, Paypal, Goldman sachs, Facebook, Uber, Cisco, Adobe
#Similar Problems:
#1. Rotate List: https://leetcode.com/problems/rotate-list/
#2. Reverse Words in a String II: https://leetcode.com/problems/reverse-words-in-a-string-ii/
####### Naive solution (Approach 1) Time Complexity : O[n*k]
arr = [1,2,3,4,5,6,7]
k = 3
for iteration in range(k):
temp = arr[-1]
for i in range(len(arr)-1,0,-1):
arr[i] = arr[i-1]
arr[0] = temp
print(arr)
####### (Approach 2) Time Complexity : O[N]+O(K) Space Complexity : O(1)
arr = [1,2,3,4,5,6,7]
k = 3
def reverse(arr,start_index,end_index):
temp = 0
while start_index < end_index:
temp = arr[start_index]
arr[start_index] = arr[end_index]
arr[end_index] = temp
start_index+=1
end_index-=1
return arr
print(reverse(arr,len(arr)-k,len(arr)-1))
print(reverse(arr,0,len(arr)-k-1))
print(reverse(arr,0,len(arr)-1))
|
#Problem Statement:
#Given a non-empty array of integers, every element appears twice except for one. Find that single one.
#Note:
#Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
#Example 1:
#Input: [2,2,1]
#Output: 1
#Example 2:
#Input: [4,1,2,1,2]
#Output: 4
#Level: Easy
#Problem Practice link: https://leetcode.com/problems/single-number/
#Python Executable code: https://onlinegdb.com/SJ1p4B2W8
#Companies Asked in: Amazon, Google, Microsoft, Facebook, Oracle, Adobe, Airbnb
#Similar Problems:
#1. Single Number II: https://leetcode.com/problems/single-number-ii/
#2. Single Number III: https://leetcode.com/problems/single-number-iii/
#3. Missing Number: https://leetcode.com/problems/missing-number/
#4. Find the Duplicate Number: https://leetcode.com/problems/find-the-duplicate-number/
### Again, we will make use of the fact that XOR of a number with itself is 0
arr = [4,1,2,1,2,4,3]
def odd(arr):
num = 0
for i in arr:
num ^= i
return num
print(odd(arr)) |
val1 = []
agua = 0
fuego = 0
x = True
while x:
frase = input("escriba su frase: \n")
if "agua" in frase:
agua=agua+1
if "fuego" in frase:
fuego=fuego+1
if "agua" in frase or "fuego" in frase:
val1.append(frase)
print("escriba salir para salir o ")
if frase == "salir":
x = False
agua = {'agua' : agua}
fuego = {'fuego' : fuego}
print("agua =", agua)
print("fuego =",fuego)
print(val1)
|
'''
1. Открыть страницу http://SunInJuly.github.io/execute_script.html.
2. Считать значение для переменной x.
3. Посчитать математическую функцию от x.
4. Проскроллить страницу вниз.
5. Ввести ответ в текстовое поле.
6. Выбрать checkbox "I'm the robot".
7. Переключить radiobutton "Robots rule!".
8. Нажать на кнопку "Submit".
'''
import math
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\Py_Projects\chromedriver\chromedriver.exe")
driver.get("https://SunInJuly.github.io/execute_script.html")
#решаем задачу со страницы - "What is ln(abs(12*sin(x)))" и возвращаем в виде строки
def calc(x):
return str(math.log(abs(12 * math.sin(int(x)))))
#Находим эелемент и присваеваем переменной x его атрибут .text
x = driver.find_element_by_css_selector('#input_value').text
#Находим инпут и вводим в него результат вычесления функции от x
driver.find_element_by_css_selector('.form-control').send_keys(calc(x))
#Скроллим страницу вниз (сколл до элемента button), чтобы футер уехал с кнопки
button = driver.find_element_by_tag_name("button")
driver.execute_script("return arguments[0].scrollIntoView(true);", button)
#Отмечаем checkbox "I'm the robot"
driver.find_element_by_css_selector('#robotCheckbox').click()
#Выбраем radiobutton "Robots rule!" и нажимаем кнопку Submit
driver.find_element_by_css_selector('#robotsRule').click()
button.click()
'''
Варианты без JS кода:
1. try:
button = driver.find_element_by_tag_name("button")
_ = button.location_once_scrolled_into_view
button.click()
assert True
finally:
driver.quit()
2. Скрыть ненужный элемент
browser.execute_script('arguments[0].style.visibility = \'hidden\'', footer)
3. Проскроллить вверх или низ страницы можно и питоном для тега body
from selenium.webdriver.common.keys import Keys
driver.find_element_by_tag_name('body').send_keys(Keys.END) #или Home если наверх
''' |
"""
CENTRO UNIVERSITÁRIO METODISTA IZABELA HENDRIX
PROGRAMAÇÃO FUNCIONAL ORIENTADA A OBJETOS PYTHON
Aula 03
por Layla Comparin
"""
# Atributo são nome, idade, raça...
# Método são as funções em negrito.
# Self - Remete a tudo que for da classe Cachorro. (Init é um método - construtor.)
class Cachorro:
def __init__(self, n, d, r):
self.nome = n
self.datanasc = d
self.raca = r
self.temOsso = False
def latir(self):
print("Au, Au!")
def comandos(self, acao):
if(acao == "Dá a pata!"):
print("Toma a patinha... ")
if(acao == "Deita!"):
print("Estou deitado. Au! Au!")
if(acao == "Pula!"):
print("Estou pulando.. ")
def pegaOsso(self):
if self.temOsso:
print("Já tenho osso!")
else:
self.temOsso = True
print("Humm.. Que osso gostoso!")
def largaOsso(self):
if self.temOsso:
self.temOsso = False
print("Larguei o osso!")
else:
print("Osso? Onde??") |
################################################
# CENTRO UNIVERSITÁRIO METODISTA IZABELA HENDRIX
# PROGRAMAÇÃO FUNCIONAL ORIENTADA A OBJETOS PYTHON
# Aula 03
# por Layla Comparin
################################################
## Estruturas de Dados:
# Listas e Dicionários:
# Lista:
nomes = ['Layla', 'Gerson', 'Edésio', 'Iago']
print(nomes)
type(nomes)
len(nomes) # Quantidade de elementos na variável
nomes[0] # O primeiro elemento começa no 0, já no R começa no 1
nomes.append('Layla') # Insere um elemento na variável nomes
nomes.pop(0) # Remove um elemento na variável nomes
nomes[3] = 'Neylson' # Substitui um elemento na variável nomes por outro
nomes[:3] # Seleciona os elementos até a posição 3 - 0,1,2
nomes[1:3] # Seleciona os elementos da 2 até posição 3 - 1,2
nomes[1:] # Seleciona os elementos da 2 posição em diante - 2...
nomes[1:-1] # Seleciona os elementos da 2 posição até o penúltimo.
nomes[:-2] # Seleciona os elementos do inicio até o antepenúltimo.
# Mesma coisa acima, usando um nome completo:
nomeCompleto = "Layla Suellen Vilela Santos Comparin"
idade = 24
# A quebra de linha somente é para ser usada para quebrar o código dentro do PY.
nomeCompleto + ' tem ' + \
str(idade) + ' anos.'
# O \n quebra a linha na visualização do Console.
print (nomeCompleto + ' tem\n' + \
str(idade) + ' anos.')
### Dicionários:
# {'key': 'valor'}
alunos = {'nome':['Layla', 'Gerson'],
'idade':[24, 25],
'curso':['CD','CD'],
'natural':['Maceió', 'Recife']}
print(alunos)
alunos['nome'] # Printa o valor do elemento no Console
alunos['idade'] # Printa o valor do elemento no Console
alunos['curso'] # Printa o valor do elemento no Console
alunos['natural'] # Printa o valor do elemento no Console
alunos['idade'][1] # Printa o valor do elemento da segunda posição no Console
alunos.keys() # Retorna só o nome das colunas do dicionários
alunos.values() # Retorna o conteúdo das colunas do dicionários
alunos['bomAluno'] = True
alunos['bomAluno']
funcionalOO = {'Nome Disciplina':'Funcional e OO',
'Professor':'Neylson Crepalde',
'Sala': '2202',
'Quantidade de Alunos': 20,
'Cursos':['CD', 'BioInfo']}
print(funcionalOO)
funcionalOO.keys() # Retorna só o nome das colunas do dicionários
funcionalOO.values() # Retorna o conteúdo das colunas do dicionários
funcionalOO['Professor']
funcionalOO['Quantidade de Computadores']
funcionalOO['Cursos'][0]
len(funcionalOO['Sala']) #Retorna o número de variáveis dentro do atributo.
type(funcionalOO)
listaCursos = funcionalOO['Cursos']
funcionalOO['Cursos'] = {'nomes': listaCursos,
'id':list(range(1,13)),
'idade':list(range(25,36))}
import numpy as np #Importar pacote numpy - Análise de Dados
import scipy as sc #Importar pacote scipy - Análise de Dados
import pandas as pd #Importar pacote pandas - Análise de Dados
x = [3,5,4,7,6,9]
print(x)
len(x) #Retorna o número de variáveis dentro do atributo.
np.mean(x) # Tira a média do números de x.
min(x) # Tira o minimo do números de x.
max(x) # Tira o maximo do números de x.
np.var(x) # Tira a variancia do números de x.
np.sqrt(x) # Tira a raiz quadrada do números de x.
np.sqrt(x[0]) # Tira a raiz quadrada apenas do primeiro elemento de x.
tuple_exemple = 0,1,4,9,16,25 # Tuples são "listas" imutáveis, não aceitam alteração, apenas inserção.
tuple_exemple
tuple_exemple[2]
tuple_exemple[2] = 6 # Como não aceitam alteração, esse código dará erro.
import math as m
math.factorial(5)
|
class Board:
ROW_COL_BASE = 1
def __init__(self, board, N):
"""
Builds a Board from a list of blocks and the size of the board. The list must hold N^2 blocks.
:param board: the list with the blocks.
:param N: the size of the board (length = width = N)
:return: a new Board with the blocks setup as passed.
"""
self.board = board
self.N = N
@classmethod
def fromMatrix(cls, blocks):
"""
Builds a Board from a matrix of blocks, i.e. from a list of list of blocks.
:param blocks: the matrix with the blocks
:return: a new Board with the blocks setup as passed.
"""
l = []
for row in blocks:
for block in row:
l.append(block)
N = len(row)
return cls(l, N)
def dimension(self):
""" board dimension N """
return self.N
# public int hamming()
# number of blocks out of place
def manhattan(self):
'''
:return: the sum of Manhattan distances between blocks and goal
'''
manhval = 0
for idx, tile in enumerate(self.board):
if tile == 0: continue
rm = (tile -1) / self.N - idx / self.N
cm = (tile -1) % self.N - idx % self.N
manhval += abs(rm) + abs(cm)
return manhval
def isgoal(self):
'''
is this board the goal board?
:return: a boolean, true if this board is the goal board
'''
NN = self.N * self.N
for idx, val in enumerate(self.board):
if (idx != (NN-1) and val != idx +1):
return False
return True
def _index(self, row, col):
return self.N * (row - self.ROW_COL_BASE) + (col - self.ROW_COL_BASE)
def twin(self):
"""
a board that is obtained by exchanging any pair of blocks
:return: Board
"""
twin = self.board[:]
idx11 = self._index(1, 1)
idx12 = self._index(1, 2)
idx21 = self._index(2, 1)
idx22 = self._index(2, 2)
if (twin[idx11] == 0):
twin[idx12] = self.board[idx22] # 0 A
twin[idx22] = self.board[idx12] # x B
else:
if (twin[idx12] == 0):
twin[idx11] = self.board[idx21] # A 0
twin[idx21] = self.board[idx11] # B x
else:
twin[idx11] = self.board[idx12] # A B
twin[idx12] = self.board[idx11] ## ? ?
return Board(twin, self.N);
def neighbors(self):
"""
all neighboring boards
:return: a list of neighbours Boards
"""
blankidx = self.board.index(0)
brow = blankidx / self.N
bcol = blankidx % self.N
idx0 = self._index(brow + 1, bcol + 1)
nbrs = []
if brow > 0: # move space up
nbrs.append(self._neighborBoard(brow, bcol + 1, idx0))
if brow < self.N - 1: # move space down
nbrs.append(self._neighborBoard(brow + 2, bcol + 1, idx0))
if bcol > 0: # move space left
nbrs.append(self._neighborBoard(brow + 1, bcol, idx0))
if bcol < self.N - 1: # move space right
nbrs.append(self._neighborBoard(brow + 1, bcol + 2, idx0))
return nbrs
def _neighborBoard(self, brow, bcol, idx0):
idxdst = self._index(brow, bcol) # +1 is for 1 based row and cols
brd = self.board[:]
brd[idx0] = self.board[idxdst];
brd[idxdst] = self.board[idx0];
b = Board(brd, self.N)
return b
def __eq__(self, other):
if other is None: return False
if other is self: return True
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
def __ne__(self, other):
if other is None: return True
return not self.__eq__(other)
def toString(self):
"""
:return: the string representation of this board.
"""
s = '{N}\n'.format(N = self.N)
for idx, val in enumerate(self.board):
s += '{0:2d}'.format(val)
if ((idx + 1) % self.N) == 0: s += '\n'
return s
# public static void main(String[] args) // unit tests (not graded)
|
def stringspliter(sentence):
holder = int(0)
sentence = str(sentence)
print(sentence)
words = sentence.split(" ")
word_amount = len(words)
print("Your sentence has " + str(word_amount) + " words")
while holder != word_amount:
print(words[holder])
holder += 1
stringspliter(input("Input a sentence that I will break apart\n"))
|
#!/usr/bin/python
import sys
import re
import json
import getopt
import io
def parse_tweet_json(tweet, list_of_keys):
parsed_tweet = json.loads(tweet)
# a filtered tweet using a dictionary
filtered_tweet = {}
for mykey in list_of_keys:
search_key = mykey
# simple keys
myvalue = parsed_tweet.get(mykey)
filtered_tweet[mykey] = myvalue
# complex keys
#search_key = mykey.split('__')
#filtered_tweet[mykey] = scan_dictionary(parsed_tweet, search_key)
return filtered_tweet
def scan_dictionary(my_dict, search_key):
try:
result = reduce(dict.__getitem__, search_key, my_dict)
except (KeyError, TypeError):
pass
else:
return result
def delete_lastline_comma(filename):
with open(filename,"r+") as myfile:
lines = myfile.readlines()
myfile.writelines([item for item in lines[:-1]]) #delete last line
myfile.writelines("]")
myfile.close()
def parse_file(filename, output, list_of_keys):
with open(filename, "r") as myfile, open(output, "wb") as myout:
myout.write("[")
for line in myfile:
filtered_tweet = parse_tweet_json(line, list_of_keys)
json.dump(filtered_tweet, myout)
myout.write("\n,")
myout.write("]")
myout.close()
delete_lastline_comma(output)
if __name__ == "__main__":
if len(sys.argv) < 3:
print sys.argv[0], "[input file] [output file]"
print ""
print "Description:"
print "Arguments:"
print "input file -> a JSON file containing records (one per line)"
print "output file -> a file to write the extracted key/value pairs of JSON records; one record per line"
exit(1)
# Create a list of key to extract from the tweets
list_of_keys = []
list_of_keys.append("contributors")
list_of_keys.append("text")
list_of_keys.append("geo")
list_of_keys.append("retweeted")
list_of_keys.append("in_reply_to_screen_name")
list_of_keys.append("possibly_sensitive")
list_of_keys.append("truncated")
list_of_keys.append("lang")
list_of_keys.append("entities")
list_of_keys.append("in_reply_to_status_id_str")
list_of_keys.append("id")
list_of_keys.append("source")
list_of_keys.append("in_reply_to_user_id_str")
list_of_keys.append("retweet_count")
list_of_keys.append("created_at")
list_of_keys.append("in_reply_to_user_id")
list_of_keys.append("id_str")
list_of_keys.append("place")
list_of_keys.append("text")
list_of_keys.append("user")
list_of_keys.append("coordinates")
#for i in xrange(3, len(sys.argv)):
#list_of_keys.append(sys.argv[i])
# print list_of_keys
parse_file(sys.argv[1], sys.argv[2], list_of_keys)
|
#Fibonacci Numbers
fibonacci = list()
for i in range(1,55):
if i == 1:
fibonacci.append(i)
fibonacci.append(i)
else:
fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
if fibonacci[i] >= 55:
break
print(fibonacci)
|
deque = []
n = int(input())
result = []
for i in range(0, n):
cmd = input().split()
if cmd[0] == "push_front": deque.insert(0,cmd[1])
elif cmd[0] == "push_back": deque.append(cmd[1])
elif cmd[0] == "pop_front":
if len(deque) == 0: result.append(-1)
else:
result.append(deque[0])
deque.remove(deque[0])
elif cmd[0] == "pop_back":
if len(deque) == 0: result.append(-1)
else: result.append(deque.pop())
elif cmd[0] == "size": result.append(len(deque))
elif cmd[0] == "empty":
if len(deque) == 0: result.append(1)
else:result.append(0)
elif cmd[0] == "front":
if len(deque) == 0: result.append(-1)
else: result.append(deque[0])
elif cmd[0] == "back":
if len(deque) == 0: result.append(-1)
else: result.append(deque[len(deque)-1])
for r in result:
print(r)
|
number = 0
if (number ==0):
print(number)
else:
print("Hello")
number = 12
print(number) |
# 10. 請設計一個銀行帳號的類別,有name(姓名)及balance(帳戶餘額)兩個屬性,
# withdraw()提款、deposit()存款及check_balance()檢查餘額的三個方法。
# 產生一個銀行帳號的物件時,請列印出 [Hello Jack, 您的開戶金額是NT$100元]
# 提款時會列印
# 您提了NT$50元
# 餘額NT$50元
# 或
# 您的存款不足
# 存款時會列印出
# 您存了NT$1,000元
# 餘額NT$1,050元
class bank:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
print("Hello {0}, 您的開戶金額是NT${1}元".format(self.name, self.balance))
def withdraw(self, outmoney):
if self.balance >= outmoney:
self.balance -= outmoney
print("您提了NT${}元餘額NT${}元".format(outmoney, self.balance))
else:
print("您的存款不足")
def deposit(self, inmoney):
self.balance += inmoney
print("您存了NT${}元".format(inmoney))
def check_balance(self):
print("餘額NT${}元".format(self.balance))
name = input("請輸入姓名:")
makemoney = int(input("請輸入開戶金額:"))
user = bank(name, makemoney)
outmoney = int(input("請輸入提款金額:"))
user.withdraw(outmoney)
while outmoney <= makemoney:
inmoney = int(input("請輸入存款金額:"))
user.deposit(inmoney)
user.check_balance()
break
|
# 9. 讓使用者輸入身高、體重、腰圍及性別
# 根據身高及體重算出BMI,18.6 >= BMI < 24,或男性腰圍<90、女性腰圍<80,
# 就列印出健康,否則就列印出不健康,請使用function來完成
bf = input("請輸入性別(男OR女):")
tall = int(input("請輸入身高:"))
fat = int(input("請輸入體重:"))
heavy = int(input("請輸入腰圍:"))
bmi = fat / (tall / 100 ) ** 2
def myself():
if bf == "男" :
if bmi >=18.6 and bmi < 24 and heavy < 90:
print("健康")
else :
print("不健康")
if bf == "女" :
if bmi >=18.6 and bmi < 24 and heavy < 80:
print("健康")
else :
print("不健康")
myself()
|
# 4. 列出1到1000中不能被2整除也不能被3整除的數字
math = list(range(1, 1001))
print([i for i in math if i % 2 >= 1 and i % 3 >= 1])
|
# def fun(s1,s2,count):
# s = s1 + s2
# print(s * count)
# #位置參數
# fun("Hello ", "World ", 3)
# #關鍵字參數
# fun(count=2, s1="Hello ",s2="World ")
# def fun(s1, s2="World ", count=1):
# s = s1 + s2
# print(s * count)
# fun("Hello ")
# fun("Hello ", "Fiona ")
# fun("Hello ", "Steve ", 3)
# fun("Hello ", count=3)
# def count(s1,*add_all):
# print(s1)
# print(add_all)
# # count = 0
# # for ele in add_all:
# # count += ele
# # print(count)
# count(1)
# count(1,2)
# count(1,2,3)
# count(1,2,3,4)
# count(1,2,3,4,5)
# def info(**all_dict):
# print(all_dict)
# info(name="Tom")
# info(name="Tom",age=30,email="Tom@gmail.com")
def fun1(start, *args, **kwargs):
print("start=", start)
print("位置參數=", args)
print("關鍵字參數=", kwargs)
fun1(1,2,3,a=4,b=5)
|
list1 = [1,2,3,4,5,6,7,8,9,10]
# list2 = []
# for i in list1:
# list2.append(i**2)
# list2 = [i**2 for i in list1]
# print(list2)
# for i in list1:
# if i % 2 == 0:
# list2.append(i)
list2 = [i for i in list1 if i % 2 == 0]
print(list2)
|
# The goal of this program is to show an improvement
# to linear time from the recursive solution.
# It also shows a flaw in that it disregards stack limits.
# tracks the operations per calculation
operations = 0
# saves results of previous calculations
table = {0 : 0, 1 : 1}
# Accepts an position x as an integer. Calculates the
# Fibonacci sequence up to position x. Returns the
# Fibonacci number at position x.
def calcFib(x):
global operations, table
operations += 1
if x not in table :
table[x] = calcFib(x - 1) + calcFib(x - 2)
return table[x]
try:
while True:
position = input('Enter the fib you want to calc: ')
val = int(position)
print('#: ' + str(calcFib(val)))
print('# of operations: ' + str(operations))
operations = 0 # resets operation count for a new operation
except ValueError:
pass # input was not a valid integer |
# TAKE TWO NUMBERS AS INPUT AND PERFORM ALL THE ARITHMETIC OPERATIONS IN IT
x = int(input("ENTER FIRST NUMBER : "))
y = int(input("ENTER SECOND NUMBER : "))
add = x + y
sub = x - y
mult = x * y
div = x / y
floordiv = x//y
mod = x % y
exp = x ** y
print("SUM : ",add)
print("DIFFERENCE : ",sub)
print("MULTIPLICATION : ",mult)
print("DIVISION : ",div)
print("FLOOR DIVISION : ",floordiv)
print("MODULUS : ",mod)
print("EXPONENT : ",exp)
|
# # Use the file name mbox-short.txt as the file name
# fname = input("Enter file name: ")
# fh = open(fname)
# number = 0.0
# count = 0
# for line in fh:
# if not line.startswith("X-DSPAM-Confidence:"): continue
# # print(line)
# count += 1
# number += float(line[line.find(':')+1:].lstrip())
#
# print(number/count)
# fname = input("Enter file name: ")
# fh = open('hamza.txt')
#
# lst = list()
# for line in fh:
# line = line.rstrip()
# for word in line.split():
# if not word in lst:
# lst.append(word)
#
# lst.sort()
# print(lst)
# lst = lst + words
# print(lst.sort())
# fname = input("Enter file name: ")
fname = ''
if len(fname) < 1: fname = "hamza.txt"
fh = open(fname)
lst = list()
count = 0
for line in fh:
if line.rstrip().startswith('From '):
var = line.split()
print(var[1])
print(var[1])
print(var[1])
# var[2]
# res = lst
count += 1
print("There were", count, "lines in the file with From as the first word")
|
# Here we are going to see the default(naive) time demo available in python
import datetime
import time
# Cerating custom time
time_ = datetime.time(20,22,44,1000)
print(time_)
print("*"*50)
# Getting the default time
time_default = time.localtime(time.time())
print(time_default) |
# In this file we are going to see the different loops available in Python
# and Operations on it
myList = list(range(11))
print(myList,end="-")
print()
# While Loop
length = len(myList)
i = 0
while(i < length):
print(myList[i],end="-")
i += 1
print()
# For Loop
for i in myList:
print(i,end="==")
print() |
# In this tutorial, we are going to see the different operators
# available in Python
# Arithematic Operators
# Like +,-,*,/,%
a = 10
b = 5
print()
print("*"*50)
print(a+b) # addition
print(a-b) # substraction
print(a*b) # multiplication
print(a/b) # divison
print(a%b) # modulus
# Logical/Conditional Operators
# and, or, xor
print("*"*50)
print(a and b)
print(a or b)
# Bitwise Operator
# &,|,^
print("*"*50)
print(a & b)
print(a | b)
# Relational operators
# >,>=,==,=<,<
print("*"*50)
if(a > b):
print(a)
else:
print(b)
# Assignment Operators
# = (equal operator)
print("*"*50)
data = list(range(5))
print(data)
# Ternary Operators
# (Condition) ? OnTrue(Statement) : OnFalse(Statement)
print("*"*50)
res = a if a > b else b
print(res)
# Membership Operator
# in,not in
print("*"*50)
mobiles = ['Samsung','Apple','RealMe','Mi','AT&T']
# in operator
if 'RealMe' in mobiles:
print("That's the new Phone")
else:
print("All are old Models")
print("*"*50)
# not in operator
if 'MicroMax' not in mobiles:
print("No Indian Brand Mobiles")
else:
print("Micromax Mobiles are available")
#==========================================
# Identity Operators
# Like is,not is
# These operator are used to check the value of variables (two or more variables)
print("*"*50)
collection = ["name",1,3,44.44,False,"Ram"]
# Is Opertaor : It Checks whether both the value are of same of two differen varibles
for i in collection:
for j in collection:
print("I : ",i," == J : ",j)
if i is j :
print("Both are Same Data Type")
else:
print("Both are Different Data type")
# not is Operator : It Just the reverse of the is operator
print("*"*50)
for i in collection:
for j in collection:
print("I : ",i," !== J : ",j)
if i is not j :
print("true")
else:
print("false") |
def minMoves(h, w, h1, w1):
'''
:param h: initial high
:param w: initial width
:param h1: final high
:param w1: final width
:return: min moves to fold paper from initial to final dimentions
'''
moves = 0
# high
while h - h1 >= h1:
h = h // 2 + h % 2
moves += 1
if h%h1 != 0:
h -= h%h1
moves += 1
# width
while w - w1 >= w1:
w = w // 2 + w % 2
moves += 1
if w%w1 != 0:
w -= w%w1
moves += 1
return moves
print(minMoves(5, 5, 2, 2))
|
# https://sites.google.com/site/dlampetest/python/vector-3d
import math
class Vec3:
''' A three dimensional vector '''
def __init__(self, v_x=0, v_y=0, v_z=0):
self.set( v_x, v_y, v_z )
def set(self, v_x=0, v_y=0, v_z=0):
if isinstance(v_x, tuple) or isinstance(v_x, list):
self.x, self.y, self.z = v_x
else:
self.x = v_x
self.y = v_y
self.z = v_z
def __getitem__(self, index):
if index==0: return self.x
elif index==1: return self.y
elif index==2: return self.z
else: raise IndexError("index out of range for Vec3")
def __mul__(self, other):
'''Multiplication, supports types Vec3 and other
types that supports the * operator '''
if isinstance(other, Vec3):
return Vec3(self.x*other.x, self.y*other.y, self.z*other.z)
else: #Raise an exception if not a float or integer
return Vec3(self.x*other, self.y*other, self.z*other)
# python2 def __div__(self, other):
def __truediv__(self, other):
'''Division, supports types Vec3 and other
types that supports the / operator '''
if isinstance(other, Vec3):
return Vec3(self.x/other.x, self.y/other.y, self.z/other.z)
else: #Raise an exception if not a float or integer
return Vec3(self.x/other, self.y/other, self.z/other)
def __add__(self, other):
'''Addition, supports types Vec3 and other
types that supports the + operator '''
if isinstance(other, Vec3):
return Vec3( self.x + other.x, self.y + other.y, self.z + other.z )
else: #Raise an exception if not a float or integer
return Vec3(self.x + other, self.y + other, self.z + other)
def __sub__(self, other):
'''Subtraction, supports types Vec3 and other
types that supports the - operator '''
if isinstance(other, Vec3):
return Vec3(self.x - other.x, self.y - other.y, self.z - other.z)
else: #Raise an exception if not a float or integer
return Vec3(self.x - other, self.y - other, self.z - other )
def __abs__(self):
'''Absolute value: the abs() method '''
return Vec3( abs(self.x), abs(self.y), abs(self.z) )
def __neg__(self):
'''Negate this vector'''
return Vec3( -self.x, -self.y, -self.z )
def __str__(self):
return '<' + ','.join(
[str(val) for val in (self.x, self.y, self.z) ] ) + '>'
def __repr__(self):
return str(self) + ' instance at 0x' + str(hex(id(self))[2:].upper())
def length(self):
''' This vectors length'''
return math.sqrt( self.x**2 + self.y**2 + self.z**2 )
def length_squared(self):
''' Returns this vectors length squared
(saves a sqrt call, usefull for vector comparisons)'''
return self.x**2 + self.y**2 + self.z**2
def cross(self, other):
'''Return the cross product of this and another Vec3'''
return Vec3( self.y*other.z - other.y*self.z,
self.z*other.x - other.z*self.x,
self.x*other.y - self.y*other.x )
def dot(self, other):
'''Return the dot product of this and another Vec3'''
return self.x*other.x + self.y*other.y + self.z*other.z
def normalized(self):
'''Return this vector normalized'''
return self/self.length()
def normalize(self):
'''Normalize this Vec3'''
self /= self.length()
|
"""
This file has functions for a bubble sort and a random list GeneratorExit
Using the bubble_sort() function:
bubble_sort(*put the variable name or the list you want to be sorted*)
Using the get_random_list() function:
get_random_list(*put the length of the list you want*, *put the range of the list you want from 0,x*)
"""
from random import randint
from customerror import custom_error_raiser
def bubblesort(the_list): # This function runs a bubble sorting algorithm
swapped = True # This is used to determine whether the list is already sorted or not
length_remover = -1 # Decreases the length fo the for loop
while swapped:
swapped = False
length_remover += 1
for current in range(len(the_list)-1-length_remover): # In the for loop is when the swapping occurs
if the_list[current] > the_list[current+1]: # Swaps the values
the_list[current], the_list[current+1] = the_list[current+1], the_list[current]
swapped = True
return the_list # The output of the function
|
def swap_case(s):
result = []
for word in s.split(' '):
temp = []
for s in word:
if ord(s) >= 65 and ord(s) <= 90:
temp.append(s.lower())
elif ord(s) >= 97 and ord(s) <= 122:
temp.append(s.upper())
else:
temp.append(s)
result.append(''.join(temp))
return ' '.join(result)
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
|
#Link to problem https://leetcode.com/problems/palindrome-number/
class Solution:
def __init__(self): #value in x can be edited to test other solutions
x = -121 #must be of type int
result = self.isPalindrome(x) #must be of type bool
print('Answer: ', result)
def isPalindrome(self, x: int) -> bool:
if not isinstance(x, int) or x < 0:
return False
d_stripped = [d for d in str(x)]
d_flipped = d_stripped[::-1]
if (d_flipped == d_stripped):
return True
else:
return False
Solution() |
class Point:
row = 30
col = 30
fruitx = None
fruity = None
def __init__(self):
self.x =0
self.y =0
def __init__(self,x,y,check =True):
if x>-1 and x<self.row and y>-1 and y<self.col :
self.x = x
self.y = y
else:
raise ValueError
if x == Point.fruitx and y ==Point.fruity and check:
raise AssertionError
|
class Vechile:
def __init__(self, name, color):
self.name = name
self.color = color
def setname(self):
pass
class Bus(Vechile):
def __init__(self, name, color, brand):
self.brand = brand
Vechile.__init__(self, name, color)
# member function
def getname(self):
return self.name
def getcolor(self):
return self.color
def getbrand(self):
return self.brand
if __name__ == '__main__':
bus_obj = Bus("xy", "red", "mercedise")
print ("the name of the bus")
print (bus_obj.getname())
print ("the color of the bus")
print (bus_obj.getcolor())
#### MRO concepts ###### (method resolution concepts )
##
#### Diamond problem ###
# class A
# m()
# class B
# m() class c
# m()
# class D(B, C)
|
class Person(object):
def __init__(self, name, age=None, phone_no=None):
self.name = name
self.age = age
self.phone = phone_no
# for python code debugging we will use interactive python debugger
#import ipdb; ipdb.set_trace()
person = Person("rahul")
print (person.name)
# class Employee:
# # member varaible
# # member function
# pass
# obj = Employee()
# object is kind of memory in the python heap
####################################################
### mutable and immutable
# mutable == we can change (list, dictionary)
# immutable = we can't change during run time(tuple, string)
# gender ("male", "female")
# string pool
# pep8 Python Enhanement proposal
# > standard way of writing programme
# > like .. class will always start with upper case
# method willl always start with lower case
# def method() # this is not allowed
######################
|
class Dog:
Info = {} #commen for all objects
# def __init__(self): #default constructor
def __init__(self,name,age,weight):
self.name=name#instance variable
self.age=age
self.weight=weight
def printDetails(self):
print(self.name)
print(self.age)
print(self.weight)
def fillInfo(self,info):
self.Info.clear()
self.Info.update(info)
def bark(self):
for x in self.Info:
print(x+" : "+str(self.Info[x]))
print("Baww baww baww.....")
# bula =Dog()
# bula.Info.setdefault("name","Bula")
# bula.Info.setdefault("age",5)
# bula.Info.setdefault("color","Brown")
# bula.bark()
# tommy=Dog()
# tommy.Info.setdefault("name","Tommy")
# tommy.Info.setdefault("age",4)
# tommy.Info.setdefault("kind","Labrador")
# tommy.bark()
tommy=Dog("Tommy",23,53.5)
# tommy.fillInfo({"name":"Tommy","weight":40})
# tommy.bark()
tommy.printDetails() |
i=1
# while(i<10):
# print(i)
# i+=1
# else:
# print("End of the loop")
# while(i<10):
# s=10*i
# print("10 x %i = %s"%(i,s))
# i+=1
# for i in range(1,11):
# print("10 x %d = %d" % (i,i*10))
# list1=["apple","banana","orange","grapes"]
# for fruite in list1:
# print(fruite +" is a fruite")
# tp1=("apple","banana","orange","grapes")
# for fruite in tp1:print(fruite +" is a fruite")
dict1={1:"apple",2:"banana",3:"orange",4:"grapes"}
# for i in dict1:
# print(dict1[i] )
# print(type(dict1[i]))
# for x in dict1.items():
# print(x)
# for x in dict1.values():
# print(x)
# for x,y in dict1.items():
# print(x,y)
# list1=[[1,"kani"],[2,"thari"],[3,"abey"]]
# for x,y in list1:
# print(str(x)+" is "+y)
list1=[[["kamal","male"],10],[["nimala","female"],50]]
for x,y in list1:
print(x[0]+" is a "+x[1]+ " age is "+str(y))
|
import time,threading
class User(threading.Thread):
def __init__(self, x, y, username,client):
threading.Thread.__init__(self)
self.client=client
self.x = x
self.y = y
self.username = username
self.step=0
self.Running=True
self.inputs=[0,0,0,0] #left,right,up,down
def run(self):
while self.Running:
start_time = time.time()
self.move()
self.step+=1
end_time = time.time()
time.sleep(max(.01666-(end_time-start_time),0))#Go at 60 steps/second
def move(self):
if self.inputs[0]==1:
self.x-=5
if self.inputs[1]==1:
self.x+=5
if self.inputs[2]==1:
self.y-=5
if self.inputs[3]==1:
self.y+=5
|
#!/usr/bin/python
# could be more readable, but looks pretty :D
def isLeapYear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
return False
return True
return False
# days up to and including a month
# assumes not a leap year
def daysToMonth(month):
if month == 1:
return 31
t = 30 * month + month / 2 # integer division, drops 0.5 when month odd
if month % 2 == 0 and month <= 6:
return t - 2
return t - 1
def getDay(year, month, day):
# basic error checking (still allows for 02/30)
if year < 0:
return -1
if month < 1 or month > 12:
return -2
if day < 1 or day > 31:
return -3
if month == 1:
return 31
l = 1 if isLeapYear(year) else 0
return daysToMonth(month - 1) + day + l
|
def binarySearch( theValues, target ):
# Start with the entire sequence of elements.
low = 0
high = len(theValues) - 1
# Repeatedly subdivide the sequence in half until the target is found.
while low <= high:
mid = ( high + low ) // 2
if theValues[mid] == target:
return True
elif target < theValues[mid]:
high = mid - 1
else:
low = mid + 1
return False
# Performs a recursive binary search on a sorted sequence.
def recBinarySearch( theSeq, target, first, last ):
if first > last:
return False
else:
mid = ( last + first ) // 2
if theSeq[mid] == target:
return True
elif target < theSeq[mid]:
return recBinarySearch( theSeq, target, first, mid - 1)
else:
return recBinarySearch( theSeq, target, mid + 1, last )
if __name__ == '__main__':
l_value = [2, 4, 5, 10, 13, 18, 23, 29, 31, 51, 64]
t_value = 10
print 'binary search using loop: '
print binarySearch(l_value, t_value)
print 'bianry search using recursive: '
print recBinarySearch( l_value, t_value, 0, len(l_value) )
|
# Print the moves required to solve the Towers of Hanoi puzzle.
def move( n, src, dst, tmp ):
if n >= 1:
move( n-1, src, tmp, dst )
print "Move %d -> %d" % ( src, dst )
move( n-1, tmp, dst, src )
print "moving tower of hanoi starts: "
move( 1, 1, 3, 2 )
|
# ===================Bubble Sort=====================================
# Sorts a sequence in ascending order using the bubble sort algorithm.
def bubbleSort( theSeq ):
n = len( theSeq )
for i in range( n-1 ):
for j in range( n-i-1 ):
if theSeq[j] > theSeq[j+1]:
tmp = theSeq[j]
theSeq[j] = theSeq[j+1]
theSeq[j+1] = tmp
print 'iter ' + str(i+1)
for ele in theSeq:
print ele,
print ''
# ====================Selection Sort====================================
# Sorts a sequence in ascending order using the selection sort algorithm
def selectionSort( theSeq ):
n = len( theSeq )
for i in range( n-1 ):
smallNdx = i
for j in range( i+1, n ):
if theSeq[j] < theSeq[smallNdx ]:
smallNdx = j
if smallNdx != i:
tmp = theSeq[i]
theSeq[i] = theSeq[smallNdx]
theSeq[smallNdx] = tmp
print 'iter ' + str(i+1)
for ele in theSeq:
print ele,
print ''
# ===================Insertion Sort======================================
# Sorts a sequence in ascending order using the insertion sort algorithm.
def insertionSort( theSeq ):
n = len( theSeq )
for i in range(1, n):
value = theSeq[i]
pos = i
while pos > 0 and value < theSeq[pos-1]:
theSeq[pos] = theSeq[pos-1]
pos -= 1
theSeq[pos] = value
print 'iter ' + str(i)
for j in range(i+1):
print theSeq[j],
print ''
# ===================Merge Sort 01=======================================
# Merges two sorted lists to create and return a new sorted list.
def mergeSortedLists( listA, listB ):
newList = list()
a = 0
b = 0
# Merge the two lists together until one is empty
while a < len( listA ) and b < len( listB ):
if listA[a] < listB[b]:
newList.append( listA[a] )
a += 1
else:
newList.append( listB[b] )
b += 1
# If listA contains more items, append them to newList.
while a < len( listA ):
newList.append( listA[a] )
a += 1
# Or if listB contains more items, append them to newList.
while b < len( listB ):
newList.append( listB[b] )
b += 1
return newList
# Sorts a Python list in ascending order using the merge sort algorithm.
def MergeSort( theList ):
# Check the base case - the list contains s single item.
if len( theList ) <= 1:
return theList
else:
mid = len( theList ) // 2
leftHalf = MergeSort( theList[ :mid ] )
rightHalf = MergeSort( theList[ mid: ] )
newList = mergeSortedLists( leftHalf, rightHalf )
for ele in newList:
print ele,
print ''
return newList
# ========================Merge Sort 02==================================
# Sorts a virtual subsequence in ascending order using merge sort.
def recMergeSort( theSeq, first, last, tmpArray ):
if first == last:
return
else:
mid = ( first + last ) // 2
recMergeSort( theSeq, first, mid, tmpArray )
recMergeSort( theSeq, mid+1, last, tmpArray )
mergeVirtualSeq( theSeq, first, mid+1, last+1, tmpArray )
for ele in tmpArray:
print ele,
print ''
# Merges the two sorted virtual sublists: [left...right) [right..end)
def mergeVirtualSeq( theSeq, left, right, end, tmpArray ):
a = left
b = right
m = 0
while a < right and b < end:
if theSeq[a] < theSeq[b]:
tmpArray[m] = theSeq[a]
a += 1
else:
tmpArray[m] = theSeq[b]
b += 1
m += 1
while a < right:
tmpArray[m] = theSeq[a]
a += 1
m += 1
while b < end:
tmpArray[m] = theSeq[b]
b += 1
m += 1
for i in range( end - left ):
theSeq[i+left] = tmpArray[i]
# a wrapper function for the virtual subsequence merge sort
def mergeVirtualSort( theSeq ):
from myarray import myArray
n = len( theSeq )
tmpArray = myArray(n)
recMergeSort( theSeq, 0, n-1, tmpArray )
# ===========================Quick Sort===============================
# Sorts an array or list using the recursive quick sort algorithm
def quickSort( theSeq ):
n = len( theSeq )
recQuickSort( theSeq, 0, n-1 )
# The recursive implementation using virtual segments.
def recQuickSort( theSeq, first, last ):
if first >= last:
#for i in range(len(theSeq)):
# print theSeq[i],
#print ''
return
else:
#pivot = theSeq[first]
pos = partitionSeq( theSeq, first, last )
for i in range(first, pos):
print theSeq[i],
print ''
print theSeq[pos]
for i in range(pos+1, last+1):
print theSeq[i],
print ''
print '======='
recQuickSort( theSeq, first, pos-1 )
recQuickSort( theSeq, pos+1, last )
def partitionSeq( theSeq, first, last ):
pivot = theSeq[first]
print 'current pivot: %d' % pivot
left = first + 1
right = last
#print left, right
while left <= right:
# Find the first key larger than the pivot
while left < right and theSeq[left] < pivot:
left += 1
# Find the last key smaller than the pivot
while right >= left and theSeq[right] >= pivot:
right -= 1
# Swap the two keys
if left < right:
tmp = theSeq[left]
theSeq[left] = theSeq[right]
theSeq[right] = tmp
elif left == right:
break
if right != first:
theSeq[first] = theSeq[right]
theSeq[right] = pivot
return right
# =======================heap sort 01==================================
def simpleHeapSort( theSeq ):
from arrayheap import MaxHeap
# Create an array-based max-heap.
n = len( theSeq )
heap = MaxHeap( n )
# Build a max-heap from the list of values.
for item in theSeq:
heap.add( item )
# Extract each value from the heap and store them back into the list.
for i in range(n)[::-1]:
theSeq[i] = heap.extract()
# =======================heap sort 02==================================
# heap sort in place
def heapSort( theSeq ):
n = len( theSeq )
# Build a max-heap within the same array.
for i in range( n ):
_siftUp( theSeq, i )
for i in range( n ):
print theSeq[i],
print ''
# Extract each value and rebuild the heap.
for j in range( n-1, 0, -1 ):
tmp = theSeq[ j ]
theSeq[j] = theSeq[0]
theSeq[0] = tmp
_siftDown( theSeq, j-1, 0 )
for i in range( n ):
print theSeq[i],
print ''
# help function used in heapsort
def _siftUp( theSeq, ndx ):
if ndx > 0:
parent = ( ndx - 1 ) // 2
if theSeq[ndx] > theSeq[parent]:
tmp = theSeq[ndx]
theSeq[ndx] = theSeq[parent]
theSeq[parent] = tmp
_siftUp( theSeq, parent )
# help function used in heapsort
def _siftDown( theSeq, end_ndx, begin_ndx ):
left = 2 * begin_ndx + 1
right = 2 * begin_ndx + 2
largest = begin_ndx
if left <= end_ndx and theSeq[left] >= theSeq[largest]:
largest = left
if right <= end_ndx and theSeq[right] >= theSeq[largest]:
largest = right
if largest != begin_ndx:
tmp = theSeq[begin_ndx]
theSeq[begin_ndx] = theSeq[largest]
theSeq[largest] = tmp
_siftDown( theSeq, end_ndx, largest )
# =======================radix sort====================================
# Sorts a sequence of positive integers using the radix sort algorithm.
def radixSort( intList, numDigits ):
from llistqueue import Queue
from myarray import myArray
# Create an array of queues to represent the bins.
binArray = myArray( 10 )
for k in range( 10 ):
binArray[k] = Queue()
column = 1
# Iterate over the number of digits in the largest value.
for d in range( numDigits ):
# Distribute the keys across the 10 bins.
for key in intList:
digit = (key // column) % 10
binArray[digit].enqueue( key )
# Gather the keys from the bins and place them back in intList.
i = 0
for bin in binArray:
while not bin.isEmpty():
intList[i] = bin.dequeue()
i += 1
# Advance to the next column value.
column *= 10
for ele in intList:
print ele,
print ''
# =======================module test===================================
if __name__ == '__main__':
#theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
#print 'Bubble Sort: '
#bubbleSort(theSeq)
#theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
#print 'Selection Sort: '
#selectionSort(theSeq)
#theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
#print 'Insertion Sort: '
#insertionSort(theSeq)
#theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
#print 'Merge Sort: '
#sortedSeq = MergeSort( theSeq )
#for ele in sortedSeq:
# print ele,
#print ''
#theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
#print 'Merge Sort ( using virtual subsequence )'
#mergeVirtualSort( theSeq )
#for ele in theSeq:
# print ele,
#print ''
#theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
#print 'Quick Sort: '
#quickSort( theSeq )
#for ele in theSeq:
# print ele,
#print ''
#theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
#print 'Heap Sort: '
#simpleHeapSort( theSeq )
#for ele in theSeq:
# print ele,
#print ''
theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
print 'Heap Sort in place: '
heapSort( theSeq )
for ele in theSeq:
print ele,
print ''
#theSeq = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]
#print 'Radix Sort: '
#radixSort( theSeq, 2 )
|
# Implementation of the Sparse Matrix ADT using a list.
class SparseMatrix:
# Create a sparse matrix of size numRows * numCols initialized to 0.
def __init__( self, numRows, numCols ):
self._numRows = numRows
self._numCols = numCols
self._elementList = list()
# Return the number of rows in the matrix
def numRows( self ):
return self._numRows
# Return the number of colums in the matrix.
def numCols( self ):
return self._numCols
# Return the value of element (i, j): x[i, j]
def __getitem__( self, ndxTuple ):
row = ndxTuple[0]
col = ndxTuple[1]
assert row >=0 and row < self.numRows() and col >=0 and col < self.numCols(), \
"subscript out of range"
ndx = self._findPosition( row, col )
if ndx is not None:
return self._elementList[ndx].value
else:
return 0
# Set the value of element (i,j) to the value s: x[i,j] = s
def __setitem__( self, ndxTuple, scalar ):
ndx = self._findPosition( ndxTuple[0], ndxTuple[1] )
if ndx is not None:
if scalar != 0.0:
self._elementList[ndx].value = scalar
else:
self._elementList.pop( ndx )
else:
if scalar != 0.0:
element = _MatrixElement( ndxTuple[0], ndxTuple[1], scalar )
self._elementList.append( element )
# Scalar the matrix by the given scalar.
def scaleBy( self, scalar ):
for element in self._elementList:
element.value *= scalar
# add
def __add__( self, rhsMatrix ):
assert rhsMatrix.numRows() == self.numRows() and \
rhsMatrix.numCols() == self.numCols(), \
"Matrix sizes not compatible for the add operation."
# Create the new matrix
newMatrix = SparseMatrix( self.numRows(), self.numCols() )
# Duplicate the lhsmatrix. The elements are mutable, thus we must
# create new objects and not simply copy the reference.
for element in self._elementList:
dupElement = _MatrixElement( element.row, element.col, element.value)
newMatrix._elementList.append( dupElement )
# Iterate through each non-zero element of the rhsMatrix.
for element in rhsMatrix._elementList:
value = newMatrix[ element.row, element.col ]
value += element.value
newMatrix[ element.row, element.col ] = value
# Return the new matrix
return newMatrix
# sub
def __sub__( self, rhsMatrix ):
assert rhsMatrix.numRows() == self.numRows() and \
rhsMatrix.numCols() == self.numCols(), \
"Matrix sizes not compatible for the sub operation."
# Create the new matrix
newMatrix = SparseMatrix( self.numRows(), self.numCols() )
# Duplicate the lhsMatrix.
for element in self._elementList:
dupElement = _MatrixElement( element.row, element.col, element.value )
newMatrix._elementList.append( dupElement )
# Iterator through each non-zero element of the rhsMatrix.
for element in rhsMatrix._elementList:
value = newMatrix[ element.row, element.col ]
value -= element.value
newMatrix[ element.row, element.col ] = value
# Return the new matrix
return newMatrix
# multiply
def __mul__( self, rhsMatrix ):
assert rhsMatrix.numRows() == self.numCols(), \
"Marix sizes not compatible for the multiply operation."
# Create the new matrix
newMatrix = SparseMatrix( self.numRows(), rhsMatrix.numCols() )
for row in range( self.numRows() ):
for col in range( rhsMatrix.numCols() ):
tmp_sum = 0
for kk in range( self.numCols() ):
if self[ row, kk ] != 0 and rhsMatrix[ kk, col ] != 0:
tmp_sum += self[ row, kk ] * rhsMatrix[ kk, col ]
newMatrix[ row, col ] = tmp_sum
return newMatrix
# Helper method used to find a specific matrix element (row, col) in the
# list of non-zero entries. None is returned if the element is not found.
def _findPosition( self, row, col ):
n = len( self._elementList )
for i in range( n ):
if row == self._elementList[i].row and \
col == self._elementList[i].col:
return i
return None
# Storage class for holding the non-zero matrix elements.
class _MatrixElement:
def __init__( self, row, col, value ):
self.row = row
self.col = col
self.value = value
if __name__ == '__main__':
sparse_mat_A = SparseMatrix( 3, 4 )
sparse_mat_B = SparseMatrix( 3, 4 )
sparse_mat_C = SparseMatrix( 4, 2 )
sparse_mat_A[0, 0] = 1
sparse_mat_A[2, 3] = 3
sparse_mat_B[1, 2] = 4
sparse_mat_B[2, 3] = -3
sparse_mat_B[2, 2] = 1
sparse_mat_C[0, 0] = 5
sparse_mat_C[2, 1] = 2
sparse_mat_C[3, 1] = 11
print 'mat A: '
for i in range(3):
for j in range(4):
print sparse_mat_A[i, j],
print ''
print 'mat B: '
for i in range(3):
for j in range(4):
print sparse_mat_B[i, j],
print ''
print 'mat C: '
for i in range(4):
for j in range(2):
print sparse_mat_C[i, j],
print ''
add_mat_01 = sparse_mat_A + sparse_mat_B
print 'A + B: '
for i in range( add_mat_01.numRows() ):
for j in range( add_mat_01.numCols() ):
print add_mat_01[i, j],
print ''
sub_mat_02 = sparse_mat_A - sparse_mat_B
print 'A - B: '
for i in range( sub_mat_02.numRows() ):
for j in range( sub_mat_02.numCols() ):
print sub_mat_02[i, j],
print ''
mul_mat_03 = sparse_mat_A * sparse_mat_C
print ' A * C: '
for i in range( mul_mat_03.numRows() ):
for j in range( mul_mat_03.numCols() ):
print mul_mat_03[i, j],
print ''
|
#! python3
import requests
rs = requests.get('http://automatetheboringstuff.com/files/rj.txt')
# to check if link is ok in shell, only raise exception on error
rs.raise_for_status()
#this print the length of the downloaded link as a string.
print('The article is ' + str(len(rs.text)) + ' words long.')
#this print out the text itself, from 0 till the 500 character.
#print(rss.text[:500])
#To write it to a file, you can use a for loop with the iter_content() method.
#You can specify how many byte of "chunk" is written into it, 100000 is generally a good size.
pyFile = open('RJ.txt', 'wb') #wb means write binary
for chunk in rs.iter_content(100000):
pyFile.write(chunk)
pyFile.close()
'''
The for loop and iter_content() stuff may seem complicated compared to the open()/write()/close() workflow you’ve been using to write text files,
but it’s to ensure that the requests module doesn’t eat up too much memory even if you download massive files.
You can learn about the requests module’s other features from http://requests.readthedocs.org/.
''' |
import random
def isPrime(x):
for i in range(2,x):
if x%i == 0:
return False
return True
def genRandPrime():
index = random.randrange(65)
for i in xrange(2,2**32):
if isPrime(i):
if(index == 0):
return i
index -= 1
def genRsaKeys():
q = p = genRandPrime()
while p == q:
q = genRandPrime()
n = p*q
fn = (p-1)*(q-1)
e = 0
while e == 0:
i = random.randrange(0, fn)
if gcd(i, fn) == 1:
e = i
for i in reversed(range(1, fn)):
if (i*e)%fn == 1:
d = i
break
return {'public': [e, n], 'private': [d, n]}
from fractions import gcd
if __name__ == "__main__":
print(genRsaKeys())
|
def is_prime(x):
for i in range(2, x / 2 + 1):
if x % i == 0:
return False
return True
def find(fn):
for i in range(2,fn):
if fn % i == 0 and is_prime(i):
print(i)
if __name__ == "__main__":
find(int(input())) |
#!/usr/bin/python
def encrypt(keys, number):
return number**keys[1] % keys[0]
def decrypt(keys, number):
return number**keys[2] % keys[0]
if __name__ == '__main__':
n = int(input("Enter N: "))
t = 'a'
while t != 'E' and t != 'D':
t = raw_input("Enter Encrypt/Decrypt: ")
i = int(input("Enter key: "))
num = int(input("Enter integer: "))
if t == 'E':
print "Encrypted:", encrypt((n,i,0), num)
else:
print "Decrypted:", decrypt((n,0,i), num)
|
dict = {}
n = input()
for i in range(n):
name,m1,m2,m3 = map(str,raw_input().split())
l = []
name = str(name)
l.append(float(m1))
l.append(float(m2))
l.append(float(m3))
dict[name] = l
avg = 0
find_name = raw_input()
for i in dict[find_name]:
avg = avg+i
print "%.2f" %( avg/3.0)
|
import re
n = input()
for i in range(n):
a = raw_input()
a = a.split(' ',1)
if (len(a)>1):
a = a[1]
match = re.findall(r'#[a-f A-F 0-9]{6}|#[a-f A-F 0-9]{3}',a)
for j in match:
print j
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 2 00:45:12 2018
Name: Kewen Deng
Student ID: 29330440
Last modified date: May 4 2018
Description:
In this file, I have defined a class in this task for analysing the number of occurrences for each type of English sentences from the decoded sequences.
This class have a instance variable which is a dictionary structure that is used for keeping track of the number of occurrences for each type of sentences,
which is decoded by the Morse Code decoder in Task 1.
"""
class SentenceAnalyser:
def __init__(self):
# Build count of each character to by values in Dictionary
self.count = [0]*3
# Build '.', ',', '?' to be keys in Dictionary
self.cha = ['.', ',', '?']
self.dict = dict(zip(self.cha, self.count))
def __str__(self):
answer = 'The occurrences for each type of English sentences are: \n'
# Readbale format print
if any(self.dict.values()):
for key in self.dict:
answer = answer + key + ':' + str(self.dict[key]) + '\n'
return answer
else:
return 'No sentences occurrence.'
def analyse_sentences(self, decoded_sequence):
comma_close = True # Judge the comma has been ended by '.'/'?' or not
for i in decoded_sequence:
if i == '.':
self.dict['.'] += 1
if comma_close == False: # If the comma has been ended by '.', count of ',' plus 1.
comma_close = True
self.dict[','] += 1
if i == '?':
self.dict['?'] += 1
if comma_close == False: # If the comma has been ended by '?', count of ',' plus 1.
comma_close = True
self.dict[','] += 1
if i == ',':
self.dict[','] += 1
comma_close = False
|
print('------basic------')
print ('hello world!')
myStr = 'abc'
print(myStr)
a, b, c, d, e = 1, 'b', True, 3.14, 4+3j
print(type(a),type(b),type(c),type(d),type(e))
print('\n------number------')
print('2/4:',2/4)
print('2//4:',2//4)
print('2 ** 5:', 2 ** 5)
print('\n------str------')
s = 'Yes,he\'s'
print(s,type(s),len(s))
print('c:\a\b')
print(r'c:\a\b')
print('str'+'ing','alex'*2)
p = 'Python'
print(p[0],p[5])
print(p[-6],p[-1])
print(p[0:1])
print(p[-6:-5])
print(p[2:])
print(p[-4:])
print('\n------list------')
a = ['She','is','my','lover']
print(a)
print(a + ['He','is','my','boy'])
a[3] = 'wife';
print(a)
print(a[2:3])
print(a[2:])
a[2:] = []
print(a)
|
# follow.py
#
# Follow a file like tail -f.
import time
import pandas as pd
from io import StringIO
# create generator that yields line
# generators can be iterated through only once
def follow(thefile):
thefile.seek(0,2) # 0 is offset, 2 is whence (relative to file end)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line # return line
if __name__ == '__main__':
logfile = open("file.csv","r")
loglines = follow(logfile) # create object of the generator
# for loop runs the generator code in every iteration
# once it reaches yield, it returns the line
for line in loglines:
line = line.split('$')
# line contains data separated with $
# the number of columns is 13
# however some dataframes will show len < 13 because the data is written incompletely by tshark
# every few seconds 1 dataframe will be dropped
if len(line) == 13:
print(pd.DataFrame([line])) |
(S, C) = ('John Doe; Peter Benjamin Parker; Mary Jane Watson-Parker; John Elvis Doe; John Evan Doe; Jane Doe; Peter Brian Parker', 'Example')
print(C.lower())
naemDict = {}
resLst = []
for name in S.split('; '):
nameType = name.split()
if len(nameType) == 2:
firstName = nameType[0].lower()
lastName = nameType[1].lower()
elif len(nameType) == 3:
firstName = nameType[0].lower()
middleName = nameType[1].lower()
lastName = nameType[2].lower()
tempLastName = ''
for i in lastName:
if i != '-':
tempLastName += i
lastName = tempLastName
emailPrefix = firstName+'.'+lastName[:8]
try:
naemDict[emailPrefix] += 1
except:
naemDict[emailPrefix] = 1
if naemDict[emailPrefix] == 1:
email = '{emailPrefix}.{C}.com'.format(
emailPrefix=emailPrefix, C=C.lower())
else:
email = '{emailPrefix}{count}.{C}.com'.format(
emailPrefix=emailPrefix, C=C.lower(), count=naemDict[emailPrefix])
resLst.append(email)
print('; '.join(resLst))
# 제출
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(S, C):
# write your code in Python 3.6
naemDict = {}
resLst = []
for name in S.split('; '):
nameType = name.split()
# middle name이 존재하는 경우
if len(nameType) == 2:
firstName = nameType[0].lower()
lastName = nameType[1].lower()
# middle name이 존재하지 않는 경우
elif len(nameType) == 3:
firstName = nameType[0].lower()
middleName = nameType[1].lower()
lastName = nameType[2].lower()
# 하이픈이 있을때 제외하고 진행
tempLastName = ''
for i in lastName:
if i != '-':
tempLastName += i
lastName = tempLastName
emailPrefix = firstName+'.'+lastName[:8]
# first name , last name 중복이 있을 경우
# 중복 개수 확인
try:
naemDict[emailPrefix] += 1
except:
naemDict[emailPrefix] = 1
# 중복이 있을 경우와 없을 경우 output 생성
if naemDict[emailPrefix] == 1:
email = '{emailPrefix}@{C}.com'.format(
emailPrefix=emailPrefix, C=C.lower())
else:
email = '{emailPrefix}{count}@{C}.com'.format(
emailPrefix=emailPrefix, C=C.lower(), count=naemDict[emailPrefix])
# 샘플별 결과 저장
resLst.append(email)
# result format으로 변경
res = '; '.join(resLst)
return res
|
# evaluate a string
def parse_integer(s):
i = int(s)
return i
def parse_float(s):
i = float(s)
return i
def parse_string(s):
i = str(s).lower()
return i
def evaluate_string(s):
try:
st = parse_string(s)
if any(i in st for i in 'aeiou'):
return True
else:
return False
except ValueError:
return False |
import tkinter as tk
from tkinter import ttk
def greet():
print(f'Hello, {user_name.get() or "World"}.')
root = tk.Tk()
user_name = tk.StringVar()
name_label = ttk.Label(root, text='Name: ') # Pode-se colocar espaço após a label dessa forma
name_label.pack(side='left', padx=(0, 10)) # Ou então dessa forma
name_entry = ttk.Entry(root, width=25, textvariable=user_name)
name_entry.pack(side='left')
name_entry.focus()
greet_button = ttk.Button(root, text='Greet', command=greet)
greet_button.pack(side='left')
quit_button = ttk.Button(root, text='Quit', command=root.destroy)
quit_button.pack(side='right')
root.mainloop()
|
#!/usr/bin/env python3
# Copyright 2019 Ricardo Iván Vieitez Parra
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
def krampus(num) -> int:
squared = num * num
numStr = str(squared)
for i in range(1, len(numStr)):
num1 = int(numStr[i:])
num2 = int(numStr[:i])
if num1 == 0 or num == 0: return 0
if num1+num2 == num: return num
return 0
sum = 0
for num in open("krampus.txt").readlines():
sum += krampus(int(num))
print(sum)
|
#!/usr/bin/python
from __future__ import print_function
print("Hello World!")
1 + 1
2 ** 2 ** 2 ** 2 ** 2
x=5
type(x)
x=5.0
type(x)
y = x
x, y = 17, 42
l = [1, 2, 3]
l[0]
x = [1, 3, 7]
y = x
y
x[1] = 6
y
4 ** 62
1.0 / 2
0xBEE
hex(3054)
0b10
int('0b10',2)
bin(2)
5 % 2
5 == 6
str = "Look how easy!"
"I am %d years old, and my cat's name is %s." % (17, 'Shmulik')
chr(97)
ord('a')
"%d"%1234
len('Hello')
'look at me'.split(' ')
s = 'ugifletzet'
s[1]
s[1] = 'G'
S = s.upper()
S.lower()
# bytes type - Python 3 equivalent for strings in Python 2
b'one'
b'one'[0]
hex(b'one'[0])
b'one'.upper()
'Hello'.index('H')
'Hello'.find('b')
x = [1, 2, 3, 4, 5]
x = x + [6]
x.append(6)
x[0] = 7
x * 3
x[1:3]
x[1::2]
x[::-2]
x = [1, 2, 3]
y = x[:]
y.append(4)
t = (1, 2, 3)
t
t[0] = 2
(a, b, c) = (1, 2, 3)
x, y = y, x
d = {}
d[1] = "Sunday"
d
d = {1: 'Sunday', 2: 'Monday'}
1 in d
3 in d
d.keys()
d.values()
d.items()
num = 5
if num > 3:
print (num * 2)
num = 17
if (num > 5) or (num == 15):
print ("something")
sky = 'Blue'
if not 4 == 7:
print ("always true")
if sky == 'Red':
print ("Hell's rising!!")
elif sky == 'Yellow':
print ('Just a sunny day ^_^')
elif sky == 'Green':
print ('Go see a doctor')
else:
print ('It appears the sky is %s' % (sky, ))
i = 0
while i < 10:
print (i)
i += 1
days = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
for day in days:
print (day)
for i in range(10):
print (i)
def func():
print ("I am a function") # funny comment here
def f(num):
num = 3
x = 1
f(x)
x
def func_with_defaults(x, y=5, z=17):
return x, y, z
opened_file = open('x.txt', 'w')
opened_file.write('my first file!\n')
opened_file.close()
file = open('x.txt', 'r')
content = file.read()
file.close()
func()
cipher = "wklv phvvdjh lv qrw wrr kdug wr euhdn"
print(cipher.replace("w","t"))
# print(cipher) #notice, it is immutable
# print cipher #in python2.7 this works too
# print(cipher.replace("w","t").replace("r","o"))
plain = ""
for c in cipher:
if c == ' ':
plain += c
else:
plain += chr(ord(c) - 3)
print(plain)
|
print('Módulo importado com sucesso!!!')
def encontra_indice(lista, alvo):
for i, value in enumerate(lista):
if value == alvo:
return 1
return -1
teste = 'Testado.' |
"""
7. Para resolver as questões abaixo considere o livro "Generative
Art: A Practical Guide Using Processing" por Matt Pearson.
Sugere-se que se use Python, mas admite-se a solução em qualquer
programa que não seja o "Processing" cujas soluções estão
apresentadas no livro. Todas essas questões devem ser bem
explicadas (e enunciadas), bem referenciadas e um código deve ser
implementado na linguagem de sua escolha. Você pode e deve
abusar a sua solução com o uso de
guras.
a) (*) Replique Figuras 4.7 e 4.8.
p. 74 do livro
"""
import turtle
import math
import random
def ruido(valor, regular):
"""Retorna o ruído com base no valor recebido com parâmetro
Se o ruído é regular, o valor do ruído é o seno ao cubo.
Se o ruído não é regular, o valor do ruído é o seno elevado ao resto
da divisão inteira por 12 do valor recebido como parâmetro
"""
if regular:
return math.pow(math.sin(valor), 3)
else:
count = int((valor % 12))
return math.pow(math.sin(valor), count)
def desenha_ruido(raio_regular, regular):
"""Desenha o ruído ao redor do círculo"""
turtle.pensize(1) # grossura do traço
turtle.begin_fill() # figura será colorida no final
val_ruido = random.randrange(10) # gera um número aleatório entre 0 e 10
for i in range(360):
"""Desenha o ruído ao redor do círculo com espaçamento de um grau"""
val_ruido += 0.1
raio_variavel = 30 * ruido(val_ruido, regular)
raio = raio_regular + raio_variavel # a cada iteração é desenhada uma linha com tamanho tamanho do raio regular mais um valor variável
rads = (i/180) * math.pi # converte de graus para radianos
x = raio * math.cos(rads)
y = raio * math.sin(rads)
if (i == 0):
turtle.penup() # não desenha a linha na primeira movimentação
x_inicial = x # armazena a posição inicial para fechar a figura
y_inicial = y
else:
turtle.pendown()
turtle.setpos(x, y)
turtle.dot(size = 2)
turtle.setpos(x_inicial, y_inicial) # fecha a figura
turtle.end_fill()
def desenha_circulo(raio_regular):
"""Desenha o círculo interno da figura"""
turtle.penup() # para não desenhar a linha na primeira movimentação
turtle.setpos(0, -raio_regular) # a posição inicial do círculo é a parte mais baixa dele e não o centro
turtle.pendown()
turtle.pensize(3) # largura do círculo é maior que a largura do desenho que envolve o circulo
turtle.circle(raio_regular) # desenha um círculo de raio 100
if __name__ == '__main__':
# https://ecsdtech.com/8-pages/121-python-turtle-colors
turtle.color("light gray", "dim gray") # primeira cor é da linha e segunda é do preenchimento
turtle.speed(10) # seta a velocidade máxima do turtle
turtle.home()
raio_regular = 100
regular = 0 # se 1, o ruido é regular e a figura 4.7 é desenhada; se 0, o ruído não é regular e a figura 4.8 é desenhada
desenha_ruido(raio_regular, regular)
desenha_circulo(raio_regular)
turtle.done()
turtle.exitonclick() |
# INPUT_FILE = 'test_input.txt'
INPUT_FILE = 'input.txt'
class BingoBoard():
def __init__(self, row_list):
self.board = row_list # 2d 5x5 array of ints
self.marked = [[False for _ in range(5)] for _ in range(5)]
self.marked_cols = [[False for _ in range(5)] for _ in range(5)]
self.setup_coords_dict() # sets up dict like { num1: (x1, y1), num2: (x2, y2), etc }
def process_num(self, num):
if num in self.coords_dict:
x,y = self.coords_dict[num]
self.mark(x,y)
def row(self, idx):
return self.board[idx]
def col(self, idx):
return list(zip(*self.board[idx]))
def mark(self, x, y):
self.marked[x][y] = True
self.marked_cols[y][x] = True
def won(self):
return any(all(row) for row in self.marked) or any(all(row) for row in self.marked_cols)
def score(self, final_num):
unmarked_sum = 0
for x in range(5):
for y in range(5):
if not self.marked[x][y]:
unmarked_sum += self.board[x][y]
return unmarked_sum * final_num
def setup_coords_dict(self):
self.coords_dict = {}
for x in range(5):
for y in range(5):
val = self.board[x][y]
self.coords_dict[val] = (x,y)
def parse_board(board_str):
result = []
for row in board_str.split('\n'):
formatted_row = [int(x) for x in filter(None, row.split(" "))]
result.append(formatted_row)
return result
def parse_input(input_file):
# returns ([draw_list], [bingo_board_list])
with open(input_file, 'r') as f:
inputs = [x for x in f.read().split('\n\n')]
draw_list = [int(x) for x in inputs[0].split(',')]
boards = [BingoBoard(parse_board(x)) for x in inputs[1:]]
return (draw_list, boards)
def winning_board(boards):
for b in boards:
if b.won():
return b
return None
def part_one():
draw_list, boards = parse_input(INPUT_FILE)
draw_idx = 0
last_drawn = None
winner = None
while winner is None:
last_drawn = draw_list[draw_idx]
draw_idx += 1
for b in boards:
b.process_num(last_drawn)
winner = winning_board(boards)
print(winner.score(last_drawn))
return winner
def main():
draw_list, boards = parse_input(INPUT_FILE)
original_boards = boards.copy()
draw_idx = 0
last_drawn = None
while len(boards) > 1:
last_drawn = draw_list[draw_idx]
draw_idx += 1
for b in boards:
b.process_num(last_drawn)
boards = list(filter(lambda x: not x.won(), boards))
# breakpoint()
losing_board = boards[0]
while not losing_board.won():
last_drawn = draw_list[draw_idx]
draw_idx += 1
losing_board.process_num(last_drawn)
# breakpoint()
print(losing_board.score(last_drawn))
return losing_board
if __name__ == '__main__':
main() |
'''
平衡树
'''
import copy
import time
def cral_time(fun):
def wrapper(*args, **kwargs):
start_time = time.time()
result = fun(*args, **kwargs)
end_time = time.time()
print("执行时间:", end_time - start_time)
return result
return wrapper
@cral_time
def num_split(n):
if n == 1:
li_res = []
li_res.append([1])
return li_res
else:
li_res = [[1]]
# print(len(li_res))
for i in range(n - 1):
li_zj = []
for j in range(len(li_res)):
dep_copy = copy.deepcopy(li_res[j])
# li_res[j].append(1)
# li_zj.append(li_res[j])
# print(dep_copy)
# print(li_zj)
for k in range(len(li_res[j])):
dep_copy = copy.deepcopy(li_res[j])
dep_copy[k] += 1
dep_copy.sort(reverse=True)
if dep_copy not in li_zj:
li_zj.append(dep_copy)
li_res[j].append(1)
li_zj.append(li_res[j])
li_res = li_zj
return li_res
res = num_split(31)
res.sort(key=lambda x: len(x))
print(len(res))
print(res)
|
from . import np
from NeuralNetworks.activations.sigmoid import sigmoid
def logistic_predict(w, b, X):
'''
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (n_x, number of examples)
Returns:
Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
'''
# Compute vector "A" predicting the probabilities of a cat being present in the picture
A, _ = sigmoid(np.dot(w.T, X) + b)
Y_prediction = (A > 0.5).astype(int)
assert (Y_prediction.shape == (1, X.shape[1]))
return Y_prediction
def linear_predict(w, b, X):
'''
Predict whether the label is 0 or 1 using learned linear regression parameters (w, b)
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Returns:
Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
'''
# Compute vector "A" predicting the probabilities of a cat being present in the picture
A = np.dot(w.T, X) + b
assert (A.shape == (1, X.shape[1]))
return A
|
import matplotlib.pyplot as plt
import numpy as np
from 求导 import first_derivative, second_derivative
from Functions import fun2
def fun(x):
return x**3 - 2*x + 1
def display(fun, x0=6, a=-1, b=6, h=6, delta=0.001):
# fun: 输入的函数, 二维
# x0: 初始点坐标
# a: 范围的下限
# b: 范围的上限
# delta: 步长
# return: 迭代的次数,结果的坐标
ax=plt.gca()
X = np.linspace(a, b, 100)
plt.plot(X, fun(X), color='y')
# h = np.random.randint(1, 10)
x = x0
times = 0
while abs(h) > delta:
ax.scatter(x,fun(x), c='green',marker='o')
plt.pause(0.2)
times += 1
if fun(x + h) < fun(x):
h *= 2
x += h
else:
h *= -1 / 4
x += h
ax.scatter(x,fun(x), c='red',marker='o')
plt.show()
return times, x
if __name__ == "__main__":
times, x = display(fun, x0=-0.5, h=0.5)
print("迭代次数为:{:}, 极小值点为:{:}".format(times, x))
|
#!/usr/bin/env python3
def funcao5():
so = "so"
trabalho = " trabalho"
sem = " sem"
diversao = " diversao"
faz = " faz"
de = " de"
joao = " joao"
em = " em"
chato = " chato"
print(so+trabalho+sem+diversao+faz+de+joao+em+chato)
funcao5()
|
# digest_network.py
# written by Chris Coletta for BIOF 518
# takes as input a file containing node pairs (edges) one per line
# and calculates statistics such as diameter and clustering coefficients
import re
from copy import deepcopy
import sys
debug = 0
#================================================================
class AutoVivification(dict):
"""This is just an convenience class which is an implementation of
Perl's autovivification functionality."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
#================================================================
def PrintNetwork( the_network ):
"""PrintNetwork takes a Python dictionary containing nodes and edges
and just prints out the information in node order from smallest number of edges to largest"""
nodecount = 0
for k in sorted( the_network.keys(), lambda x,y: cmp( len(the_network[x]), len(the_network[y]) ) ):
nodecount += 1
print 'node {} has edges with {} members: {}'.format(k, len(the_network[k]), the_network[k])
# how many nodes are in the network
print '\nNetwork has {} nodes\n'.format( nodecount )
#================================================================
def NetworkWithoutMe( me, the_network ):
"""NetworkWithoutMe prunes the node "me" from the inputted network and returns
the smaller pruned network"""
if debug: print "\t deleting me: {}".format(me)
smaller_network = deepcopy( the_network )
# first delete any of my neighbors that are only connected to me and my neighbors
# meaning, delete neighbor if neighbor's edges is a subset of my edges
my_neighbors = the_network[me]
if debug: print "\t{}'s neighbors: {}".format( me, my_neighbors )
for edge in my_neighbors:
# remove me from my neighbor's neighbor list since I'm going anyway
if debug: print "\t{}'s neighbor {}:".format(me, edge)
if debug: print "\t\t{}'s neighbors: {}".format(edge, smaller_network[edge])
smaller_network[edge].remove(me)
if smaller_network[edge].issubset( my_neighbors ):
if debug: print "\t\ti can delete {} because {} is subset of {}".format( edge, smaller_network[edge], my_neighbors )
for departing_neighbors_neighbor in smaller_network[edge]:
smaller_network[departing_neighbors_neighbor].remove( edge )
del smaller_network[edge]
del smaller_network[me]
return smaller_network
#================================================================
def GetDistance( this_node, that_node, orig_network, depth=0):
"""GetDistance returns the shortest distance between two nodes"""
the_network = orig_network.copy()
if debug: print "depth {}: calculating distance between {} and {}".format(depth, this_node, that_node )
if this_node == that_node:
if debug: print "identity"
return 0
# check to see if that_node is in this_node's list of edges
if debug: print "check if {} is in {}'s set of edges: {}".format(that_node, this_node, node_dict[this_node] )
my_neighbors = the_network[this_node].copy()
for link in the_network[this_node]:
if link == that_node:
if debug: print "******FOUND:{} has edge with {}".format( this_node, that_node )
return 1
# if not, remove me from the network and continue to find dists from my viable neighbors
if debug: print "removing {} from depth {} network (size {})".format(this_node, depth, len(the_network))
smaller_network = NetworkWithoutMe( this_node, the_network )
# remove any nodes from my_neighbors that got pruned from the smaller network
set_of_nodes_in_smaller_netw = set()
for node in smaller_network.keys():
set_of_nodes_in_smaller_netw.add(node)
my_neighbors.intersection_update( set_of_nodes_in_smaller_netw )
min_dist = 999
for link in my_neighbors:
link_dist = GetDistance( link, that_node, smaller_network, depth+1)
if link_dist < min_dist:
min_dist = link_dist
return 1 + min_dist
#================================================================
def GetClusteringCoefficient( node, the_network ):
debugg = 1
if debugg: print "\n"
if debugg: print "node: {}".format(node)
my_neighbors = the_network[node]
if debugg: print 'neighbors "Nv": {}'.format( my_neighbors)
num_neighbors = len( my_neighbors )
if debugg: print "num_neighbors: {}".format(num_neighbors)
edges_among_neighbors = 0
for neighbor in my_neighbors:
neighbors_neighbors = the_network[ neighbor ]
shared = neighbors_neighbors & my_neighbors
if debugg: print "neighbors of {} that are also neighbors of {}: {}".format( node, neighbor, shared )
edges_among_neighbors += len( shared )
edges_among_neighbors /= 2
if debugg: print 'non-redundant edges among all neighbors "E(Nv): {}'.format(edges_among_neighbors)
value = float()
if num_neighbors > 1:
# divide by 2 first since every edge is counted twice a->b and b->a
value = 2 * float(edges_among_neighbors) / ( num_neighbors * ( num_neighbors - 1) )
if debugg: print " coeff = 2 * {0} / ( {1} * ( {1} -1) ) = {2}".format(edges_among_neighbors, num_neighbors, value )
else:
value = 0
return value
def CalculateClusteringCoeffsForNetwork( the_network ):
coeffs = {}
for node in the_network.keys():
coeffs[node] = GetClusteringCoefficient( node, the_network )
return coeffs
#================================================================
# MAIN PROGRAM
#================================================================
def main():
input_filename = sys.argv[1]
input_file = open( input_filename, 'r' )
lines = input_file.read().splitlines()
input_file.close()
node_dict = dict()
for line in lines:
m = re.search( r'^(\w+)\s(\w+)', line)
if m:
if debug: print m.groups()
node1 = m.group(1)
node2 = m.group(2)
if debug: print 'node1: {} node2: {}\n'.format( node1, node2 )
if node1 in node_dict:
node_dict[node1].add(node2)
else:
node_dict[node1] = set()
node_dict[node1].add(node2)
if node2 in node_dict:
node_dict[node2].add(node1)
else:
node_dict[node2] = set()
node_dict[node2].add(node1)
PrintNetwork( node_dict )
distance_matrix = AutoVivification()
rows = sorted(deepcopy( node_dict.keys() ) )
report = ""
for key in rows:
report += "{}\t".format(key)
report += "\n"
already_done = set()
num_dists = 0
avg = 0
for row in rows:
for col in rows:
if col not in already_done:
dist = GetDistance( row, col, node_dict )
print "++++++distance betw {} and {} is {}".format(row, col, dist)
distance_matrix[row][col] = dist
report += "{}\t".format( dist )
if dist != 0:
num_dists += 1
avg += dist
else:
report += "\t"
report += "{}\n".format(row)
already_done.add(row)
print report
print "\ndiameter = {}\n".format( float(avg) / float(num_dists) )
#print distance_matrix
if debug:
for key in rows:
print "{}\n".format(distance_matrix[key])
clustering_coeffs = CalculateClusteringCoeffsForNetwork( node_dict )
print "\n\nClustering Coefficients:"
for node in sorted( clustering_coeffs.keys(), lambda x,y: cmp( clustering_coeffs[x], clustering_coeffs[y]) ):
print "{}:\t{}".format(node, clustering_coeffs[node])
if __name__ == "__main__":
main()
|
def calculate_sums(numbers):
""" Calculate and return a list with the sum of
every number pair in given list of numbers """
sums = []
for i in range(len(numbers)):
for j in range(len(numbers)):
if numbers[i] == numbers[j]: # may not be equal
continue
sums.append(numbers[i] + numbers[j])
return sums
filename = "input.txt"
with open(filename, "r") as f:
data = f.readlines()
numbers = [int(line.strip()) for line in data]
PREAMBLE_LEN = 25
head = 0
tail = head + PREAMBLE_LEN
violation = -1
# Find the violating number
while True:
if tail == len(numbers):
break
sums = calculate_sums(numbers[head:tail])
head += 1
next_number = numbers[tail]
tail = head + PREAMBLE_LEN
if next_number not in sums:
violation = next_number
break
print(violation)
# Find a contiguos set of numbers that
# sum to the violation number
head = 0
tail = 1
while True:
current_range = numbers[head:tail + 1]
_sum = sum(current_range)
if _sum == violation:
print(current_range)
break
if _sum > violation:
head += 1
else:
tail += 1
_min = min(current_range)
_max = max(current_range)
print("Encryption weakness:", _min + _max)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.