text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 15:51:45 2019
@author: Paul
"""
# Solution to Advent of Code 2019 Day 17: Set and Forget
import random
import numpy as np
import matplotlib.pyplot as plt
import time
def read_data(filename):
"""
Reads csv file into a list, and converts string entries to ints, then turns
the list into a dictionary of memory locations and their valuesfor in intcode.
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip('\n').split(',')
int_data = [int(i) for i in data]
f.close()
data_dict = {k:int_data[k] for k in range(len(int_data))}
return data_dict
def run_intcode(program, phase_input, power_input, position, mem_state, rel_base_mem, inp_mem, initialised):
"""
Takes data, dict of memory location : value ints to run int_code on.
Takes phase input - phase to be used to initialise amplifier
Takes power input - initial input or input from another amplifier
Position - Position to start running the intcode from
Initialised - Flag to determine if amplifier has been phase initialised or not
Returns list of ints after intcode program has been run.
Running Intcode program looks reads in the integers sequentially in sets of 4:
data[i] == Parameter Mode + Opcode (last two digits)
data[i+1] == Entry 1
data[i+2] == Entry 2
data[i+3] == Entry 3
If Opcode == 1, the value of the opcode at index location = entry 1 and 2
in the program are summed and stored at the index location of entry 3.
If Opcode == 2, the value of the opcode at index location = entry 1 and 2
in the program are multiplied and stored at the index location of entry 3.
If Opcode == 3, the the single integer (input) is saved to the position given
by index 1.
If Opcode == 4, the program outputs the value of its only parameter. E.g. 4,50
would output the value at address 50.
If Opcode == 5 and entry 1 is != 0, the intcode position moves to the index stored
at entry 2. Otherwise it does nothing.
If Opcode == 6 and entry 1 is 0, the intcode postion moves to the index stored
at entry 2. Otherwise it does nothing.
If Opcode == 7 and entry 1> entry 2, store 1 in position given by third param,
otherwise store 0 at position given by third param.
If Opcode == 8 and entry 1 = entry 2, store 1 in position given by third param,
otherwise store 0 at position given by third param.
If Opcode == 9 the relative base is changed by the value of its only parameter.
If Opcode == 99, the program is completed and will stop running.
Parameters are digits to the left of the opcode, read left to right:
Parameter 0 -> Position mode - the entry is treated as an index location
Parameter 1 -> Immediate mode - the entry is treated as a value
Parameter 2 -> Relative mode - the entry is treated as position, but relative
base (starts at zero and changed by Opcode 9) is added.
"""
data = program.copy()
answer = mem_state
params = [0, 0, 0]
param_modes = ['', '', '']
out_code = 0
rel_base = rel_base_mem
write_pos = 0
inp = inp_mem
# If the amplifier has not been initialised, use phase and input, otherwise just input
if not initialised:
input_num = 1
else:
input_num = 2
i = position
while (i < len(program)):
#print("i = ", i)
#print("Rel Base = ", rel_base)
# Determine Opcode and parameter codes:
opcode_str = "{:0>5d}".format(data[i])
#print(opcode_str)
opcode = int(opcode_str[3:])
param_modes[0] = opcode_str[2]
param_modes[1] = opcode_str[1]
param_modes[2] = opcode_str[0]
#print("Opcode: ", opcode)
op_lens = {1:4, 2:4, 3:2, 4:2, 5:3, 6:3, 7:4, 8:4, 9:2, 99:2}
# Set parameter values correctly depending on parameter mode.
for j in range(op_lens[opcode] - 1):
if param_modes[j] == '0':
try:
params[j] = data[data[i+j+1]]
except KeyError:
if (i+j+1) not in data.keys():
data[i+j+1] = 0
if data[i+j+1] not in data.keys():
data[data[i+j+1]] = 0
params[j] = data[data[i+j+1]]
elif param_modes[j] == '1':
try:
params[j] = data[i+j+1]
except KeyError:
data[i+j+1] = 0
params[j] = data[i+j+1]
else:
try:
params[j] = data[data[i+j+1] + rel_base]
except KeyError:
if (i+j+1) not in data.keys():
data[i+j+1] = 0
if (data[i+j+1] + rel_base) not in data.keys():
data[data[i+j+1] + rel_base] = 0
params[j] = data[data[i+j+1] + rel_base]
# Set write positions correctly for code 3
if str(opcode) == '3':
if param_modes[0] == '0':
write_pos = data[i+1]
else:
write_pos = data[i+1] + rel_base
# Set write positions correctly for codes 1,2,7,8
if str(opcode) in ['1','2','7','8']:
if param_modes[2] == '0':
write_pos = data[i+3]
else:
write_pos = data[i+3] + rel_base
#print("Write-pos:", write_pos)
#print(params, param_modes)
# If opcode is 1, add relevant entries:
if opcode == 1:
data[write_pos] = params[0] + params[1]
i += 4
# If opcode is 2, multiply the relevant entries:
elif opcode == 2:
data[write_pos] = params[0] * params[1]
i += 4
# If opcode is 3, store input value at required location.
elif opcode == 3:
if input_num == 1:
data[write_pos] = phase_input
input_num += 1
elif input_num == 2:
try:
data[write_pos] = power_input[inp]
inp += 1
except IndexError:
print("Problem with the Program: Too many inputs needed")
out_code = -1
break
i += 2;
# If opcode is 4, print out the input stored at specified location.
elif opcode == 4:
answer = params[0]
#print("Program output: ", answer)
i += 2
break
# If the opcode is 5 and the next parameter !=0, jump forward
elif opcode == 5:
if params[0] != 0:
i = params[1]
else:
i += 3
# If the opcode is 6 and next parameter is 0, jump forward
elif opcode == 6:
if params[0] == 0:
i = params[1]
else:
i += 3
# If the opcode is 7, carry out less than comparison and store 1/0 at loc 3
elif opcode == 7:
if params[0] < params[1]:
data[write_pos] = 1
else:
data[write_pos] = 0
i += 4
# If the opcode is 8, carry out equality comparison and store 1/0 at loc 3
elif opcode == 8:
if params[0] == params[1]:
data[write_pos] = 1
else:
data[write_pos] = 0
i += 4
# If the opcode is 9, change the relative base by its only parameter
elif opcode == 9:
rel_base += params[0]
i += 2
# If the opcode is 99, halt the intcode
elif opcode == 99:
print("Program ended by halt code")
out_code = 99
break
# If opcode is anything else something has gone wrong!
else:
print("Problem with the Program: Incorrect Intcode")
outcode = -1
break
return data, answer, out_code, i, rel_base, inp
def calibrate_cameras(program, input_inst = [0], text_map = False):
"""
Takes an intcode ASCII program and runs it, outputing the characters on
screen to represent the camera visuals.
Returns a screen dictionary representing the camera visualisation at each coordinate.
"""
#Initialise visualisation of room map
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
fig.show()
# Initialise Intcode program arguments
data = program.copy()
prog_pos = 0
phase = 0
status_code = 0
init = True
out_code = -1
rel_base_mem = 0
inp_mem = 0
output = 0
output_last = 0
# Dictionary to store a copy of the camera output
screen = {}
x_pos = 0
y_pos = 0
# Repeat steps until end of program reached
while out_code!= 99 and output < 1000:
# Run intcode program
data, output, out_code, prog_pos, rel_base_mem, inp_mem = run_intcode(data, phase, input_inst, prog_pos, status_code, rel_base_mem, inp_mem, init)
if text_map and output in [46,35,10,60,62,94,86,118]:
print(chr(output), end='')
if output != 10 and output in [46,35,60,62,94,86,118] :
screen[(x_pos, y_pos)] = output
x_pos += 1
else:
x_pos = 0
y_pos += 1
output_cur = output
# New screen is denoted by two newlines in a row
if output_cur + output_last == 20:
x_pos = 0
y_pos = 0
pixels = 0
# Update visualisation
picture = dict_to_image(screen)
ax1.clear()
ax1.imshow(picture)
fig.canvas.draw()
output_last = output_cur
return screen, output
def alignment_params(screen):
"""
Takes a camera screen dictionary as input. Locates all scaffold intersections
and calculates their alignment parameter (distance from left edge * distance
from top edge).
Returns the sum of the alignment parameters and an updated screen showing their positions.
"""
intersections = []
alignment_param = 0
moves = {0:(0,1), 1: (0,-1), 2: (1, 0), 3: (-1, 0)}
for tile in screen:
intersect = True
pos_x, pos_y = tile
if screen[tile] == 35:
for i in range(4):
dx, dy = moves[i]
test_pos = (pos_x + dx, pos_y + dy)
if test_pos not in screen or screen[test_pos] != 35:
intersect = False
break
if intersect:
intersections.append(tile)
alignment_param += pos_x * pos_y
for tile in intersections:
screen[tile] = 48
return screen, alignment_param
def dict_to_image(screen):
""" Takes a dict of room locations and their block type output by RunGame.
Renders the current state of the game screen.
"""
picture = np.zeros((51, 51))
# Color tiles according to what they represent on screen:.
for tile in screen:
pos_x, pos_y = tile
if pos_x < 51 and pos_y < 51:
if screen[tile] == 46:
picture[pos_y][pos_x] = 0;
elif screen[tile] == 35:
picture[pos_y][pos_x] = 240;
else:
picture[pos_y][pos_x] = 150
return picture
def instr_to_intcode(instructions):
"""
Takes a string of instructions written in ASCII and converts them to integers
for using as input for the intcode program.
"""
output = []
for char in instructions:
output.append(ord(char))
output.append(ord('\n'))
return output
program_input = read_data('day17input.txt')
#print(program_input)
# Part 1
print('Calibrating Cameras...')
screen_out, output1 = calibrate_cameras(program_input, text_map = False)
screen, align_val = alignment_params(screen_out)
print('Part 1: Sum of Alignment Parameters: ', align_val)
plt.imshow(dict_to_image(screen))
plt.savefig('day17_scaffold_start.png')
plt.show()
#time.sleep(5)
plt.close()
# Part 2
# Instructions required for Robot were read from the map and decoded by hand
inst_list = instr_to_intcode('A,B,A,C,C,A,B,C,B,B')
inst_A = instr_to_intcode('L,8,R,10,L,8,R,8')
inst_B = instr_to_intcode('L,12,R,8,R,8')
inst_C = instr_to_intcode('L,8,R,6,R,6,R,10,L,8')
camera = [121,10]
no_camera = [110, 10]
input_inst = inst_list + inst_A + inst_B + inst_C + camera
print('Running Robot over Scaffolding...')
program_input[0] = 2
screen_out2, output2 = calibrate_cameras(program_input, input_inst, text_map = False)
print('Part 2: Dust Collected at end of Scaffold: ', output2)
plt.imshow(dict_to_image(screen_out2))
plt.savefig('day17_scaffold_end.png')
plt.show()
# Maze Path: L,8,R,10,L,8,R,8,L,12,R,8,R,8,L,8,R,10,L,8,R,8,L,8,R,6,R,6,R,10,L,8,L,8,R,6,R,6,R,10,L,8,L,8,R,10,L,8,R,8,L,12,R,8,R,8,L,8,R,6,R,6,R,10,L,8,L,12,R,8,R,8,L,12,R,8,R,8
#A,B,A,C,C,A,B,C,B,B
#A: L,8,R,10,L,8,R,8,L,8
#B: L,12,R,8,R,8
#C: L,8,R,6,R,6,R,10,L,8
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 10:53:42 2019
@author: Paul
"""
# Advent of Code Day 16: Flawed Frequency Transmission
def read_data(filename):
"""
Reads data file into a list of ints.
"""
int_data = []
f = open(filename, 'r')
for line in f:
data = line.strip('\n')
int_data += [int(char) for char in data]
f.close()
return int_data
def fft(signal, num_phases, offset):
"""
Runs fft algorithm on signal for specified number of phases
At each phase, it multiplies each element of the signal by the repeating pattern
[0, 1, 0, -1], sums the result, and takes the smallest digit. When calculating the result
for each element the repeated pattern is extended i.e. [0,0,-1,-1,0,0,1,1] for the second element.
The final result for each phase is then used as the signal input for the next phase.
offset determines the point in the signal code you are interested in. When calculating
the digits at this point all previous elements will be multiplied by repeat pattern [0],
and so will not affect the result.
Returns the processed signal.
"""
signal_in = signal
print('Running FFT...')
# Run process for required number of phases
for i in range(num_phases):
#print('Calculating phase:', i)
output_str = ''
# Iterate over each digit of ouput
for j in range(offset, len(signal_in), 1):
#print('Calculating digit: ', j)
repeat_pattern = [0] * (j+1) + [1] * (j+1) + [0] * (j+1) + [-1] * (j+1)
result = 0
# Iterate over all signal elements, multiply and sum to get digit of output
for k in range (offset, len(signal_in), 1):
pattern = repeat_pattern[(k+1) % len(repeat_pattern)]
#print('k: ', k)
#print(pattern)
#print(signal_in[k])
result += pattern * signal_in[k]
# Get output digit and out to the output string
output_str += str(abs(result) % 10)
# Output signal used as input signal for next phase
signal_in = signal[0:offset] + [int(x) for x in output_str]
return output_str
def fft_offset(signal, num_phases, offset):
"""
Runs fft algorithm on signal for specified number of phases, where the offset
is bigger than half the signal length.
Where the offset is > 1/2 the signal length, all the repeated pattern parameters
are 0 or 1. To calculate each digit, the sum of all values in the signal from the
offset point is calculated - This gives the result for digit 0. The result for
digit 1 can then be calculated by subtracting the first signal value fromthe offset point.
Returns the processed signal, starting from the offset point.
"""
signal_in = signal[offset:]
print('Running Optimised FFT with offset > 1/2 signal length...')
# Run process for required number of phases
for i in range(num_phases):
#print('Calculating phase:', i)
output_str = ''
# Get the first result
results = []
results.append(sum(signal_in))
output_str += str(results[0] % 10)
# Next result is previous result minus first signal digit, etc:
for k in range(0, len(signal_in)-1):
results.append(results[k] - signal_in[k])
output_str += str(results[k+1] % 10)
# Output signal used as input signal for next phase
signal_in = [int(x) for x in output_str]
return output_str
signal = read_data('day16input.txt')
#print(signal)
# Test for part 1
#test = fft([1,2,3,4,5,6,7,8], 4, 1) # 01029498
#print(test)
# Part 1:
result1 = fft(signal, 100, 0)
print('Part 1: First 8 digits output after 100 phases FFT: ', result1[0:8])
# Test for part 2
#test2 = fft_offset([1,2,3,4,5,6,7,8], 4, 4) # 9498
#print(test2)
# Part2:
result2 = fft_offset(signal*10000,100, 5972351) # 5972351
print('Part2: 8 Digits at offset location (5972351): ', result2[0:8])
|
str=raw_input('enter the string:')
str1=str+'.'
print(str1)
|
a=input()
if a.count('(')==a.count(')'):
print("yes")
else:
print("no")
|
import numpy as np
arredondar = lambda num: float('%.6f' % num) # função que arredonda o nº para 6 casas decimais
def isPossibleandDeterm(matrix): # função que determina se o sistema é possível ou não
det = np.linalg.det(matrix) # Cálculo do determinante
if (det > 0) or (det < 0): # Sistema possivel e determinado
return True
elif det == 0: # Sistema possivel e indeterminado ou impossivel
return False
def isConvergent(matrix_original): # critério de convergência das linhas
matrix = np.copy(matrix_original)
diag = matrix.diagonal()
copy = np.copy(diag) # é preciso copiar pois o diag se perde depois do fill_diagonal
np.fill_diagonal(matrix, 0) # ESSA FUNÇÃO ALTERA A MATRIZ ORIGINAL, QUE _ É ESSA?
# print('diag: ', diag) # diag some logo depois do fill_diagonal
# print('copy: ', copy) # por isso, copia-se
soma = np.sum(matrix, axis=1)
for i in range(len(soma)):
if soma[i] > copy[i]:
return False # O método não convergirá para uma solução; o usuário deve corrigir a ordem do sistema
return True # O método irá convergir para um resultado
def sciNotation(n, k): # Notação científica -> n * 10^(k)
a = '{}e{}'.format(n, k)
a = float(a)
return a
def list_to_comparate(tamanho):
lista = [0]
for i in range(0, tamanho):
if i not in lista:
lista.append(i)
return lista
def main8(): # (14/04/2019) # Gauss-Seidel
contador = 1
E = sciNotation(1, -1)
A = np.array([[4, 2, 1],
[1, 5, 2],
[2, 1, 4]])
dimAi, dimAj = A.shape
# print(dimAi, dimAj)
B = [1, 3, -2]
X = [0]*len(B)
Xn = [0]*len(B)
Xabs = [0]*len(B)
if isPossibleandDeterm(A) == True:
if isConvergent(A) == False:
print('Não irá convergir; usuário, por favor altere a ordem do sistema')
return False
while True:
for i in range(1, dimAi+1):
Xn[i-1] = B[i-1]
for j in range(1, dimAj+1):
# print(Xn)
# print(i, j)
if i != j:
if i != 0:
listtemp = list_to_comparate(i)
if j in listtemp:
Xn[i-1] = Xn[i-1] - (A[i-1][j-1] * Xn[j-1])
else:
Xn[i-1] = Xn[i-1] - (A[i-1][j-1] * X[j-1])
Xn[i-1] = Xn[i-1]/A[i-1][i-1]
print(Xn)
for i in range(len(Xn)):
Xabs[i] = np.abs(Xn[i] - X[i])
if Xabs[i] > E:
break
else:
break
for i in range(len(Xn)):
X[i] = Xn[i]
contador += 1
# print('=================')
for i in range(len(Xn)):
Xn[i] = arredondar(Xn[i])
print('final:', Xn)
print('contador:', contador)
else:
print('O Sistema é possivel e indeterminado ou impossivel')
if __name__ == '__main__':
main8()
|
def swap(d, key1, key2):
if key1 == key2:
return
val1 = d[key1]
val1 = val1.copy() if isinstance(val1, dict) else val1
val2 = d[key2]
val2 = val2.copy() if isinstance(val2, dict) else val2
d[key1], d[key2] = val2, val1
|
import unittest
from benedict.core import items_sorted_by_keys as _items_sorted_by_keys
from benedict.core import items_sorted_by_values as _items_sorted_by_values
class items_sorted_test_case(unittest.TestCase):
"""
This class describes an items sorted test case.
"""
def test_items_sorted_by_keys(self):
i = {
"y": 3,
"a": 6,
"f": 9,
"z": 4,
"x": 1,
}
o = _items_sorted_by_keys(i)
r = [
("a", 6),
("f", 9),
("x", 1),
("y", 3),
("z", 4),
]
self.assertEqual(o, r)
def test_items_sorted_by_keys_reverse(self):
i = {
"y": 3,
"a": 6,
"f": 9,
"z": 4,
"x": 1,
}
o = _items_sorted_by_keys(i, reverse=True)
r = [
("z", 4),
("y", 3),
("x", 1),
("f", 9),
("a", 6),
]
self.assertEqual(o, r)
def test_items_sorted_by_values(self):
i = {
"a": 3,
"b": 6,
"c": 9,
"e": 4,
"d": 1,
}
o = _items_sorted_by_values(i)
r = [
("d", 1),
("a", 3),
("e", 4),
("b", 6),
("c", 9),
]
self.assertEqual(o, r)
def test_items_sorted_by_values_reverse(self):
i = {
"a": 3,
"b": 6,
"c": 9,
"e": 4,
"d": 1,
}
o = _items_sorted_by_values(i, reverse=True)
r = [
("c", 9),
("b", 6),
("e", 4),
("a", 3),
("d", 1),
]
self.assertEqual(o, r)
|
#CLASSES
class Pet:
def __init__(self,name,age,color):
self.name = name
self.age = age
self.color = color
class Dog(Pet):
def __init__(self,name,age,color,breed,attitude):
self.breed = breed
self.attitude = attitude
Pet.__init__(self,name,age,color)
def getName(self):
return self.name
def speak(self):
print("Woof!")
def isAdopted(self):
return self.adopted
def setAdopted(self,adopt):
self.adopted = adopt
def bio(self):
print(self.name + " is a " + self.color + " " + self.breed + " who is " + self.attitude + "!")
class Dragon(Pet):
def __init__(self,name,age,color,breed,skill):
self.breed = breed
self.skill = skill
Pet.__init__(self,name,age,color)
def getName(self):
return self.name
def bio(self):
print(self.name + " is a " + self.color + " " + self.breed + " who can " + self.skill + "!")
class Wolf(Pet):
def __init__(self,name,age,color,position):
self.position = position
Pet.__init__(self,name,age,color)
def getName(self):
return self.name
def bio(self):
print(self.name + " is a " + self.color + " wolf " + " who is the " + self.position + " of the pack!")
#RUNNING CODE
spot = Dog("Spot","2","Black and White", "Terrier", "Friendly")
fred = Dog("Fred","1","Brown","Boxer","Sassy")
clifford = Dog("Clifford","3", "Red", "Big Red Dog", "Nice")
storm = Dog("Storm","2","White", "Husky", "Hyper")
dogs = [spot, fred, clifford, storm]
toothless = Dragon("Toothless", "1000", "Black", "Nightfury", "strike lightning")
dragons = [toothless]
blaze = Wolf("Blaze", "20", "Gray", "Alpha")
wolf = [blaze]
print("Welcome to the Girls Who Code Animal Shelter!")
print("Let me introduce you to our Animals")
for each in dogs:
each.speak()
print("Thats " + each.getName())
each.bio()
for each in dragons:
print("Thats " + each.getName())
each.bio()
for each in wolf:
print("Thats " + each.getName())
each.bio()
pet.py
Open with Google Docs
Displaying pet.py.
|
from gesture import *
from player import *
import time
import random
import getpass
class Game:
def __init__(self):
self.rounds = 0
self.current_round = 0
self.players = 0
self.player_1 = None
self.player_2 = None
self.run = False
self.rock = Rock()
self.paper = Paper()
self.scissor = Scissor()
self.lizard = Lizard()
self.spock = Spock()
self.gestures = [self.rock, self.paper, self.scissor, self.lizard, self.spock]
self.round_winner = ""
def run_game(self):
self.main_menu()
self.run = True
while self.run == True:
self.round_winner = self.decide_round()
self.get_round_winner()
self.determine_winner()
def main_menu(self):
print("Welcome to Rock, Paper, Scissors, Lizard, Spock!")
print()
time.sleep(1)
print('You must run this from the terminal by "cd" in to the directory and using the command "python3 main.py"')
print()
time.sleep(2)
print("Rules are simply just like Rock, Paper, Scissors. Just with the addition of 2 more options of lizard and spock.")
time.sleep(2)
print("Rock crushes Scissors, Scissors cuts Paper, Paper covers Rock, Rock crushes Lizard, Lizard poisons Spock, Spock smashes Scissors, Scissors decapitates Lizard, Lizard eats Paper, Paper disproves Spock, Spock vaporizes Rock")
print()
time.sleep(3)
print('Got it, good')
time.sleep(2)
print()
print('For the number of players enter 1 to play against the AI, enter 2 to play against another human')
time.sleep(2)
print()
print('When choosing a gesture hit a single number and hit enter the number that you have selected will not '
'be displayed in terminal.')
print()
valid_1 = False
number_of_rounds = 0
num_players = 0
while valid_1 == False:
num_players = int(input("Please select a number of players: (1 or 2): "))
if num_players != 1 and num_players != 2:
print("Invalid input please try again.")
else:
valid_1 = True
valid_2 = False
while valid_2 == False:
number_of_rounds = int(input("Please select the best out of '' : for game length: "))
if number_of_rounds % 2 == 0:
print("Needs to be an odd number for best out of.")
else:
valid_2 = True
self.rounds = number_of_rounds
if num_players == 1:
self.player_1 = Human()
print("Player 1:")
self.player_1.set_name()
self.player_2 = Computer()
else:
self.player_1 = Human()
print("player 1: ")
self.player_1.set_name()
self.player_2 = Human()
print("player 2: ")
self.player_2.set_name()
def choose_gesture_player_1(self):
print("Player 2 look away")
print()
time.sleep(2)
player_1_choice = ""
valid = False
while valid == False:
# player_1_choice = int(input("Choose a gesture by picking a number (1: rock) (2: paper) (3: scissors) (4: lizard) (5: Spock): ")) - 1
player_1_choice = int(getpass.getpass("Choose a gesture by picking a number (1: rock) (2: paper) (3: scissors) (4: lizard) (5: Spock): ")) - 1
if player_1_choice != 0 and player_1_choice != 1 and player_1_choice != 2 and player_1_choice != 3 and player_1_choice != 4:
print("Invalid input please try again!")
else:
valid = True
time.sleep(2)
selected_gesture = self.gestures[player_1_choice]
return selected_gesture
def choose_gesture_player_2(self):
if self.player_2.name == 'AI':
player_2_choice = random.randint(0, 4)
selected_gesture = self.gestures[player_2_choice]
return selected_gesture
else:
print("Player 1 look away")
print()
time.sleep(2)
player_2_choice = ""
valid = False
while valid == False:
# player_2_choice = int(input(
# "Choose a gesture by picking a number (1: rock) (2: paper) (3: scissors) (4: lizard) (5: Spock): ")) - 1
player_2_choice = int(getpass.getpass(
"Choose a gesture by picking a number (1: rock) (2: paper) (3: scissors) (4: lizard) (5: Spock): ")) - 1
if player_2_choice != 0 and player_2_choice != 1 and player_2_choice != 2 and player_2_choice != 3 and player_2_choice != 4:
print("Invalid input please try again!")
else:
valid = True
time.sleep(2)
selected_gesture = self.gestures[player_2_choice]
return selected_gesture
def decide_round(self):
player_1_hand = self.choose_gesture_player_1()
player_2_hand = self.choose_gesture_player_2()
for lose in player_1_hand.loses_to:
if lose == player_2_hand.name:
result = 'player_2'
print(f'{self.player_1.name} picked {player_1_hand.name} ')
print()
time.sleep(2)
print(f'{self.player_2.name} picked {player_2_hand.name}')
print()
time.sleep(2)
print(f'{result} won the round')
print()
self.current_round += 1
return result
for lose in player_2_hand.loses_to:
if lose == player_1_hand.name:
result = 'player_1'
print(f'{self.player_1.name} picked {player_1_hand.name} ')
print()
time.sleep(1.5)
print(f'{self.player_2.name} picked {player_2_hand.name}')
print()
time.sleep(1.5)
print(f'{result} won the round')
time.sleep(1.5)
print()
self.current_round += 1
return result
if player_1_hand.name == player_2_hand.name:
result = "tie"
print(f'{self.player_1.name} picked {player_1_hand.name} ')
print()
time.sleep(1.5)
print(f'{self.player_2.name} picked {player_2_hand.name}')
print()
time.sleep(1.5)
print('Round is tied')
print()
time.sleep(1.5)
self.current_round += 1
return result
def get_round_winner(self):
if self.round_winner == "player_1":
self.player_1.rounds_won += 1
print(f'Player One : {self.player_1.rounds_won} to Player Two : {self.player_2.rounds_won}')
print()
time.sleep(2)
elif self.round_winner == "player_2":
self.player_2.rounds_won += 1
print(f'Player One : {self.player_1.rounds_won} to Player Two : {self.player_2.rounds_won}')
print()
time.sleep(2)
def determine_winner(self):
if self.player_1.rounds_won == (self.rounds // 2) + 1:
print(f"{self.player_1.name} has WON the game!!!")
self.play_again()
if self.player_2.rounds_won == (self.rounds // 2) + 1:
print(f"{self.player_2.name} has WON the game!!!")
self.play_again()
if self.current_round == self.rounds:
if self.player_1.rounds_won > self.player_2.rounds_won:
print(f"{self.player_1.name} has WON the game!!!")
self.play_again()
elif self.player_2.rounds_won > self.player_1.rounds_won:
print(f'{self.player_2.name} has WON the game!!!')
self.play_again()
else:
print("All right, we'll call it a draw")
self.play_again()
def play_again(self):
selection = input("Do you want to play again? (y/n): ")
valid_selection = selection.lower()
if valid_selection == "y":
self.player_1.rounds_won = 0
self.player_2.rounds_won = 0
else:
self.run = False
|
import math
def detect_triangle(b , c, d):
# -1 : nhap sai
# -2 : khong lam tam giac
# 0 : tam giac deu
# 1 : tam giac vuong can
# 2 : tam giac can
# 3 : tam giac vuong
# 4 : tam giac thuong .
a = [0]*3
a[0] = b;
a[1] = c;
a[2] = d;
try :
a[1] = float(a[1])
a[2] = float(a[2])
a[0] = float(a[0])
except ValueError:
print "Nhap sai"
return -1
if a[0] <= 0 or a[1]<= 0 or a[2] <= 0 or a[0] >= 2**32 -1 or a[1] >= 2**32 -1 or a[2] >= 2**32 -1:
print "Canh phai lon hon khong "
return -1
elif a[0] + a[1] <= a[2] or a[1] + a[2] <= a[0] or a[0] + a[2] <= a[1] :
print "Khong phai tam giac"
return -2
elif a[0] == a[1] and a[1] == a[2] :
print "La tam giac deu"
return 0
elif a[0] == a[1] or a[1] == a[2] or a[0] == a[2] :
if math.fabs(a[0]*a[0] + a[1]*a[1] -(a[2]*a[2])) < 10**-9 or math.fabs(a[2]*a[2] + a[1]*a[1] - a[0]*a[0]) < 10**-9 or math.fabs(a[2]*a[2] + a[0]*a[0] - a[1]*a[1]) < 10**-9 :
print "La tam giac vuong can "
return 1
else :
print "La tam giac can"
return 2
elif math.fabs(a[0]*a[0] + a[1]*a[1] - a[2]*a[2]) < 10**-9 or math.fabs(a[2]*a[2] + a[1]*a[1] - a[0]*a[0]) < 10**-9 or math.fabs(a[2]*a[2] + a[0]*a[0] - a[1]*a[1])< 10**-9 :
print "La tam giac vuong"
return 3
else :
print "La tam giac"
return 4
|
# Budget App
# Create a Budget class that can instantiate objects based on different budget categories like food, clothing, and entertainment. These objects should allow for
# 1. Depositing funds to each of the categories
# 2. Withdrawing funds from each category
# 3. Computing category balances
# 4. Transferring balance amounts between categories
class budgetApp:
features= ["Deposit","Withdraw", "bugdetBalance", "transferin", "transferout", "budgetBalance"]
noOffeatures=len(features)
def __init__ (self,budgetType, amtDeposited, amtWithdrawn, transferin, transferout, budgetBalance):
self.budgetType=budgetType
self.amtDeposited=amtDeposited
self.amtWithdrawn=amtWithdrawn
self.transferin=transferin
self.transferout=transferout
self.budgetBalance=budgetBalance
def budgetCategory(self):
print(" ************* You are currently in {} Budget***********".format(self.budgetType))
def deposit(self):
self.amtDeposited=int(input("Enter amount to be deposited in the budget \n"))
print("Your deposit of {} is successful: ".format(self.amtDeposited))
BudgetBal=self.amtDeposited
print("Your budget balance is: {}".format(BudgetBal))
def withdraw(self):
self.amtWithdrawn=int(input("Enter amount to be withdrawan from budget \n"))
print("Your have successfully withdrawn {} from your budget".format(self.amtWithdrawn))
BudgetBal=self.amtDeposited-self.amtWithdrawn
print("Your budget balance is: {}".format(BudgetBal))
def transferReceived(self):
self.transferin=int(input("Enter amount to be transferred to this budget line \n"))
print("Your have successfully transferred in {} to your {} budget".format(self.transferin, self.budgetType))
BudgetBal=self.amtDeposited-self.amtWithdrawn+self.transferin
print("Your budget balance is: {}".format(BudgetBal))
def transferOutOfBudget(self):
self.transferout=int(input("Enter amount to be transferred out of this budget line \n"))
print("Your have successfully transferred out {} from your {} budget".format(self.transferout, self.budgetType))
BudgetBal=self.amtDeposited-self.amtWithdrawn+self.transferin-self.transferout
print("Your budget balance is: {}".format(BudgetBal))
def remainingBudgetBal(self):
BudgetBal=self.amtDeposited-self.amtWithdrawn+self.transferin-self.transferout
print("Your budget balance is: {}".format(BudgetBal))
# Creating Object Food; Clothing & Entertainment
budgetFood = budgetApp("Food","","","","","")
budgetClothing = budgetApp("Clothing","","","","","")
budgetEntertainment = budgetApp("Entertainment","","","","","")
#Calling Properties
print("These are the available features: {}".format(budgetFood.features))
print("The number of available feature is: {}".format(budgetFood.noOffeatures))
#Testing with Food Object - Calling Methods
budgetFood.budgetCategory()
budgetFood.deposit()
budgetFood.withdraw()
budgetFood.transferReceived()
budgetFood.transferOutOfBudget()
budgetFood.remainingBudgetBal()
#Testing with Clothing Object - Calling Methods
budgetClothing.budgetCategory()
budgetClothing.deposit()
budgetClothing.withdraw()
budgetClothing.transferReceived()
budgetClothing.transferOutOfBudget()
budgetClothing.remainingBudgetBal()
#Testing with Entertainment Object - Calling Methods
budgetEntertainment.budgetCategory()
budgetEntertainment.deposit()
budgetEntertainment.withdraw()
budgetEntertainment.transferReceived()
budgetEntertainment.transferOutOfBudget()
budgetEntertainment.remainingBudgetBal() |
# Python program to translate
# speech to text and text to speech
import webbrowser
import speech_recognition as sr
import pyttsx3
import wikipedia
from googlesearch.googlesearch import search
from datetime import datetime
# Initialize the recognizer
r = sr.Recognizer()
# Function to convert text to speech
def SpeakText(command):
# Initialize the engine
engine = pyttsx3.init('dummy')
engine.say(command)
engine.runAndWait()
engine = pyttsx3.init()
engine.say("Hi I am JARVIS, your personal assistant")
engine.runAndWait()
# Loop infinitely for user to speak
text_length = 0
# It will going to continue run until it count the text length less than 80.
while(text_length < 80):
# Exception handling to handle
# exceptions at the runtime
try:
engine = pyttsx3.init()
engine.say("How can i help you")
engine.runAndWait()
# use the microphone as source for input.
with sr.Microphone() as source2:
# wait for a second to let the recognizer
# adjust the energy threshold based on
# the surrounding noise level
r.adjust_for_ambient_noise(source2, duration=0.2)
#listens for the user's input
audio2 = r.listen(source2)
# Using google to recognize audio
MyText = r.recognize_google(audio2)
MyText = MyText.lower()
print("Command: \n"+MyText)
SpeakText(MyText)
if MyText == "hai" or MyText == "hello":
engine = pyttsx3.init()
engine.say("hello")
engine.runAndWait()
elif MyText == "open google" or MyText == "google":
webbrowser.open_new_tab("http://www.google.com")
engine = pyttsx3.init()
engine.say("Done")
engine.runAndWait()
elif MyText == "your name" or MyText == "what is your name":
engine = pyttsx3.init()
engine.say("Hello, my name is Jarvis")
engine.runAndWait()
elif MyText == "play music" or MyText == "music":
webbrowser.open_new_tab("https://music.youtube.com/watch?v=HC3-gSNbx00&list=RDAMVMHC3-gSNbx00")
engine = pyttsx3.init()
engine.say("Here the music")
engine.runAndWait()
elif MyText == "open gmail" or MyText == "gmail":
webbrowser.open_new_tab("http://www.gmail.com")
engine = pyttsx3.init()
engine.say("Here your gmail account")
engine.runAndWait()
elif MyText == "tell me about yourself" or MyText == "who are you" or MyText == "about yourself":
engine = pyttsx3.init()
engine.say("I am JARVIS... version ..1 point O...I have been created by... J. V. S. D. Co-operation. Its Members are JASPREET...VISHAL....Sonu.....DHRUV.")
engine.runAndWait()
elif MyText == "open youtube" or MyText == "youtube":
webbrowser.open_new_tab("http://www.youtube.com")
engine = pyttsx3.init()
engine.say("opened youtube")
engine.runAndWait()
# elif MyText == "artificial intelligence" or MyText == "what is artificial intelligence":
# webbrowser.open_new_tab("https://en.wikipedia.org/wiki/Artificial_intelligence")
# engine = pyttsx3.init()
# engine.say("Artificial Intelligence is Technique that mimics Human Behaviour.It is widely used today in every field.")
# engine.runAndWait()
# elif MyText == "deep learning" or MyText == "what is deep learning":
# webbrowser.open_new_tab("https://www.forbes.com/sites/bernardmarr/2018/10/01/what-is-deep-learning-ai-a-simple-guide-with-8-practical-examples/?sh=2c6e82058d4b")
# engine = pyttsx3.init()
# engine.say("Deep learning is a subset of machine learning where artificial neural networks, algorithms inspired by the human brain, learn from large amounts of data..")
# engine.runAndWait()
elif MyText == "open blackboard" or MyText == "blackboard":
webbrowser.open_new_tab("https://cuchd.blackboard.com/?new_loc=%2Fultra%2Fcourse")
engine = pyttsx3.init()
engine.say("Here's The Blackboard From Chandigarh University")
engine.runAndWait()
elif MyText == "open university portal":
webbrowser.open_new_tab("https://uims.cuchd.in/UIMS/Login.aspx")
engine = pyttsx3.init()
engine.say("Here's Your C U I M S account")
engine.runAndWait()
elif MyText == "current time":
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
engine = pyttsx3.init()
engine.say(current_time)
engine.runAndWait()
elif MyText == "stop" or MyText == "bye" or MyText == "no thanks" or MyText == "bye bye jarvis":
text_length = 90
engine = pyttsx3.init()
engine.say("OK,Bye have a good day")
engine.runAndWait()
else:
engine = pyttsx3.init()
engine.say(wikipedia.summary(MyText, sentences=2))
engine.runAndWait()
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
except sr.UnknownValueError:
engine = pyttsx3.init()
engine.say("Say something")
engine.runAndWait()
|
import re
import string
from collections import defaultdict
from typing import Dict, Tuple, List
skip_words = {"и", "а", "в", "я", "на", "не", "что",
"с", "она", "они", "оно", "он", "как",
"мне", "меня", "но", "его", "ее", "это",
"к", "так", "за", "по", "же", "из", "то",
"о", "от"}
class Entry:
pages: Dict[int, int]
count: int
def __init__(self, count: int = 0, pages: List[Tuple[int, int]] = None):
self.count = count
if pages is not None:
self.pages = defaultdict(int, pages)
else:
self.pages = defaultdict(int)
def add_page(self, page: int) -> None:
self.pages[page] = self.pages[page] + 1
self.count = self.count + 1
def __repr__(self) -> str:
def format_pages(x: Tuple[int, int]) -> str:
page, count = x
scount = f"({count})" if count > 1 else ""
return f"{page}{scount}"
pages = ", ".join(map(format_pages, self.pages.items()))
return f"{self.count}, {pages}"
def __eq__(self, other):
return self.count == other.count and self.pages == other.pages
class Index:
number_of_lines_per_page: int
entries: Dict[str, Entry]
def __init__(self):
self.entries = defaultdict(Entry)
self.number_of_lines_per_page = 45
def add_word(self, word: str, page: int) -> None:
entry = self.entries[word]
entry.add_page(page)
def build(self, filename: str) -> None:
with open(filename, "rt") as fp:
for cnt, line in enumerate(fp):
words = re.sub('[' + string.punctuation + string.ascii_letters + "à-ö0-9]", "", line.lower()).split()
words = [x for x in words if x not in skip_words]
page = cnt // self.number_of_lines_per_page + 1
for word in words:
self.add_word(word, page)
def save(self, filename: str) -> None:
with open(filename, "w") as fp:
for entry in sorted(self.entries.items()):
k, v = entry
fp.write(f"{k}: ")
fp.write(f"{str(v.count)}: ")
for idx, (page, count) in enumerate(sorted(v.pages.items())):
fp.write(str(page))
if count > 1:
fp.write(f"({str(count)})")
fp.write(",")
if idx < len(v.pages) - 1:
fp.write(" ")
fp.write("\n")
def load(self, filename: str) -> None:
def read_pages(t: Tuple[str, str]):
if t[1]:
return int(t[0]), int(t[1])
else:
return int(t[0]), 1
with open(filename, "rt") as fp:
for line in fp:
word, count, pstr = line.split(":")
pages = list(map(read_pages, re.findall(r"(\d+)(?:\((\d+)\))?, ?", pstr)))
entry = Entry(int(count), pages)
self.entries[word] = entry # pages
def most_freq_used(self, count: int) -> Tuple[str, Entry]:
swords: Tuple[str, Entry] = sorted(self.entries.items(), key=lambda kv: -kv[1].count)
return swords[:count]
def __eq__(self, other):
return self.entries == other.entries
|
# --- Exercício 3 - Funções
# --- Escreva uma função para listar pessoas cadastradas:
# --- a função deve retornar todas as pessoas cadastradas na função do ex1
# --- Escreva uma função para exibi uma pessoa específica:
# a função deve retornar uma pessoa cadastrada na função do ex1 filtrando por id
def pessoas_cadastradas_arquivo():
arquivo = open('banco_pessoas.txt','r')
for linha in arquivo:
linha_limpa = linha.strip()
lista_dados = linha_limpa.split(';')
print(f"nome: {lista_dados[0]} - sobrenome: {lista_dados[1]} - idade: {lista_dados[2]} - id: {lista_dados[3]}")
arquivo.close()
def pessoa_por_id_arquivo():
#id = input('\n Informe o id pessoal para consulta: ')
arquivo = open('banco_pessoas.txt','r')
id = input('Informe o ID para consulta: ')
for linha in arquivo:
linha_limpa = linha.strip()
linha_dados = linha_limpa.split(';')
if linha_dados[3] == id:
print(f'ID: {linha_dados[3]} - nome: {linha_dados[0]} - sobrenome: {linha_dados[1]} - idade {linha_dados[2]}')
arquivo.close()
def pessoas_cadastradas(lista):
for i in lista:
print(f" id: {i['id']}")
print(f" nome: {i['nome']}")
print(f" sobrenome: {i['sobrenome']}")
print(f" idade: {i['idade']}")
print('\n')
def pessoas_por_id(lista):
id = int(input('\n Informe o id pessoal para consulta: '))
for pessoa in lista:
for chaves, valores in pessoa.items():
if chaves == 'id' and valores == id:
print('\n')
print('*'*10)
print(f"nome: {pessoa['nome']}")
print(f"sobrenome: {pessoa['sobrenome']}")
print(f"idade: {pessoa['idade']}")
print(f"id: {pessoa['id']}")
print('\n')
|
#--- Exercício 5 - Funções
#--- Crie uma função para calculo de raiz
#--- A função deve ter uma variável que deternine qual é o indice da raiz(raiz quadrada, raiz cubica...)
#--- Leia um número do console, armazene em uma variável e passe para a função
#--- Realize o calculo da raiz e armazene em uma segunda variável e retorne
#--- Imprima o resultado e uma mensagem usando f-string, fora da função
def calculo_raiz(numero,raiz):
resultado_raiz=numero**(1/raiz)
return resultado_raiz
numero = int(input('informe o número que deseja calcular a raiz: '))
raiz = int(input('informe o número que deseja calcular a raiz: '))
resultado=calculo_raiz(numero,raiz)
print(f'O resultado do numero {numero} pela raiz de {raiz} é: {resultado}')
|
# A List is a collection which is ordered and changeable. Allows duplicate members.
# Create list
# numbers = [1, 2, 3, 4, 5]
# Using a constructor
numbers = list((1, 2, 3, 4, 5))
print(numbers)
|
import string
from random import randint
str1 = string.printable
print(str1)
print(len(str1))
for i in range (6):
print (str1[randint(1,100)],end=" ")
|
import numpy as np
def sigmoid():
"""
Returns a lambda function that takes the form of the sigmoid function.
The package bigfloat is used to get more precision
:return: float
"""
return lambda z: float(1 / (1 + np.exp(z)))
def perceptron():
"""
Returns a lambda function that takes the form of the perceptron or step
function.
:return: int
"""
return lambda z: 1 if z > 0 else 0
def relu():
"""
Returns a lambda function that takes the form of the rectified linear
unit or ReLU function.
:return: float
"""
return lambda z: z if z > 0 else 0
|
'''
conditional statements
----------------------
if (con):
# something
elif (con):
# something
else:
# something
'''
def main():
num = 25
if (num<20):
print("%s is smaller than 20" % (num))
elif(num < 30):
print("%s is smaller than 30" % (num))
else:
print("%s is greater than or equal to 30" % (num))
main()
|
# Built-in Data Types
# Variables can store data of different types, and different types can do different things.
# str
x = "Hello World"
print(x)
print(type(x))
# int
x = 20
print(x)
print(type(x))
# float
x = 20.7
print(x)
print(type(x))
# complex
x = 1-8j
print(x)
print(type(x))
# list
x = ["apple", "banana", "cherry"]
print(x)
print(type(x))
# tuple
x = ("apple", "banana", "cherry")
print(x)
print(type(x))
# range
x = range(6)
print(x)
print(type(x))
# dict
x = {"name" : "John", "age" : 36}
print(x)
print(type(x))
# set
x = {"apple", "banana", "cherry"}
print(x)
print(type(x))
# bool
x = True
print(x)
print(type(x))
|
# Built-in Math Functions
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
x = abs(-7.25)
print(x)
x = pow(4, 3)
print(x)
# Math Module
# Python has also a built-in module called math, which extends the list of mathematical functions.
import math
x = math.sqrt(64)
print(x)
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
x = math.pi
print(x)
|
# Python Dates
# A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
|
# Global Variables
# Variables that are created outside of a function are known as global variables.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
x = "awesome"
def myfunc1():
x = "fantastic"
print("Python is " + x)
myfunc1()
print("Python is " + x)
# global Keyword
'''
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
'''
x = "awesome"
def myfunc2():
global x
x = "fantastic"
myfunc2()
print("Python is " + x) |
import requests
import sqlite3
from bs4 import BeautifulSoup
# author: Hope Foreman
# date: 11, Oct 2021
# setting up the database
database_name = 'golfers.db'
conn = sqlite3.connect(database_name)
c = conn.cursor()
# setting up connection with beautiful soup and web page
url = 'http://www.owgr.com/ranking'
r = requests.get(url)
# checks to see if the request is 200/passes
print(r.status_code)
# using beautifulsoup to find the table
soup = BeautifulSoup(r.text, 'lxml')
table = soup.find('table')
ranking = []
def create_golfer_table():
c.execute("""CREATE TABLE golfers (
this_week INTEGER,
last_week INTEGER,
end_2020 INTEGER,
name TEXT,
average_points REAL,
total_points REAL,
events_played INTEGER,
points_lost REAL,
points_gained REAL
)""")
# method for indexing the row
def find_table_row(index):
for row in table.find_all('tr')[index]:
ranking.append(row.getText().strip())
while "" in ranking:
ranking.remove("")
ranking.pop()
#print(ranking)
# method to print record
def print_record(record):
print(record[0], record[1], record[2], record[3],
record[4], record[5], record[6], record[7], record[8])
# method to insert a persons row stats in sqlite
# param takes in the row's number
def inserting_sql(record_number):
sql = """INSERT INTO golfers
(this_week, last_week, end_2020, name, average_points, total_points, events_played, points_lost, points_gained)
VALUES(?,?,?,?,?,?,?,?,?);"""
c.execute(sql, record_number)
# calling the method to create sql table in database
create_golfer_table()
# gets and stores the top 100 rows from table into database
for i in range(100):
find_table_row(i+1)
print_record(ranking)
inserting_sql(ranking)
ranking = []
conn.commit()
conn.close()
|
import math
def main():
letters, words, sentences = 0, 1, 0
sentence_test = ["!", ".", "?"]
text = input("Text: ")
for i in text:
letters += 1 if i.isalpha() else 0
words += 1 if i.isspace() else 0
sentences += 1 if i in sentence_test else 0
print(letters, words, sentences)
w_by_l = (letters / words) * 100
sentence_by_words = (sentences / words) * 100
index = (0.0588 * w_by_l) - (0.296 * sentence_by_words) - 15.8
index = round(index)
print_grade(index)
def print_grade(index):
if index < 1:
print("Before Grade 1")
elif index >= 16:
print("Grade 16+")
else:
print(f"Grade {index}")
main()
|
target = "zymotic"
with open('/home/zhang/learn_python/github_repo/python/word-play/words.txt') as f:
words = f.read()
words = words.split()
target = ["one", "two", "three", "four", "five", "six", "seven"]
with open('testwords.txt') as f:
words = f.read()
words = words.split()
def search(target):
index = len(words) // 2 + len(words) % 2
while True:
if target == words[index]:
return index
index = index // 2 + index % 2
elif target < words[index]:
index = index - index // 2
elif target > words[index]:
index = index + index // 2
if index index
for i in target:
print(search(i))
print(search(target))
|
print('hello world')
message = 'Hello World'
print(message)
print(len(message))
print('*' * 10)
message = '"Hello" World'
print(message)
book = "zhang's book"
print(book)
print('*' * 10)
# Wrong
# book = 'zhang's book'
# print(book)
message = """zhang
li
wang"""
print(message)
print(len(message))
print('*' * 10)
# slicing
slice_string = "Hello World"
print(slice_string[0:5])
print(slice_string[6:])
print(slice_string[:-1])
print(slice_string[1:3])
print(slice_string[:])
print('*' * 10)
# method
message = 'Hello World'
print(message.upper())
print(message)
message = 'Hello World'
print(message.count('hello'))
print(message.count('Hello'))
print(message.count('l'))
print(message.find('l'))
print(message.find('World'))
print('*' * 10)
message = 'Hello World'
message.replace('World', 'Universe')
print(message)
print( message.replace('World', 'Universe'))
message = message.replace('World', 'Universe')
print(message)
print('*' * 10)
greeting = 'Hello'
name = 'Michael'
message = greeting + name
print(message)
message = greeting + ', ' + name + '. Welcome!'
print(message)
message = '{}, {}. Welcome!'.format(greeting, name)
# f string
message = f'{greeting}, {name}. Welcome!'
print(message)
message = f'{greeting}, {name.upper()}. Welcome!'
print(message)
print('*' * 10)
# dir, help function
# print(dir(name))
# print(help(str))
# print(help(str.upper))
|
word = 'abcasfsddfds'
def is_abecdarian(word):
first = 0
for letter in word[:-1]:
if letter > word[first + 1]:
return False
first += 1
return True
print(is_abecdarian(word))
def is_abecdarian_2(word):
i = 0
while i <= len(word) - 2:
current = word[i]
forwoard = word[i + 1]
if current <= forwoard:
i += 1
continue
return False
return True
print(is_abecdarian_2(word))
|
# index [0, 1, 2, 3...]
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
print(courses)
print(len(courses))
print(courses.count('Math'))
print(courses[3])
print(courses[-1])
print(courses[:-1])
print(courses[:])
print(courses[0:2])
print('*' * 10)
# add item
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
courses.append('last')
print(courses)
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
courses.insert(0, 'first')
print(courses)
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
courses_2 = ['list1', 'list2']
courses.insert(0, courses_2)
print(courses)
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
courses.extend(courses_2)
print(courses)
print('*' * 10)
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
courses.remove('Math')
print(courses)
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
courses.pop()
print(courses)
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
poped = courses.pop()
print(poped)
# reverse
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
courses.reverse()
print(courses)
courses.sort()
print(courses)
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
nums = [3, 5, 2, 4, 1]
courses.sort(reverse=True)
nums.sort(reverse=True)
print(courses, nums)
print('*' * 10)
# function
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
nums = [3, 5, 2, 4, 1]
sorted_courses = sorted(courses)
print(courses)
print(sorted_courses)
print(max(nums), min(nums), sum(nums))
print('*' * 10)
# index
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
print(courses.index('CompSci'))
print('Art' in courses, 'Math' in courses)
print('*' * 10)
# loop
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
for course in courses:
print(course)
for index, course in enumerate(courses):
print(index, course)
for index, course in enumerate(courses, start=1):
print(index, course)
print('*' * 10)
# join method
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
courses_str = ', '.join(courses)
print(courses_str)
new_list = courses_str.split(', ')
print(new_list)
# Mutable
list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1
print(list_1)
print(list_2)
list_1.append('Art')
print(list_1)
print(list_2)
list_2.append('Education')
print(list_1)
print(list_2)
# Imutalbe
tuple_1 = ('History', 'Math', 'Physics', 'ComSci')
tuple_2 = tuple_1
print(tuple_2)
# wrong
# tuple_1.append('Art')
print('*' * 10)
# Sets
cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Math'}
print(cs_courses)
print('Math' in cs_courses)
art_courses = {'History', 'Math', 'Art', 'Design'}
print(cs_courses.intersection(art_courses))
print(cs_courses.difference(art_courses))
print(cs_courses - art_courses)
print(cs_courses.union(art_courses))
# wrong
# print(cs_courses + art_courses)
# empty
empty_list = []
empty_list = list()
empty_tuple = ()
empty_tuple = tuple()
empty_set = set()
# wrong
# empty_set = {}
dictionary = {}
|
class Employee:
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = f'{self.first}.{self.last}@email.com'
self.pay = pay
def fullname(self):
return f'{self.first} {self.last}'
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
emp_1 = Employee('zhang', 'wen', 5000)
emp_2 = Employee('wang', 'liang', 6000)
# raise_amount instance variable
# print(emp_1.pay)
# emp_1.apply_raise()
# print(emp_1.pay)
|
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def insercion(I):
for i in range(len(I)):
for j in range(i,0,-1):
if(I[j-1]>I[j]):
aux=I[j]
I[j]=I[j-1]
I[j-1]=aux
print(I)
>>> I=[6,5,3,1,8,7,2,4]
>>> print(I)
[6, 5, 3, 1, 8, 7, 2, 4]
>>> insercion(I)
[1, 2, 3, 4, 5, 6, 7, 8]
>>>
|
import pygame
import games.zeilen.Globals as globals
import games.zeilen.Resources as resources
tiles = list()
#Background class
#The background class is basicly the water tile. Several instances of this are created and used to fill the screen with water.
class Background(pygame.sprite.Sprite):
scroll_speed = 1 # Speed at which a tile goes downwards.
# The '__init__' method of a class is always automaticly executed when a new instance is created (constructor)
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(
self) # Idk what this does, but it's needed to make the sprite behave as a pygame sprite.
self.image = resources.sprites[
"spr_water"] # Sets the image of this sprite to the image of the water tile we loaded earlier
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
globals.background_sprites.add(self) # Add this newly created instance to the globals.background_sprites Group
tiles.append(self)
# Update method is called ever single loop in order to ensure that the background behav
def update(self):
self.rect.y += self.scroll_speed
if self.rect.top == globals.window_height:
self.rect.top = -32
#This method is used to create the background water. The background consists of water tiles (32x32) that are used to fill the screen
#Each water tile is a seperate instance which is scripted to move downwards with a consistant speed to create the illusion of movement.
def create_background():
screenx = globals.window_width
for i in range(0,screenx,32):
Background(i,-32)
Background(i,32*0)
Background(i,32*1)
Background(i,32*2)
Background(i,32*3)
Background(i,32*4)
Background(i,32*5)
Background(i,32*6)
Background(i,32*7)
Background(i,32*8)
Background(i,32*9)
Background(i,32*10)
Background(i,32*11)
Background(i,32*12)
Background(i,32*13)
Background(i,32*14)
Background(i,32*15)
Background(i,32*16)
Background(i,32*17)
Background(i,32*18)
|
#!/bin/python3
import random
print('''
Random Code Generator
=====================
''')
# Characters to use
chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ123456789'
length = input('Code length?')
length = int(length)
nb = input('How many Codes?')
nb = int(nb)
csvData = []
for pwd in range(nb):
password = ''
for c in range(length):
password += random.choice(chars)
csvData.append(password)
# Print the passwords
# print(password)
import csv
with open('codes.csv', 'w') as csvFile:
writer = csv.writer(csvFile, delimiter=",")
writer.writerows([c.strip() for c in r.strip(', ').split(',')]
for r in csvData)
csvFile.close()
|
from tkinter import messagebox, Tk, simpledialog
if __name__ == '__main__':
window = Tk()
window.withdraw()
name = simpledialog.askstring(None, 'Please enter a name')
if name.lower() == 'charlie':
messagebox.showinfo('Charlie', 'Charlie is very enthusiastic')
elif name.lower() == 'zachary':
messagebox.showinfo('Zachary', 'Zachary is very independent')
elif name.lower() == 'dave':
messagebox.showinfo('Dave', 'Dave is very funny')
else:
messagebox.showinfo(None, "Sorry, I don't know that name")
|
from functools import reduce as _reduce
def gen_cand_and_clean(votes):
"""
params:
- votes (list (dict {'a : Ord 'b})): The list of votes, which are
candidates mapped to a preference
returns:
- candidates (set 'a): The set of candidates
- cleaned votes (list (dict {'a : Ord 'b}))
This utility function generates a set of all candidates ranked in the
votes cast, and returns that set along with a cleaned set of votes
"""
candidates = _reduce(set.union,
[set(v.keys()) for v in votes],
set())
return candidates, clean_votes(candidates, votes)
def clean_votes(candidates, votes):
"""
params:
- candidates (list 'a): The list of candidates
- votes (list (dict {'a : Ord 'b})): The list of votes, which are
candidates mapped to a preference
returns:
- cleaned votes (list (dict {'a : Ord 'b}))
Cleans votes by adding a 0 for each non-present candidate, which means
votes should be in high-preference, high rank order (1-10 worst-best)
"""
for vote in votes:
for candidate in candidates:
if candidate not in vote:
vote[candidate] = 0
return votes
|
from random import randrange
# 3번 연속이기면 승리
def game():
com = randrange(0, 3)
print(' COM: ', com)
user = int(input('가위 0, 바위 1, 보 2 \n YOU: '))
if com < user :
com = com + 3
result = com -user
result_str = ''
if result == 2:
result_str = 'USER WIN'
if result == 1:
result_str = 'COM WIN'
if result == 0:
result_str = 'DRAW'
print(result_str)
return (result_str)
before = ''
count = 0
while True:
result = game()
if result == 'DRAW':
continue
elif result == before:
count = count + 1
else:
count = 1
before = result
if count == 3:
break
|
from random import randint
class Board(object):
def __init__(self, size):
assert isinstance(size, int)
self.size = size
self.positions = [["-"] * self.size for i in range(self.size)]
def __repr__(self):
board_string = '\n'.join(['|'.join(self.positions[i]) for i in range(self.size)])
return 'I am board of size %i \n' % self.size + board_string
def __getitem__(self, positions):
return self.positions[positions[0]][positions[1]]
def clear(self):
self.positions = [[" -"] * self.size for i in range(self.size)]
def insert(self, symbol_type, positions):
assert (symbol_type == 'X' or symbol_type == 'Y')
self.positions[positions[0]][positions[1]] = symbol_type
def check_victory_conditions(self):
rows = list(map(lambda x: ''.join(x), self.positions))
columns = list(map(lambda x: ''.join(x), zip(*self.positions)))
antydiag = list(map(lambda x: ''.join(x), [[self.positions[i][j]
for i in range(self.size)
for j in range(self.size)
if i + j == k]
for k in range(2 * self.size - 1)]))
diag = list(map(lambda x: ''.join(x), [[self.positions[i][j]
for i in range(self.size)
for j in range(self.size)
if -i + j == k]
for k in range(-self.size + 1, self.size)]))
return 'X' * self.size in rows or 'Y' * self.size in rows \
or 'X' * self.size in columns or 'Y' * self.size in columns \
or 'X' * self.size in diag or 'Y' * self.size in diag \
or 'X' * self.size in antydiag or 'Y' * self.size in antydiag
class NoughtsAndCorsses(object):
def __init__(self, size):
self.board = Board(size)
def _play_turn(self, player_mark):
assert player_mark in 'XY'
fieldpos_x = randint(0, self.board.size - 1)
fieldpos_y = randint(0, self.board.size - 1)
while (self.board[fieldpos_x, fieldpos_y] != '-'):
fieldpos_x = randint(0, self.board.size - 1)
fieldpos_y = randint(0, self.board.size - 1)
return (fieldpos_x, fieldpos_y)
def play_bot_game(self):
turn = 0
end = False
while not end and turn < self.board.size ** 2:
turn += 1
mark = 'X' if turn % 2 == 0 else 'Y'
self.board.insert(mark, self._play_turn(mark))
print(self.board)
end = self.board.check_victory_conditions()
outcome = 'Winner is player %s' % mark if (turn < self.board.size ** 2) \
else "The game ended with draw"
print(outcome)
game = NoughtsAndCorsses(5)
game.play_bot_game()
|
"""
Chapter 6, Our first NN with
backpropagation and conditional correlation
"""
import numpy as np
np.random.seed(1)
def relu(x):
# Our Relu method for conditional correlation in the middle layer
# it will set all negative numbers to 0, "turning off" middle nodes.
return (x > 0) * x
def relu_deriv(output):
# Dervicatve of relu, returns 1 for input > 0, 0 otherwise
return output > 0
alpha = 0.2
hidden_size = 4
streetlights = np.array([
[1, 0, 1],
[0, 1, 1],
[0, 0, 1],
[1, 1, 1],
])
walk_vs_stop = np.array([
[1, 1, 0, 0],
]).T # transpose 1x4 vector
# Two set of weights now to connect the three layers (randomly initialized)
weights_0_1 = 2 * np.random.random((3, hidden_size)) - 1
weights_1_2 = 2 * np.random.random((hidden_size, 1)) - 1
for iteration in range(60):
layer_2_error = 0
for i in range(len(streetlights)):
layer_0 = streetlights[i:i + 1]
layer_1 = relu(np.dot(layer_0, weights_0_1)) # Pass input to weights (dot prod) then apply relu
layer_2 = np.dot(layer_1, weights_1_2) # where negative values become 0 -> becomes input for the next layer
# Squared error calculation of layer 2
layer_2_error += np.sum((layer_2 - walk_vs_stop[i:i + 1]) ** 2)
layer_2_delta = (walk_vs_stop[i:i + 1] - layer_2)
# The following line computes the delta at layer_1 given the delta at layer_2 by taking
# the layer_2 delta and multiplying it by it's connecting weights
layer_1_delta = layer_2_delta.dot(weights_1_2.T) * relu_deriv(layer_1)
# Updating our weights based on our previously calculated deltas
weights_1_2 += alpha * layer_1.T.dot(layer_2_delta)
weights_0_1 += alpha * layer_0.T.dot(layer_1_delta)
if (iteration % 10 == 9):
print(f"Error: {layer_2_error}")
|
# define the fibonacci() function below...
def fibonacci(n):
# base cases
if n == 1:
return n
if n == 0:
return n
# recursive step
print("Recursive call with {0} as input".format(n))
return fibonacci(n - 1) + fibonacci(n - 2)
fibonacci(5)
# set the appropriate runtime:
# 1, logN, N, N^2, 2^N, N!
fibonacci_runtime = "2^N" |
# Elliptic Curve Implementation
import collections
Coord = collections.namedtuple("Coord", ["x", "y"])
def inv(n, q):
"""
Find the inverse on n modulus q
"""
return egcd(n, q)[0] % q
def egcd(a, b):
"""
This function performs an extended GCD according to euclid's algorithm.
It finds a pair (s, t) such that a*s + b*t == gcd
"""
s0, s1, t0, t1 = 1, 0, 0, 1
while b > 0:
q, r = divmod(a, b)
a, b = b, r
s0, s1, t0, t1 = s1, s0 - q * s1, t1, t0 - q * t1
return s0, t0, a
class EC(object):
def __init__(self, a, b, Prime, G, order):
"""
Initialize an Elliptic Curve, Defined as:
(y^2 = x^3 + ax + b) modulus Prime
"""
assert 0 <= a and a < Prime and 0 <= b and b < Prime and Prime > 2
assert (4 * (a ** 3) + 27 * (b ** 2)) % Prime != 0
self.a = a # Coefficient of x
self.b = b # Constant term
self.Prime = Prime # Large prime number - limiting the finite field
self.G = G # Generator point / Base point
self.zero = Coord(0, 0) # Zero point
# Order -
# An elliptic curve defined over a finite field has a finite number of points.
# The number of points in a group is called the order of the group.
self.order = order
def add(self, p1: Coord, p2: Coord):
"""
This function returns the addition of two points on the elliptic curve.
For point addition, we take two points on the elliptic curve and then add them together (R=P+Q).
"""
# Base Cases
# Adding a point to (0, 0)
if p1 == self.zero:
return p2
if p2 == self.zero:
return p1
# Adding inverse points
if p1.x == p2.x and (p1.y != p2.y or p1.y == 0):
return self.zero
# Calculating the slope (Self-Addition)
# ((3x^2 + a) / 2y) mod Prime
if p1.x == p2.x:
slope = (3 * p1.x * p1.x + self.a) * \
inv(2 * p1.y, self.Prime) % self.Prime
# General Case
# So if we use x^3+ax+b (mod p),
# and we have two points P (x1,y1) and Q(x2,y2) that we want to add,
# we calculate the gradient between the points: s=(y1−y2)/(x1−x2)
# Then to determine the new point R(x3,y3), we use: x=s^2−x1−x2, y=s(x1−x2)−y1
else:
temp1 = (p2.y - p1.y)
temp2 = inv(p2.x - p1.x, self.Prime)
slope = temp1 * temp2 % self.Prime
x = (slope * slope - p1.x - p2.x) % self.Prime
y = (slope * (p1.x - x) - p1.y) % self.Prime
return Coord(x, y)
def mul(self, Point, n):
"""
This function returns the nth multiplication of a point on the elliptic curve.
The straightforward way of computing a point multiplication is through repeated addition.
"""
result = self.zero
addPoint = Point
# According to Double-and-Add algorithm to Point Multiplication
# As described in pseudo-code in https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication
while n > 0:
if n & 1 == 1:
result = self.add(result, addPoint)
addPoint = self.add(addPoint, addPoint)
n = n >> 1
return result
|
def crypt(args, x):
ciphertext = str(args)
shift = int(x)
ciphertext = ciphertext.split()
sentence = []
for word in ciphertext:
cipher_ords = [ord(x) for x in word]
plaintext_ords = [o + shift for o in cipher_ords]
plaintext_chars = [chr(i) for i in plaintext_ords]
plaintext = ''.join(plaintext_chars)
sentence.append(plaintext)
sentence = ' '.join(sentence)
print('Decryption Successful\n')
print('Your encrypted sentence is:', sentence)
return sentence
def decrypt(args, x):
ciphertext = str(args)
shift = int(x)
ciphertext = ciphertext.split()
sentence = []
for word in ciphertext:
cipher_ords = [ord(x) for x in word]
plaintext_ords = [o - shift for o in cipher_ords]
plaintext_chars = [chr(i) for i in plaintext_ords]
plaintext = ''.join(plaintext_chars)
sentence.append(plaintext)
sentence = ' '.join(sentence)
return sentence
|
import pygame,random
from pygame.locals import*
screen_width = 800
screen_height = 800
pygame.init()
game_display = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Tic Tac Toe')
clock = pygame.time.Clock()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
blue = (0,0,255)
board_size = 3
player1 = 1
player2 = 2
##startx = 150
##endx = 650
##vertical_start_x = 300
##vertical_end_x = 500
##vertical_start_y = 100
##vertical_end_y = 500
##hor_start_x = 150
##hor_start_y = 100 + 400//3
##hor_end_x = 650
##hor_end_y = 100 + 800//3
def draw_board(board):
game_display.fill(white)
pygame.draw.line(game_display, black, (300,100), (300,700))
pygame.draw.line(game_display, black, (500,100), (500,700))
pygame.draw.line(game_display, black, (100,300),(700,300))
pygame.draw.line(game_display, black, (100,500),(700,500))
for x in range(board_size):
for y in range(board_size):
if board[x][y] == player1:
pygame.draw.circle(game_display, red, (200 + 200 * x, 200 + 200 * y),50,1)
elif board[x][y] == player2:
pygame.draw.line(game_display, blue, (100 + x * 200 + 50, 100 + y * 200 + 50),(300 + 200 * x - 50, 300 + 200 * y - 50))
pygame.draw.line(game_display, blue ,(300 + 200 * x - 50, 100 + y * 200 + 50),(100 + 200 * x + 50, 300 + 200 * y - 50))
pygame.display.update()
clock.tick()
def get_board():
board = []
for i in range(board_size):
board.append([None]*board_size)
return board
def text_objects(text,font,color):
text_surf = font.render(text, True, color)
return text_surf,text_surf.get_rect()
def is_win(board,player):
for x in range(board_size):
for y in range(board_size-2):
if board[x][y] == board[x][y+1] == board[x][y+2] == player:
return True
for x in range(board_size - 2):
for y in range(board_size):
if board[x][y] == board[x+1][y] == board[x+2][y] == player:
return True
for x in range(board_size - 2):
for y in range(board_size - 2):
if board[x][y] == board[x+1][y+1] == board[x+2][y+2] == player:
return True
if board[2][0] == board[1][1] == board[0][2] == player:
return True
return False
def is_tie(board):
for x in range(board_size):
for y in range(board_size):
if board[x][y] != None:
return False
return True
def play():
board = get_board()
if random.randint(0,1)==1:
turn = player2
else:
turn = player1
while True:
draw_board(board)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if turn == player1:
board = get_player_move(board,player1)
turn = player2
if is_win(board,player1):
text = 'Player 1 Wins'
break
elif turn == player2:
board = get_player_move(board,player2)
turn = player1
if is_win(board,player2):
text = 'Player 2 Wins'
break
if is_tie(board):
text = 'It''s a tie'
break
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == MOUSEBUTTONDOWN:
play()
text_name = pygame.font.Font('freesansbold.ttf',55)
text_surf,text_rect = text_objects(text,text_name,black)
text_rect.center = ((400,50))
game_display.blit(text_surf, text_rect)
pygame.display.update()
clock.tick()
def get_player_move(board,player):
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
elif event.type == MOUSEBUTTONDOWN:
posx,posy = event.pos
if 100 < posx < 7000 and 100 < posy < 700:
col = (posx - 100)//200
row = (posy - 100)//200
if board[col][row] == None:
board[col][row] = player
draw_board(board)
return board
return board
play()
|
import numpy as np
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
N_of_english_chars = 26
# frequency taken from http://en.wikipedia.org/wiki/Letter_frequency
englishLetterFreq = {'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36, 'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29, 'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10, 'Z': 0.07}
def decrypt(key, message):
result = ""
list = []
for letter in message:
if letter in letters: #if the letter is actually a letter
#find the corresponding ciphertext letter in the alphabet
letter_index = (letters.find(letter) - key) % len(letters)
result = result + letters[letter_index]
else:
result = result + letter
list = result
return list
#
# Python code to implement
# Vigenere Cipher
# This function generates the
# key in a cyclic manner until
# it's length isn't equal to
# the length of original text
def generateKey(string, key):
key = list(key)
if len(string) == len(key):
return (key)
else:
for i in range(len(string) -
len(key)):
key.append(key[i % len(key)])
return ("".join(key))
# This function returns the
# encrypted text generated
# with the help of the key
def cipherText(string, key):
cipher_text = []
for i in range(len(string)):
x = (ord(string[i]) +
ord(key[i])) % 26
x += ord('A')
cipher_text.append(chr(x))
return ("".join(cipher_text))
# This function decrypts the
# encrypted text and returns
# the original text
def originalText(cipher_text, key):
orig_text = []
for i in range(len(cipher_text)):
x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26
x += ord('A')
orig_text.append(chr(x))
return ("".join(orig_text))
def calculate_frequency(test):
all_freq = {}
for i in test:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
# printing result
return all_freq
def sum_frequency(sum_frequency):
calculate = 0
N=0
for key, value in sum_frequency.items():
calculate += value * (value - 1)
N +=value
IC = calculate / (float(N) * (N - 1))
return IC*26
def average_IC_return_number(length, text):
split = [''] * length # string with empty spaces by key size
sum = 0
for n, letter in enumerate(text):
split[n % length] += letter
for i in range(length):
sum += sum_frequency(calculate_frequency(split[i]))
return sum / length,
def calc_ic_for_each_key():
key_length = 1
average = []
for n in range(1, 15):
average += average_IC_return_number(n, test_str)
max = abs(1.73 - np.float_(average[0]))
for n in range(len(average)):
item = abs(1.73 - np.float_(average[n]))
if max > item :
max = item
key_length = n+1 #array starts from 0 place
print ("The key length is:" , key_length )
return key_length
def split_string_return_string(length, text):
split = [''] * length # string with empty spaces by key size
sum = 0
for n, letter in enumerate(text):
split[n % length] += letter
return split
def calculate_X_formula(key_frnq):
x = 0
lol = {k: v * key_frnq[k] for k, v in englishLetterFreq.items() if k in key_frnq}
for key, value in lol.items():
x += value
return x
# Driver code
# string taken from https://en.wikipedia.org/wiki/Index_of_coincidence
if __name__ == "__main__":
string = "MUSTCHANGEMEETINGLOCATIONFROMBRIDGETOUNDERPASSSINCEENEMYAGENTSAREBELIEVEDTOHAVEBEENASSIGNEDTOWATCHBRIDGESTOPMEETINGTIMEUNCHANGEDXX"
keyword = "EVERY"
key = generateKey(string, keyword)
cipher_text = cipherText(string, key)
print("Ciphertext :", cipher_text)
print("Original/Decrypted Text :",
originalText(cipher_text, key))
# initializing string
# string taken from https://en.wikipedia.org/wiki/Index_of_coincidence
test_str = "QPWKALVRXCQZIKGRBPFAEOMFLJMSDZVDHXCXJYEBIMTRQWNMEAIZRVKCVKVLXNEICFZPZCZZHKMLVZVZIZRRQWDKECHOSNYXXLSPMYKVQXJTDCIOMEEXDQVSRXLRLKZHOV"
key_length_was_found = calc_ic_for_each_key()
stirng_key_find = split_string_return_string(key_length_was_found, test_str)
max_x = 0
founded_key_letters = []
total_key= ""
for g in range(0,key_length_was_found):
for i in range(0,N_of_english_chars):
a = []
a = decrypt(i,stirng_key_find[g])
a_a = calculate_frequency(a)
a_a_a = calculate_X_formula(a_a)
if max_x < a_a_a:
max_x = a_a_a
founded_key_letters = letters[i]
total_key += founded_key_letters
max_x = 0
print "The 'KEY' is: ",total_key
new_key = generateKey(test_str,total_key)
print 'OriginalText is:' ,originalText(test_str,new_key)
|
def outer(a):
def inner(*args, **kwargs):
for arg in args:
if not isinstance(arg, str):
print("Not all arguments are string")
return inner
for kwarg in kwargs.values():
if not isinstance(kwarg, str):
print("Not all arguments are string")
return inner
else:
a(*args, **kwargs)
return inner
@outer
def function1(str1, str2, str3):
print(str1, str2, str3)
@outer
def function2(a, b, c):
print(a, b, c)
@outer
def function3(name1, name2):
print(name1, name2)
function1(str1 = "suresh", str2 = "vasan", str3 = "saurav")
function2(1, "jim", "harry")
function3("ben", name2 = "ten")
|
# 실수(real number) 1개를 입력받아 줄을 바꿔 3번 출력해보자.
# 예시
# ...
# print(f) #f에 저장되어있는 값을 출력하고 줄을 바꾼다.
# print(f)
# print(f)
# 와 같은 방법으로 3번 줄을 바꿔 출력할 수 있다.
# 참고
# python 코드 사이에 설명(주석)을 작성해 넣고 싶은 경우 샵('#') 기호를 사용하면 된다.
# #가 시작된 위치부터 그 줄을 마지막까지는 python 인터프리터에 의해서 실행되지 않는다.
# 소스코드 부분 부분에 설명, 내용, 표시를 한 줄 설명으로 넣을 경우에 편리하게 사용할 수 있다.
# 여러 줄로 설명을 넣는 방법도 있다. 스스로 찾아보자!
f = input()
for i in range(3):
print(f) |
# 빨강(red), 초록(green), 파랑(blue) 빛을 섞어 여러 가지 다른 색 빛을 만들어 내려고 한다.
# 빨강(r), 초록(g), 파랑(b) 각 빛의 가짓수가 주어질 때,
# 주어진 rgb 빛들을 섞어 만들 수 있는 모든 경우의 조합(r g b)과 만들 수 있는 색의 가짓 수를 계산해보자.
# **모니터, 스마트폰과 같은 디스플레이에서 각 픽셀의 색을 만들어내기 위해서 r, g, b 색을 조합할 수 있다.
# **픽셀(pixel)은 그림(picture)을 구성하는 셀(cell)에서 이름이 만들어졌다.
r, g, b = input().split(' ')
r = int(r)
g = int(g)
b = int(b)
for i in range(r):
for j in range(g):
for k in range(b):
print(i, j, k)
print(r * g * b) |
# 친구들과 함께 3 6 9 게임을 하던 영일이는 잦은 실수 때문에 계속해서 벌칙을 받게 되었다.
# 3 6 9 게임의 왕이 되기 위한 369 마스터 프로그램을 작성해 보자.
# ** 3 6 9 게임은?
# 여러 사람이 순서를 정한 후, 순서대로 수를 부르는 게임이다.
# 만약 3, 6, 9 가 들어간 수를 자신이 불러야 하는 상황이라면, 수를 부르는 대신 "박수(X)" 를 쳐야 한다.
# 33과 같이 3,6,9가 두 번 들어간 수 일때, "짝짝"과 같이 박수를 두 번 치는 형태도 있다.
# 참고
# ...
# for i in range(1, n+1) :
# if i%10==3 :
# print("X", end=' ') #출력 후 공백문자(빈칸, ' ')로 끝냄
# ...
n = int(input())
result = ''
for i in range(1, n + 1):
clap = ''
tens = i // 10
ones = i - (tens * 10)
if(tens != 0 and tens % 3 == 0):
clap = clap + "X"
if(ones != 0 and ones % 3 == 0):
clap = clap + "X"
if clap != '':
result = result + clap + " "
else:
result = result + str(i) + " "
print(result) |
# 공백을 두고 입력된정수(integer) 2개를 입력받아 줄을 바꿔 출력해보자.
# 예시
# a, b = input().split()
# print(a)
# print(b)
# 과 같은 방법으로 두 정수를 입력받아 출력할 수 있다.
# 참고
# python의 input()은 한 줄 단위로 입력을 받는다.
# input().split() 를 사용하면, 공백을 기준으로 입력된 값들을 나누어(split) 자른다.
# a, b = 1, 2
# 를 실행하면, a에는 1 b에는 2가 저장된다.
# (주의 : 하지만, 다른 일반적인 프로그래밍언어에서는 이러한 방법을 지원하지 않기 때문에 a=1, b=2 를 한 번에 하나씩 따로 실행시켜야 한다.)
num1, num2 = input().split(' ')
print(num1)
print(num2) |
# 10진수를 입력받아 16진수(hexadecimal)로 출력해보자.
# 예시
# a = input()
# n = int(a) #입력된 a를 10진수 값으로 변환해 변수 n에 저장
# print('%x'% n) #n에 저장되어있는 값을 16진수(hexadecimal) 소문자 형태 문자열로 출력
# 참고
# 10진수 형태로 입력받고
# %x로 출력하면 16진수(hexadecimal) 소문자로 출력된다.
# (%o로 출력하면 8진수(octal) 문자열로 출력된다.)
# 10진법은 한 자리에 10개(0 1 2 3 4 5 6 7 8 9)의 문자를 사용하고,
# 16진법은 영문 소문자를 사용하는 경우에 한 자리에 16개(0 1 2 3 4 5 6 7 8 9 a b c d e f)의 문자를 사용한다.
# 16진수 a는 10진수의 10, b는 11, c는 12 ... 와 같다.
num = int(input())
print("%x" %num) |
# 정수 2개(a, b)를 입력받아
# a를 b번 곱한 거듭제곱을 출력하는 프로그램을 작성해보자.
# 예시
# ...
# c = int(a)**int(b)
# print(c)
# 참고
# python 언어에서는 거듭제곱을 계산하는 연산자(**)를 제공한다.
# 일반적으로 수학 식에서 거듭제곱을 표현하는 사용하는 서컴플렉스/케릿 기호(^)는 프로그래밍언어에서 다른 의미로 쓰인다.
a, b = input().split(' ')
result = int(a) ** int(b)
print(result) |
# 점수(정수, 0 ~ 100)를 입력받아 평가를 출력해보자.
# 평가 기준
# 점수 범위 : 평가
# 90 ~ 100 : A
# 70 ~ 89 : B
# 40 ~ 69 : C
# 0 ~ 39 : D
# 로 평가되어야 한다.
# 예시
# ...
# if n>=90 :
# print('A')
# else :
# if n>=70 :
# print('B')
# else :
# if n>=40 :
# print('C')
# else :
# print('D')
# ...
# 참고
# 여러 조건들을 순서대로 비교하면서 처리하기 위해서 조건문을 여러 번 중첩할 수 있다.
# if 조건식1 :
# ...
# else :
# if 조건식2 :
# ...
# else :
# if 조건식3 :
# ...
# else :
# ...
# ...
# 와 같이 조건/선택 실행 구조를 겹쳐 작성하면 순서대로 조건을 검사할 수 있다.
# 어떤 조건이 참이면 그 부분의 내용을 실행하고 전체 조건/선택 구조를 빠져나가게 된다.
# if 조건식1 :
# ...
# elif 조건식2 :
# ...
# elif 조건식3 :
# ...
# else :
# ...
# 도 똑같은 기능을 한다. elif는 else if 의 짧은 약어라고 생각해도 된다.
# elif 를 사용하면 if ... else ... 구조를 겹쳐 사용할 때처럼, 여러 번 안 쪽으로 들여쓰기 하지 않아도 된다.
score = int(input())
if score >= 90:
print("A")
elif score >= 70:
print("B")
elif score >= 40:
print("C")
else:
print("D") |
word = "tallie"
#removes letter from alphabet once guessed
def remove_guessed_letter(word): #remove letter once guessed
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for charactors in list(alphabet):
if charactors in word:
alphabet = alphabet.replace(charactors," ")
return alphabet
guess1 = "t"
print remove_guessed_letter() |
age = input("Enter_your_age_here:")
if 18 <= int(age):
print("You are an adult!")
else:
print("You are a small boy")
input("Press enter to exit") |
import random
possible_cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
print("Please note that the dealer stands at 16.")
while True:
players_hand = ""
dealers_hand = ""
while players_hand == "" and dealers_hand == "":
players_hand = random.choice(possible_cards) + random.choice(possible_cards)
dealers_hand = random.choice(possible_cards)
print("Your hand is " + str(players_hand))
print("Dealers first card is " + str(dealers_hand))
while players_hand > 0 and dealers_hand > 0:
action = input("Hit or Stand?: ")
dealers_second_face = random.choice(possible_cards)
dealers_hand = dealers_hand + dealers_second_face
if action == "hit":
drew1 = random.choice(possible_cards)
players_hand = players_hand + drew1
print("Your drew a " + str(drew1))
if players_hand == 21:
print("Your hand is 21. You have blackjack!")
break
elif players_hand > 21:
print("Your hand is " + str(players_hand) + " . Unlucky!. You busted!")
break
elif players_hand < 21:
print("Your hand is " + str(players_hand))
second_action = input("Hit or Stand?: ")
if second_action == "stand":
print("Dealer's second card is " + str(dealers_second_face))
print("Dealer's hand is " + str(dealers_hand))
while dealers_hand < 16:
drewd2 = random.choice(possible_cards)
dealers_hand = dealers_hand + drewd2
print("The dealer drew a " + str(drewd2))
print("The dealer's hand is now " + str(dealers_hand))
if dealers_hand > 21:
print("Dealer's hand is " + str(dealers_hand) + ". The dealer busted. You win!")
break
if dealers_hand > players_hand:
print("The dealer has " + str(dealers_hand) + ". You have " + str(
players_hand) + ". Unlucky. You lose.")
elif players_hand > dealers_hand:
print("The dealer has " + str(dealers_hand) + ". You have " + str(players_hand) + ". You win.")
break
elif dealers_hand == 21 and players_hand == 21:
print("Both got Blackjack. Push.")
break
elif dealers_hand == 21 and players_hand < 21:
print("Dealer got Blackjack. You lose.")
break
elif second_action == "hit":
drew2 = random.choice(possible_cards)
players_hand = players_hand + drew2
print("Your drew a " + str(drew2))
if players_hand == 21:
print("Your hand is 21. You've got blackjack!")
break
elif players_hand > 21:
print("Your hand is " + str(players_hand) + " . Unlucky!. You busted!")
break
elif players_hand < 21:
print("Your hand is " + str(players_hand))
third_action = input("Hit or Stand?: ")
if third_action == "stand":
print("Dealer's second card is " + str(dealers_second_face))
print("Dealer's hand is " + str(dealers_hand))
while dealers_hand < 16:
drewd3 = random.choice(possible_cards)
dealers_hand = dealers_hand + drewd3
print("The dealer drew a " + str(drewd3))
print("The dealer's hand is now " + str(dealers_hand))
if dealers_hand > 21:
print("Dealer's hand is" + str(dealers_hand) + ". The dealer busted. You win!")
break
if dealers_hand > players_hand:
print("The dealer has " + str(dealers_hand) + ". You have " + str(
players_hand) + ". Unlucky. You lose.")
break
elif players_hand > dealers_hand and dealers_hand > 16:
print("The dealer has " + str(dealers_hand) + ". You have " + str(
players_hand) + ". You win.")
break
elif dealers_hand == 21 and players_hand == 21:
print("Both got Blackjack. Push.")
break
elif dealers_hand == 21 and players_hand < 21:
print("Dealer got Blackjack. You lose.")
break
if third_action == "hit":
drew3 = random.choice(possible_cards)
players_hand = players_hand + drew3
print("Your drew a " + str(drew3))
if players_hand == 21:
print("Your hand is 21. You've got blackjack!")
break
elif players_hand > 21:
print("Your hand is " + str(players_hand) + " . Unlucky!. You busted!")
break
elif players_hand < 21:
print("You have " + str(players_hand))
if dealers_hand > players_hand and dealers_hand > 16:
print("The dealer has " + str(dealers_hand) + ". You have " + str(
players_hand) + ". Unlucky. You lose.")
break
elif players_hand > dealers_hand:
print("The dealer has " + str(dealers_hand) + ". You have " + str(
players_hand) + ". You win.")
break
if action == "stand":
print("Dealer's second card is " + str(dealers_second_face))
print("Dealer's hand is " + str(dealers_hand))
while dealers_hand < 16:
drewd1 = random.choice(possible_cards)
dealers_hand = dealers_hand + drewd1
print("The dealer drew a " + str(drewd1))
print("The dealer's hand is now " + str(dealers_hand))
if dealers_hand > 21:
print("Dealer's hand is " + str(dealers_hand) + ". The dealer busted. You win!")
break
if dealers_hand > players_hand and dealers_hand < 21:
print(
"The dealer has " + str(dealers_hand) + ". You have " + str(players_hand) + ". Unlucky. You lose.")
break
elif players_hand > dealers_hand:
print("The dealer has " + str(dealers_hand) + ". You have " + str(players_hand) + ". You win.")
break
elif dealers_hand == 21 and players_hand == 21:
print("Both got Blackjack. Push.")
break
elif dealers_hand == 21 and players_hand < 21:
print("Dealer got Blackjack. You lose.")
break
|
# Dropbox Python Authentication Tutorial
# Include Dropbox SDK libraries
from dropbox import client, rest, session
# Set APP_KEY, APP_SECRET, and ACCESS_TYPE
APP_KEY = 'ongci9riiqkrtll'
APP_SECRET = 'jyae8eqk2088hdp'
ACCESS_TYPE = 'app_folder' # application has access to application folder only
# Set up session variable
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
request_token = sess.obtain_request_token()
# User must authorize our application
# We'll send the user to the Dropbox website to allow our app access to their account
# Build url for user to authorize our application to access their Dropbox account
url = sess.build_authorize_url(request_token)
print 'Url: ', url
raw_input()
# We'll want to automatically send the user to the authorization URL
# and probably also pass in a callback URL so that the user is seamlessly redirected back to your app after pressing a button
#
#
# Once the user has successfully granted permission to your app
# we can upgrade the now-authorized request token to an access token
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
# The access token is all you'll need for all future API requests on behalf of this user,
# so you should store it away for safe-keeping (even though we don't for this tutorial).
# By storing the access token, you won't need to go through these steps again unless
# the user reinstalls your app or revokes access via the Dropbox website.
# Now that the hard part is done, all you'll need to sign your other API calls is
# to pass the session object to DropboxClient and attach the object to your requests.
client = client.DropboxClient(sess)
|
from selenium import webdriver
driver = webdriver.Chrome()#install the chrome divers for this code to work(accordance to your chrome version)
driver.get('https://web.whatsapp.com/')
name = input('Enter the name of user or group : ')#whom you wanna sent
msg = input('Enter your message : ')#what you wanna sent
input('Enter anything after scanning QR code')#just to make sure u scanned the code (you can remove it if u want)
user = driver.find_element_by_xpath(f'//span[@title = "{name}"]')#finds the path(where to go) to the name of the person or group
user.click()#click on that group/user
msg_box = driver.find_element_by_class_name('_1Plpp')# you should change this according to you(more info at the bottom of the code)
msg_box.send_keys(msg)
button = driver.find_element_by_class_name('_35EW6')
button.click()
# open web whatsapp>log in > press F12 > Go to elements(by default you are already on it)
# Then in body scroll through divs' to and hover on the div's to see which div selects what part of your web whatsapp
# deep in the divs > you will find footer > where you will find a class name
# paste that class name there and the code should work just fine
|
#
# Copyright (c) 2018 Andera del Monaco
#
# The following example shows how to import the Yahoo Finance Python Interface
# into your own script, and how to use it.
#
# In particular, we will download the timeseries of APPLE close daily price from 2017-09-1 to 2018-08-31,
# and then will plot them using the matplotlib package.
# In order to illustrate the implementation of pandas.DataFrame within the YahooFinancePynterface,
# we will plot the 20-periods Bollinger bands on the same figure.
#
import yahoo_finance_pynterface as yahoo
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
if __name__ == '__main__':
fig, ax = plt.subplots(1);
r = yahoo.Get.Prices("AAPL", period=['2017-09-01','2018-08-31']);
if r is not None:
mu = r.Close.rolling(20).mean()
sigma = r.Close.rolling(20).std()
plt.plot(r.index.values, r.Close, color='dodgerblue', label="", zorder=30);
plt.plot(r.index.values, mu, color='orange', label="SMA(20)", zorder=20);
plt.fill_between(r.index.values,mu+2*sigma,mu-2*sigma, color='moccasin', label="", zorder=10);
ax.grid(True, alpha=0.5);
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1));
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'));
ax.yaxis.set_major_locator(mticker.FixedLocator(range(100,300,10)))
ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x,pos: f"{x}.00 $"))
print(r.Close);
else:
print("something odd happened o.O");
plt.title("Apple Inc.")
plt.legend();
plt.gcf().autofmt_xdate();
plt.show();
|
class Rect(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self._x_center = x + (width / 2)
self._y_center = y + (height / 2)
@property
def x_center(self):
return int(self.x +(self.width / 2))
@property
def y_center(self):
return int(self.y +(self.height / 2))
def check_collision(self, other_rect):
if self.x + self.width in range(other_rect.x, other_rect.x + other_rect.width) and self.y + self.height in range(other_rect.y, other_rect.y + other_rect.height) or \
self.x in range(other_rect.x, other_rect.x + other_rect.width) and self.y in range(other_rect.y, other_rect.y + other_rect.height):
return True
return False |
# print('enter a number')
""" a = int(input())
print('Enter a second number')
b = int(input())
c = a+b
print("out put is \n",c) """
'''
x = input()[0]
print(x);
'''
'''x = eval(input())
print(x)
'''
"""
if 1 != 1 :
print('dfd')
print(5464)
print(445)
else:
print(54365436)
print(454365463)
a = 5
b = 6
if a < b:
if a == 5:
print(654)
else:
print(54)
elif b == 6:
if a <= 5:
print(664)
else:
print(545)
"""
"""count = 5
a=0
while count > 0:
a += 1
print('iteration:', a, end=" ")
count -= 1
"""
"""list1 = [45, 5, 45, 45, 54, 54, 54]
for i in list1:
if i % 2 == 0:
print(i)
x = 'krishna'
for j in x:
print(j, end="")
"""
"""
for k in range(1, 101):
if k%2 == 0:
print(k)
"""
# patterns
"""for i in range(1, 5):
for j in range(1, 5):
print('#', end=" ")
print('')
"""
# this is for else
nums = [5, 61, 43, 51, 61]
for n in nums:
if n%2 ==0:
print(n)
break
else:
print('Not Found')
|
f = open('My Personal Details', 'r')
print(f)
# print(f.read()) # print entire content
# print(f.readline()) # print 1st line
# print(f.readline()) # print 2nd line it has inbuild next function
# print(f.readline(3)) # print mentioned line number
# print(f.readable()) # it returns boolean which file is readable or not
'''TO WRITE DATA'''
f1 = open('Emptyfile','w') # if file not exist it will create file with mentioned name
print(f1)
f1.write('Hello World')
print(f1.writable())
f1.write('hkfvgfghligdsf')
f1 = open('abc','a')
print(f1)
# a = append
f1.write('Hello') # it delete previous data nd wirte this content
# copying f data in f1
for data in f:
f1.write(data)
# we can do with images etc also |
n=input("enter string\n")
k=input("enter key\n")
k=int(k)
a=""
b=" "
for i in range(len(n)):
b=ord(n[i])-97
b=(b+k)%26
b=chr(b+97)
a=a+b
print("Encrypted")
print(a)
c=""
b=" "
for i in range(len(a)):
b=ord(a[i])-97
b=(b-k)%26
b=chr(b+97)
c=c+b
print("Decrypted")
print(c)
|
####################序列通用操作####################
#Indexing
greeting = "Hello"
print(greeting[0]) #第一个元素
print(greeting[-1]) #右起第一个元素
print("Hello"[1]) #序列字面量直接使用索引,不需要借助变量引用
#print(input("Year: ")[3]) #直接对函数返回值进行索引操作
#Slicing
tag = "<a href='http://www.python.org'>Python web site</a>"
print(tag[9:30])
print(tag[32:-4])
numbers = [1,2,3,4,5,6,7,8,9,10]
print(numbers[3:6]) #[4,5,6]
print(numbers[-3:]) #如果分片所得部分包括序列结尾的元素,冒号后的索引置空即可
print(numbers[:3]) #规则同样适用于序列开始的元素
#提取域名
#url = input("Please enter the URL: ")
#domain = url[11:-4]
#print("Domain name: " + domain)
print(numbers[0:10:2]) #步长为2,输出[1,3,5,7,9]
print(numbers[10:0:-2]) #步长为-2,从右边往左提取元素,输出[10,8,6,4,2]
#Adding
print([1,2,3] + [4,5]) #[1, 2, 3, 4, 5]
print("hello" + "world") #helloworld
#Multiplying
print("python " * 5) #python python python python python
print([1,2] * 5) #[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
sequence = [None] * 10 #初始化一个长度为10的列表
#成员资格
permissions = "rw"
print('w' in permissions) #True
print('x' in permissions) #False
users = ['mlh', 'foo', 'bar']
#print(input('Enter your name: ') in users)
#长度、最小值、最大值
numbers = [100,34,678]
print(len(numbers))
print(min(numbers))
print(max(numbers))
####################序列通用操作####################
####################列表####################
#list函数
print(list("Hello")) #['H', 'e', 'l', 'l', 'o']
print(list((1,2,3))) #[1, 2, 3]
#元素赋值
x=[1,1,1]
x[1] = 2
print(x)
#删除元素
names = ["A","B","C","D"]
del names[2]
print(names) #['A', 'B', 'D']
#分片赋值
name = list("Perl")
print(name) #['P', 'e', 'r', 'l']
name[2:] = list("ar")
print(name) #['P', 'e', 'a', 'r']
name[1:] = list("ython")
print(name) #['P', 'y', 't', 'h', 'o', 'n']
numbers = [1,5]
numbers[1:1] = [2,3,4]
print(numbers) #[1, 2, 3, 4, 5]
numbers[1:4] = []
print(numbers) #[1, 5]
#append方法
lst = [1,2,3]
lst.append(4)
print(lst) #[1, 2, 3, 4]
#count方法
x = [[1,2],1,1,[2,1,[1,2]]]
print(x.count(1)) #2,两个独自出现的1才是要计算的元素
#extend方法
a = [1,2]
b = [3,4]
a.extend(b)
print(a) #[1, 2, 3, 4]
#注意与连接操作的不同
a = [1,2]
b = [3,4]
print(a+b) #[1, 2, 3, 4]
print(a) #[1, 2],列表a没有被改变
#分片赋值实现extend方法
a = [1,2]
b = [3,4]
a[len(a):] = b
print(a) #[1, 2, 3, 4]
#index方法
knights = ["We", "are", "the", "who", "say"]
print(repr(knights[3])) #'who'
print(knights.index('who')) #3
#print(knights.index("i")) #抛出异常
#insert方法
numbers = [1,2,3,5]
numbers.insert(3,"four")
print(numbers) #[1, 2, 3, 'four', 5]
#pop方法
x = [1,2,3]
print(x.pop()) #3
print(x) #[1, 2]
print(x.pop(0)) #指定抛出索引对应的元素,1
print(x) #[2]
#出栈入栈相互抵消
x = [1,2,3]
x.append(x.pop())
print(x) #[1, 2, 3]
#remove方法
x = ["to","be","or","not","to","be"]
x.remove("be")
print(x) #['to', 'or', 'not', 'to', 'be']
#x.remove("bee") #抛出异常
#reverse方法
x = [1,2,3]
x.reverse()
print(x) #[3, 2, 1]
#sort方法
x = [4,6,2,1,7,9]
x.sort()
print(x) #[1, 2, 4, 6, 7, 9]
#sorted函数
x = [4,6,2,1,7,9]
y = sorted(x)
print(x) #[4, 6, 2, 1, 7, 9]
print(y) #[1, 2, 4, 6, 7, 9]
#高级排序
x = ["asadf","sc","dfsa","etqerq"]
x.sort(key=len)
print(x) #['sc', 'dfsa', 'asadf', 'etqerq']
x.sort(key=len,reverse=True)
print(x) #['etqerq', 'asadf', 'dfsa', 'sc']
####################列表####################
####################元组####################
#tuple函数
print(tuple([1,2,3])) #(1, 2, 3)
print(tuple("abc")) #('a', 'b', 'c')
#创建元组
x = 1,2,3
print(x)
#元组分片
print(x[0:2])
####################元组####################
|
####################更加抽象####################
#创建自己的类
__metaclass__ = type #确定使用新式类
#新式类的语法中,需要在模块或脚本开始的地方使用上述语句
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print("Hello, world! I'm %s" % self.name)
#self是对于对象自身的引用,没有它的话,成员方法就没法访问他们要对其特性进行操作的对象本身了
foo = Person()
bar = Person()
foo.setName('Luke')
bar.setName('Anak')
foo.greet()
bar.greet()
print(foo.name)
#特性、函数和方法
#self参数事实上正是方法和函数的区别
#绑定方法将第一个参数绑定到所属的实例上,无需显式提供该参数
#子类调用超类的方法,直接通过类调用,没有绑定自己的self参数到任何东西上,称为非绑定方法
#Python并不直接支持私有方式,使用小技巧可以达成,在名字前加上双下划线即可
class Secretive:
def __inaccessible(self):
print("Bet you can't see me")
def accessible(self):
print("The secret message is:")
self.__inaccessible()
s = Secretive()
#s.__inaccessible() #抛出异常
s.accessible()
#其实,类的内部定义中,所有以双下划线开始的名字都被编译成前面加上单下划线和类名的形式。
s._Secretive__inaccessible() #可以调用,但是不应该这么做
#Python并没有真正的私有化支持
#类的命名空间
#所有位于class语句中的代码块都在特殊的命名空间中执行——类命名空间(class namespace),这个命名空间可由类内所有成员访问
class MemberCounter:
members = 0
def init(self):
MemberCounter.members += 1
m1 = MemberCounter()
m1.init()
print(MemberCounter.members)
m2 = MemberCounter()
m2.init()
print(MemberCounter.members)
print(m2.members)
print(m1.members)
#注意不同
m1.members = "Two"
print(m2.members) #2
print(m1.members) #Two
#指定超类
class Filter:
def init(self):
self.blocked = []
def filter(self, sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter): #SPAMFilter是Filter的子类
def init(self): #重写Filter超类中的init方法
self.blocked = ['SPAM']
f = Filter()
f.init()
print(f.filter([1,2,3]))
s = SPAMFilter()
s.init()
print(s.filter(['SPAM', 'SPAM', 'eggs', 'SPAM', 'bacon']))
#检查继承
print(issubclass(SPAMFilter, Filter))
#查看已知类的基类
print(SPAMFilter.__bases__)
#注:子类的实例就是父类的实例,想要知道对象属于哪个类,可以使用__class__特性
print(s.__class__)
#多个超类
#多重继承,除非特别熟悉,否则应该尽量避免使用
#当一个方法从多个超类继承,先继承的类中的方法会重写后继承的类中的方法。
#如果超类们共享一个超类,查找给定方法或者属性时访问超类的顺序称为MRO(Method Resolution Order)
class Calculator:
def calculate(self, expression):
self.value = eval(expression)
class Talker:
def talk(self):
print("Hi, my value is", self.value)
class TalkingCalculator(Calculator, Talker):
pass
tc = TalkingCalculator()
tc.calculate("1+2*3")
tc.talk()
#接口和内省
#处理多态对象时,只要关心公开的方法和特性。Python中,不必显式地指定对象必须包含哪些方法才能作为参数接收。
|
####################网络编程####################
#John Goerzen的Foundations of Python Network Programming
#socket模块
#网络编程中的一个基本组件就是套接字(socket),基本上是两个端点的程序之间的“信息通道”
#Python中的大多数网络编程都隐藏了socket模块的基本细节,不直接和套接字交互
#套接字包括两个:服务器套接字和客户机套接字
#一个套接字就是socket模块中的socket类的一个实例,实例化需要3个参数
#第1个参数是地址族(默认socket.AF_INET)
#第2个参数是流(socket.SOCK_STREAM,默认值)或数据报(socket.SOCK_DGRAM)
#第3个参数是使用的协议(默认是0)
#对于一个普通的套接字,不需要提供任何参数
#服务器端套接字使用bind方法后,再调用listen方法去监听某个特定的地址
#客户端套接字使用connect方法连接到服务器,connect方法中使用的地址与服务器bind方法中的地址相同
#服务器端套接字开始监听后,就可以接受客户端的连接,这个步骤使用accept方法来完成
#这个方法会阻塞(等待)直到客户机连接,然后返回一个格式为(client, address)的元组,client是一个客户端套接字,address是之前解释的地址
#这种形式的服务器编程称为阻塞或者同步网络编程
#套接字有两个方法:send和recv,用于传输数据
#SocketServer模块是标准库中很多服务器框架的基础,所有服务器框架都为基础服务器增加了特定的功能
#SocketServer包含4个基本的类:
#针对TCP流式套接字的TCPServer
#针对UDP数据报套接字的TDPServer
#针对性不强的UnixStreamServer和UnixDatagramServer
#如果编写一个SocketServer框架的服务器,会将大部分代码放在一个请求处理程序(request handler)中
#每当服务器收到一个请求,就会实例化一个请求处理程序,并且它的各种处理方法(handler method)会在处理请求时被调用
#具体调用哪个方法取决于特定的服务器和使用的处理程序类(handler class)
#多个连接
#分叉(forking)、线程(threading)、异步I/O(asynchronous I/O)
#分叉是针对于进程的,比较耗费资源,享有独立的内存;线程是轻量级的进程或子进程,所有的线程都存在于相同的(真正的)进程中,共享内存
#资源消耗下降,共享内存必须确保变量不会冲突,如果不想被同步问题所困扰,分叉是一个很好的选择
#现代操作系统(除Windows,它不支持分叉),分叉实际是很快的
#避免线程和分叉的另一种方法是转换到Stackless Python,支持一种叫做微线程的类线程的并行形式,比真线程的伸缩性要好
#异步I/O基本机制是select模块的select函数
#带有select和poll的异步I/O
#asyncore/asynchat框架和Twisted框架采用的方法是:只处理在给定时间内真正要进行通信的客户端
#不需要一直监听,只要监听(或读取)一会儿,然后把它放到其他客户端的后面
#select和poll函数都来自select模块,poll的伸缩性更好,但是只能在UNIX系统中使用
#select函数需要3个序列作为它的必选参数,还有一个可选的以秒为单位的超时时间作为第4个参数;3个序列用于输入、输出以及异常情况
#select函数的返回值是3个序列(一个长度为3的元组),每个代表相应参数的一个活动子集
|
# grocery list
grocery=['Chocolate','Milk','Cereal']
for i in grocery:
print(i)
|
from tkinter import *
root = Tk()
v = IntVar()
def show():
win = Tk()
Label(win,bg = "white",text = str(v.get())).pack()
#for i in range(5):
bt = Checkbutton(root,text = "455",
variable = v,
)
Button(root,text="text",command = show).pack()
bt.pack()
mainloop()
|
from tkinter import *
root = Tk()
enter = Entry(root)
ls = Listbox(root,selectmode = "extended")
v = StringVar()
#l = StringVar()
enter["textvariable"] = v
enter.pack()
def show():
val = ls.get(ls.curselection()) #返回列表框选定的值
v.set(val) #设置在entry显示的值
t = ["chen","li","shen","liu","tang"]
for i in t:
ls.insert(END,i)
ls.pack()
Button(root,text="dddd",command = show).pack()
print(ls.curselection())
mainloop()
|
#!/usr/bin/env python
# coding: utf-8
# ## Assignment
# ### Number of Task :: 3
# #### 1. A list of all cricket players who have ever played ODI matches
# #### 2. Runs they have made every year in their career
# #### 3. Cummulify the scores by year for each player
#
#
#
# ##### **Note :: All the data are fetched from http://howstat.com
#
# ### TASK 1
# #### Importing all the Library
# In[ ]:
import requests
from bs4 import BeautifulSoup
import csv
import re
import pandas as pd
import numpy as np
# <p> The below cell extracts all the playerid and in the next segment while fetching the runs we will fetch the names, as the present url from which the playerid is fetched does not contain the full name. <br> Function "find_odi_player" is defined which takes an href tag and checks whether that particular link starts with "PlayerOverview_ODI.asp?PlayerID=" if its True that means that particular player has played atleast one ODI <br> soup.find_all(href=find_odi_player) returns list of tags which is then passed through the lambda function to extract the playerid and store it in List_Of_Player<p>
# In[ ]:
List_Of_Player = []
for group in range(65,67):
url = f'http://howstat.com/cricket/Statistics/Players/PlayerList.asp?Country=ALL&Group={chr(group)}'
source = requests.get(url).text
soup = BeautifulSoup(source,'lxml')
def find_odi_player(href):
return True if href and href.startswith('PlayerOverview_ODI.asp?PlayerID=') else False
List_Of_Player += list(map(lambda x: x['href'].split('=')[1] , soup.find_all(href=find_odi_player)))
# ### Task 2
# <p> The below code defines "d" which is of type dictionary and is going to store data for each player, the keys are Name and years from (1971-2019). Assume this as a matrix because this will be converted into dataframe in the end, I could have taken directly a matrix but for my convenience I did with dict()
# <p>
# In[ ]:
XLen = len(List_Of_Player)
d = dict()
d['Name'] = [None]*XLen
d['Country'] = [None]*XLen
for i in range(1971,2020):
d[str(i)] = [0]*XLen
# In[ ]:
df
# <p>
# The for-loop takes up each playerid from "List_Of_Player" and the appends it, to get the final url and using request and bs4 the the HTML is parsed.<br>
# The HTML contains details about every innings played by particular player which is fetched into "tables" using appropriate filter.<br>
# name : The Full Name of the Player<br>
# country : Country of the player<br>
# Then the entire table is traversed and the year of that inning and run scored is extracted, the edge-case were runs are appended with asterisk is also handled.<br>
# Lastly run is added "d[year][playerid] += run", which adds to previously scored runs of that playerid in that year.
# <p>
# <h6>**Note : I did not run the entire List_Of_Player(2547) together instead I used batches of 300 playerid<h6>
# In[ ]:
for playerid in range(0,XLen):
if playerid%10 == 0:
print(playerid)
url = f'http://howstat.com/cricket/Statistics/Players/PlayerProgressBat_ODI.asp?PlayerID={List_Of_Player[playerid]}'
source = requests.get(url).text
soup = BeautifulSoup(source,'lxml')
tables = soup.find_all('tr',bgcolor=re.compile('^#'))
name = soup.find('td',class_='Banner2').text.strip().split("(")[0]
country = re.findall(r"[\w']+", soup.find('td',class_='Banner2').text.strip())[-4]
for row in tables:
year = row.find('a').text.split("/")[-1]
d['Name'][playerid] = name
d['Country'][playerid] = country
run = 0
try:
if row.find('td',class_="AsteriskSpace"):
k = row.find('td',class_="AsteriskSpace").text.strip()
if k != '-':
run = int(k)
else:
run = int(row.find('td',align="right").text.strip()[:-1])
except:
run = 0
d[year][playerid] += run
# #### Converting dictionary into dataframe
# In[ ]:
df = pd.DataFrame(d)
# #### Storing the dataframe into file
# In[ ]:
df.to_csv('player.csv', sep=',', encoding='utf-8')
# ### Task 3
# <p> Final task was to calculate the cumulative score, so I ran loop from 1972 and added current column data
# with previous column<p>
# In[ ]:
for i in range(1972,2020):
df[str(i)] += df[str(i-1)]
|
"""
Декоратор — это структурный паттерн проектирования, который позволяет динамически добавлять объектам новую
функциональность, оборачивая их в полезные «обёртки».
Применимость:
Когда вам нужно добавлять обязанности объектам на лету, незаметно для кода, который их использует.
Недостатки:
1) Трудно конфигурировать многократно обёрнутые объекты.
2) Обилие крошечных классов.
"""
from abc import ABC, abstractmethod
class Beverage(ABC):
def __init__(self):
self.description = 'Unknown Beverage'
def get_description(self):
return self.description
@abstractmethod
def cost(self):
raise NotImplementedError
class Additions(ABC):
def __init__(self, beverage):
self.beverage = beverage
@abstractmethod
def get_description(self):
raise NotImplementedError
@abstractmethod
def cost(self):
raise NotImplementedError
class Espresso(Beverage):
def __init__(self):
super().__init__()
self.description = 'Espresso'
def cost(self):
return 1.99
class Mocha(Additions):
def __init__(self, beverage):
super().__init__(beverage=beverage)
def get_description(self):
return self.beverage.get_description() + ' Mocha'
def cost(self):
return self.beverage.cost() + 0.20
class Whip(Additions):
def __init__(self, beverage):
super().__init__(beverage=beverage)
def get_description(self):
return self.beverage.get_description() + ' Whip'
def cost(self):
return self.beverage.cost() + 0.17
beverage = Espresso()
beverage = Mocha(beverage)
beverage = Mocha(beverage)
beverage = Whip(beverage)
print(beverage.get_description())
print(beverage.cost()) |
from typing import List
def lengthOfLIS(nums: List[int]) -> int:
if not nums:
return 0
dp = []
for i in range(len(nums)):
dp.append(1)
for j in range(i):
if nums[i] > nums[j]:
# 这一步是关键,dp[i]在里层循环的时候可能会被多次更新,i越到后面越大,
# dp[i]被改写的概率同样越大,这里比较的dp[i],即当前最大子序列,和d[j]+1谁大
# 谁大就取谁。因为num[i]>num[j],所以j位最大子序列一定可以和通过拼接i位字符
# 组成一个dp[j]+1的子序列,那么剩下的就是和dp[i]到底谁大,谁大取谁。
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
if __name__ == "__main__":
nums = [10, 9, 2, 5, 3, 7, 101, 18]
print(lengthOfLIS(nums))
|
'''
有一段不知道具体长度的日志文件,里面记录了每次登录的时间戳,已知日志是按顺序从头到尾记录的,
没有记录日志的地方为空,要求当前日志的长度。
'''
import math
import numpy as np
def binextend_log(lines, high):
# print('binextend_log [high]: ', high)
lines_size = len(lines)
high_ext = high*2
index = min(high_ext, lines_size)
print('binextend_log [high]: %s, [high_ext]: %s, index: %s'%(high, high_ext, index))
# 已经发现了边界范围,下面是要缩小范围
if(lines[index] == 0):
return binsearch_log(lines, high, index)
# 还是没有发现,继续扩大查找范围
else:
return binextend_log(lines, high_ext)
def binsearch_log(lines, low, high):
print('binsearch_log, low: %s, hight: %s' %(low, high))
middle = low + (high-low)//2
if(lines[middle]==1 and lines[middle+1] ==0):
return middle
if(lines[middle]==1):
return binsearch_log(lines, middle, high)
else:
return binsearch_log(lines, low, middle)
if __name__ == "__main__":
lines = np.zeros((1000,))
lines_fill = np.ones((100,))
lines[0:100] = lines_fill
last_index = binextend_log(lines, 1)
print('length is: ', last_index+ 1)
|
# Implementing Mergesort
def mergeSort(arr):
if len(arr)==1:
return arr
else:
mid = int(round((len(arr)/2)))
return merge(
mergeSort(arr[:mid]),
mergeSort(arr[mid:len(arr)])
)
def merge(l1,l2):
if len(l1)==0:
return l2
if len(l2)==0:
return l1
if l1[0]<=l2[0]:
return [l1[0]]+merge(l1[1:],l2)
if l2[0]<l1[0]:
return[l2[0]]+merge(l1,l2[1:])
'''
array = [-3,4,5,3,9,1,4,788,9,5,100]
print mergeSort(array)
'''
|
class doubleLinkedList():
def __init__(self,key = None,prev=None,next=None):
self.next = next
self.prev = prev
self.key = key
def add(self,key):
element = doubleLinkedList(key,self,self.next)
if self.next:
self.next.prev = element
self.next = element
def getByIndex(self,index):
currentElement = self
for i in range(index):
currentElement = currentElement.next
return currentElement
def deleteByIndex(self,index):
elementToDelete = self.getByIndex(index)
if elementToDelete.prev:
elementToDelete.prev.next = elementToDelete.next
if elementToDelete.next:
elementToDelete.next.prev = elementToDelete.prev
def deleteByKey(self,key,searchIncrementor=None,deleteIncrementor=None):
index = self.search(key,searchIncrementor)
if index!=-1:
if deleteIncrementor:
deleteIncrementor.inc()
self.deleteByIndex(index)
def toString(self):
currentElement = self
listToString = ""
while currentElement != None:
listToString += str(currentElement.key)+" "
currentElement = currentElement.next
return listToString
def search(self,key,incrementor=None):
currentElement = self
i = 0
while currentElement != None:
# keeps track of number of comparisons
if incrementor:
incrementor.inc()
if currentElement.key == key:
return i
else:
currentElement = currentElement.next
i+=1
return -1
"""
head = doubleLinkedList()
head.add(8)
head.add(3)
head.add(4)
head.add(1)
print head.toString()
head.deleteByIndex(3)
print head.toString()
print head.search(4)
head.deleteByKey(4)
print head.toString()
"""
|
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2] = "2 - 菜鸟工具"
tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'}
print (dict['one']) # 输出键为 'one' 的值
print (dict[2]) # 输出键为 2 的值
print (tinydict) # 输出完整的字典
print (tinydict.keys()) # 输出所有键
print (tinydict.values()) # 输出所有值
import sys
print('命令行参数如下:')
for i in sys.argv:
print(i)
print('\n\nPython 路径为:', sys.path, '\n')
print(dir(sys))
for x in range(1, 11):
print(repr(x).rjust(6), repr(x*x).rjust(3), end=' ')
# 注意前一行 'end' 的使用
print(repr(x*x*x).rjust(4))
print(repr(x).ljust(6)) |
print("TABELA DE PREÇOS");
print("Produt o Até 5 Kg Acima de 5 Kg");
print("Morango R$ 2,50 por Kg R$ 2,20 por Kg");
print("Maçã R$ 1,80 por Kg R$ 1,50 por Kg");
qtd1 = int(input("\nQual a quantidade em Kg de Morango: "));
qtd2 = int(input("Qual a quantidade em Kg de Maçã: "));
kgT = qtd1 + qtd2;
if(kgT <= 5):
valUni1 = 2.50;
valUni2 = 1.80;
pagar = (qtd1 * valUni1) + (qtd2 * valUni2);
desconto = "0.00";
elif(kgT > 5):
valUni1 = 2.20;
valUni2 = 1.50;
pagar = (qtd1 * valUni1) + (qtd2 * valUni2);
desconto = "0.00";
if(kgT > 8 or pagar > 25.0):
pagar = pagar - ((pagar * 10)/100);
desconto = round((pagar * 10)/100, 2);
print("\n\n****** NOTA FISCAL ******");
print("Produto Kg Valor 1Kg Valor Total");
print("Morango ", qtd1 ," R$", valUni1," R$ ",(qtd1 * valUni1));
print("Maçã ", qtd2 ," R$", valUni2," R$ ",(qtd2 * valUni2));
print("\nDescontos: R$",desconto);
print("Total a pagar: R$",pagar);
print("****** *********** ******");
|
num = int(input("Digite um numero: "));
if(num > 0):
print(num, " é positivo");
else:
print(num, " é negativo");
|
print("TABELA DE PREÇOS");
print("Produtos/Tipo Até 5 Kg Acima de 5 Kg");
print("File Duplo - 1 R$ 4,90 por Kg R$ 5,80 por Kg");
print("Alcatra - 2 R$ 5,90 por Kg R$ 6,80 por Kg");
print("Picanha - 3 R$ 6,90 por Kg R$ 7,80 por Kg");
prod = int(input("\nQual a o produto comprado: "));
qtd = float(input("Qual a quantidade em Kg: "));
formPag = int(input("\nForma de Pagamento?\nCratão - 1 - 5% de desconto\nDinheiro - 2 - 0% de desconto\nQual? "))
if(qtd <= 5):
if(prod == 1):
valKg = 4.90;
pagar = (qtd * valKg);
prodT = "File Duplo";
if(formPag == 1):
pagar = pagar - ((pagar * 5)/100);
desconto = round((pagar * 5)/100, 2);
else:
desconto = "0.00";
elif(prod == 2):
valKg = 5.90;
pagar = (qtd * valKg);
prodT = "Alcatra";
if(formPag == 1):
pagar = pagar - ((pagar * 5)/100);
desconto = round((pagar * 5)/100, 2);
else:
desconto = "0.00";
elif(prod == 3):
valKg = 6.90;
pagar = (qtd * valKg);
prodT = "Picanha";
if(formPag == 1):
pagar = pagar - ((pagar * 5)/100);
desconto = round((pagar * 5)/100, 2);
else:
desconto = "0.00";
elif(qtd > 5.0):
if(prod == 1):
valKg = 5.80;
pagar = (qtd * valKg);
prodT = "File Duplo";
if(formPag == 1):
pagar = pagar - ((pagar * 5)/100);
desconto = round((pagar * 5)/100, 2);
else:
desconto = "0.00";
elif(prod == 2):
valKg = 6.80;
pagar = (qtd * valKg);
prodT = "Alcatra";
if(formPag == 1):
pagar = pagar - ((pagar * 5)/100);
desconto = round((pagar * 5)/100, 2);
else:
desconto = "0.00";
elif(prod == 3):
valKg = 7.80;
pagar = (qtd * valKg);
prodT = "Picanha";
if(formPag == 1):
pagar = pagar - ((pagar * 5)/100);
desconto = (round(pagar * 5)/100, 2);
else:
desconto = "0.00";
print("\n\n****** NOTA FISCAL ******");
print("Produto Qtd. Valor 1Kg Valor Total");
print(prodT, " ",qtd ,"Kg R$", valKg," R$ ",round((qtd * valKg), 2));
print("\nDescontos: R$", desconto);
print("Total a pagar: R$",round(pagar, 2));
print("****** *********** ******");
|
popA = 80000;
popB = 200000;
print("População A inicial: ", popA);
print("População B inicial: ", popB);
a = 0;
b = 2;
anos = 0;
while a < b:
if(popA >= popB):
a = 2;
print("\nPara que a Poupulação A ultrapasse a População B levará",anos,"anos\n");
print("População A final: ", int(popA));
print("População B final: ", int(popB));
else:
popA = popA + (popA * 3)/100;
popB = popB + (popB * 1.5)/100;
anos = anos + 1;
a = 0;
|
x = 1;
while x < 2:
nomeUser = input("Insira o seu nome de Usuário: ");
senhaUser = input("Insira uma sua senha: ");
if(senhaUser.lower() != nomeUser.lower()):
x = 2;
print("Sucesso ao fazer login!");
else:
print("\nErro. Digite novamente! Senha não pode ser igual ao nome usuario.\n");
x = 1;
|
#count even and odd no in a list
a=[1,5,3,9,10,11,20]
print(a)
count=0
c=0
for i in a:
if i%2==0:
count=count+1
else:
c=c+1
print("even no in list =",count)
print("odd no in list =",c)
|
# -*- coding: utf-8 -*-
# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
def case1():
'''使用数字,每种语言都可以用'''
l = []
for a in range(1,5):
for b in range(1,5):
for c in range(1,5):
# print('a =', a, 'b =', b, 'c =', c)
if (a != b) & (b != c) & (a != c):
# if a != b and b != c and a != c:
x = a*100 + b*10 + c
l.append(x)
# print(x)
print('总共能组成%d个符合条件的三位数'%len(l), '分别是:')
for i in l:
print(i)
def case2():
'''使用字符串特性'''
l = []
for a in range(1,5):
for b in range(1,5):
for c in range(1,5):
if a != b and b != c and a != c:
l.append(str(a) + str(b) + str(c))
print('总共能组成%d个符合条件的三位数'%len(l), '分别是:')
for i in l:
print(i)
def run():
case1()
case2()
if __name__ == '__main__':
run() |
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-06 20:43:00
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-06 21:41:14
# 打印出如下图案(菱形):
# *
# ***
# *****
# *******
# *****
# ***
# *
def print_Rhombus(n):
# 打印菱形,输入奇数行
if n % 2 == 0:
print("输入错误,退出程序")
return
L = []
mid = int((n+1)/2)
for i in range(n):
if i < mid:
s1 = " " * (mid-i-1)
s2 = "*" * (i*2 + 1)
L.append(s1 + s2)
else:
L.append(L[n-i-1])
for i in L:
print(i)
def run():
n = int(input("请输入需要打印的菱形行数:(奇数行)"))
print_Rhombus(n)
if __name__ == "__main__":
run()
|
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-03 21:45:57
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-03 21:53:31
# 输入一行字符,分别统计出其中的英文字符、空格、数字和其他字符的个数
def get_nums(s):
a, b, c, d = 0, 0, 0, 0
for i in s:
if i.isdigit():
a += 1
elif i.isalpha():
b += 1
elif i.isspace():
c += 1
else:
d += 1
return a, b, c, d
def run():
s = input("请输入一行字符串:")
a, b, c, d = get_nums(s)
print("其中英文有%d个,空格有%d个,数字有%d个,其他字符有%d个" % (b, c, a, d))
if __name__ == "__main__":
run()
|
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-20 18:27:42
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-20 18:34:50
# 有两个磁盘文件A.txt和B.txt,各存放了一行字母,要求把这两个文件中的信息合并按字母顺序排列,输出到新文件C.txt中
def run():
with open("A.txt", "r") as f:
text1 = f.read()
with open("B.txt", "r") as f:
text2 = f.read()
print("A.txt中内容为:%s\nB.txt中内容为:%s" % (text1, text2))
text3 = ""
for i in sorted(text1+text2):
text3 += i
with open("C.txt", "w") as f:
f.write(text3)
with open("C.txt", "r") as f:
print("C.txt中内容为:%s" % f.read())
if __name__ == "__main__":
run()
|
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-20 17:08:46
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-20 17:15:57
# 输入一个奇数,然后判断最少几个9除以该数的结果为整数
def function(x):
i = 1
while True:
y = int("9"*i)
if y % x == 0:
print("%d 可以被 %d 整除" % (x, y))
break
i += 1
# print(i)
def run():
x = int(input("请输入奇数:"))
if x % 2 == 0:
print("输入有误!")
else:
function(x)
if __name__ == "__main__":
run()
|
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-20 16:55:01
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-20 17:03:15
# 求0到7能组成的奇数个数,每个数字只能使用一次
def run():
count = 0
for i in range(1, 9): # 最多可组成8位数
if i == 1:
count += 4
elif i == 2:
count += 7*4
else:
count += 7*(8**(i-2))*4
print("能组成 %d 个奇数" % count)
if __name__ == "__main__":
run()
|
from turtle import Turtle, Screen
import random
race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_choice = screen.textinput(title="Choose a car", prompt="Red, Green OR Yellow?")
cars = ["Red", "Green", "Yellow"]
vertical_positions = [-70, 0, 70]
created_cars = []
# Create cars
for car in cars:
car_shape = f"gifs/{car}.gif"
screen.addshape(car_shape)
new_car = Turtle(shape=car_shape)
new_car.penup()
new_car.goto(x=-200, y=vertical_positions[cars.index(car)])
created_cars.append(new_car)
# Begin the race after choose a car
if user_choice:
race_on = True
while race_on:
for running_car in created_cars:
if running_car.xcor() > 210:
race_on = False
winning_car = running_car.shape()
winning_car_color = winning_car[5:-4] # gifs/red.gif => red
if winning_car_color.lower() == user_choice.lower():
print(f"You Win! The {winning_car_color} car is the winner!")
else:
print(f"You Lose! The {winning_car_color} car is the winner!")
# move cars forward by random integer
rand_dis = random.randint(1, 10)
running_car.forward(rand_dis)
screen.exitonclick()
|
def isUgly(n):
if n == 0:
return False
elif n == 1:
return True
else:
if (n % 5 == 0):
n //= 5
elif (n % 3 == 0):
n //= 3
elif (n % 2 == 0):
n //= 2
else:
return False
return isUgly(n)
print(isUgly(15))
|
class Caesar():
#CS50X Caesar task in python
def caesar_main(self):
key = int(input("Key (number) : ")) # get key number
caesar = input("Text : ") # get string
new_caesar = "" #converted string
for i in caesar: #loop in given string
if i.isalpha(): # if i is alpha (a-z)
ascii_offset = 65 if i.isupper() else 97 # set ascii for hexadecimal
ascii_number = ord(i) - ascii_offset #
ci = (ascii_number + key) % 26 #if there is a string z, %26 returns it to the beginning so there wont be error for alphabetic numbers
new_caesar = new_caesar + chr(ci + ascii_offset) # add converted chars to new_caesar
elif i == " ": #if there is a space, add it to new_caesar
new_caesar = new_caesar + i
else:continue #if there is a number or numeric sign, pass! - if you dont want to pass just add --> new_caesar = new_caesar + i
print(new_caesar)
return new_caesar
cs50 = Caesar()
cs50.caesar_main() |
#!/bin/local/python
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
max_num = reduce(lambda x,y : x*y, range(1,21))
test= 0
found=1
while found != 0 and test < max_num:
test += 2520
found = 0
for i in range(10,21):
found += test % i
print test
|
#!/usr/bin/python
"""Find the sum of all the multiples of 3 or 5 below 1000."""
sum=0
for y in xrange(3,1000):
if y % 3 == 0 or y % 5 == 0:
sum+=y
print sum
|
#!/usr/bin/python
"""
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the divisors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
"""
import numpy as np
import math
def get_primes(upto):
"""
Sieve method for finding primes. Implemintation taken from:
http://rebrained.com/?p=458
"""
primes=np.arange(3,upto+1,2)
isprime=np.ones((upto-1)/2,dtype=bool)
for factor in primes[:int(math.sqrt(upto))]:
if isprime[(factor-2)/2]: isprime[(factor*3-2)/2::factor]=0
return np.insert(primes[isprime],0,2)
def num_divisors(n):
primes = get_primes(int(n**0.5))
cur_num = n
divisors = {}
for i in primes:
while cur_num % i == 0:
cur_num /= i
divisors[i] = divisors.get(i, 0) + 1
if cur_num == 0:
break
num = 1
for i in divisors.values():
num *= (i + 1)
return num
def iterate_triangle_numbers():
triangle = 0
i = 1
while True:
triangle += i
i += 1
yield triangle
if __name__ == "__main__":
assert( num_divisors(24) == 8 )
n = 1
for n in iterate_triangle_numbers():
divisors = num_divisors(n)
if divisors > 500:
break
print "n = %d has %d divisors"%(n, divisors)
|
import random
import string
def generate_codes(number_of_codes: int, code_length: int):
"""Generates X number of random codes based on the provided length.
Pramas:
-------
number_of_codes (int): The number of the random codes that shall be
created which should be unique also.
code_length (int): The length of the code which will be generated.
"""
codes = set()
choices = string.ascii_uppercase + string.digits
while len(codes) < number_of_codes:
code = ''.join(random.SystemRandom().choice(choices) for _ in range(code_length))
codes.add(code)
return codes
|
import pygame
import sys
import random
# 这节课主要内容是添加了分数和生命值 改变小球的方向
pygame.init()
screen = pygame.display.set_mode((640,700))
pygame.display.set_caption("BAll")
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
ball_x = 110
ball_y = 100
rect_x = 300
rect_y = 650
speed = 10
speedx = speed
speedy = speed
clock = pygame.time.Clock() # 设置时钟
font1 = pygame.font.Font(None, 24)
def print_text(scr, font, x, y, text, color = (250, 25, 255)):
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))
lives = 3
score = 0
while True:
print(lives)
clock.tick(60) # 每秒执行60次
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill((255,255,255))
print_text(screen, font1, 0, 0, 'Live:' + str(lives))
print_text(screen, font1, 500, 0, 'Score:' + str(score))
ball_y += speedy
ball_x += speedx
if ball_y > 700: # 球超过屏幕
ball_y = -30
ball_x = random.randint(20, 480)
lives = lives - 1
if ball_y < 0 and speedy<0: # 球超过屏幕
# speedx = -speedx
speedy = -speedy
if ball_x<30or ball_x>610: # 检查左右边缘
speedx = -speedx
if ball_y > 650-30: # 检查挡板是否借住
if ball_x > rect_x and ball_x < rect_x + 200:
speedx = -speedx
speedy = -speedy
score += 1
# else:
# lives = lives-1
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
rect_x -= 5
if keys[pygame.K_RIGHT]:
rect_x += 5
if rect_x > 640 - 100:
rect_x = 640 - 100
if rect_x < 0:
rect_x = 0
pygame.draw.circle(screen, (100, 40, 30), (ball_x, ball_y), 30, 0)
pygame.draw.rect(screen, (0, 0, 255),(rect_x, rect_y, 200, 30)) # 其中第一个元组(x, y)表示的是该矩形左上角的坐标,第二个元组 (width, height)表示的是矩形的宽度和高度。
pygame.display.update() # 刷新屏幕内容显示
pygame.quit() # 退出pygame |
import pygame
import sys
# 1.初始化pygame
pygame.init()
# 2. 设置窗口大小
screen = pygame.display.set_mode((640, 480)) # 设置窗口大小 显示窗口
width = 640
height = 480
# 3. 设置窗口名字
pygame.display.set_caption('BALL')
ball = pygame.image.load('./img/ball.png') # 加载图片
ballrect = ball.get_rect() # 获取矩形区域
# ballrect = pygame.Rect(0, 0, 16, 16) # pygame.Rect(left, top, width, height)
speed = [1, 1] # 设置移动的X轴、Y轴
clock = pygame.time.Clock() # 设置时钟
while True: # 死循环确保窗口一直显示
clock.tick(60) # 每秒执行60次
for event in pygame.event.get(): # 遍历所有事件
if event.type == pygame.QUIT: # 如果单击关闭窗口,则退出
sys.exit()
ballrect = ballrect.move(speed) # 移动小球
# 碰到左右边缘
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
# 碰到上下边缘
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill((0,0,0)) # 填充颜色(设置为0,执不执行这行代码都一样)
screen.blit(ball, ballrect) # 将图片画到窗口上
pygame.display.update() # 更新全部显示
pygame.quit() # 退出pygame |
'''
Python算术运算符
+ 加 - 两个对象相加 a + b 输出结果 31
- 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -11
* 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b 输出结果 210
/ 除 - x 除以 y b / a 输出结果 2.1
% 取模 - 返回除法的余数 b % a 输出结果 1
** 幂 - 返回x的y次幂 a**b 为10的21次方
// 取整除 - 向下取接近除数的整数
Python比较运算符
== 等于 - 比较对象是否相等 (a == b) 返回 False。
!= 不等于 - 比较两个对象是否不相等 (a != b) 返回 True。
> 大于 - 返回x是否大于y (a > b) 返回 False。
< 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 (a < b) 返回 True。
>= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。
<= 小于等于 - 返回x是否小于等于y。
Python赋值运算符
= 简单的赋值运算符 c = a + b 将 a + b 的运算结果赋值为 c
+= 加法赋值运算符 c += a 等效于 c = c + a
-= 减法赋值运算符 c -= a 等效于 c = c - a
*= 乘法赋值运算符 c *= a 等效于 c = c * a
/= 除法赋值运算符 c /= a 等效于 c = c / a
%= 取模赋值运算符 c %= a 等效于 c = c % a
**= 幂赋值运算符 c **= a 等效于 c = c ** a
//=
if的讲解和使用
多路分支:if elif else
'''
var1 = 100
if var1:
print("1 - if 表达式条件为 true")
print(var1)
var2 = 0
if var2:
print("2 - if 表达式条件为 true")
print(var2)
print("Good bye!")
'''
#### 练习2:掷骰子决定做什么
```Python
"""
掷骰子决定做什么事情
Version: 0.1
Author: 骆昊
"""
from random import randint
face = randint(1, 6)
if face == 1:
result = '唱首歌'
elif face == 2:
result = '跳个舞'
elif face == 3:
result = '学狗叫'
elif face == 4:
result = '做俯卧撑'
elif face == 5:
result = '念绕口令'
else:
result = '讲冷笑话'
print(result)
```
```课堂代码
"""
百分制成绩转等级制成绩
90分以上 --> A
80分~89分 --> B
70分~79分 --> C
60分~69分 --> D
60分以下 --> E
Version: 0.1
Author: 骆昊
"""
score = float(input('请输入成绩: '))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
print('对应的等级是:', grade)
```
```Python
"""
输入年份 如果是闰年输出True 否则输出False
Version: 0.1
Author: 骆昊
"""
year = int(input('请输入年份: '))
# 如果代码太长写成一行不便于阅读 可以使用\或()折行
is_leap = (year % 4 == 0 and year % 100 != 0 or
year % 400 == 0)
print(is_leap)
''' |
# 读取数据和简单的数据探索
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris() # 可以看成字典
print(iris.keys())
print(iris.data) # 拿到数据
print(iris.data.shape)
x = iris.data[:,:2] # 只能绘制2维图像,所以只要前两列
plt.scatter(x[:,0],x[:,1])
plt.show()
|
'''
常用算法:
穷举法 - 又称为暴力破解法,对所有的可能性进行验证,直到找到正确答案。
贪婪法 - 在对问题求解时,总是做出在当前看来
最好的选择,不追求最优解,快速找到满意解。
分治法 - 把一个复杂的问题分成两个或更多的相同或相似的子问题,再把子问题分成更小的子问题,
直到可以直接求解的程度,最后将子问题的解进行合并得到原问题的解。
回溯法 - 回溯法又称为试探法,按选优条件向前搜索,当搜索到某一步发现原先选择并不优或达不到目标时,
就退回一步重新选择。
动态规划 - 基本思想也是将待求解问题分解成若干个子问题,先求解并保存这些子问题的解,避免产生大量的重复运算。
穷举法例子:百钱百鸡和五人分鱼。
# 公鸡5元一只 母鸡3元一只 小鸡1元三只
# 用100元买100只鸡 问公鸡/母鸡/小鸡各多少只
for x in range(20):
for y in range(33):
z = 100 - x - y
if 5 * x + 3 * y + z // 3 == 100 and z % 3 == 0:
print(x, y, z)
''' |
import numpy as np
# numpy 中的矩阵的操作
# print(np.__version__)
# array = np.array([[1,2,3],[2,3,4]]) # 只能有一种类型
# print(array.dtype)
# array[1][1] = 5.0
# print(array)
#
# l = [i for i in range(10)]
#
# print(l)
#
# print(np.zeros(10,dtype=float))
#
# print(np.zeros(shape=(3,5)))
#
# print(np.ones(shape=(3,5)))
#
# print(np.full(shape=(6,5),fill_value=5))
#
# print(np.arange(0,20,2)) # 和 for循环很一样
#
# print(np.linspace(0,20,10)) # 从0开始到20结束,中间等长的截出十个点 ,包括0和20
#
# # random
# print(np.random.randint(1,21)) # 整数
#
# print(np.random.randint(0,20,size=10))
#
# print(np.random.randint(5,21,size=(3,5)))
#
# # 设置一个随机种子,让两次随机数相同
# np.random.seed(5)
# print(np.random.randint(5,21,size=(3,5)))
# np.random.seed(5)
# print(np.random.randint(5,21,size=(3,5)))
#
# # 小数 均匀分布
# print(np.random.random())
# print(np.random.random(10))
# print(np.random.random(size=(3,5)))
# # 正态分布
# print(np.random.normal())
# # 指定均值和方差
# print(np.random.normal(5,10))
#
# print(np.random.normal(5,10,size=(3,5)))
#
# print(np.random)
######################################################################################################
'''
# numpy.array的基本操作
x = np.arange(10)
X = np.arange(15).reshape(3,5)
print(x)
print(X)
# 数组的基本属性
print(x.ndim) # 查看维度
print(x.shape) #查看是几行几列
print(x.size) # 元素个数
# 数据访问
print(x)
print(x[-1])
print(X)
print(X[1][1]) # 不建议
print(X[2,2]) # 推荐
#切片
print(x[0:5])
print(X[:2,:3]) # 前两行的前三列
print(X[0,:]) # X[0] 第一个行
print(X[:,0]) # 第一列
# 子矩阵是直接应用原矩阵的,所以修改子矩阵会影响原矩阵
# 切片后是和原矩阵相关的,修改子矩阵会修改了原矩阵,不相关怎么做 .copy
subX= X[:2,:3].copy()
print(subX)
'''
# 合并操作
x = np.array([1,2,3])
y = np.array([3,2,1])
print(np.concatenate([x,y]))
A = np.array([[1,8,98],
[9,87,12]])
z = np.array([1,8,265])
print(np.concatenate([A,A])) # 默认列拼接
print(np.concatenate([A,A],axis=1))# 行拼接
print(np.concatenate([A,z.reshape(1,-1)]))
# 太麻烦,下面是简写
print(np.vstack([A,z])) # 垂直方向拼接 hstack 水平方向拼接
# 分割操作
x = np.arange(10)
print(x)
x1,x2,x3 = np.split(x,[3,7]) # 从3 和7 开始切分,分成三段
A = np.arange(16).reshape((4,4))
A1,A2 = np.split(A,[2]) # 就是分成了两行
A3,A4 = np.split(A,[2],axis=1) # 就是分成了两列
upper,lower = np.vsplit(A,[2]) # 垂直切分
left,right = np.hsplit(A,[2]) # 水平切分
|
# -*- coding: utf-8 -*-
# @Time : 2019/7/21 9:59
# @Author : liuqi
# @FileName: day10.py
# @Software: PyCharm
# 猜字游戏
import random
x = random.randint(0, 99)
while(True):
num = input("请猜猜是多少")
if(num.isdigit()):
num = int(num)
if(x == num):
print("恭喜你,猜对了")
break
elif(x>num):
print("你猜小了")
elif(x<num):
print("你猜大了") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.