blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
06173b58bc60a65c20f5b558c8b1fbbbd08fb3e3 | xhackax47/Python | /2019_ril/cards.py | 790 | 3.921875 | 4 | from random import shuffle
# Jeu de cartes sous Python
# Declaration variables
cards = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'V', 'D', 'R')
cards_symbols= ('♣', '♥', '♠', '♦')
# Expression de boucle For de compréhension de liste pour ajout dans le deck des cartes
cards_deck = [card + card_symbol for card in cards for card_symbol in cards_symbols]
# Mélange des cartes du deck
shuffle(cards_deck)
# Affichage des résultats
print("Contenu du deck : " + str(cards_deck))
print("Nombre de cartes présentes dans le deck : " + str(len(cards_deck)))
# Expression FOR classique
"""
for card in cards:
for card_symbol in cards_symbols:
cards_deck.append(card+card_symbol)
print(cards_deck)
print(len(cards_deck))
""" |
2818b45e3d9df84667806b8968acc68ed43a04d2 | xhackax47/Python | /2019_ril/dict_samples.py | 662 | 3.953125 | 4 | pizzas = {"Anchois": 9.60,
"Jambon": 10.5,
"Royale": 12}
name = input("Entrer le nom d'une pizza \n")
total = 0
# Premiere méthode
if name in pizzas:
print(f"Prix Première Pizza : {pizzas[name]}")
else:
print("Pizza inconnue")
# Deuxième méthode
name = input("Entrer le nom d'une pizza \n")
try:
print(f"Prix Deuxième Pizza : {pizzas[name]}")
except KeyError:
print("Pizza inconnue")
# Troisième méthode
name = input("Entrer le nom de la troisième pizza \n")
if price := pizzas.get(name) is not None:
print(f"Prix Troisième Pizza : {pizzas[name]}")
else:
print("Pizza inconnue")
|
1de4aa4b62a5a6978ae2b4bb01c98487e7e34d42 | stwinter2014/Motion-planning-algorithm | /Старое новое/Interpolation.py | 1,985 | 3.5625 | 4 | from math import fabs, sqrt, pow
"""Подсчет длины траектории при линейной траектории.
Входные данные:
1. Координаты начальной точки [x, y, z];
2. координаты конечной точки [x, y, z].
Выходные данные:
1. Длина траектории, мм."""
def LengthLinear(start, end):
length = sqrt((pow((end[0]-start[0]), 2))+(pow((end[1]-start[1]), 2)))
return length
#Линейная интерполяция
"""Расчет движения инструмента по координатам.
Входные данные:
1. координаты начальной точки [x, y];
2. координаты конечной точки [x, y];
3. список скоростей, мм/с;
4. скорость на предыдущем блоке, мм/с;
5. длина блока, мм;
6. время интерполяции, с.
Выходные данные:
1. список координат по оси X, мм;
2. список координат по оси Y, мм."""
def InterpolationLinear(p_start, p_finish, vellist, vellast, length, tsam):
S = 0
x_list = []
y_list = []
x_list.append(p_start[0])
y_list.append(p_start[1])
x_tmp = p_start[0]
y_tmp = p_start[1]
for i in range (len(vellist)):
#расчет единичного перемещения
if i == 0:
Si = tsam*(vellist[i]+vellast)/2
else:
Si = tsam*(vellist[i]+vellist[i-1])/2
#расчет приращений для каждой координаты
delta_x = Si*(fabs(p_finish[0]-p_start[0])/length)
delta_y = Si*(fabs(p_finish[1]-p_start[1])/length)
x_tmp += delta_x
y_tmp += delta_y
x_list.append(x_tmp)
y_list.append(y_tmp)
S += Si
print("Длина пути по интерполятору: " + str(S))
return x_list, y_list, S
|
6846db0ae0139a826e43b4d2752ab0bb7b136b04 | soumyasen1809/Mini_Projects_OOP | /Cricket Score Maintenance.py | 4,243 | 3.765625 | 4 | # https://www.codewithc.com/cricket-score-sheet-project-c/
# Cricket Score Maintenance - OOP to maintain a cricket team
import random
class Player: # Defining the class Player with name and team
def __init__(self, name, team):
self.name = name
self.team = team
class Bowler(Player): # subclass Bowler inheriting from Player class
wicket = 0
def __init__(self, name, team):
Player.__init__(self, name, team)
def addWicket(self):
self.wicket = self.wicket + 1 # adding a wicket count to the bowler when successfully takes a wicket
class Batsman(Player):
run = 0
balls_played = 0
def __init__(self, name, team):
Player.__init__(self, name, team)
def addRun(self, run_hit):
self.run_hit = run_hit # adding run count to the batsman when successfully scores run
self.run = self.run + run_hit # run_hit is the runs hit by the batsman in a ball (values from 0 to 6)
def addBallsPlayed(self):
self.balls_played = self.balls_played + 1 # number of balls played by the batsman
class MatchScore: # class defines the various operations in a cricket match
def __init__(self, batsquad, bowlsquad): # takes the entire batting and bowling squad
self.batsquad = batsquad
self.bowlsquad = bowlsquad
def takeRun(self):
play_num = random.randint(0,1) # randomly chooses from the 1st two batsmen (players currently on field)
self.batsquad[play_num].addRun(random.randint(0,6)) # batsman randomly hits a run (from 0 to 6)
self.batsquad[play_num].addBallsPlayed() # 1 ball played added to the batsman
def takeWicket(self):
play_num = random.randint(0, len(bowlsquad)-1) # randomly chooses from all bowlers (players currently on field)
self.bowlsquad[play_num].addWicket() # bowler takes a wicket
self.batsquad[0].addBallsPlayed() # 1 ball played added to the batsman (wicket drop ball)
for i in range(len(batsquad) - 1):
batsquad[i], batsquad[i + 1] = batsquad[i + 1], batsquad[i] # Push the batsman to the back (don't pop)
# Squad lineup
Bats1 = Batsman("Kevin Peterson", "England")
Bats2 = Batsman("Ricky Ponting", "England")
Bats3 = Batsman("Brian W. Lara", "England")
Bats4 = Batsman("Adam Gilchrist", "England")
Bowl1 = Bowler("Shane M. Warne", "Australia")
Bowl2 = Bowler("Nathan P. Bold", "Australia")
batsquad = [Bats1, Bats2, Bats3, Bats4] # Create list of batting squad
bowlsquad = [Bowl1, Bowl2] # Create list of bowling squad
# Game play
wick_count = 0
balls_count = 0
for i in range(0, 20): # Playing a max of 20 balls
input_val = random.randint(0,1) # Randomly playing the game - if 0: run scored, if 1: wicket drop
if wick_count < len(batsquad): # Check if all wickets have fallen already
balls_count = balls_count + 1
if input_val == 0:
MatchScore(batsquad, bowlsquad).takeRun()
else:
MatchScore(batsquad, bowlsquad).takeWicket()
wick_count = wick_count + 1
# Printing the score-card
print ("-------------- England vs Australia -------------- \n")
print ("-------------- England Batting --------------")
print ("Name of player" + "\t" + "Runs" + "\t" + "Balls")
for i in range(len(batsquad)):
print (str(batsquad[i].name) + "\t" + str(batsquad[i].run) + "\t \t" + str(batsquad[i].balls_played))
print ("-------------- Australia Bowling --------------")
print ("Name of player" + "\t" + "Wickets taken")
for i in range(len(bowlsquad)):
print (str(bowlsquad[i].name) + "\t \t" + str(bowlsquad[i].wicket))
print ("-------------- Total Stats --------------")
total_runs = 0
for i in range(len(batsquad)):
total_runs = total_runs + batsquad[i].run
print ("Total runs scored:" + "\t" + str(total_runs))
print ("Total balls delivered:" + "\t" + str(balls_count))
print ("Total wickets taken:" + "\t" + str(wick_count))
|
05ac0c19111797aeeae48e605b25b5322c773bdc | AdamSarach/thewall | /backend/soup.py | 2,178 | 3.578125 | 4 | from bs4 import BeautifulSoup
import requests
# url = "http://bankier.pl"
# response = requests.get(url)
from pathlib import Path
def get_data_to_read():
"""Read from file instead of make request"""
base_dir_ = Path(__file__).resolve().parent.parent
path_to_file = base_dir_ / "test_file.txt"
file = open(path_to_file, "r")
data = file.read()
file.close()
return data
# def extract_data(text):
# money_list = []
# money_domain = "https://www.money.pl/"
# soup = BeautifulSoup(text, 'html.parser')
# ul_element = soup.find("ul", {"class": "w4z002-3 bzICKL"})
# for link in ul_element.find_all('li'):
# inner_link = link.find("a")
# description = inner_link['title']
# path = inner_link['href']
# url = money_domain + path
# list_element = {
# "url": url,
# "description": description
# }
# money_list.append(list_element)
# return money_list
# extract_data(get_data_to_read())
# def extract_wnp_data(text):
# wnp_list = []
# soup = BeautifulSoup(text, 'html.parser')
# tabs = soup.find("div", {"class": "tabs"})
# news = tabs.find("div", {"class": "one active"})
# for link in news.find_all('a'):
# url = link['href']
# description = link.find("h3").text
# list_element = {
# "url": url,
# "description": description
# }
# wnp_list.append(list_element)
# return wnp_list
# def extract_bankier_data(text):
#
# bankier_list = []
# soup = BeautifulSoup(text, 'html.parser')
# section = soup.find("div", {"class": "o-home-dailynews-box__list"})
# for link in section.find_all('a', {"class": "m-title-with-label-item"}):
# class_list = link.get_attribute_list('class')
# if len(class_list) > 1:
# continue
#
# url = link['data-vr-contentbox-url']
# image = link.find("img")
# description = image["alt"]
# list_element = {
# "url": url,
# "description": description
# }
# bankier_list.append(list_element)
#
# return bankier_list
|
2d3fb98cd2c98c632c60fc9da686b6567c1ea68d | jaimedaniels94/100daysofcode | /day2/tip-calculator.py | 402 | 4.15625 | 4 | print("Welcome to the tip calculator!")
bill = float(input("What was the total bill? $"))
tip = int(input("What percentage tip would you like to give? 10, 12, or 15? "))
split = int(input("How many people will split the bill? "))
bill_with_tip = tip / 100 * bill + bill
bill_per_person = bill_with_tip / split
final_amount = round(bill_per_person, 2)
print(f"Each person should pay ${final_amount})
|
17ec3f12074f33e8804dade2464a27e6c822602c | jaimedaniels94/100daysofcode | /day4/final.py | 1,128 | 4.25 | 4 | #Build a program to play rock, paper, scissors against the computer.
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
ascii = [rock, paper, scissors]
print("READY TO ROCK, PAPER, SCISSORS?")
player_num = int(input("Choose your weapon. \n0 for rock, 1 for paper, or 2 for scissors.\n"))
if player_num > 2 or player_num < 0:
print("Invalid entry. Play again.")
else:
print(f"You chose:\n{ascii[player_num]}")
computer_num = random.randint(0, 2)
print(f"Computer chose:\n{ascii[computer_num]}")
if player_num == 0 and computer_num == 2:
print("You win!")
elif player_num == 2 and computer_num == 1:
print("You win!")
elif player_num == 1 and computer_num == 0:
print("You win!")
elif player_num == computer_num:
print("It's a draw. Play again.")
else:
print("You lose. Hahah you lost to a computer.") |
01864af5da79ea6a29ed528c31fb75bafc14bb8b | c0r4line/Practicas-y-entregas | /desafios/desafio2-3.py | 513 | 3.90625 | 4 | #implementar una función que dada una cadena de texto, retorne las palabras que contiene en orden alfabético.
def ordeno1(cadena):
""" Implementación usando sort"""
lista = cadena.split()
#lista.sort(key=str.lower)
lista.sort()
return lista
print(ordeno1("Hoy puede ser un gran día. "))
# Otra posible solución
def ordeno2(cadena):
""" Implementación usando sorted"""
lista = cadena.split()
return sorted(lista, key=str.lower)
print(ordeno2("Hoy puede ser un gran día. ")) |
4dd124ce3f9df6db9df56ccae7b6cc8745105db0 | c0r4line/Practicas-y-entregas | /ejercicio12.py | 1,884 | 3.53125 | 4 | #EJERCICIO BUSCAMINAS ANALIZAR Y COMPILAR!!!!
def convertir_mapa_en_matriz(b_lleno):
""" Convierte mapa en matriz de caracteres y reemplaza guiones por 0s
"""
for i in range(len(b_lleno)):
b_lleno[i] = b_lleno[i].replace("-","0") # Reemplazar guiones por 0
b_lleno[i] = list(b_lleno[i])
return b_lleno
def convertir_mapa_en_strings(b_lleno):
""" Vuelve a convertir la matriz en filas de strings
"""
fila = ""
for i in range(len(b_lleno)):
for j in range(len(b_lleno[i])):
fila += str(b_lleno[i][j])
b_lleno[i] = fila
fila = ""
return b_lleno
def incrementar_minas(b_lleno, posX, posY):
"""Incrementa las cantidad de minas alrededor de la posicion indicada
posX (int): ubicacion de la fila
posY (int): ubicacion de la columna
"""
maximoFila = len(b_lleno)
maximoColumna = len(b_lleno[0])
for i in range(-1,2):
for j in range(-1,2):
posX1 = posX + i
posY1 = posY + j
if (-1 < posX1 < maximoFila) and (-1 < posY1 < maximoColumna):
if b_lleno[posX1][posY1] != "*":
b_lleno[posX1][posY1] = str(int(b_lleno[posX1][posY1]) + 1)
return b_lleno
def imprimir_resultados(b_lleno):
""" Imprime los resultados del buscaminas en formate del juego
"""
for fila in b_lleno:
print(fila)
# programa principal
buscamina_lleno = [
'-*-*-',
'--*--',
'----*',
'*----',
]
buscamina_lleno = convertir_mapa_en_matriz(buscamina_lleno)
for i in range(len(buscamina_lleno)): # cantidad de filas
for j in range(len(buscamina_lleno[i])): # logitud de la fila
if buscamina_lleno[i][j] == "*": # si encuentra una mina
buscamina_lleno = incrementar_minas(buscamina_lleno, i, j)
buscamina_lleno = convertir_mapa_en_strings(buscamina_lleno)
imprimir_resultados(buscamina_lleno) |
3f9b454fbbd125847485c6499c70773d7d259d0d | vpoloromero/Curso-Python | /programacion_desde_cero_con_python/conjuntos.py | 762 | 3.96875 | 4 | """
@author: Octavio Gutiérrez de Código Máquina
URL del canal: https://www.youtube.com/CodigoMaquina
URL del video: https://youtu.be/rHiu2ZAp4eA
"""
nombres2020 = {"Juan", "Pedro", "Luis", "Pedro"}
nombres2021 = {"Luis", "Maria", "Rosa"}
print(nombres2020)
print(nombres2021)
nombres2021.add("Luis")
print(nombres2021)
nombres2021.add("Jose")
print(nombres2021)
nombres2021.remove("Jose")
print(nombres2021)
print(nombres2020)
nombres = nombres2020.union(nombres2021)
print(nombres)
nombres_ambos_anios = nombres2020.intersection(nombres2021)
print(nombres_ambos_anios)
nombres.difference(nombres_ambos_anios)
print(nombres)
print(nombres2021.issubset(nombres))
print(nombres.issubset(nombres2020))
print(nombres.issuperset(nombres2020))
|
3526a1be9fcce327a76e5917ba0ac4e1caa6a271 | vpoloromero/Curso-Python | /programacion_desde_cero_con_python/listas.py | 1,021 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
@author: Octavio Gutiérrez de Código Máquina
URL del canal: https://www.youtube.com/CodigoMaquina
URL del video: https://youtu.be/WCfR0nWOKdU
"""
edades = [13, 45, 23, 13]
print(edades[0])
print(edades[2])
edades[2]=33
print(edades)
print(edades[0:2])
print(edades[:2])
print(edades[2:])
print(len(edades))
print(max(edades))
print(min(edades))
print(sum(edades))
print(sum(edades)/len(edades))
edades.insert(2, 50)
print(edades)
edades.append(55)
print(edades)
edades.extend([56])
print(edades)
edades.extend([80, 88])
print(edades)
del edades[1]
print(edades)
edades.remove(50)
print(edades)
edades.pop()
print(edades)
print(edades.count(33))
print(edades.count(13))
print(edades.index(55))
print(edades.sort())
edades.reverse()
print(edades)
persona1 = ["Juan", 44]
print(persona1[0])
print(persona1[1])
persona2 = ["Maria", 30]
personas = [persona1, persona2]
print(personas[0])
print(personas[1])
print(personas[0][0], personas[0][1])
|
7bf92868ee3190ae24e6d595b586a62c5761e149 | debjbhow/Voting-System-using-Python | /1.py | 1,105 | 4.03125 | 4 | nominee_1 = input("Enter the nominee 1 name: ")
nominee_2 = input("Enter the nominee 2 name: ")
nom_1_votes = 0
nom_2_votes = 0
votes_id = [1,2,3,4,5,6,7,8,9,10]
num_of_voter = len(votes_id)
while True:
if votes_id== []:
print("voting session over")
if nom_1_votes>nom_2_votes:
percent= (nom_1_votes/num_of_voter)*100
print(nominee_1,"has won", "with", percent, "% votes")
break
elif nom_2_votes>nom_1_votes:
percent= (nom_2_votes/num_of_voter)*100
print(nominee_2,"has won", "with", percent, "% votes")
break
voter= int(input("Enter your voter id no: "))
if voter in votes_id:
print("You are a voter")
votes_id.remove(voter)
vote = int(input("Enter your vote 1 or 2: "))
if vote == 1:
nom_1_votes+=1
print("Thank you for casting your vote")
elif vote == 2:
nom_2_votes+=1
print("Thank you for casting your vote")
else:
print("You are not a voter here or you have already voted") |
2b47e8987cc92f9069fa12915030329d764cf032 | tomahim/project-euler | /python_solutions/problem3.py | 780 | 4.125 | 4 | from python_solutions.utils import timing
@timing
def compute_largest_prime_factor(value: int):
denominator = 2
while denominator < value:
disivion_result = value / denominator
if disivion_result.is_integer():
value = disivion_result
else:
denominator += 1
return value
if __name__ == '__main__':
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
example_value = 13195
example_answer = 29
assert example_answer == compute_largest_prime_factor(example_value)
problem_value = 600851475143
result = compute_largest_prime_factor(problem_value)
print(f'Largest prime factor of {problem_value} is : {result}')
|
fd225d62b402bee57d0fe6227f184ac27a6fb636 | adiatgit/leetcode | /searchMatrix.py | 949 | 3.78125 | 4 | def searchMatrix(matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
# Brute force
# for i in matrix:
# for j in i:
# if j == target:
# return True
# return False
def binarySearch(l, u, ele, arr):
if l <= u:
m = int(l + (u - l) / 2)
if arr[m] == ele:
return True
if ele < arr[m]:
return binarySearch(l, m - 1, ele, arr)
elif ele > arr[m]:
return binarySearch(m + 1, u, ele, arr)
return False
row = len(matrix[0])
for i in matrix:
if binarySearch(0, len(matrix[0]), target, i) == True:
return True
return False
print(searchMatrix(
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
],
5)) |
1fd8801c616d56d363b01e7056585fb106a440be | adiatgit/leetcode | /dailyTemperature.py | 835 | 3.625 | 4 | def dailyTemperatures( T):
"""
:type T: List[int]
:rtype: List[int]
"""
number_of_days = []
for i in range(0, len(T)):
count =0
flag = 0
for j in range(i+1, len(T)):
count = count +1
if(T[i] < T[j]):
number_of_days.append(count)
flag = 1
break
if(flag == 0):
number_of_days.append(0)
return number_of_days
print dailyTemperatures([73,74,75,71,69,72,76,73])
def anotherdailyTemperatures( T):
"""
:type T: List[int]
:rtype: List[int]
"""
number_of_days = []
temp = T[0]
count = 0
for i in range(1, len(T)):
count = count +1
if(temp < T[i]):
number_of_days.append(count)
temp = i
return number_of_days
|
bfc04a40200b11d2696a80ddf58e78211fb934d0 | adiatgit/leetcode | /OddEvenLinkList.py | 776 | 3.96875 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def listtoListNode(numbers):
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
def oddEvenList(Numbers):
"""
:type head: ListNode
:rtype: ListNode
"""
head = listtoListNode(Numbers)
tempList = []
even = x = ListNode(0)
odd = y = ListNode(0)
while (head):
odd.next = head
even.next = head.next
odd = odd.next
even = even.next
head = head.next.next if even else None
odd.next = y.next
return x.next
m = oddEvenList([1,2,3,4,5])
while(m):
print(m.val)
m = m.next
|
5cb0bedced084da01660398e79dce6a5ba55f5d1 | imabr777/logger | /logger.py | 1,606 | 3.546875 | 4 | #!usr/bin/env python3
import os
from datetime import datetime
def start_run(file_path):
"""Starts timer on this run and writes a starting line in the input file
:param file_path: A file path to which the starting line in the log will be written
:return:
"""
_write_helper("START {0} at {1}".format(os.path.basename(file_path), datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
def end_run(file_path):
"""Ends timer on this run and writes an ending line in the input file
:param file_path: A file path to which the ending line in the log will be written
:return:
"""
_write_helper("END {0} at {1}".format(os.path.basename(file_path), datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
def write_error(file_path, error_msg):
"""Writes an exception message to the input file
:param file_path: A file path to which the exception will be written
:param error_msg: The error message to be written
:return:
"""
_write_helper("ERROR - {0} at {1}".format(error_msg, datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
def write_log(file_path, log_msg):
"""Writes a log message to the input file
:param file_path: A file path to which the log message will be written
:param log_msg: The log message to be written
:return:
"""
_write_helper("LOG - {0} at {1}".format(log_msg, datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
def _write_helper(file_path, msg):
"""Does actual work of writing to the log file
:param file_path: A file path to which the log message will be written
:param msg: The full log message
:return:
"""
with open(file_path, "a") as log:
log.writelines(msg)
print(msg) |
67641880324a5be7dd35b96c07aef5edea6851fd | Saphall/Python-Projects | /1Vehicle_detector/Vehicle_detect_in_video_frame.py | 924 | 3.53125 | 4 | # Detect Cars in Video_Frame
# import python OpenCV
import cv2
# capture frames from video
cap = cv2.VideoCapture('video.avi')
# Trained XML classifiers describes some features of object we want to detect
car_cascade = cv2.CascadeClassifier('cars.xml')
# loop runs if capturing is initialized
while True:
# reads frames from video
ret, frames = cap.read()
# convert to gray scale of each frames
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
# detects cars of different sizes in input image
cars = car_cascade.detectMultiScale(gray, 1.1, 1)
# drawing rectangle in each cars
for (x, y, w, h) in cars:
cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 0, 255), 2)
# display frames in window
cv2.imshow('Vehicle Detection', frames)
# wait for ESC key to stop
if cv2.waitKey(33) == 27:
break
# de-allocate any associated memory usage
cv2.destroyAllWindows()
|
2aaf41b3a62527bf56d17a3d1a8d0e1523aa401c | CRUZEAAKASH/HackerRankPythonPratice | /Strings/SwaptheCase.py | 223 | 4.0625 | 4 |
string = input()
print(len(string))
string1 = ""
for item in range(0, len(string)):
if string[item].islower():
string1 += string[item].upper()
else:
string1 += string[item].lower()
print(string1)
|
7bd6a1d2c6123bf23aac3d1ba0a1daba18e688bb | 4chloedawson/usgstidal | /data-packager/adapters/wind_obs_csv_parser.py | 653 | 3.640625 | 4 | import csv
import json
# Takes the data from a location's CSV file and stores it in a JSON file
# Handles wind observation data!
# obsData
# fileNames : noaaID_wind_obs.csv
# time : YYYY-MM-DD hh:mm:ss+00:00
# direction: wind direction [deg]
# gusts : wind gusts [m/s]
# speed : wind speed [m/s]
# Note: speed is in m/s, when displayed in graph it is converted to mph
def parse_wind_obs_csv(filePath) :
csvfile = open(filePath, 'r')
data = [] # output
fieldnames = ("time", "direction", "gusts", "speed")
reader = csv.DictReader(csvfile, fieldnames)
next(reader)
return [row for row in reader]
|
559d1fda15c90a189c07fc023258334f08dc9a2f | cedwards036/HandshakeFDSDataProcessor | /test/test_survey_data_model/test_location.py | 2,144 | 3.515625 | 4 | import unittest
from src.survey_data_model import Location
class TestLocation(unittest.TestCase):
def assert_full_loc(self, expected: str, location: Location):
self.assertEqual(expected, location.full_location)
def test_null_location(self):
self.assert_full_loc('', Location())
def test_passing_empty_string_counts_as_null(self):
self.assertEqual(Location(), Location(city='', state='', country=''))
self.assertEqual(Location(city='Hong Kong'), Location(city='Hong Kong', state='', country=''))
def test_full_location_is_set_given_only_one_location_field(self):
self.assert_full_loc('Baltimore', Location(city='Baltimore'))
self.assert_full_loc('Maryland', Location(state='Maryland'))
self.assert_full_loc('United States', Location(country='United States'))
def test_full_location_is_set_given_two_location_fields(self):
self.assert_full_loc('Baltimore, Maryland', Location(city='Baltimore', state='Maryland'))
self.assert_full_loc('Baltimore, United States', Location(city='Baltimore', country='United States'))
self.assert_full_loc('Maryland, United States', Location(state='Maryland', country='United States'))
def test_full_location_is_set_given_all_three_fields(self):
self.assert_full_loc('Baltimore, Maryland, United States', Location(city='Baltimore', state='Maryland', country='United States'))
def test_full_location_responds_to_field_updates(self):
location = Location(city='Baltimore', state='Maryland', country='United States')
self.assert_full_loc('Baltimore, Maryland, United States', location)
location.city = 'London'
self.assert_full_loc('London, Maryland, United States', location)
location.state = 'England'
location.country = 'United Kingdom'
self.assert_full_loc('London, England, United Kingdom', location)
def test_to_dict(self):
self.assertEqual({'city': 'Baltimore', 'state': 'Maryland', 'country': 'United States'},
Location(city='Baltimore', state='Maryland', country='United States').to_dict())
|
a494c6df41d3048f256a711f1d4371910f348876 | katadoka/Basic-Python | /lesson3/func_average_arithmetic_elements.py | 259 | 4.0625 | 4 | # a function that accepts an array
# and returns the arithmetic mean of its elements
def averege_arithmetic(mass):
aver = sum(mass)/len(mass)
return aver
mass = [int(x) for x in input("Enter the numbers: ").split()]
print(averege_arithmetic(mass))
|
90da75f3996535b822da796675a6aa145fd70f3f | thumarrushik/Leetcode | /DFS.py | 588 | 3.5 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DFS_visit(self, v, visited):
visited[v] = 1
print(v)
for i in self.graph[v]:
if visited[i] == 0:
self.DFS_visit(i, visited)
def DFS(self, v):
visited = [0]* len(self.graph)
self.DFS_visit(v,visited)
g= Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
g.DFS(2)
|
330386fc909cf50fbb1d4e8566d8b49d74550ef2 | rais2-pivotal/pythonsamples | /loopwhiledone.py | 318 | 4.0625 | 4 | #!/usr/bin/env python
answer = 0
numsum = 0
while True:
answer = input("Enter a number: ")
if answer == 'done':
break
try:
val = int(answer)
numsum += val
except ValueError:
print("Invalid input")
continue
print("Total sum of inputs: " + str(numsum))
|
396ba9f44f9c4f853cc3f89053c4a5ecf07b0c2b | Hemangi3598/chap-5_p7 | /p7.py | 505 | 4.09375 | 4 | # wapp to read two strings and find if they are anagrams
# strings having same letters but different meanings
# listen <--> slient fried <--> fired earth <--> heart
# elinst <--> elinst
# race <--> care elbow <--> below
s1 = input(" enter first string ")
d1 = sorted(s1)
ns1 = "".join(d1)
s2 = input(" enter second string ")
d2 = sorted(s2)
ns2 = "".join(d2)
if ns1 == ns2:
print(" yes it is an anagram")
else:
print("nopes its not an anagram ")
# DRY --> dont repeat yourself
|
b4755568bc692d8dd483ed1c55f00cb314d5b230 | jcolvert99/Dictionaries | /csv_customers_read.py | 419 | 4 | 4 | import csv
customers = open('customers.csv', 'r')
customer_file = csv.reader(customers, delimiter=',')
#skip header line
next(customer_file)
for record in customer_file:
print(record)
print('first name:',record[1])
print('last name:',record[2])
print('city:',record[3])
print('country:',record[4])
print('phone:',record[5])
input()
#input runs through each record as you press enter |
75a4e792db19694cfc58f6cee4edc8f1d64bbbeb | lwher/Algorithm-exercise | /python/leetcode/44-Wildcard-Matching/solution.py | 910 | 3.515625 | 4 | class Solution(object):
def match(self, s, p):
l = len(s)
for i in range(l):
if not(s[i] == p[i] or p[i] == '?'):
return False
return True
def isMatch(self, s, p):
s = '#$%' + s + '#$%'
p = '#$%' + p + '#$%'
ls = len(s)
lp = len(p)
newp = p.split('*')
L = []
for x in newp:
L.append(len(x))
if ls < L[0] or not(self.match(s[:L[0]], newp[0])):
return False
now = 1
i = L[0]
while i < ls:
if ls - i >= L[now] and self.match(s[i : i + L[now]], newp[now]):
i += L[now]
now += 1
else:
i += 1
if now < len(newp):
return False
else:
return True
"""
:type s: str
:type p: str
:rtype: bool
"""
|
894d5dcbf9c844bc2a73028e60f1c1290f5f3dcd | lwher/Algorithm-exercise | /python/leetcode/57-Insert-Interval/solution.py | 1,047 | 3.953125 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
l = newInterval.start
r = newInterval.end
flag = False
res = []
for x in intervals:
if (x.start >= l and x.start <= r) or (x.end >= l and x.end <= r) or (x.start >= l and x.end <= r) or (x.start <= l and x.end >= r):
if l > x.start:
l = x.start
if r < x.end:
r = x.end
elif x.end < l:
res.append(x)
else:
if flag == False:
res.append(Interval(l, r))
flag = True
res.append(x)
if flag == False:
res.append(Interval(l, r))
return res
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
|
6484b99ed4813d12eedf29bdc02e1eec1c6f7c10 | Daniel-Wuthnow/python_nov_2017 | /Daniel_Wuthnow/Python_OOP/product.py | 813 | 3.65625 | 4 | class product(object):
def __init__(self, price, name, weight, brand, status="for sale"):
self.price = price
self.name = name
self.weight = weight
self.brand = brand
self.status = status
def sell(self):
self.status = "sold"
return self
def add_tax(self, t):
self.price = self.price + (self.price * t)
return self
def returns(self, status, open):
if status == 'defective':
self.price = 0
self.status = 'defective'
if open == 'true':
status = 'used'
self.price = self.price * .80
return self
def display(self):
print "Price is ${}".format(self.price)
print self.name
print self.weight
print self.brand
print self.status
product1 = product(10, 'shoes', 20, "ironshore")
product1.add_tax(.12).sell().display()
# product1.returns('for sale','true').display() |
feb06eadee3d04c79b399fc22abba282dbf0797c | Daniel-Wuthnow/python_nov_2017 | /Daniel_Wuthnow/Python_fundamentals/dictcionarie_practice.py | 153 | 4.0625 | 4 | info = {"name":"Daniel","age": 22, "country of birth": "United States", "Fav lang": "Python"}
for key in info:
print "My {} is {}".format(key,info[key]) |
0a5bdcb040aa085bbb0708b16556c69ba7ea92d1 | cwiertniamichal/SimulatedAnnealing | /TravellingSalesman.py | 4,694 | 3.59375 | 4 | import City
import random
import matplotlib.pyplot as plt
def arbitrary_swap(world):
city1 = random.randint(0, (len(world) - 1))
city2 = random.randint(0, (len(world) - 1))
while city1 == city2:
city2 = random.randint(0, (len(world) - 1))
return [city1, city2]
def consecutive_swap(world):
city1 = random.randint(0, (len(world) - 2))
city2 = city1 + 1
return [city1, city2]
def swap(list, index1, index2):
tmp = list[index1]
list[index1] = list[index2]
list[index2] = tmp
def count_distance(world):
dist = 0
for i in range(len(world) - 1):
dist += world[i].distance(world[(i + 1) % (len(world) - 1)])
return dist
def simulated_annealing(world):
best_dist = count_distance(world)
dist = count_distance(world)
best = []
last_result = dist
delta = 0
curr_dist = 0
T = 200
i = 0
t = [T]
y = []
while T > 0 and i < 50000:
cities = arbitrary_swap(world)
city1 = cities[0]
city2 = cities[1]
swap(world, city1, city2)
curr_dist = count_distance(world)
if curr_dist < dist:
y.append(curr_dist)
dist = curr_dist
if dist < best_dist:
best_dist = dist
best = world[:]
else:
if random.uniform(0,1) < (2.72)**(((dist - curr_dist)/T)):
dist = curr_dist
y.append(dist)
else:
swap(world, city1, city2)
y.append(dist)
T *= 0.9999
t.append(T)
i += 1
delta += abs(last_result - dist)
last_result = dist
if i%100 == 0:
if delta < 5:
plt.plot(t)
plt.savefig('ene.png')
plt.close()
plt.plot(y)
plt.savefig('example.png')
plt.close()
for j in range(len(best) - 1):
plt.scatter(best[j].x,best[j].y)
# plt.annotate(j, xy=(best[j].x, best[j].y))
plt.plot([best[j].x, best[j + 1].x], [best[j].y, best[j + 1].y])
plt.scatter(best[len(best) - 1].x,best[len(best) - 1].y)
#plt.annotate(len(best) - 1, xy=(best[len(best) - 1].x, best[len(best) - 1].y))
plt.savefig('path_example.png')
plt.close()
return best
else:
delta = 0
plt.plot(t)
plt.savefig('ene.png')
plt.close()
plt.plot(y)
plt.savefig('example.png')
plt.close()
for i in range(len(best) - 1):
plt.scatter(best[i].x,best[i].y)
#plt.annotate(i, xy=(best[i].x, best[i].y))
plt.plot([best[i].x, best[i + 1].x], [best[i].y, best[i + 1].y])
plt.scatter(best[len(best) - 1].x,best[len(best) - 1].y)
#plt.annotate(len(best) - 1, xy=(best[len(best) - 1].x, best[len(best) - 1].y))
plt.savefig('path_example.png')
plt.close()
return best
def generate_world(n):
world = []
for i in range(0, n):
world.append(City.City(random.randint(0, 100), random.randint(0, 100), i))
return world
def generate_world_normal(n):
world = []
for i in range(0, n):
world.append(City.City(random.normalvariate(20, 10), random.normalvariate(20, 10), i)) #20 10 30 5 30 10 20 15
return world
def generate_world_seperated(n):
world = []
for i in range(0, n):
if i % 9 == 0:
world.append(City.City(random.randint(0, 30), random.randint(0, 30), i))
if i % 9 == 1:
world.append(City.City(random.randint(0, 30), random.randint(50, 80), i))
if i % 9 == 2:
world.append(City.City(random.randint(0, 30), random.randint(100, 130), i))
if i % 9 == 3:
world.append(City.City(random.randint(50, 80), random.randint(0, 30), i))
if i % 9 == 4:
world.append(City.City(random.randint(50, 80), random.randint(50, 80), i))
if i % 9 == 5:
world.append(City.City(random.randint(50, 80), random.randint(100, 130), i))
if i % 9 == 6:
world.append(City.City(random.randint(100, 130), random.randint(0, 30), i))
if i % 9 == 7:
world.append(City.City(random.randint(100, 130), random.randint(50, 80), i))
if i % 9 == 8:
world.append(City.City(random.randint(100, 130), random.randint(100, 130), i))
return world
def main():
n = 50
world = generate_world(n)
best = simulated_annealing(world)
print()
sum = 0
for i in range(0, n):
sum += best[i].distance(best[(i + 1) % n])
print(sum)
main()
|
28d6ea6b97dc33e56472e8ff6b2a3bd7876be913 | 14likhit/EfficientPath | /efficientPath/test_sample.py | 5,474 | 3.609375 | 4 | import math
DIRECTION_NORTH_EAST = 'NE'
DIRECTION_NORTH_WEST = 'NW'
DIRECTION_SOUTH_WEST = 'SW'
DIRECTION_SOUTH_EAST = 'SE'
# Euclidean Distance Formula->
# distance = sqrt((x2-x1)*(x2-x1)+(y2-y1)(y2-y1))
def distance_formula(x1, y1, x2, y2):
return math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))
# Implementing A* Algorithm using Euclidean distance
# f=g+h
# g=distance of starting pt to the immediate moving pt
# h=distance of immediate moving pt to destination pt
def calculate_a_star(start_x, start_y, moving_x, moving_y, dest_x, dest_y):
g = distance_formula(start_x, start_y, moving_x, moving_y)
h = distance_formula(moving_x, moving_y, dest_x, dest_y)
return g + h
# checking steps conditions in one direction in one shot
# NE-3,SE-4,NW-5,SW-2
# Since while computing I am staring from 0 steps for each direction
# Making computation is post Increment , greater than is compute on less
def check_steps_in_one_dir(direction, steps):
if (direction == DIRECTION_NORTH_EAST) & (steps > 2):
return False
elif (direction == DIRECTION_SOUTH_EAST) & (steps > 1):
return False
elif (direction == DIRECTION_NORTH_WEST) & (steps > 4):
return False
elif (direction == DIRECTION_SOUTH_WEST) & (steps > 3):
return False
return True
# As per A* Computing probables in given four direction
# Moving to minimum F as per A*
def compute_efficient_path(x, y):
print('Insect is about to move to destination via efficeint path')
temp_x = 0
temp_y = 0
direction_steps = [0, 0, 0, 0]
steps = 0
list_coordinates = list()
while (temp_x != x) | (temp_y != y):
print('Insect is moving')
steps += 1
list_coordinates.append((temp_x, temp_y))
f_ryt = calculate_a_star(temp_x, temp_y, temp_x + 1, temp_y + 1, x, y)
f_left = calculate_a_star(temp_x, temp_y, temp_x - 1, temp_y - 1, x, y)
f_up = calculate_a_star(temp_x, temp_y, temp_x - 1, temp_y + 1, x, y)
f_bot = calculate_a_star(temp_x, temp_y, temp_x + 1, temp_y - 1, x, y)
if not check_steps_in_one_dir(DIRECTION_NORTH_EAST, direction_steps[0]):
min_f = min([f_left, f_up, f_bot])
elif not check_steps_in_one_dir(DIRECTION_SOUTH_WEST, direction_steps[1]):
min_f = min([f_ryt, f_up, f_bot])
elif not check_steps_in_one_dir(DIRECTION_NORTH_WEST, direction_steps[2]):
min_f = min([f_ryt, f_left, f_bot])
elif not check_steps_in_one_dir(DIRECTION_SOUTH_EAST, direction_steps[3]):
min_f = min([f_ryt, f_left, f_up])
else:
min_f = min([f_ryt, f_left, f_up, f_bot])
if (min_f == f_ryt) & (check_steps_in_one_dir(DIRECTION_NORTH_EAST, direction_steps[0])):
direction_steps = [direction_steps[0] + 1, 0, 0, 0]
temp_x = temp_x + 1
temp_y = temp_y + 1
elif (min_f == f_left) & (check_steps_in_one_dir(DIRECTION_SOUTH_WEST, direction_steps[1])):
direction_steps = [0, direction_steps[1] + 1, 0, 0]
temp_x = temp_x - 1
temp_y = temp_y - 1
elif (min_f == f_up) & (check_steps_in_one_dir(DIRECTION_NORTH_WEST, direction_steps[2])):
direction_steps = [0, 0, direction_steps[2] + 1, 0]
temp_x = temp_x - 1
temp_y = temp_y + 1
elif (min_f == f_bot) & (check_steps_in_one_dir(DIRECTION_SOUTH_EAST, direction_steps[3])):
direction_steps = [0, 0, 0, direction_steps[3] + 1]
temp_x = temp_x + 1
temp_y = temp_y - 1
list_coordinates.append((temp_x, temp_y))
print('Hurray Insect reach the destination')
print('The efficient path insect followed was:')
print(list_coordinates)
def start_computing(x, y):
print('starting processing')
# distance = math.sqrt((x * x) + (y * y))
# # distance = math.sqrt((x - x)**2 + (y - y)**2)
if x == 0 and y == 0:
print('Insect stays at origin')
# elif x == 0 and y < 0 and distance <= 4:
# # SE-4
# print('oneshot')
# elif x == 0 and y > 0 and distance <= 5:
# # NW-5
# print('oneshot')
# elif y == 0 and x < 0 and distance <= 2:
# # SW-2
# print('oneshot')
# elif y == 0 and x > 0 and distance <= 3:
# # NE-3
# print('oneshot')
else:
compute_efficient_path(x, y)
# def original_coordinates(x, y):
# print("original")
#
# rotate plane 45 degree counterclockwise
# def updated_coordinates(x, y):
# # rotation axes by angle a = (x,y)-->(X,Y)
# # X=xcos(a)+ysin(a)
# # Y=-xsin(a)+ycos(a)
# # here a = 45
# angle = math.radians(45)
# return (x * math.cos(angle)) + (y * math.sin(angle)), (y * math.cos(angle)) - (x * math.sin(angle))
def check_input(user_response):
try:
float(user_response)
is_dig = True
except ValueError:
is_dig = False
return is_dig
def convert_number(user_response):
if user_response >= 0:
return math.ceil(user_response)
else:
return math.floor(user_response)
if __name__ == '__main__':
print('Hello! Lets Help Insect')
user_response_x = input("Please Enter x coordinate")
user_response_y = input("Please Enter y coordinate")
if (check_input(user_response_x)) & (check_input(user_response_y)):
start_computing(float(user_response_x), float(user_response_y))
else:
print("Please Provide Proper Input")
|
05b84dea5ced1308598cf5d1424ddf17f72d4fbd | bmbayad/dynamicConnectivity | /Sort/insertion_sort.py | 631 | 4.0625 | 4 | __author__ = 'bmbayad'
class Insertion(object):
def __init__(self, array):
self.array = array
def sort(self):
array_size = len(self.array)
for i in range(1, array_size):
j = i
while j > 0:
if self.array[j - 1] > self.array[j]:
self.swap(j - 1, j)
j -= 1
def swap(self, i, j):
element = self.array[i]
self.array[i] = self.array[j]
self.array[j] = element
if __name__ == '__main__':
insertion = Insertion([3, 1, 0, 5, 8, 2, 5, 7, 3, 1, 5])
insertion.sort()
print insertion.array
|
35622e41836c3986442f032ca834d7259d16e7c0 | Nooralwachi/top_words.py | /top_words.py | 432 | 3.609375 | 4 | from collections import defaultdict
def top_words(filename):
words_count=defaultdict(int)
with open(filename, 'r') as f:
for line in f:
words= line.strip().split()
for word in words:
words_count[word]+=1
sorted_words=sorted(words_count.items(), key=lambda x:x[1], reverse=True)
value=c=0
for (word,count) in sorted_words:
c+=1
if c<4 or count==value:
print(word, count)
value=count
top_words('word.txt') |
44f45aa4e46976b2291163005729d1d3a756bd20 | zhaowenfeng555/PythonStudy | /data_structures/search_tree.py | 900 | 3.90625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def generator_tree(self, nums, root):
# if len(nums) <= 0:
# return None
mid = len(nums) // 2
root.val = nums[mid]
print('1....')
print(root)
if mid - 1 > 0:
root.left = TreeNode()
self.generator_tree(nums[0: mid], root.left)
print('2....')
print(root)
if mid + 1 <= len(nums) - 1:
root.right = TreeNode()
self.generator_tree(nums[mid + 1: len(nums)], root.right)
print('3....')
def sortedArrayToBST(self, nums):
root = TreeNode()
self.generator_tree(nums, root)
return root
print (Solution().sortedArrayToBST([-10,-3,0,5,9])) |
96bf7f69cc7565eed855cd1c071662221e93bb9f | r-hall/sliding-puzzle | /sliding_puzzle.py | 17,587 | 3.546875 | 4 | # import sys
import numpy as np
# import copy
import heapq
from collections import deque
from collections import OrderedDict
import time
import math
# import ast
# import resource
class Board:
def __init__(self, board, current_score=0):
"""
Board: 2d numpy array representing game board
Goal: 2d numpy array representing end of game board
Current Score: metric used to determine board quality
"""
self.board = board
self.goal = np.arange(self.board.shape[0]**2).reshape(self.board.shape[0], self.board.shape[0])
self.current_score = current_score
def __eq__(self, other):
"""
Override equality operator to just check for same board
"""
return np.array_equal(self.board, other.board)
def __ne__(self, other):
"""
Override equality operator to just check for different board
"""
return not np.array_equal(self.board, other.board)
def get_board(self):
"""
Returns Game Board (2d numpy array)
"""
return self.board
def get_goal(self):
"""
Returns Goal
"""
return self.goal
def get_current_score(self):
"""
Returns score of board
"""
return self.current_score
def goal_test(self):
"""
Determines whether given board is a finished board
Input: board to test
Output: True or False
"""
return np.array_equal(self.board, self.goal)
def find_num(self, board, num):
"""
Gives the row and column numbers for the location of the element
Helper function used in score_board function to determine board quality,
as well as finding the row and column of the 0 in the board
Input: board (2d numpy array), desired element
Output: row and column values (integers) of the element
"""
row, col = map(int, np.where(board==num))
return (row, col)
def string_board(self):
"""
Gives board as a string representation, so it can be used as a key in a dict
Input: board (2d numpy array)
Output: string representation of board
"""
sb = ''.join([''.join(item) for item in self.board.astype(str)])
return sb
def score_board(self):
"""
Calculates and returns score of board for heuristic (Manhattan distance)
"""
score = 0
# for every tile, determine how far away it is from its position in the goal board
for i in range(1, self.board.shape[0]**2):
board_row, board_col = self.find_num(self.board, i)
goal_row, goal_col = self.find_num(self.goal, i)
score += abs(board_row - goal_row) + abs(board_col - goal_col)
return score
def move_up(self):
"""
Gives new board (copy) after moving the 0 up if possible
Input: board
Output: new board (copy) after up move, or False if not possible
"""
# find the row and column of the 0 tile
row, col = self.find_num(self.board, 0)
if row > 0:
new_board = np.copy(self.board)
# swap the 0 with the number above it
new_board[row][col], new_board[row-1][col] = new_board[row-1][col], new_board[row][col]
return Board(new_board, self.get_current_score() + 1)
return False
def move_down(self):
"""
Gives new board (copy) after moving the 0 down if possible
Input: board
Output: new board (copy) after down move, or False if not possible
"""
row, col = self.find_num(self.board, 0)
if row < self.board.shape[0] - 1:
new_board = np.copy(self.board)
# swap the 0 with the number below it
new_board[row][col], new_board[row+1][col] = new_board[row+1][col], new_board[row][col]
return Board(new_board, self.get_current_score() + 1)
return False
def move_left(self):
"""
Gives new board (copy) after moving the 0 left if possible
Input: board
Output: new board (copy) after left move, or False if not possible
"""
row, col = self.find_num(self.board, 0)
if col > 0:
new_board = np.copy(self.board)
# swap the 0 with the number to its left
new_board[row][col], new_board[row][col-1] = new_board[row][col-1], new_board[row][col]
return Board(new_board, self.get_current_score() + 1)
return False
def move_right(self):
"""
Gives new board (copy) after moving the 0 right if possible
Input: board
Output: new board (copy) after right move, or False if not possible
"""
row, col = self.find_num(self.board, 0)
if col < self.board.shape[1] - 1:
new_board = np.copy(self.board)
# swap the 0 with the number to its left
new_board[row][col], new_board[row][col+1] = new_board[row][col+1], new_board[row][col]
return Board(new_board, self.get_current_score() + 1)
return False
def retrieve_state(method, frontier):
"""
Returns item from frontier according to type of data structure
Input: frontier and method of search
Output: next state from frontier
"""
# breadth-first search
if method == 'bfs':
return frontier.popleft()
# depth-first search
if method == 'dfs':
return frontier.pop()
# A* search
if method == 'ast':
return heapq.heappop(frontier)[2]
def initialize_frontier(method, board):
"""
Initializes frontier depending on search method and returns frontier
Input: search method and starting board
Output: frontier
"""
# use double-ended queue (operations will provide queue functionality) for bfs
if method == 'bfs':
frontier = deque()
frontier.append(board)
# use double-ended queue (operations will provide stack functionality) for dfs
if method == 'dfs':
frontier = deque()
frontier.append(board)
# use priority queue for A* search
if method == 'ast':
frontier = []
heapq.heappush(frontier, (0, 0, board))
return frontier
def update_frontier(method, state, parents, frontier, frontier_dict, max_search_depth, explored, astar_frontier_dict, nodes_expanded, entry_count):
"""
Updates frontier for BFS, DFS and A* methods
Input: search method, current board, dictionary of parent-child relationships, frontier data structure,
frontier dictionary for O(1) lookup, current maximum search depth achieved, dictionary of explored boards,
special dictionary for A* search, total number of nodes expanded, number of nodes added to frontier (only used for A*)
Output: number of nodes expanded, current max_search_depth
Mutated: parents, frontier, frontier_dict, explored, astar_frontier_dict
"""
# update nodes_expanded
nodes_expanded += 1
# add this board to dictionary of explored boards
explored[state.string_board()] = True
# get all possible moves (or False if move is not possible)
up_board = state.move_up()
down_board = state.move_down()
left_board = state.move_left()
right_board = state.move_right()
# keep particular order for exploration
moves_bfs = [up_board, down_board, left_board, right_board]
moves_dfs = [right_board, left_board, down_board, up_board]
if method == 'bfs':
# remove the board from the frontier
del frontier_dict[state.string_board()]
for move in moves_bfs:
if move:
ms = move.string_board()
# check to see if board has already been explored or added to frontier
if ms not in explored and ms not in frontier_dict:
frontier_dict[ms] = True
# remember relationship to previous board
parents[ms] = state.string_board()
# update max_search_depth if applicable
if move.get_current_score() > max_search_depth:
max_search_depth = move.get_current_score()
# add move to frontier
frontier.append(move)
return (nodes_expanded, entry_count, max_search_depth)
if method == 'dfs':
# operations are similar to bfs above
del frontier_dict[state.string_board()]
for move in moves_dfs:
if move:
ms = move.string_board()
if ms not in explored and ms not in frontier_dict:
frontier_dict[ms] = True
parents[ms] = state.string_board()
if move.get_current_score() > max_search_depth:
max_search_depth = move.get_current_score()
frontier.append(move)
return (nodes_expanded, entry_count, max_search_depth)
if method == 'ast':
del astar_frontier_dict[state.string_board()]
for move in moves_bfs:
if move:
ms = move.string_board()
if ms not in explored and ms not in astar_frontier_dict:
entry_count += 1
parents[ms] = state.string_board()
if move.get_current_score() > max_search_depth:
max_search_depth = move.get_current_score()
astar_frontier_dict[ms] = (move.get_current_score(), move.get_current_score() + move.score_board(), entry_count, move)
heapq.heappush(frontier, (move.get_current_score() + move.score_board(), entry_count, move))
# if the board is in the frontier, compare the number of moves made in respective paths to same board
elif ms in astar_frontier_dict:
old_score, old_priority_value, old_entry_count, old_board = astar_frontier_dict[ms]
if move.get_current_score() < old_score:
entry_count += 1
parents[ms] = state.string_board()
if move.get_current_score() > max_search_depth:
max_search_depth = move.get_current_score()
# remove old board from the frontier and replace with new board
del astar_frontier_dict[ms]
astar_frontier_dict[ms] = (move.get_current_score(), move.get_current_score() + move.score_board(), entry_count, move)
# remove old board from the frontier
del frontier[frontier.index((old_priority_value, old_entry_count, old_board))]
# add new board to frontier and heapify
heapq.heappush(frontier, (move.get_current_score() + move.score_board(), entry_count, move))
heapq.heapify(frontier)
return (nodes_expanded, entry_count, max_search_depth)
def string_to_board(string):
"""
Convert string into Board
"""
return Board(np.asarray(list(map(int, [char for char in string]))).reshape(int(math.sqrt(len(string))),int(math.sqrt(len(string)))))
def get_direction(state, children):
"""
Called from evaluate
Get move that transforms current state to its child
Input: board and children dictionary
"""
# lazy checking -> won't continue to second conditional if first is False
if state.move_up() and state.move_up().string_board() == children[state.string_board()]:
return 'Up'
if state.move_down() and state.move_down().string_board() == children[state.string_board()]:
return 'Down'
if state.move_left() and state.move_left().string_board() == children[state.string_board()]:
return 'Left'
if state.move_right() and state.move_right().string_board() == children[state.string_board()]:
return 'Right'
def evaluate(board, parents):
"""
Called from search
Extracts three relevant metrics given parent dictionary from search
Input: starting board and parents dictionary from search
Output: path to goal, cost of path and search_depth
"""
# get the goal board as a string
goal = Board(board.get_goal()).string_board()
# initialize dictionary
children = OrderedDict()
children[goal] = None
# build up children dictionary using parents dictionary
next_board = parents[goal]
if next_board:
children[next_board] = goal
while next_board:
if parents[next_board] == None:
break
if parents[next_board] != None:
children[parents[next_board]] = next_board
next_board = parents[next_board]
# initialize path_to_goal list
path_to_goal = []
# start at starting board and build up path to goal with children dictionary
current_state = board.string_board()
while current_state != goal:
state = string_to_board(current_state)
path_to_goal.append(get_direction(state, children))
current_state = children[current_state]
# cost of path is number of moves taken to get to goal
cost_of_path = len(path_to_goal)
return (path_to_goal, cost_of_path)
def search(method, board):
"""
Performs search (BFS, DFS or A*) on sliding puzzle board to find goal
Input: starting board and search method
Output: path to goal, cost of the path, number of nodes expanded, search
depth to goal, maximum search depth and total time taken
"""
# get start time
start_time = time.time()
# get starting board as a string
start = board.string_board()
# initialized max_search_depth for search function
max_search_depth = 0
# remember parent-child relationships between boards to get path
parents = OrderedDict()
parents[start] = None
# remember boards that have already been explored to prevent rework
explored = {}
# intialize frontier dictionaries for O(1) lookup
frontier_dict = {start: True}
# (current # moves made, current # moves made + board score, board)
# just use 0 for starting board score since it will be only element in heap and automatically retrieved first
astar_frontier_dict = {start: (0, 0, board)}
# initialize entry count to be used in comparisons for heap for A*
entry_count = 0
# initialize number of nodes_expanded for search function
nodes_expanded = 0
# set up frontier based upon search method and add starting board
frontier = initialize_frontier(method, board)
# while there are boards in the frontier, continue to explore
max_frontier_size = 0
while frontier:
if len(frontier) > max_frontier_size:
max_frontier_size = len(frontier)
# get next board to be explored from frontier
state = retrieve_state(method, frontier)
# check to see if board matches the goal board
if state.goal_test():
total_time = time.time() - start_time
# max_ram_usage = resource.getrusage(resource.RUSAGE_SELF)[2]
# get the path from start to goal, the cost of the path
path_to_goal, cost_of_path = evaluate(board, parents)
return (path_to_goal, cost_of_path, nodes_expanded, max_search_depth, total_time, max_frontier_size)
nodes_expanded, entry_count, max_search_depth = update_frontier(method, state, parents, frontier, frontier_dict, max_search_depth, explored, astar_frontier_dict, nodes_expanded, entry_count)
def output(method, path_to_goal, cost_of_path, nodes_expanded, max_search_depth, total_time, max_frontier_size):
"""
Writes relevant metrics to output file
"""
with open('output.txt', 'a') as f:
f.write('method: ' + method + '\n')
f.write('path_to_goal: ' + str(path_to_goal) + '\n')
f.write('path_length: ' + str(cost_of_path) + '\n')
f.write('nodes_expanded: ' + str(nodes_expanded) + '\n')
f.write('max_search_depth: ' + str(max_search_depth) + '\n')
f.write('max_frontier_size: ' + str(max_frontier_size) + '\n')
f.write('running_time: ' + str(total_time) + '\n')
f.write('\n')
def test_program(method, test_board):
"""
Retrieves input, solves search problem and writes metrics to output file
"""
# method, test_board = sys.argv[1], sys.argv[2]
# test_board = ast.literal_eval(test_board)
dim = int(math.sqrt(len(test_board)))
test_board = np.asarray(test_board).reshape(dim, dim)
board = Board(test_board)
path_to_goal, cost_of_path, nodes_expanded, max_search_depth, total_time, max_frontier_size = search(method, board)
output(method, path_to_goal, cost_of_path, nodes_expanded, max_search_depth, total_time, max_frontier_size)
test_program('bfs', [0,8,7,6,5,4,3,2,1])
test_program('dfs', [0,8,7,6,5,4,3,2,1])
test_program('ast', [0,8,7,6,5,4,3,2,1])
|
c70b8b6d2966f6620ad280ca6cabd29bac4cadc1 | Harrywekesa/Sqlite-database | /using_place_holders.py | 562 | 4.1875 | 4 | import sqlite3
#Get personal data from the user aand insert it into a tuple
First_name = input("Enter your first name: ")
Last_name = input("Enter your last name: ")
Age = input("Enter your age: ")
personal_data = (First_name, Last_name, Age)
#Execute insert statement for supplied personal data
with sqlite3.connect("place_holder.db") as conn:
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS people")
c.execute("CREATE TABLE people(First_name TEXT, Last_name TEXT, Age INT)")
c.execute("INSERT INTO people VALUES(?, ?, ?)", personal_data)
|
7fa2e476f937018f2140e766f2550778d2adcb7a | Chunkygoo/Algorithms | /Arrays/moveElementToEnd.py | 1,135 | 3.59375 | 4 | # O(N^2) T O(1) S
def moveElementToEnd(array, toMove):
pointer = 0
while pointer < len(array):
if array[pointer] == toMove:
for i in range(pointer + 1, len(array)):
if array[i] != toMove:
# swap(array, pointer, i)
array[pointer], array[i] = (
array[i],
array[pointer],
) # This is the easier swap
pointer += 1
return array
# def swap(array, indexOne, indexTwo):
# temp = array[indexOne]
# array[indexOne] = array[indexTwo]
# array[indexTwo] = temp
# return array
# O(N) T O(1) S
def moveElementToEnd2(array, toMove):
leftPointer = 0
rightPointer = len(array) - 1
while leftPointer < rightPointer:
while array[leftPointer] != toMove and leftPointer < rightPointer:
leftPointer += 1
while array[rightPointer] == toMove and leftPointer < rightPointer:
rightPointer -= 1
array[leftPointer], array[rightPointer] = (
array[rightPointer],
array[leftPointer],
)
return array
|
a8249d6827d564c356a09b385b9814dd4b156ab9 | Chunkygoo/Algorithms | /LinkedLists/mergeLinkedLists.py | 527 | 3.765625 | 4 | # This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
# O(N+M) T O(1) S
def mergeLinkedLists(headOne, headTwo):
p1 = headOne
p2 = headTwo
pre = None
while p1 is not None and p2 is not None:
if p1.value >= p2.value:
if pre is not None:
pre.next = p2
pre = p2
p2 = p2.next
pre.next = p1
else:
pre = p1
p1 = p1.next
if p1 is None:
pre.next = p2
return headOne if headOne.value < headTwo.value else headTwo
|
3d7c59a177104134b77c552b8c74e8667b197f50 | Chunkygoo/Algorithms | /Sorting/selectionSort.py | 372 | 3.765625 | 4 | # O(N^2) T O(1) S
def selectionSort(array):
for index in range(len(array)):
smallest = array[index]
swapIndex = index
for j in range(index, len(array)):
if array[j] < smallest:
smallest = array[j]
swapIndex = j
array[index], array[swapIndex] = array[swapIndex], array[index]
return array
|
a7ad5b55b8f162ad988646df4abb68617dc01ae4 | Chunkygoo/Algorithms | /Arrays/longestPeak.py | 1,586 | 3.578125 | 4 | # O(N^2) T O(1) S
def longestPeak(array):
longestPeakLength = 0
if len(array) > 2:
for i in range(1, len(array) - 1):
currentPeakLength = 0
isPeak = False
if array[i] > array[i - 1] and array[i] > array[i + 1]:
isPeak = True
if isPeak:
currentPeakLength = 1
j = i
k = i
while j >= 1 and array[j - 1] < array[j]:
j -= 1
currentPeakLength += 1
while k < len(array) - 1 and array[k + 1] < array[k]:
k += 1
currentPeakLength += 1
if currentPeakLength > longestPeakLength:
longestPeakLength = currentPeakLength
return longestPeakLength
# O(N) T O(1) S
def longestPeak2(array):
longestPeakLength = 0
if len(array) > 2:
i = 1
while i < len(array) - 1:
currentPeakLength = 0
if array[i] > array[i - 1] and array[i] > array[i + 1]: # if isPeak
currentPeakLength = 1
j = i
k = i
while j >= 1 and array[j - 1] < array[j]:
j -= 1
currentPeakLength += 1
while k < len(array) - 1 and array[k + 1] < array[k]:
k += 1
currentPeakLength += 1
i = k
if currentPeakLength > longestPeakLength:
longestPeakLength = currentPeakLength
i += 1
return longestPeakLength
|
320be5c40be937895f5cbb645ecf8f1e99f0fde2 | Chunkygoo/Algorithms | /BinaryTrees/iterativeInOrderTraversal.py | 505 | 3.578125 | 4 | # O(N) T O(1) S Note: pN, cN and nN are previousNode, currentNode and nextNode respectively
def iterativeInOrderTraversal(tree, callback):
pN = None
cN = tree
while cN is not None:
if pN is None or cN.parent == pN:
if cN.left is not None:
nN = cN.left
else:
callback(cN)
nN = cN.right if cN.right is not None else cN.parent
elif cN.left == pN:
callback(cN)
nN = cN.right if cN.right is not None else cN.parent
elif cN.right == pN:
nN = cN.parent
pN = cN
cN = nN
|
55b9f5cbd15d4ea4b6b8bd3ded163f3fa4b2bd6f | Chunkygoo/Algorithms | /BinaryTrees/nodeDepths.py | 932 | 3.9375 | 4 | # O(N) T O(h) S where h is the maximum height/depth of the tree. Recall that a function is
# popped off the stack when the other is called
def nodeDepths(root):
return nodeDepthsR(root, 0)
def nodeDepthsR(node, tempDepth):
if node.left is None and node.right is None:
return tempDepth
elif node.left is not None and node.right is not None:
return (
tempDepth
+ nodeDepthsR(node.left, tempDepth + 1)
+ nodeDepthsR(node.right, tempDepth + 1)
)
elif node.left is not None and node.right is None:
return tempDepth + nodeDepthsR(node.left, tempDepth + 1)
elif node.left is None and node.right is not None:
return tempDepth + nodeDepthsR(node.right, tempDepth + 1)
# This is the class of the input binary tree.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
|
15040db4a82c3c82e2a4492300a9a1c64b44b973 | skvrd/leetcode.py | /problems/746/solution.py | 293 | 3.515625 | 4 | from typing import List
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
m1 = m2 = 0 # running totals minimums
for c in reversed(cost):
m = min(m1, m2) # hold current minimum
m1, m2 = m + c, m1
return min(m1, m2)
|
7e20590fec6ba13807a853da6f2ce7d52764ff7d | dhruvang9083/Python_100 | /p10.py | 156 | 3.859375 | 4 | # setence upper letter
x=int(input("total Number of name :"))
l=[]
for i in range(0,x):
words=str(input())
words=words.upper()
l.append(words)
print (l) |
f3fad1c2559329b4fa3c608e45040a48ea24e145 | taikeung/pythonDev | /db/mysql.py | 654 | 3.53125 | 4 | #coding: utf-8
##连接mysql数据库比较常用的两个driver:1.MySQLdb(c语言实现) 2.mysql-connector(纯python实现)
import MySQLdb
# import mysql.connector
conn = MySQLdb.connect (host = "127.0.0.1", user = "root", passwd = "mysql", db = "master")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "MySQL server version:", row[0]
cursor.close ()
conn.close ()
# cnx = mysql.connector.connect(user='root',password='mysql',host='127.0.0.1',database='master')
# cur=cnx.cursor()
# cur.execute('SELECT VERSION()')
# print cur.fetcone()[0]
# cur.close()
# cnx.close() |
0af2e4089a0eefc09d184b4132dad57133338f4f | taikeung/pythonDev | /funcs/built_in.py | 641 | 3.890625 | 4 | # coding:utf-8
#内置函数
#1.abs(num),求绝对值
abs(-1)
#2.cmp(x,y),比较两个值的大小
#如果x<y,返回-1,如果x==y,返回0,如果x>y,返回1:
cmp(1,2)
#3.类型转换
int('123')
#>>>123
int(12.34)
#>>>12
float('12.34')
#>>>12.34
str(1.23)
#>>>'1.23'
unicode(100)
#>>>u'100'
bool(1)
#>>>True
bool('')
#>>>False
#4.函数取别名
#函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”:
a = abs # 变量a指向abs函数
a(-1) # 所以也可以通过a调用abs函数
#>>>1
|
48dd4f5d37c4382212ad61886285759ec93e478f | marseille6/leetcode | /字母异位词分组.py | 1,203 | 3.6875 | 4 | """
人一生不会踏进同一条河流
__author__ = 'marseille'
__date__ = '2021/1/13 13:58'
"""
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
strsDic = {}
for st in strs:
strList = [0 for _ in range(26)]
# key = ''.join(sorted(str))
for a in st:
strList[ord(a) - ord('a')] += 1
key = ""
for num in range(26):
if strList[num]:
key = key + chr(num + ord('a'))+ str(strList[num])
if key in strsDic:
strsDic[key].append(st)
else:
strsDic[key] = [st]
res = [[single for single in group] for _,group in strsDic.items()]
strsDic.values()
return res
class Solution2:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
strsDic = {}
for str in strs:
key = ''.join(sorted(str))
if key in strsDic:
strsDic[key].append(str)
else:
strsDic[key] = [str]
res = [[single for single in group] for _, group in strsDic.items()]
strsDic.values()
return res |
6bf30cee5dd9540236adf1b68cad31f527251859 | gnimal/Python | /Program2.py | 289 | 3.65625 | 4 | print(3*2*3)
print("12*1",12*1)
print("12*2",12*2)
print("12*3",12*3)
print("12*4",12*4)
print("12*5",12*5)
print("12*6",12*6)
print("12*7",12*7)
print("12*8",12*8)
print("12*9",12*9)
print("12*10",12*10)
print(" is 2>3 ",2>3)
print("is 3>3",3>3)
print("2=2",2==2)
|
1da602f728c6e99caaef7eb0277f2f9ee52833ea | cuitianfeng/Python | /python3基础/10.Python修炼第十层/2 线程相关/11 条件Condition.py | 3,261 | 3.953125 | 4 | # 使得线程等待,只有满足某条件时,才释放n个线程
重要的方法:
wait(timeout=None) #当前线程等待着另外的线程发起通知,才向下执行。
notify() # 发出通知
import threading
def run(n):
con.acquire()
con.wait()
print("run the thread: %s" %n)
con.release()
if __name__ == '__main__':
con = threading.Condition()
for i in range(10):
t = threading.Thread(target=run, args=(i,))
t.start()
while True:
inp = input('>>>')
if inp == 'q':
break
con.acquire()
con.notify(int(inp))
con.release()
def condition_func():
ret = False
inp = input('>>>')
if inp == '1':
ret = True
return ret
def run(n):
con.acquire()
con.wait_for(condition_func)
print("run the thread: %s" %n)
con.release()
if __name__ == '__main__':
con = threading.Condition()
for i in range(10):
t = threading.Thread(target=run, args=(i,))
t.start()
import threading
"""
张三:床前明月光
李四:疑是地上霜
张三:举头望明月
李四:低头思故乡
怎么实现两个线程的交替说话,如果只有两句,可以使用锁机制,让某个线程先执行,这里有多句话交替出现,最好使用condition
"""
class ZSThead(threading.Thread):
def __init__(self, name, cond):
super(ZSThead, self).__init__()
self.name = name
self.cond = cond
def run(self):
# 必须先调用with self.cond,才能使用wait()、notify()方法
with self.cond:
# 讲话
print("{}:床前明月光".format(self.name))
# 等待李四的回应
self.cond.notify()
self.cond.wait()
# 讲话
print("{}:举头望明月".format(self.name))
# 等待李四的回应
self.cond.notify()
self.cond.wait()
class LSThread(threading.Thread):
def __init__(self, name, cond):
super(LSThread, self).__init__()
self.name = name
self.cond = cond
def run(self):
with self.cond:
# wait()方法不仅能获得一把锁,并且能够释放cond的大锁,这样张三才能进入with self.cond中
self.cond.wait()
print(f"{self.name}:疑是地上霜")
# notify()释放wait()生成的锁
self.cond.notify()
self.cond.wait()
print(f"{self.name}:低头思故乡")
self.cond.notify()
cond = threading.Condition()
zs = ZSThead("张三", cond)
ls = LSThread("李四", cond)
# 启动顺序很重要,必须先启动李四,让他在那里等待着,因为先启动张三时,他说了话就发出了通知,但是当时李四的进程还没有启动,
# 并且condition外面的大锁也没有释放,李四也没法获取self.cond这把大锁
# condition有两层锁,一把底层锁在线程调用了wait()方法就会释放
# 每次调用wait()方法后,都会创建一把锁放进condition的双向队列中,等待notify()方法的唤醒
ls.start()
zs.start()
'''
张三:床前明月光
李四:疑是地上霜
张三:举头望明月
李四:低头思故乡
''' |
b9696a9f2d7fa91e6ee989e82113badb93eac931 | cuitianfeng/Python | /python3基础/6.Python修炼第六层/20 csa模块.py | 1,848 | 3.90625 | 4 | 2.【csv模块 -Excel表格.csv】
## (1)猫砂
import csv
with open(‘sample/Excel.csv‘,‘r‘,newline=‘‘) as f:
r=csv.reader(f) # a按表格的行读取
for i in r:
print(i)
### 下面是读取内容:
# [‘商品编号‘, ‘商品名称‘, ‘单价‘, ‘库存‘, ‘销量‘]
# [‘1‘, ‘猫零食‘, ‘12‘, ‘3313‘, ‘5164‘]
# [‘2‘, ‘普通猫粮‘, ‘33‘, ‘5055‘, ‘2231‘]
# [‘3‘, ‘猫粮四合‘, ‘187‘, ‘212‘, ‘334‘]
### 要存放2行
with open(‘sample/Excel.csv‘,‘a+‘, newline=‘‘) as f:
# with open(‘sample/Excel.csv‘,‘w+‘, newline=‘‘) as f:
# 写入方式w/a都可以,因为没有循环for
w=csv.writer(f) # <class list>嵌套列表
# 按行写入
w.writerow([‘4‘, ‘猫砂‘, ‘25‘, ‘1022‘, ‘886‘])
w.writerow([‘5‘, ‘猫罐头‘, ‘18‘, ‘2234‘, ‘3121‘])
with open(‘sample/Excel.csv‘,‘r‘, newline=‘‘) as f:
h=csv.reader(f) # <class list>嵌套列表
for i in h:
print(i)
## (2)写入、读取收件人
import csv
data=[[‘收件人‘,‘邮箱‘],[‘刘‘,‘702352870@qq.com‘],[‘杨‘,‘1427369427@qq.com‘]]
## excel表格.csv文件写入要 列表嵌套
with open(‘sample/recipient.csv‘,‘w‘,newline=‘‘) as a:
# with open(‘sample/recipient.csv‘,‘a‘,newline=‘‘) as a:
# 如果是‘a‘则第一行就是空的??‘w‘就没有这个bug!!
# 因为有循环for,也算写入一行,没有输出就返回空行!!
b=csv.writer(a) # 写入内容放入b
# 按行写入
for i in data: # i=[‘收件人‘,‘邮箱‘]
b.writerow(i)
with open(‘sample/recipient.csv‘,‘r‘,newline=‘‘) as a:
c=csv.reader(a) # 读取内容放入c
for i in c:
print(i) |
ec5c426decc56bfffd74ba6c3fbccdb1d88d4e95 | cuitianfeng/Python | /python3基础/5.Python修炼第五层/1 函数递归.py | 3,557 | 4.125 | 4 | 一\递归调用的定义
# 函数递归调用:递归调用是函数嵌套调用的一种特殊形式,函数在调用时,直接或间接调用了自身,就是递归调用。
import sys
print(sys.getrecursionlimit()) # 默认为1000
sys.setrecursionlimit(2000) # 修改递归深度
print(sys.getrecursionlimit()) # 修改后为2000
n=1
def func1():
global n
print('from func1',n)
n+=1 # 局部作用域可以读取全局作用域的名字,但是如果想要修改全局名字的值需要global 声明为全局变量。
func1() # 直接调用函数本身
func1()
def func():
print('from func')
bar() # 间接调用本身
def bar():
func()
func()
# 调用函数会产生局部的名称空间,占用内存,因为上述这种调用会无需调用本身,python解释器的内存管理机制为了防止其无限制占用内存,对函数的递归调用做了最大的层级限制。
可以修改递归最大深度
import sys
sys.getrecursionlimit()
sys.setrecursionlimit(2000)
def f1(n):
print('from f1',n)
f1(n+1)
f1(1)
# 虽然可以设置,但是因为不是尾递归,仍然要保存栈,内存大小一定,不可能无限递归,而且无限制地递归调用本身是毫无意义的,递归应该分为两个明确的阶段,递推与回溯.
二\递归调用应该分为两个明确的阶段:递推,回溯
回溯阶段必须要有一个明确地结束条件,每进入下一次递归时,问题的规模都应该有所减少(否则,单纯地重复调用自身是毫无意义的)
因为不是一下子得到结果的,每一次递归的结果在内存中保存着,决定着递归的效率不高。
递归分为两个重要的阶段:递推+回溯
递推:一层一层往下找, 每次一层都在依赖下一层给返回的结果自己才有有明确的结果.
回溯:当在某一层找到了结果,或者终止条件触发了,再一层层往回退,一层层返回结果.
# 有五个人,问第五个人的年纪时他说他比第四个人大2岁,以此类推。当问到最后一个人时他说他18岁。
# age(5)=age(4)+2
# age(4)=age(3)+2
# age(3)=age(2)+2
# age(2)=age(1)+2
# age(1)=18
# 此递归的结束条件,避免死循环。
# n!=1 # age(n)=age(n-1)+2
# n=1 # age(n)=18
def age(n):
if n == 1:
res = 18
return res
# return 18 # 简写
res = age(n-1)+2
return res # res=age(4)+2 、res=age(3)+2、res=age(2)+2、res=age(1) ,执行完所有的递推+回溯后将返回值return
# return age(n-1)+2 # 简写
print(age(5)) # 26岁
\总结递归调用:
#1:进入下一次递归时,问题的规模必须降低。每递归一次规模就少一次。
#2:递归调用必须要有一个明确的结束条件
#3:在python中没有尾递归优化,递归调用的效率就是不高.
案例; 取出多层列表中的每个值
l=[1,2,[3,[4,[5,[6,7,[8,9,[10,[11,[12,]]]]]]]]]
def get(l):
for item in l:
# get(item) if isinstance(item,list) else print(item) # 用一行三元表达式代替下面的if判断
if isinstance(item,list): # 判断item是不是list类型,isinstance可以判断所有数据类型。
get(item)
else:
print(item)
get(l)
# 示例
def bar():
import time
time.sleep(3)
return 4
def foo():
res=bar()+3 # 都执行完才return
return res
print(foo()) # 7
|
e0bd73808aeccd4d2f189defc0dda40e2a10b7f2 | cuitianfeng/Python | /python3基础/4.Python修炼第四层/7 列表推倒式与生成器表达式.py | 4,501 | 3.84375 | 4 | \列表解析,也叫列表推到式
# 1、语法
[expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
]
类似于
res=[]
for item1 in iterable1:
if condition1:
for item2 in iterable2:
if condition2
...
for itemN in iterableN:
if conditionN:
res.append(expression)
# 2、案例:下10个鸡蛋,将大于等于3的放入列表中
egg_list=[]
for i in range(10):
if i >= 3:
res='egg%s' %i
egg_list.append(res
print(egg_list)
# 3、优点:方便,改变了编程习惯,可称之为声明式编程
\使用列表推倒式实现:
# 将上述的for循环方在中括号中使用列表解析的方式实现
l=['egg%s' %i for i in range(10) if i >= 3] # for循环结果方左边,其他判断放右边。可以写的更复杂。(针对range比较小的时候使用)
print(l) # 以列表的形式保存
# 多个for
one = ['A']
two = ['a','b','c']
def aaa():
print([i + y for i in one for y in two]) # 每个for取一个值,两只值相加。for循环的次数是以最长的列表为依据。
aaa() # ['Aa', 'Ab', 'Ac']
\使用生成器表达式实现:
# 1、把列表推导式的[]换成()就是生成器表达式
# 2、示例:上面是给了一筐鸡蛋,而这个是给你一只老母鸡,用的时候就下蛋,这也是生成器的特性
# 放在小括号中,变成一个生成器,然后一个一个下。
chicken=('egg%s' %i for i in range(10) if i >= 3) # 使用圆括号、结果是个生成器(生成器本身就是迭代器),(针对range比较大的时候可以这么使用)。
print(next(chicken)) # 每next一次取一个值
print(list(chicken)) # 因chicken可迭代,因而可以转成列表。
# 可以写多层,但是不太易于理解。
for i in ...:
if ...:
for i in ...:
if ...:
for ...
# 3、优点:省内存,一次只产生一个值在内存中.
练习题:
1、将names=['egon','alex_sb','wupeiqi','yuanhao']中的名字全部变大写
2、将names=['egon','alex_sb','wupeiqi','yuanhao']中以sb结尾的名字过滤掉,然后保存剩下的名字长度
3、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)
4、求文件a.txt中总共包含的字符个数?思考为何在第一次之后的n次sum求和得到的结果为0?(需要使用sum函数)
5、思考题
with open('a.txt') as f:
g=(len(line) for line in f)
print(sum(g)) #为何报错?
6、文件shopping.txt内容如下
mac,20000,3
lenovo,3000,10
tesla,1000000,10
chicken,200,1
求总共花了多少钱?
打印出所有商品的信息,格式为[{'name':'xxx','price':333,'count':3},...]
求单价大于10000的商品信息,格式同上
#题目一
names=['egon','alex_sb','wupeiqi','yuanhao']
names=[name.upper() for name in names]
#题目二
names=['egon','alex_sb','wupeiqi','yuanhao']
names=[len(name) for name in names if not name.endswith('sb')] # upper变成大写,endswith过滤掉结尾包含sb的。
#题目三
with open('a.txt',encoding='utf-8') as f:
print(max(len(line) for line in f))
#题目四
with open('a.txt', encoding='utf-8') as f:
print(sum(len(line) for line in f))
print(sum(len(line) for line in f)) # 求包换换行符在内的文件所有的字符数,为何得到的值为0?
print(sum(len(line) for line in f)) # 求包换换行符在内的文件所有的字符数,为何得到的值为0?
#题目五(略)
#题目六:每次必须重新打开文件或seek到文件开头,因为迭代完一次就结束了
with open('a.txt',encoding='utf-8') as f:
info=[line.split() for line in f]
cost=sum(float(unit_price)*int(count) for _,unit_price,count in info)
print(cost)
with open('a.txt',encoding='utf-8') as f:
info=[{
'name': line.split()[0],
'price': float(line.split()[1]),
'count': int(line.split()[2]),
} for line in f]
print(info)
with open('a.txt',encoding='utf-8') as f:
info=[{
'name': line.split()[0],
'price': float(line.split()[1]),
'count': int(line.split()[2]),
} for line in f if float(line.split()[1]) > 10000]
print(info)
|
b76bbf847d672dba26fc1cc315f705a2684c029a | cuitianfeng/Python | /python3基础/5.Python修炼第五层/7 包介绍.py | 4,851 | 3.984375 | 4 | \1、什么是包?
#官网解释
Packages are a way of structuring Python’s module namespace by using “dotted module names”
包是一种通过使用“.模块名”来组织python模块名称空间的方式。
#具体的:包就是一个包含有__init__.py文件的文件夹,所以其实我们创建包的目的就是为了用文件夹将文件/模块组织起来
#需要强调的是:
1. 在python3中,即使包下没有__init__.py文件,import 包仍然不会报错,而在python2中,包下一定要有该文件,否则import包会报错。
2. 创建包的目的不是为了运行,而是被导入使用,记住,包只是模块的一种形式而已,包的本质就是一种模块。
\2、为何要使用包
包的本质就是一个文件夹,那么文件夹唯一的功能就是将文件组织起来.随着功能越写越多,我们无法将所以功能都放到一个文件中,于是我们使用模块去组织功能,
而随着模块越来越多,我们就需要用文件夹将模块文件组织起来,以此来提高程序的结构性和可维护性。
\3、注意事项
# 1.关于包相关的导入语句也分为import和from ... import ...两种,但是无论哪种,无论在什么位置,在导入时都必须遵循一个原则:凡是在导入时带点的,
# 点的左边都必须是一个包,否则非法。可以带有一连串的点,如item.subitem.subsubitem,但都必须遵循这个原则。但对于导入后,在使用时就没有这种限制了,点的左边可以是包,模块,函数,类(它们都可以用点的方式调用自己的属性)。
# 2、import导入文件时,产生名称空间中的名字来源于文件,import 包,产生的名称空间的名字同样来源于文件,即包下的__init__.py,导入包本质就是在导入该文件。
# 3、包A和包B下有同名模块也不会冲突,如A.a与B.a来自俩个命名空间
\案例文件:“7 包的使用,test.py是执行文件,aaa是包。”
有点像俄罗斯套娃,也和linux路径的绝对路径一个意思。
\4、上课流程
# 1 实验一
准备:
执行文件为test.py,内容
#test.py
import aaa
同级目录下创建目录aaa,然后自建空__init__.py(或者干脆建包)
需求:验证导入包就是在导入包下的__init__.py
解决:
先执行看结果
再在__init__.py添加打印信息后,重新执行.导入aaa会出发__init__的执行。
# 2、实验二
准备:基于上面的结果
需求:
aaa.x
aaa.y
解决:在__init__.py中定义名字x和y
# 3、实验三
准备:在aaa下建立m1.py和m2.py
#m1.py
def f1():
print('from 1')
#m2.py
def f2():
print('from 2')
需求:
aaa.m1 #进而aaa.m1.f1()
aaa.m2 #进而aaa.m2.f2()
解决:在__init__.py中from aaa import m1,m2,强调: 环境变量(模块搜索路径)是以执行文件为准.
# from aaa import m1
# from aaa import m2
# __init__相当于是执行文件和包之间的桥梁,执行文件执行会触发__init__文件执行,__init__文件中去导入包。
需求
aaa.f1 #进而aaa.f1()
aaa.f2 #进而aaa.f2()
# from aaa.m1 import f1
# from aaa.m2 import f2
# 4、实验四
准备:在aaa下新建包bbb
需求:
aaa.bbb
解决:在aaa的__init__.py内导入名字bbb
# from aaa import bbb
# 5、实验五
准备:
在bbb下建立模块m3.py
#m3.py
def f3():
print('from 3')
需求:
aaa.bbb.m3 #进而aaa.bbb.m3.f3()
解决:是bbb下的名字m3,因而要在bbb的__init__.py文件中导入名字m3
# from aaa.bbb import m3
# 6、实验六
准备:基于上面的结果
需求:
aaa.m1()
aaa.m2()
aaa.m3()
进而实现
aaa.f1()
aaa.f2()
aaa.f3()
先用绝对导入,再用相对导入
解决:在aaa的__init__.py中拿到名字m1、m2、m3
# from aaa.m1 import f1
# from aaa.m2 import f2
# from aaa.bbb.m3 import f3
包内模块直接的相对导入,强调包的本质:包内的模块是用来被导入的,而不是被执行的
用户无法区分模块是文件还是一个包,我们定义包是为了方便开发者维护
# 7、实验七
将包整理当做一个模块,移动到别的目录下xxx/yyy下,保证不影响使用。就好像包移动了位置或者是下载别人的包。
操作sys.path
import sys
sys.path.append(r'/Users/zhanghongyang/Documents/软通动力/Github/python3基础/5.Python修炼第五层/7 包的使用/xxx/yyy') # 将test.py执行文件平级的yyy加入到环境变量即可。
|
77ad7f7bd72fb7da2db6a23856788f9aaa4b03f5 | cuitianfeng/Python | /python3基础/12.Python修炼第十二层/7. 盒子模型.py | 31,085 | 3.625 | 4 | \1、什么是CSS盒子模型?
HTML文档中的每个元素都被比喻成矩形盒子, 盒子模型通过四个边界来描述:
margin(外边距) # 用于控制元素与元素之间的距离;margin的最基本用途就是控制元素周围空间的间隔,从视觉角度上达到相互隔开的目的。
border(边框) # 用于控制内容与边框之间的距离;
padding(内填充) # 围绕在内边距和内容外的边框。可以用来把标签撑起来。
content(内容区域) # 盒子的内容,显示文本和图像。
如果把一个盒子比喻成一个壁挂相片,那么
# 外边距margin ===== 一个相框与另外一个相框之间的距离
# 边框border ===== 边框指的就是相框
# 内边距padding ===== 内容/相片与边框的距离
# 宽度width/高度height ===== 指定可以存放内容/相片的区域
提示:可以通过谷歌开发者工具查看盒子的各部分属性
#如图所示:
盒子模型:内容 —— 内填充 —— 边框 —— 外边距
想要调整内容和边框之间的距离用: padding
想要调整不同标签之间的距离用:margin
# margin 外边距
<style type="text/css">
.margin-test {
margin-top:5px;
margin-right:10px;
margin-bottom:15px;
margin-left:20px;
}
</style>
四个值简写:顺序(上右下左)
<style type="text/css">
.margin-test {
margin: 5px 10px 15px 20px;
}
</style>
三个值简写:顺序(上 左右 下)
<style type="text/css">
.margin-test {
margin: 5px 10px 20px;
}
</style>
常见居中简写:顺序(上下 右左)
<style type="text/css">
.mycenter {
margin: 0 auto; # 0是上下 auto是左右
}
</style>
# padding 内填充
<style type="text/css">
.padding-test {
padding-top: 5px;
padding-right: 10px;
padding-bottom: 15px;
padding-left: 20px;
}
</style>
推荐使用简写:
<style type="text/css">
.padding-test {
padding: 5px 10px 15px 20px;
}
</style>
顺序:上右下左
补充padding的常用简写方式:
提供一个,用于四边;
提供两个,第一个用于上-下,第二个用于左-右;
如果提供三个,第一个用于上,第二个用于左-右,第三个用于下;
提供四个参数值,将按上-右-下-左的顺序作用于四边;
\2、盒子模型的宽度和高度
1、内容的宽度和高度
通过标签的width和height属性设置
2、元素/盒子模型的宽度和高度
宽度= 左边框 + 左内边距 + width(内容的宽) + 右内边距 + 右边框高度
高度= 。。。。
3、元素/盒子模型空间的宽度和高度
宽度= 左外边距 + 左边框 + 左内边距 + width(内容的宽) + 右内边距 + 右边框高度 + 右外边距
高度= 。。。。
# 示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子模型宽度和高度</title>
<style>
span,a,b,strong {
display: inline-block;
width: 100px;
height: 100px;
border: 6px solid #000;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<span>我是span</span>
<a href="#"> 我是草链接</a>
<b>我是加粗</b>
<strong>我是强调</strong>
</body>
</html>
# 补充:为什么 height:100%; 不起作用?
如何让 height:100% 起作用:你需要给这个元素的所有父元素的高度设定一个有效值。换句话说,你需要这样做:
现在你给div的高度为100%,它有两个父元素<body>和<html>。为了让你的div的百分比高度能起作用,你必须设定<body>和<html>的高度。
<html style="height: 100%;">
<body style="height: 100%;">
<div style="height: 100%;">
<p>
这样这个div的高度就会100%了
</p>
</div>
</body>
</html>
相似的例子:可以查看qq注册界面https://ssl.zc.qq.com/v3/index-chs.html
\3、!!!css显示模式:块级、行内、行内块级
在HTML中HTML将所有标签分为两类,分别是 容器级 和 文本级
在CSS中CSS也将所有标签分为两类,分别是容器级是 块级元素 和 行内元素
1、HTML中容器级与文本级
容器级标签:可以嵌套其他的所有标签
div、h、ul>li、ol>li、dl>dt+dd
文本级标签:只能嵌套文字、图片、超链接
span、p、buis、strong、em、ins、del
2、CSS中块级与行内
块级:块级元素会独占一行,所有的容器类标签都是块级,文本标签中的p标签也是块级
div、h、ul、ol、dl、li、dt、dd 还有标签p
行内:行内元素不会独占一行,所有除了p标签以外的文本标签都是行内
span、buis、strong、em、ins、del
3、块级元素与行内元素的区别
1、块级元素block
独占一行
可以设置宽高
若没有设置宽度,那么默认和父元素一样宽(比如下例中的div的父元素是body,默认div的宽就是body的宽)
若没有设置宽高,那么就按照设置的来显示
2、行内元素inline
不会独占一行
不可以设置宽高
盒子宽高默认和内容一样
3、行内块级元素inline-block
不会独占一行
可以设置宽高
# 示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
/*块级元素*/
div,p,h1 {
background-color: red;
width: 200px;
height: 100px;
}
/*行内元素*/
span,b,strong {
background-color: blue;
width: 200px;
height: 100px;
}
/*行内块级元素*/
img {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<!--块级-->
<div>我是div</div>
<p>我是段落</p>
<h1>我是标题</h1>
<hr>
<!--行内-->
<span>我是span</span>
<b>我是加粗</b>
<strong>我是强调</strong>
<hr>
<!--行内块级-->
<img src="../imags/1.png" alt="">
<img src="../imags/1.png" alt="">
</body>
</html>
\4、!!!CSS显示模式转换
属性 描述 值
display 可以通过标签的display属性设置显示模式 none HTML文档中元素存在,但是在浏览器中不显示。一般用于配合JavaScript代码使用
block 块级
inline 行内
inline-block 行内块级
display:"none"与visibility:hidden的区别: visibility:hidden: 可以隐藏某个元素,但隐藏的元素仍需占用与未隐藏之前一样的空间。也就是说,该元素虽然被隐藏了,但仍然会影响布局。
display:none: 可以隐藏某个元素,且隐藏的元素不会占用任何空间。也就是说,该元素不但被隐藏了,而且该元素原本占用的空间也会从页面布局中消失。
\5、div与span
页面布局都是用块级元素,而行内元素是控制内容显示的。
1、div标签
一般用于配合css完成网页的基本布局
2、span标签
一般用于配合css修改网页中的一些局部信息,比如一行文字我们只为一部分加颜色<p>我是<span>egon</span></p>
3、div和span有什么区别?
div一般用于排版,而span一般用于局部文字的样式
1、站在HTML的角度:div是一个块级元素、独占一行,而span是一个行内元素、不会单独占一行
2、站在CSS的角度:div是一个容器级标签,而span是一个文本级标签
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div与span标签</title>
<style>
.header {
margin: 0 auto;
width: 980px;
height: 100px;
background: pink;
margin-bottom: 10px;
}
.content {
margin: 0 auto;
width: 980px;
height: 500px;
background: #e9ca37;
margin-bottom: 10px;
}
.footer {
margin: 0 auto;
width: 980px;
height: 100px;
background: #7e1487;
}
.logo {
width: 200px;
height: 50px;
background: #bfccdb;
float: left;
margin: 20px;
}
.nav {
width: 600px;
height: 50px;
background: palegreen;
float: right;
margin: 20px;
}
.aside {
width: 250px;
height: 460px;
background: #cccccc;
float: left;
margin: 20px;
}
.article {
width: 650px;
height: 460px;
background: green;
float: right;
margin: 20px;
}
span {
color: red;
}
</style>
</head>
<body>
<div class="header">
<div class="logo"></div>
<div class="nav"></div>
</div>
<div class="content">
<div class="aside">
<p>
我是<span>EGON</span>,一个最接近<span>神的男人</span>
</p>
</div>
<div class="article"></div>
</div>
<div class="footer"></div>
</body>
</html>
\6、盒子模型各部分详解
# 1、border边框
同时设置四条边的边框 border: 边框的宽度 边框的样式 边框的颜色
分别设置四条边的边框 border-left: 边框的宽度 边框的样式 边框的颜色
border-top: 边框的宽度 边框的样式 边框的颜色
border-right: 边框的宽度 边框的样式 边框的颜色
border-bottom: 边框的宽度 边框的样式 边框的颜色
分别指定宽度、格式、颜色 1、连写:(分别设置四条边的边框)
border-width: 上 右 下 左
border-style: 上 右 下 左
border-color:上 右 下 左
2 、注意点:
1、这三个属性时按照顺时针,即上、右、下、左来赋值的
2、这三个属性的取值省略时的规律
省略右面,右面默认同左面一样
省略下面,下面默认跟上面一样
只留一个,那么其余三边都跟这一个一样
了解非连写 border-left-width: ;
border-left-style: ;
border-left-color: #000;
border-top-width: ;
border-top-style: ;
border-top-color: #000;
border-right-width: ;
border-right-style: ;
border-right-color: #000;
border-bottom-width: ;
border-bottom-style: ;
border-bottom-color: #000;
其他:
http://www.w3school.com.cn/cssref/pr_border-style.asp
边框的样式 none 无边框。
dotted 点状虚线边框。
dashed 矩形虚线边框。
solid 实线边框。
border-radius /* 单独设置一个角:数值越大,弧度越大*/
border-top-left-radius: 20px;
border-top-right-radius: 20px;
border-bottom-left-radius: 20px;
border-bottom-right-radius: 20px;
/* 缩写设置 */
border-radius: 20px;/* 所有角设置相同值 */
border-radius: 20px 10px 10px 20px; /* 顺时针顺序:上左 上右 下左 下右*/
/* 百分比设置 */
border-radius: 50%;
/* 椭圆圆弧设置 */
border-radius: 25%/50%; /* 前面一个值代表水平方向的半径占总宽度的,后面一个值代表垂直方向 */
边框练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>边框属性</title>
<style>
div {
width: 100px;;
height: 100px;
}
.box1 {
/*border: 5px solid black;*/
/*border-left: 5px solid black;*/
/*border-top: 5px solid black;*/
/*border-right: 5px solid black;*/
/*border-bottom: 5px solid black;*/
border-width: 5px;
border-style: solid;
border-color: black;
}
.box2 {
/*border-left: 5px solid purple;*/
/*border-top: 5px solid red;*/
/*border-right: 5px solid green;*/
/*border-bottom: 5px solid blue;*/
border-width: 5px;
border-style: solid;
border-color: red green blue purple;
}
.box3 {
/*border: 5px solid red;*/
/*border-right: 5px dashed red;*/
border-width: 5px;
border-style: solid dashed solid solid;
border-color: red;
}
.box4 {
border-width: 5px;
border-style: solid dashed solid dashed;
border-color: red;
}
.box5 {
border:5px solid black;
border-bottom: none;
}
/*!!!在企业开发中要尽量降低网页的体积,图片越多,体积肯定越大,访问速度肯定越慢,所以针对简单的图形,可以只用用边框画出来
使用下面的方法制作就可以
*/
.box6 {
width: 0px;
height: 0px;
border-width:25px;
border-style: solid;
border-color: black white skyblue white;
border-bottom: none;
}
</style>
</head>
<body>
<div class="box1"></div>
<hr>
<div class="box2"></div>
<hr>
<div class="box3"></div>
<hr>
<div class="box4"></div>
<hr>
<div class="box5"></div>
<hr>
<div class="box6"></div>
</body>
</html>
# border-radius练习1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box1 {
margin: 0 auto;
height: 100px;
width: 920px;
border-radius: 20px 20px 0px 0px;
background-color: blue;
}
</style>
</head>
<body>
<div class="box1"></div>
</body>
</html>
# border-radius练习 - (圆形头像)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
img {
width: 185px;
border-radius: 50%;
}
</style>
</head>
<body>
<img src="https://images2018.cnblogs.com/blog/1036857/201805/1036857-20180511163924274-1737036731.png" alt="">
</body>
</html>
# 2、padding内边距:边框与内容之间的距离就是内边距
非连写 padding-top:20px;
padding-right:20px;
padding-bottom:20px;
padding-left:20px;
连写 padding:上 右 下 左;
注意 1 给标签设置内边距后,标签内容占有的宽度和高度会发生变化,设置padding之后标签内容的宽高是在原宽高的基础上加上padding值。如果不想改变实际大小,那就在用宽高减掉padding对应方向的值
2 padding是添加给父级的,改变的是父级包含的内容的位置
3 内边距也会有背景颜色
# 内边距练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>内边距属性</title>
<style>
div {
width: 100px;
height: 110px;
border: 1px solid red;
}
.box1 {
padding-top: 30px;
}
.box2 {
padding-right: 40px;
}
.box3 {
padding-bottom: 50px;
}
.box4 {
padding-left: 60px;
}
.box5 {
/*只留一个。全都相等*/
padding: 70px;
background-color: red;
}
</style>
</head>
<body>
<div class="box1">
我是文字我是文字我是文字我是文字我是文字我是文字我是文字
</div>
<hr>
<div class="box2">
我是文字我是文字我是文字我是文字我是文字我是文字我是文字
</div>
<hr>
<div class="box3">
我是文字我是文字我是文字我是文字我是文字我是文字我是文字
</div>
<hr>
<div class="box4">
我是文字我是文字我是文字我是文字我是文字我是文字我是文字
</div>
<hr>
<div class="box5">
我是文字我是文字我是文字我是文字我是文字我是文字我是文字
</div>
</body>
</html>
# 添加边框与padding后保持盒子大小不变:方式一 做减法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box1 {
/*width: 100px;*/
/*height: 100px;*/
background-color: red;
border: 10px solid #000;
padding: 10px;
width: 60px;
height: 60px;
}
</style>
</head>
<body>
<div class="box1">我是文字</div>
</body>
</html>
# 添加边框与padding后保持盒子大小不变:方式二 box-sizing
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box1 {
width: 100px;
height: 100px;
background-color: red;
border: 10px solid #000;
padding: 10px;
/*本质原理就是做减法*/
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="box1">我是文字</div>
</body>
</html>
# 3、外边距:标签与标签之间的距离就是外边距
非连写 margin-top:20px;
margin-right:20px;
margin-bottom:20px;
margin-left:20px;
连写 margin:上 右 下 左;
注意 1、外边距的那一部分是没有背景颜色的
2、外边距合并现象
在默认布局的水平方向上,默认两个盒子的外边距会叠加
而在垂直方向上,默认情况下两个盒子的外边距是不会叠加的,会出现合并现象,谁的外边距比较大,就听谁的
# 外边距合并现象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>外边距合并现象
</title>
<style>
span {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid #000;
}
div {
height: 100px;
border: 1px solid #000;
}
/*水平方向上。外边距会叠加*/
.hezi1 {
margin-right: 50px;
}
.hezi2 {
margin-left: 100px;
}
/*垂直方向上。外边距不会叠加,会合并成一个,谁比较大就听谁的*/
.box1 {
margin-bottom: 50px;
}
.box2 {
margin-top: 100px;
}
</style>
</head>
<body>
<!--
快捷创建
span.hezi${我是span}*2
-->
<span class="hezi1">我是span</span><span class="hezi2">我是span</span>
<div class="box1">我是div</div>
<div class="box2">我是div</div>
</body>
</html>
# margin-top塌陷
两个嵌套的盒子,内层盒子设置margin-top后会将外层盒子一起顶下来,解决方法如下:
1、外部盒子设置一个边框
2、外部盒子设置 overflow: hidden; 当子元素的尺寸超过父元素的尺寸时,内容会被修剪,并且其余内容是不可见的,此属性还有清除浮动、清除margin-top塌陷的功能。
3、使用伪元素类:
.clearfix:before{
content: '';
display:table;
}
#示范
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子模型宽度和高度</title>
<style>
.outter {
background-color: green;
width: 300px;
height: 300px;
/*方式一*/
/*border: 1px solid #000;*/
/*方式二*/
/*overflow: hidden;*/
}
.inner {
background-color: red;
width: 200px;
height: 200px;
margin-top: 100px;
}
/*方式三*/
.clearfix:before {
display: table;
content: "";
}
</style>
</head>
<body>
<div class="outter clearfix">
<div class="inner"></div>
</div>
</body>
</html>
# 4、内边距vs外边距
#1、在企业开发中,一般情况下如果需要控制嵌套关系盒子之间的距离
应该首先考虑padding
其次再考虑margin
margin本质上是用于控制兄弟直接的关系的,padding本质才是控制父子关系的关系
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.egon {
width: 300px;
height: 300px;
background-color: yellow;
padding: 50px;
box-sizing: border-box;
}
.alex {
width: 100px;
height: 100px;
background-color: green;
}
.linhaifeng {
width: 300px;
height: 300px;
background-color: purple;
padding: 50px;
box-sizing: border-box;
margin-top: 100px;
}
.liuqingzheng {
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="egon">
<div class="alex"></div>
</div>
<div class="linhaifeng">
<div class="liuqingzheng"></div>
</div>
</body>
</html>
#2、如果两个盒子是嵌套关系,那么设置了里面一个盒子顶部的外边距,那么外面一个盒子也会被顶下来
如果外面的盒子不想被遗弃顶下来,,那么可以给外面的盒子设置一个边框属性
示范
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.egon {
width: 300px;
height: 300px;
background-color: yellow;
box-sizing: border-box;
border: 1px solid #000;
}
.alex {
width: 100px;
height: 100px;
background-color: green;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="egon">
<div class="alex"></div>
</div>
</body>
</html>
# 5、盒子居中与内容居中
内容居中
1、让一行内容在盒子中水平且垂直居中
/*水平居中*/
text-align: center;
/*垂直居中*/
line-height: 500px;
2、让多行内容在盒子中垂直居中(水平居中与单行内容一样)
让行高与盒子高度一样,只能让一行内容垂直居中,如果想让多行内容垂直居中,
比如下面这种,想让div中的多行内容垂直居中,一看div中的文字是两行,每一行
的行高为20,加起来就是40,80-40=40,需要让文字距离顶部pading为20,底部padding为20
*/
height: 80px;
line-height: 20px;
padding-top: 20px;
padding-bottom: 20px;
box-sizing: border-box;
示范
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子居中和内容居中</title>
<style>
div {
width: 300px;
height: 300px;
background-color: red;
/*多行内容水平居中与单行一样*/
text-align: center;
/*多行内容垂直居中*/
line-height: 30px;
padding-top: 120px;
box-sizing: border-box;
}
</style>
</head>
<body>
<div>
我是文字我是文字我是文字我是文字我是文字我是文字我是文字
</div>
</body>
</html>
盒子居中
text-align center;只能让盒子中存储的文字、图片水平居中
如果想让盒子自己相对于父元素水平居中,需要用到
margin: 0 auto;
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子居中和内容居中</title>
<style>
.son {
width: 300px;
height: 300px;
background-color: red;
/*多行内容水平居中与单行一样*/
text-align: center;
/*多行内容垂直居中*/
line-height: 30px;
padding-top: 120px;
box-sizing: border-box;
/*盒子本身水平居中*/
margin: 0 auto;
}
.father {
width: 500px;
height: 500px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="father">
<div class="son">
我是文字我是文字我是文字我是文字我是文字我是文字我是文字
</div>
</div>
</body>
</html>
# 6、防止文字溢出 word-break: break-all;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>欢迎界面</title>
<style type="text/css">
div {
width: 200px;
height: 200px;
/*字母、数字溢出,可以用下列属性控制自动换行:允许在单词内换行。
http://www.w3school.com.cn/cssref/pr_word-break.asp
*/
word-break: break-all;
}
.box1 {
background-color: red;
}
.box2 {
background-color: green;
}
.box3 {
background-color: blue;
}
</style>
</head>
<body>
<div class="box1">
<p>asdfasdfsadfasdfasdfasdfad sfasdfsadasDSfafsafaasdfasdfasfdqwerqwerwqersdfqerwrsdf你好我的啊啊啊啊啊啊啊啊啊啊啊啊</p>
</div>
<div class="box2">遗憾白鹭上青天两个黄鹂鸣翠柳啊哈哈哈
</div>
<div class="box3">我是12312312312312312312312312312312312312312312312312312312312我
</div>
</body>
</html>
# 7、清除默认边距
#1、为什么要清空默认边距(外边距和内边距)
浏览器会自动附加边距,在企业开发中为了更好的控制盒子的宽高和计算盒子的宽高等等
编写代码之前的第一件事情就是清空默认的边距,不同的浏览器可能默认的边距大小不太一样。
#2、如何清空默认的边距
* {
margin: 0px;
padding: 0px;
}
#3、注意点:
通配符选择器会找到(遍历)当前界面中所有的标签,所以性能不好,参考:https://yuilibrary.com/yui/docs/cssreset/
拷贝代码:
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0}
可以查看京东,bat主页也是这么做的,在企业开发中也应该像上面这么写
示范
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>清除默认边距</title>
<style>
/*
* {
margin: 0px;
padding: 0px;
}
*/
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0}
.box1 {
width: 100px;
height: 100px;
background-color: green;
}
.box2 {
width: 100px;
height: 100px;
background-color: yellow;
}
.box3 {
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</body>
</html>
|
df81af32b32343b6e20ddddd57e80bdb0b6bb971 | cuitianfeng/Python | /python3基础/9.Python修炼第九层/并发编程/2 开启子进程的两种方式-multiprocessing模块.py | 5,330 | 3.703125 | 4 | \一 multiprocessing模块介绍
python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程。Python提供了multiprocessing。
multiprocessing模块用来开启子进程,并在子进程中执行我们定制的任务(比如函数),该模块与多线程模块threading的编程接口类似。
multiprocessing模块的功能众多:支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。
需要再次强调的一点是:与线程不同,进程没有任何共享状态,进程修改的数据,改动仅限于该进程内。
\二 Process类的介绍
# 创建进程的类:
Process([group [, target [, name [, args [, kwargs]]]]]),由该类实例化得到的对象,表示一个子进程中的任务(尚未启动)
强调:
1. 需要使用关键字的方式来指定参数
2. args指定的为传给target函数的位置参数,是一个元组形式,必须有逗号
# 参数介绍:
group参数未使用,值始终为None
target表示调用对象,即子进程要执行的任务
args表示调用对象的位置参数元组,args=(1,2,'egon',)
kwargs表示调用对象的字典,kwargs={'name':'egon','age':18}
name为子进程的名称
# 方法介绍:
p.start():启动进程,并调用该子进程中的p.run()
p.run():进程启动时运行的方法,正是它去调用target指定的函数,我们自定义类的类中一定要实现该方法
p.terminate():强制终止进程p,不会进行任何清理操作,如果p创建了子进程,该子进程就成了僵尸进程,使用该方法需要特别小心这种情况。如果p还保存了一个锁那么也将不会被释放,进而导致死锁
p.is_alive():如果p仍然运行,返回True
p.join([timeout]):主线程等待p终止(强调:是主线程处于等的状态,而p是处于运行的状态)。timeout是可选的超时时间,需要强调的是,p.join只能join住start开启的进程,而不能join住run开启的进程
# 属性介绍:
p.daemon:默认值为False,如果设为True,代表p为后台运行的守护进程,当p的父进程终止时,p也随之终止,并且设定为True后,p不能创建自己的新进程,必须在p.start()之前设置
p.name:进程的名称
p.pid:进程的pid
p.exitcode:进程在运行时为None、如果为–N,表示被信号N结束(了解即可)
p.authkey:进程的身份验证键,默认是由os.urandom()随机生成的32字符的字符串。这个键的用途是为涉及网络连接的底层进程间通信提供安全性,这类连接只有在具有相同的身份验证键时才能成功(了解即可)
\开启进程的两种方式
##开启进程的方式一: 使用函数
from multiprocessing import Process # Process 的P是大写的
import time,random
def piao(name):
print('%s is piaoing' %name)
time.sleep(random.randint(1,3))
print('%s is over' % name)
if __name__ == '__main__':
# p=Process(target=piao,kwargs={'name':'alex'}) # 这个方式是按照位置传
p=Process(target=piao,args=('alex',)) #必须加,号
p.start() #仅仅只是向操作系统发送了一个创建子进程p的信号,主进程并不会在这里等待子进程执行完再执行下面的代码,等子进程都执行完了主进程才结束。
print('主')
'''
主
alex is piaoing
alex is over
'''
import time
import random
from multiprocessing import Process
def piao(name):
print('%s piaoing' %name)
time.sleep(random.randrange(1,5))
print('%s piao end' %name)
p1=Process(target=piao,args=('egon',)) #必须加,号
p2=Process(target=piao,args=('alex',))
p3=Process(target=piao,args=('wupeqi',))
p4=Process(target=piao,args=('yuanhao',))
p1.start()# 并不是谁先start就是谁先执行,这只是提交给操作系统一个请求。由操作系统决定。
p2.start()
p3.start()
p4.start()
print('主线程')
##开启进程的方式二: 使用类
from multiprocessing import Process
import time,random
class MyProcess(Process):
def __init__(self,name): # 如果使用MyProcess类实例化时要传参数就需要实现__init__方法
super(MyProcess,self).__init__() # 需要将父类的__init__带过来
self.name=name
def run(self): # 必须叫run
print('%s is piaoing' %self.name)
time.sleep(random.randint(1,3))
print('%s is over' % self.name)
if __name__ == '__main__':
p=MyProcess('P1')
p.start() # 仅仅只是向操作系统发送了一个创建子进程p的信号、start会自动调用run
print('主')
'''
主
P1 is piaoing
P1 is over
'''
import time
import random
from multiprocessing import Process
class Piao(Process):
def __init__(self,name):
super().__init__()
self.name=name
def run(self):
print('%s piaoing' %self.name)
time.sleep(random.randrange(1,5))
print('%s piao end' %self.name)
p1=Piao('egon')
p2=Piao('alex')
p3=Piao('wupeiqi')
p4=Piao('yuanhao')
p1.start() #start会自动调用run
p2.start()
p3.start()
p4.start()
print('主线程') |
19e67b26e33be4b1b1ee557c3c9cb8043c251ecd | cuitianfeng/Python | /python3基础/5.Python修炼第五层/day5预习/协程函数.py | 2,905 | 4.28125 | 4 | #yield:
#1:把函数的执行结果封装好__iter__和__next__,即得到一个迭代器
#2:与ruturn功能类似,都可以返回值,
# 但不同的是,return只能返回一次值,而yield可以返回多次值
#3:函数暂停与再继续运行的状态是有yield保存
# def func(count):
# print('start')
# while True:
# yield count
# count+=1
#
# g=func(10)
# # print(g)
# print(next(g))
# print(next(g))
# # next(g)
#yield的表达式形式的应用
# def eater(name):
# print('%s 说:我开动啦' %name)
# while True:
# food=yield
# print('%s eat %s' %(name,food))
#
# alex_g=eater('alex')
# # print(alex_g)
# # next(alex_g)
# print(next(alex_g))
# print('==========>')
# next(alex_g)
# # 用法
# def eater(name):
# print('%s 说:我开动啦' %name)
# food_list=[]
# while True:
# food=yield food_list
# food_list.append(food) #['骨头','菜汤']
# print('%s eat %s' %(name,food))
#
# alex_g=eater('alex')
#
# #第一阶段:初始化
# next(alex_g) #等同于alex_g.send(None)
# print('========>')
#
# #第二阶段:给yield传值
# print(alex_g.send('骨头')) #1 先给当前暂停位置的yield传骨头 2 继续往下执行 ,直到再次碰到yield,然后暂停并且把yield后的返回值当做本次调用的返回值
# # print('========>')
# print(alex_g.send('菜汤'))
# print(alex_g.send('狗肉包子'))
# # 函数上下切换运行
# def eater(name):
# print('%s 说:我开动啦' %name)
# food_list=[]
# while True:
# food=yield food_list
# food_list.append(food) #['骨头','菜汤']
# print('%s eat %s' %(name,food))
#
# def producer():
# alex_g=eater('alex')
# #第一阶段:初始化
# next(alex_g) #等同于alex_g.send(None)
# #第二阶段:给yield传值
# while True:
# food=input('>>: ').strip()
# if not food:continue
# print(alex_g.send(food))
#
# producer()
#解决初始化问题
def init(func):
def wrapper(*rags,**kwargs):
g=func(*rags,**kwargs)
next(g)
return g
return wrapper
@init
def eater(name):
print('%s 说:我开动啦' %name)
food_list=[]
while True:
food=yield food_list
food_list.append(food) #['骨头','菜汤']
print('%s eat %s' %(name,food))
alex_g=eater('alex')
#第一阶段:初始化 用init装饰器实现 就无需再next
# next(alex_g) #等同于alex_g.send(None)
print('========>')
#第二阶段:给yield传值
print(alex_g.send('骨头')) #1 先给当前暂停位置的yield传骨头 2 继续往下执行 ,直到再次碰到yield,然后暂停并且把yield后的返回值当做本次调用的返回值
# print('========>')
|
ec69318657265193042b1440bed891bbd0aa0b20 | cuitianfeng/Python | /python3基础/3.Python修炼第三层/16 名称空间与作用域.py | 5,912 | 4.09375 | 4 | \一、什么是名称空间?
# 名称空间:存放名字的地方,三种名称空间,(之前遗留的问题x=1,1存放于内存中,那名字x存放在哪里呢?名称空间正是存放名字x与1绑定关系的地方)
'''
名称空间:存放名字与值绑定关系的地方
内置名称空间:
存放的是:内置的名字与值的绑定关系(print、len)
生效:python解释器启动
失效:Python解释器关闭
全局名称空间
存放的是:py文件级别定义的名字与值的绑定(变量)
生效:执行python文件时,将该文件级别定义的名字与值的绑定关系存放起来
失效:文件执行完毕
局部名称空间
存放的是:函数内部定义的名字与值的绑定关系
生效:调用函数时,临时生效
失效:函数调用结束
'''
\二、名称空间的加载顺序
'''
加载顺序:先内置名称空间 --> 再全局名称空间 --> 最后局部名称空间
python test.py
#1、python解释器先启动,因而首先加载的是:内置名称空间
#2、执行test.py文件,然后以文件为基础,加载全局名称空间
#3、在执行文件的过程中如果调用函数,则临时产生局部名称空间
'''
\三、名字的查找顺序
'''
查找名字的顺序:先局部名称空间 --> 再全局名称空间 --> 最后内置名称空间
'''
# 需要注意的是:在全局无法查看局部的,在局部可以查看全局的,如下示例
# max=1
def f1():
# max=2
def f2():
# max=3
print(max) # 局部虽然可以读到全局的max变量,但是如果要想修改需要在局部作用域中使用global max声明为全局变量。
f2()
f1()
print(max)
\四、作用域
# 1、作用域即范围
# - 全局作用域范围(包含内置名称空间与全局名称空间属于该范围):全局存活,全局有效。
# - 局部作用域范围(包含局部名称空间属于该范围):临时存活,局部有效。
# 2、作用域关系是在函数定义阶段就已经固定的,与函数的调用位置无关,如下
x=1
def f1():
def f2():
print(x)
return f2
x=100
def f3(func):
x=2
func()
x=10000
f3(f1())
\查看作用域:globals(),locals()
LEGB # 代表名字查找顺序: locals -> enclosing function -> globals -> __builtins__
locals() # 是函数内的名字空间,包括局部变量和形参
enclosing # 外部嵌套函数的名字空间(闭包中常见)f3上层的f2那层的名字空间
globals() # 全局变量,函数定义所在模块的名字空间
builtins # 内置模块的名字空间
作用域关系,在函数定义时就已经固定
于调用位置无关,在调用函数时,必须必须必须
回到函数原来的定义的位置去找作用域关系
\global与locals关键字
x=1011111111111111111111111111111111111111111
def f1(a):
y='fffffffffffffffffffffffffffffff1'
print(locals()) # 查看局部作用域中的名字,a也是f1的locals中的名字
print(globals()) # 查看全局作用域中的名字
print(locals())
print(globals())
print(dir(globals()['__builtins__'])) # dir可以查看内部名称空间的名字
print(locals() is globals())
f1(12321312312312312312312312312312312312313213)
'''
#作用域关系,在函数定义时,就已经固定了,与调用位置无关
'''
x=10000000000000000000000000
def f1():
print(x)
def f2():
# x='123123123123123123123123123123123'
print(x)
return f2 # 通过将f2函数返回,可以跨层级调用函数。
f=f1()
# print(f) # 可以看到是f1内部的f2,f()调用的是f1内部的f2函数
def func():
x=123
f() # 在这里调f函数要到f函数定义的位置的层级关系中去找x的值。
x='hello' # 在func之前修改x的值f2中的x就是hello,因为f2是f1中return的函数。而在f1中打印x还是全局的x的值
func()
\闭包函数:
#1. 定义在函数内部的函数
#2. 包含对外部作用域名字的引用,而不是对全局作用域名字的引用,那么该内部函数就称为闭包函数.
闭包函数 了解
global与nonlocal关键字
什么是闭包
#内部函数包含对外部作用域而非全局作用域的引用
#提示:之前我们都是通过参数将外部的值传给函数,闭包提供了另外一种思路,包起来喽,包起呦,包起来哇
def counter():
n=0
def incr():
nonlocal n
x=n
n+=1
return x
return incr
c=counter()
print(c())
print(c())
print(c())
print(c.__closure__[0].cell_contents) #查看闭包的元素
闭包的意义与应用
#闭包的意义:返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域
#应用领域:延迟计算(原来我们是传参,现在我们是包起来)
from urllib.request import urlopen
def index(url):
def get():
return urlopen(url).read()
return get
baidu=index('http://www.baidu.com')
print(baidu().decode('utf-8'))
\global、nonlocal关键字
# 互相不冲突 1是全局 10是局部
x=1
def f1():
x=10
f1()
print(x) # 1
# global声明全局: 指定局部变量,为全局变量.
x=1
def f1():
global x
x=10
f1()
print(x) # 10
# nonlocal会在本函数里面找往上层找变量,一层一层找,如果函数内部所有层级都没有找到 就报错。但不会去全局找。
x=1
def f1():
x=2 # nonlocal改的是这样的x,在函数内部一层一层找。
def f2():
nonlocal x
x=111111
f2()
print(x)
f1()
|
79871a2b3fe9035e06b2009eafaaddbf2ca487ab | cuitianfeng/Python | /python3基础/5.Python修炼第五层/2 二分法.py | 2,419 | 4.09375 | 4 | \想从一个按照从小到大排列的数字列表中找到指定的数字,遍历的效率太低,用二分法(算法的一种,算法是解决问题的方法)可以极大缩小问题规模.
# 用二分法实现类似in的效果
l=[1,2,10,30,33,99,101,200,301,402] #从小到大排列的数字列表,如果不是从小到大排序的可以先用sorted()排序。
# 用for循环遍历,需要一个一个匹配。运气好第一个值就找到了,运气不好可能遍历到最后一个值才能匹配到。效率低。
num=200
for item in l:
if num == item:
print('find it')
break
# 用二分法,将列表一分为二后判断是在左边还是右边,再进行判断
def get(num,l):
print(l)
if len(l) > 0: # 列表不为空,则证明还有值是可以执行二分法逻辑的
mid=len(l)//2
if num > l[mid]: # 判断num如果在右边,mid当索引使用
l=l[mid+1:] # 将列表一切为二,+1是为了不算mid这个值。因为mid这个值已经比较过了。
elif num < l[mid]: # 判断num如果在左边
l=l[:mid] # 每次切完重新赋值给l
else:
print('find it')
return # 找到后结束
get(num,l) # 没有找到继续递归查找,将if和elif中都要执行的get提出来写一份。避免重复代码
else: #列表为空,则证明根本不存在要查找的值
print('not exists')
return
get(200,l)
'''
[1, 2, 10, 30, 33, 99, 101, 200, 301, 402]
[101, 200, 301, 402]
[101, 200]
find it
'''
# 实现类似于l.index(30)的效果,输出值的索引。
l=[1,2,10,30,33,99,101,200,301,402]
def search(num,l,start=0,stop=len(l)-1):
if start <= stop:
mid=start+(stop-start)//2
print('start:[%s] stop:[%s] mid:[%s] mid_val:[%s]' %(start,stop,mid,l[mid]))
if num > l[mid]:
start=mid+1
elif num < l[mid]:
stop=mid-1
else:
print('find it',mid)
return
search(num,l,start,stop)
else: #如果stop > start则意味着列表实际上已经全部切完,即切为空
print('not exists')
return
search(301,l)
'''
start:[0] stop:[9] mid:[4] mid_val:[33]
start:[5] stop:[9] mid:[7] mid_val:[200]
start:[8] stop:[9] mid:[8] mid_val:[301]
find it 8
''' |
bf0fd02e8dbbeb89d79aa91ae567725d0cf211af | cuitianfeng/Python | /python3基础/1.Python修炼第一层/5 运算符.py | 5,954 | 3.8125 | 4 | 计算机可以进行的运算有很多种,可不只加减乘除这么简单,运算按种类可分为:
1、算数运算、
2、比较运算、
3、逻辑运算、
4、赋值运算、
5、成员运算、
6、身份运算、
7、位运算,
8、运算符优先级
\算数运算
以下假设变量:a=10,b=20
#运算符 描述 实例
+ 加 - 两个对象相加 a + b输出结果30
- 减 - 得到负数或是一个数减去另一个数 a - b输出结果-10
* 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b输出结果200
/ 除 - x除以y a / b输出结果2
% 取模 - 返回除法的余数 a % b输出结果0
** 幂等 - 返回x的y次方 a ** b为10的20次方,输出结果100000000000000000...
// 取整数 - 返回商的整数部分 9//2 输出结果4,9.0//2.0输出结果4.0
# a=100
# b=31
# res=a+b
# print(a+b)
# print(a-b)
# print(a*b)
# print(a/b) #真正的除法,有整数,有小数
# print(a//b) #地板除,只取整数部分
# a=10
# b=3
# print(a%b) #取模,返回除法的余数
# print(3**2)
‘’‘
131
69
3100
3.225806451612903
3
1
9
’‘’
\比较运算
以下假设变量:x=10,y=20
#运算符 描述 实例
== 等于 - 比较对象是否相等。 (x == y)返回False
!= 不等于 - 比较两个对象是否不相等。 (x != y)返回True
<> 不等于 - 比较两个对象是否不相等。 (x <> y)返回True。这个运算符类似!=。
> 大于 - 返回x是否大于y。 (x > y)返回False。
< 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的 (x < y) 返回True。
变量True和False等价。注意,这些变量名的大些。
>= 大于等于 - 返回x是否大于等于y。 (x >= y)返回False.
<= 小于等于 - 返回x是否小于等于y。 (x <= b)返回true。
# age=73
# print(age > 30)
# print(age < 30)
# print(age != 30)
# print(age != 73)
# print(age == 73)
\赋值运算
以下假设变量:a=10,b=20
#运算符 描述 实例
= 简单的赋值运算符 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
//= 取整法赋值运算符 c//=a 等效于 c=c//a
# height=180
# height+=1 #height=height+1
# print(height)
\逻辑运算
#运算符 描述 实例
and 布尔“与” - 如果x为False,x and y返回False,否则它返回y的计算值。 (a and b)都为真才返回True
or 布尔“或” - 如果x为True,它返回True。否则它返回y的计算值。 (a or b)有一个为真就返回True
not 布尔“非” - 如果x为True,它返回False。如果x为False,它返回True。取反 not(a and b)返回False
# age=11
# name='egon'
# print(age > 10 and name == 'ego111111n')
# print(age > 10 or name == 'ego111111n')
# print(not age >10) # 将结果取反
\身份运算(判断id)
# 运算符 描述 实例
is is 是判断两个标识符是不是引用自一个对象。 x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False
is not is not 是判断两个标识符是不是引用自不同对象。 x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。
#is比较的是id,而==比较的是值。
>>> x=1234567890
>>> y=1234567890
>>> id(x)
140206023973008
>>> id(y)
140206023972960
if x is y:
print('id不同')
if x == y:
print('值相同') # id不同,值可以相同。id如果相同值肯定相同。
\成员运算
# 运算符 描述 实例
in 如果在指定的序列中找到值返回 True,否则返回 False。 x 在 y 序列中 , 如果 x 在 y 序列中返回 True。
not in 如果在指定的序列中没有找到值返回 True,否则返回 False。 x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。
\运算符优先级
以下表格列出了从最高到最低优先级的所有运算符:
# 运算符 描述
** # 指数 (最高优先级)
~ + - # 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
* / % // # 乘,除,取模和取整除
+ - # 加法减法
>> << # 右移,左移运算符
& # 位 'AND'
^ | # 位运算符
<= < > >= # 比较运算符
<> == != # 等于运算符
= %= /= //= -= += *= **= # 赋值运算符
is is not # 身份运算符
in not in # 成员运算符
and or not # 逻辑运算符
python基础之数据类型与变量:https://www.cnblogs.com/linhaifeng/articles/5935801.html#_label34 |
5e8c566261b4ed1c36c030c0cfef53f0092d4c20 | cuitianfeng/Python | /python3基础/8.Python修炼第八层/面向对象/5.封装(使用双下划线定义私有属性).py | 7,656 | 4.1875 | 4 | \一 引子
# 从封装本身的意思去理解,封装就好像是拿来一个麻袋,把小猫,小狗,小王八,还有alex一起装进麻袋,然后把麻袋封上口子。照这种逻辑看,封装=‘隐藏’,这种理解是相当片面的
\二 先看如何隐藏
# 在python中用双下划线开头的方式将属性隐藏起来(设置成私有的)
# 先看如何隐藏 __开头
# 其实这仅仅这是一种变形操作且仅仅只在类定义阶段发生变形
# 类中所有双下划线开头的名称如__x都会在类定义时自动变形成:_类名__x的形式:
class A:
__N=0 # 类的数据属性就应该是共享的,但是语法上是可以把类的数据属性设置成私有的如__N,会变形为_A__N
def __init__(self):
self.__X=10 # 变形为self._A__X
def __foo(self): # 变形为_A__foo
print('from A')
def bar(self):
self.__foo() # 只有在类内部才可以通过__foo的形式访问到.
print(A._A__N) # 0 A._A__N是可以访问到的,但是不合规。
# 这种,在外部是无法通过__x这个名字访问到。为什么呢?看下面,在类中定义时带双下划线的属性都加了 _类名__属性
print(A.__dict__) # {'__module__': '__main__', '_A__N': 0, '__init__': <function A.__init__ at 0x106d32ae8>, '_A__foo': <function A.__foo at 0x106d56158>, 'bar': <function A.bar at 0x106d561e0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
obj=A()
obj.bar() # from A
# 在类内定义,在类外不让使用。那定义有什么用呢?
class Goods:
__DISCONT = 0.8 # 加了双下划线就被定义成了一个私有的属性
def __init__(self,org_price):
self.price = org_price * Goods.__DISCONT # 在内部就使用了
apple = Goods(10)
print(apple.price) # 8.0
\在继承中,父类如果不想让子类覆盖自己的方法,可以将方法定义为私有的
#正常情况
>>> class A:
... def fa(self):
... print('from A')
... def test(self):
... self.fa()
...
>>> class B(A):
... def fa(self):
... print('from B')
...
>>> b=B()
>>> b.test()
from B
#把fa定义成私有的,即__fa
>>> class A:
... def __fa(self): #在定义时就变形为_A__fa
... print('from A')
... def test(self):
... self.__fa() #只会与自己所在的类为准,即调用_A__fa
...
>>> class B(A):
... def __fa(self):
... print('from B')
...
>>> b=B()
>>> b.test()
from A
#在子类定义的__x不会覆盖在父类定义的__x,因为子类中变形成了:_子类名__x,而父类中变形成了:_父类名__x,即双下滑线开头的属性在继承给子类时,子类是无法覆盖的。
class Foo:
def __f1(self): #_Foo__f1
print('Foo.f1')
def f2(self):
self.__f1() #self._Foo_f1
class Bar(Foo):
def __f1(self): #_Bar__f1
print('Bar.f1')
# b=Bar()
# b.f2()
\封装不是单纯意义的隐藏
封装的真谛在于明确地区分内外,封装的属性可以直接在内部使用,而不能被外部直接使用,然而定义属性的目的终归是要用,外部要想用类隐藏的属性,需要我们为其开辟接口,
让外部能够间接地用到我们隐藏起来的属性,那这么做的意义何在???
# 1:封装数据:将数据隐藏起来这不是目的。隐藏起来然后对外提供操作该数据的接口,然后我们可以在接口附加上对该数据操作的限制,以此完成对数据属性操作的严格控制。
class Teacher:
def __init__(self,name,age):
# self.__name=name
# self.__age=age
self.set_info(name,age)
def tell_info(self):
print('姓名:%s,年龄:%s' %(self.__name,self.__age))
def set_info(self,name,age):
if not isinstance(name,str):
raise TypeError('姓名必须是字符串类型')
if not isinstance(age,int):
raise TypeError('年龄必须是整型')
self.__name=name
self.__age=age
t=Teacher('egon',18)
t.tell_info()
t.set_info('egon',19)
t.tell_info()
# 2:封装函数属性:为了隔离复杂度
封装方法举例:
1. 你的身体没有一处不体现着封装的概念:你的身体把膀胱尿道等等这些尿的功能隐藏了起来,然后为你提供一个尿的接口就可以了(接口就是你的。。。,),你总不能把膀胱挂在身体外面,上厕所的时候就跟别人炫耀:hi,man,你瞅我的膀胱,看看我是怎么尿的。
2. 电视机本身是一个黑盒子,隐藏了所有细节,但是一定会对外提供了一堆按钮,这些按钮也正是接口的概念,所以说,封装并不是单纯意义的隐藏!!!
3. 快门就是傻瓜相机为傻瓜们提供的方法,该方法将内部复杂的照相功能都隐藏起来了
提示:在编程语言里,对外提供的接口(接口可理解为了一个入口),可以是函数,称为接口函数,这与接口的概念还不一样,接口代表一组接口函数的集合体。
#取款是功能,而这个功能有很多功能组成:插卡、密码认证、输入金额、打印账单、取钱
#对使用者来说,只需要知道取款这个功能即可,其余功能我们都可以隐藏起来,很明显这么做
#隔离了复杂度,同时也提升了安全性
class ATM:
def __card(self):
print('插卡')
def __auth(self):
print('用户认证')
def __input(self):
print('输入取款金额')
def __print_bill(self):
print('打印账单')
def __take_money(self):
print('取款')
def withdraw(self):
self.__card()
self.__auth()
self.__input()
self.__print_bill()
self.__take_money()
a=ATM()
a.withdraw()
\封装与扩展性
封装在于明确区分内外,使得类实现者可以修改封装内的东西而不影响外部调用者的代码;而外部使用用者只知道一个接口(函数),只要接口(函数)名、参数不变,
使用者的代码永远无需改变。这就提供一个良好的合作基础——或者说,只要接口这个基础约定不变,则代码改变不足为虑。
#类的设计者
class Room:
def __init__(self,name,owner,width,length,high):
self.name=name
self.owner=owner
self.__width=width
self.__length=length
self.__high=high
def tell_area(self): # 对外提供的接口,隐藏了内部的实现细节,此时我们想求的是面积
return self.__width * self.__length
#使用者
>>> r1=Room('卧室','egon',20,20,20)
>>> r1.tell_area() # 使用者调用接口tell_area
#类的设计者,轻松的扩展了功能,而类的使用者完全不需要改变自己的代码
class Room:
def __init__(self,name,owner,width,length,high):
self.name=name
self.owner=owner
self.__width=width
self.__length=length
self.__high=high
def tell_area(self): # 对外提供的接口,隐藏内部实现,此时我们想求的是体积,内部逻辑变了,只需求修该下列一行就可以很简答的实现,而且外部调用感知不到,仍然使用该方法,但是功能已经变了
return self.__width * self.__length * self.__high
#对于仍然在使用tell_area接口的人来说,根本无需改动自己的代码,就可以用上新功能
>>> r1.tell_area() |
ab2a92334e225d22b3a78580ec47e1822ffcc659 | cuitianfeng/Python | /python3基础/6.Python修炼第六层/day6预习/排列组合.py | 536 | 3.765625 | 4 | #! /usr/bin/env python
# -*- coding=utf-8 -*-
import itertools
list1 = [1,2,3,4,5]
list2 = []
list3 = []
for i in range(1, len(list1) + 1):
iter = itertools.permutations(list1, i)
list2.append(list(iter))
list2=list2[-1]
# print(list2)
# print(list2[-1])
for item in list2:
# print(len(item))
if len(item) == 5:
# print(item)
list3.append(item)
# for item in list3:
# print(item)
print(len(list3))
# print(list3)
|
3e6f481e5c7951c58139ababacedc69370c031f8 | cuitianfeng/Python | /python3基础/2.Python修炼第二层/购物车.py | 6,435 | 3.78125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# 商城购物车
product_list = [
['Iphone7 Plus',6500],
['Iphone8 ',8200],
['MacBook Pro',12000],
['Python Book',99],
['Coffee',33],
['Bike',666],
['pen',2]
]
shopping_cart = []
f = open('user.txt','r')
lock_file = f.readlines()
f.close()
count=0
user_list={}
while True:
if count == 3:
print("用户名输入次数到达3次限制")
break
for i in lock_file:
i=i.strip()
user_list[i.split('|')[0]]={'password':i.split('|')[1]}
user_name=input("请输入您的用户名>>:")
if user_name not in user_list:
print("用户名错误")
count+=1
if user_name in lock_file:
print("用户名已锁定,请联系管理员!")
exit()
if user_name in user_list:
user_password=input("请输入您的密码>>: ")
if user_password == user_list[user_name]['password']:
print("欢迎登录电子商城")
while True:
salary = input("请输入您的工资:") # 输入金额
if not salary.isdigit(): # 判断输入的salary是不是数字
print("由于您的输入的工资不合法,请再次输入金额") # 输入金额不合法
continue
else:
salary = int(salary) # 把输入的数字转成整形
break
while True:
print(">> 欢迎来到电子商城 <<")
for index, i in enumerate(product_list): # 循环商品列表,商品列表索引
print("%s.\t%s\t%s" % (index, i[0], i[1])) # 打印商品列表,显示商品列表索引
choice = input(">>请输入商品序号或输入 exit 退出商城>>: ").strip()
if len(choice) == 0: # 判断输入字符串是否为空和字符串长度
print('-->您没有选择商品<--')
continue
if choice.isdigit(): # 判断输入的choice是不是一个数字
choice = int(choice) # 把输入的字符串转成整型
if choice < len(product_list) and choice >= 0: # 输入的整数必须小于商品列表的数量
product_item = product_list[choice] # 获取商品
if salary >= product_item[1]: # 拿现有金额跟商品对比,是否买得起
salary -= product_item[1] # 扣完商品的价格
shopping_cart.append(product_item) # 把选着的商品加入购物车
print("添加 \033[32;1m%s\033[0m 到购物车,您目前的金额是 \
\033[31;1m%s\033[0m" % (product_item[0], salary))
else:
print("对不起,您的金额不足,还差 \033[31;1m%s\033[0m" % (product_item[1] - salary,))
else:
print("-->没有此商品<--")
elif choice == "exit":
total_cost = 0
print("您的购物车列表:")
for i in shopping_cart:
print(i)
total_cost += i[1]
print("您的购物车总价是: \033[31;1m%s\033[0m" % (total_cost,))
print("您目前的余额是:\033[31;1m%s\033[0m" % (salary,))
break
break
else:
print("密码错误")
count += 1
if count == 3 :
print("您输入的密码错误次数已达3次,将锁定您的用户!")
f = open('blacklist.txt','w')
f.write('%s'%user_name)
f.close()
break
while True:
salary = input("请输入您的工资:") # 输入金额
if not salary.isdigit(): # 判断输入的salary是不是数字
print("由于您的输入的工资不合法,请再次输入金额") # 输入金额不合法
continue
else:
salary = int(salary) # 把输入的数字转成整形
break
while True:
print(">> 欢迎来到电子商城 <<")
for index, i in enumerate(product_list): # 循环商品列表,商品列表索引
print("%s.\t%s\t%s" % (index, i[0], i[1])) # 打印商品列表,显示商品列表索引
choice = input(">>请输入商品序号或输入 exit 退出商城>>: ").strip()
if len(choice) == 0: # 判断输入字符串是否为空和字符串长度
print('-->您没有选择商品<--')
continue
if choice.isdigit(): # 判断输入的choice是不是一个数字
choice = int(choice) # 把输入的字符串转成整型
if choice < len(product_list) and choice >= 0: # 输入的整数必须小于商品列表的数量
product_item = product_list[choice] # 获取商品
if salary >= product_item[1]: # 拿现有金额跟商品对比,是否买得起
salary -= product_item[1] # 扣完商品的价格
shopping_cart.append(product_item) # 把选着的商品加入购物车
print("添加 \033[32;1m%s\033[0m 到购物车,\
您目前的金额是 \033[31;1m%s\033[0m"%(product_item[0],salary))
else:
print("对不起,您的金额不足,还差 \033[31;1m%s\033[0m" % (product_item[1] - salary,))
else:
print("-->没有此商品<--")
elif choice == "exit":
total_cost = 0
print("您的购物车列表:")
for i in shopping_cart:
print(i)
total_cost += i[1]
print("您的购物车总价是: \033[31;1m%s\033[0m" % (total_cost,))
print("您目前的余额是: \033[31;1m%s\033[0m" % (salary,))
break
|
f982206eaf6bb62ad3f0ab9f605bbf604d682805 | cuitianfeng/Python | /python3基础/3.Python修炼第三层/13 函数的参数.py | 9,086 | 4.375 | 4 | \一、形参与实参
# 形参即变量名,实参即变量值,函数调用时,将值绑定到变量名上,函数调用结束,解除绑定。
# 形参:在函数定义阶段,括号内定义的参数的称为形参,就相当于变量名。分为:位置形参、默认参数
# 实参:在函数调用阶段,括号内定义的参数的称为实参,就相当于变量值。分为:位置实参、关键字实参
# 在调用阶段,实参的值会绑定给形参,在调用结束后,解除绑定
def foo(x,y): #x=1,y=2
print(x,y)
foo(1,2)
\参数的分类
\一: 位置参数
'''
位置参数:按照从左到右的顺序定义的参数
位置形参:必须被传值的参数,多一个不行,少一个也不行.
位置实参:从左到右依次赋值给形参.
'''
def foo(x,y):
print(x,y)
foo(1,2)
\二: 关键字参数
'''
无需按照位置为形参传值
在函数调用阶段,按照key=value的形式定义实参。可以不依赖位置而指名道姓地给形参传值。
需要注意的问题(可以与位置实参混用,但是):
1. 位置实参必须在关键字实参的前面
2. 不能为一个形参重传值
'''
def foo(x,y):
print(x,y)
foo(1,y=20) # 输出正常
def foo(x,y):
print(x,y)
foo(1,2,y=20) # 会报错,因为形参中只接受两个值却传了三个。
\三: 默认参数
'''
可以传值也可以不传值,经常需要变得参数定义成位置形参,变化较小的参数定义成默认参数(形参)
在定义函数阶段,已经为形参赋值了,在定义阶段已经赋值,意味着在调用阶段可以不传值。
注意的问题:
1 默认参数的值,在定义时就赋值了,调用时可传可不传。只在定义时赋值一次,只有调用时可以修改。
2 位置形参应该在默认参数的前面
3 默认参数的值应该是不可变类型,要写可变类型也可以。但是是个不好的编程习惯。
'''
def foo(x,y=10):
print(x,y)
foo(y=11,x=1) # 可以变换位置
def foo(x,y=10):
print(x,y)
foo(x=1,11) # python语法不支持给关键字形参直接传值,必须指名道姓。如:y=11
# 应用场景举例
def register(name,age,sex='male'):
print(name,age,sex)
register('egon',18)
register('wsb',18)
register('alex',38,'xxxxxx') # sex的值可传可不传,已经有默认值了。
# 默认参数的值,只在定义时赋值一次,再改也和它没关系了。
x='male'
def register(name,age,sex=x):
print(name,age,sex)
x='female'
register('alex',18) # x还是male
# 位置形参应该在默认参数的前面,下面语法会报错。
def register(name,sex='male',age):
print(name,age,sex)
\四:可变长参数
'''
实参可变长度指的是:实参值的个数是不固定的,而实参的定义形式无非两种:
1、位置实参
2、关键字实参,针对这两种形式的实参个数不固定。
相应的,形参也要有两种解决方案,即:
*:针对按照位置实参定义多出来的部分就被*处理了。
**:针对按照关键字定义的实参多出来的部分就被**处理了。
*和**即是*args,**kwargs,args和kwargs实际上可以是任意字符,只是约定俗成这样使用的。
'''
# 针对按照"位置"参数定义的溢出的那部分位置实参,形参:*args(叫什么无所谓,通常叫args)
def func(x,y,z,*args): # args=(4,5,6)
print(x,y,z)
print(args)
func(1,2,3) # 没有多出来的,args就没有值就是一个空元组。
func(1,2,3,4,5,6) # 多出来的456会被*处理成(4,5,6)元组后赋值给args。
'''
1 2 3
()
1 2 3
(4, 5, 6) # 多出来的4、5、6被*定义成元组的形式赋值给args=(4,5,6)
'''
func(1,2,3,*[4,5,6]) # 实参中只要出现*先打散成func(1,2,3,4,5,6)的形式
func(*[1,2,3,4,5,6]) # func(1,2,3,4,5,6)
func([1,2,3,4,5,6]) # func(1,2,3,4,5,6) # 不加*时这样就传了一个值,只有x有值,y和z没值会报错。
def func(x,y,z):
print(x,y,z)
l=[1,2,3]
func(*l) # 正好,不多不少。所以也不需要*args
# 针对按照"关键字"参数定义的溢出的那部分位置实参,形参:**kwargs
def foo(x,y,**kwargs): # kwargs={'a':1,'z':3,'b':2} 溢出部分**会接收过来的值放在字典里赋值给kwargs。
print(x,y)
print(kwargs)
foo(y=2,x=1,z=3,a=1,b=2)
'''
1 2
{'z': 3, 'a': 1, 'b': 2}
'''
foo(1,2,3,z=3,a=1,b=2) # 3没有地方放,会报错。可以在函数定义阶段再加个*agrs来接收益处的位置实参。
foo(y=1,x=2,**{'a':1,'b':2,'c':3}) # foo(x=2,y=1,c=3,b=2,a=1)
'''
2 1
{'a': 1, 'b': 2, 'c': 3}
'''
foo(**{'x':1,'a':1,'b':2,'c':3}) # foo(x=1,c=3,b=2,a=1),y没值会报错
def foo(x,y,z):
print(x,y,z)
dic={'x':1,'y':3,'z':1}
foo(**dic) # foo(x=1,y=3,z=1) ,字典里的key要符合函数接收的值。
'''
1 3 1
'''
# 装饰器时会用到这样的方法 *args **kwargs
def home(name,age,sex):
print('from home====>',name,age,sex)
def wrapper(*args,**kwargs): # 被*接收赋值给 args=(1,2,3,4,5,6,7),被**接收赋值给kwargs={'c':2,'b':2,'a':1}
home(*args,**kwargs) # 本质还是在调home函数
# home(*(1,2,3,4,5,6,7),**{'c':2,'b':2,'a':1}) # 上一行home(*args,**kwargs)翻译成
# home(1,2,3,4,5,6,7,a=1,b=2,c=3) # 从上一行可以看出在实参中出现了*和**,打散。
wrapper(1,2,3,4,5,6,7,a=1,b=2,c=3)
# 实际上就是把wrapper接收的所有参数原封不动的给home函数使用。执行会报错,传参时要遵循home函数的接参。
# 修改传参
def home(name,age,sex):
print('from home====>',name,age,sex)
def wrapper(*args,**kwargs): # args=(egon),kwargs={sex:'male',age:19},*args,**kwargs表示接收任意长度、任意形式的实参。
home(*args,**kwargs)
wrapper('egon',sex='male',age=19)
\五: 命名关键字参数(了解)
'''
# 形参中,在*后定义的参数称之为命名关键字参数,
# 它的特性是;传值时,必须被传值(有默认值的除外),且必须按照关键字实参的形式传递
'''
def foo(x,y,*,a,b): # *也可以不加args使用
print(x,y,a,b)
foo(1,2,b=3,a=4)
'''
1 2 4 3
'''
def foo(x,y,*args,a,b):
print(args)
print(x,y,a,b)
foo(1,2,3,4,5,b=3,a=4)
'''
(3, 4, 5)
1 2 4 3
'''
def foo(x,y=20,*args,a=1,b): # 有人会误认为位置形参跑到了关键字形参前面了,肯定得报错。但是这前面有*args,就意味这后面的都是命名关键字参数,只是有个默认值而已。
print(args)
print(x,y,a,b)
foo(1,2,3,4,5,b=3,a=4)
\传参顺序
# 位置参数,默认参数,*args,命名关键字参数,**kwargs
\练习题
1、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批量修改操作
2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表
#题目一
def modify_file(filename,old,new):
import os
with open(filename,'r',encoding='utf-8') as read_f,\
open('.bak.swap','w',encoding='utf-8') as write_f:
for line in read_f:
if old in line:
line=line.replace(old,new)
write_f.write(line)
os.remove(filename)
os.rename('.bak.swap',filename)
modify_file('/Users/jieli/PycharmProjects/爬虫/a.txt','alex','SB')
#题目二
def check_str(msg):
res={
'num':0,
'string':0,
'space':0,
'other':0,
}
for s in msg:
if s.isdigit():
res['num']+=1
elif s.isalpha():
res['string']+=1
elif s.isspace():
res['space']+=1
else:
res['other']+=1
return res
res=check_str('hello name:aSB passowrd:alex3714')
print(res)
#题目三:略
#题目四
def func1(seq):
if len(seq) > 2:
seq=seq[0:2]
return seq
print(func1([1,2,3,4]))
#题目五
def func2(seq):
return seq[::2]
print(func2([1,2,3,4,5,6,7]))
#题目六
def func3(dic):
d={}
for k,v in dic.items():
if len(v) > 2:
d[k]=v[0:2]
return d
print(func3({'k1':'abcdef','k2':[1,2,3,4],'k3':('a','b','c')}))
|
18fb7594dc397e443832e5a6fd20b271c5fd47ff | cuitianfeng/Python | /python3基础/6.Python修炼第六层/17 struct模块(字符串之间进行转换).py | 941 | 3.703125 | 4 | struct是python(包括版本2和3)中的内建模块,它用来在c语言中的结构体与python中的字符串之间进行转换,数据一般来自文件或者网络。
\struct模块中的函数
函数 return explain
pack(fmt,v1,v2…) string 按照给定的格式(fmt),把数据转换成字符串(字节流),并将该字符串返回.
pack_into(fmt,buffer,offset,v1,v2…) None 按照给定的格式(fmt),将数据转换成字符串(字节流),并将字节流写入以offset开始的buffer中.(buffer为可写的缓冲区,可用array模块)
unpack(fmt,v1,v2…..) tuple 按照给定的格式(fmt)解析字节流,并返回解析结果。
pack_from(fmt,buffer,offset) tuple 按照给定的格式(fmt)解析以offset开始的缓冲区,并返回解析结果
calcsize(fmt) size of fmt 计算给定的格式(fmt)占用多少字节的内存,注意对齐方式
|
31d10e54472af151269c56b3a31599633503948d | cuitianfeng/Python | /python3基础/1.Python修炼第一层/4 格式化输出.py | 9,024 | 4.125 | 4 | 程序中经常会有这样场景:要求用户输入信息,然后打印成固定的格式.
比如要求用户输入用户名和年龄,然后打印如下格式:
My name is xxx,my age is xxx.
很明显,用逗号进行字符串拼接,只能把用户输入的名字和年龄放到末尾,无法放到指定的xxx位置,而且数字也必须经过str(数字)的转换才能与字符串进行拼接。
\这就用到了占位符,如:
%% 百分号标记
%c 字符及其ASCII码
%s 字符串
%d 有符号整数(十进制)
%u 无符号整数(十进制)
%o 无符号整数(八进制)
%x 无符号整数(十六进制)
%X 无符号整数(十六进制大写字符)
%e 浮点数字(科学计数法)
%E 浮点数字(科学计数法,用E代替e)
%f 浮点数字(用小数点符号)
%g 浮点数字(根据值的大小采用%e或%f)
%G 浮点数字(类似于%g)
%p 指针(用十六进制打印值的内存地址)
%n 存储输出字符的数量放进参数列表的下一个变量中
参考文档: https://www.cnblogs.com/fat39/p/7159881.html
\方法1: %-formatting
# %s字符串占位符:可以接收字符串,也可接收数字
print('My name is %s,my age is %s' %('egon',18))
# %d数字占位符:只能接收数字
print('My name is %s,my age is %d' %('egon',18))
print('My name is %s,my age is %d' %('egon','18')) #报错
#接收用户输入,打印成指定格式
name=input('your name: ')
age=input('your age: ') #用户输入18,会存成字符串18,无法传给%d
print('My name is %s,my age is %s' %(name,age))
print('My name is %s,my age is %d' %(name,int(age)))
#注意:
#print('My name is %s,my age is %d' %(name,age)) #age为字符串类型,无法传给%d,所以会报错
# 也支持字典的形式
print('User[%(id)s]: %(name)s' %{'id': 123,'name': 'xiaoming'})
Out: 'User[123]: xiaoming'
# 打印整数
print("I am %d years old." %(25))
'''
I am 25 years old.
'''
# 打印浮点数(指定保留两位小数)
print ("His height is %.2f m"%(1.70))
'''
His height is 1.70 m
'''
# 指定占位符宽度
print ("Name:%10s Age:%8d Height:%8.2f"%("Alfred",25,1.70))
'''
Name: Alfred Age: 25 Height: 1.70
'''
# 指定占位符宽度(左对齐)
print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Alfred",25,1.70))
'''
Name:Alfred Age:25 Height:1.70
'''
# %s
# %10s——右对齐,占位符10位
# %-10s——左对齐,占位符10位
# %.2s——截取2位字符串
# %10.2s——10位占位符,截取两位字符串
print('%s' % 'hello world') # 字符串输出
print('%20s' % 'hello world') # 右对齐,宽度20位,不够则用空格补位
print('%-20s' % 'hello world') # 左对齐,宽度20位,不够则用空格补位,hello world ,前面有很多空格
print('[%-20s]' % 'hello world') # [hello world ]
print('%.2s' % 'hello world') # 取2位
print('%10.2s' % 'hello world') # 右对齐,取2位
print('%-10.2s' % 'hello world') # 左对齐,取2位
总结:
# 这种用法一直到现在仍然被使广泛使用,但是其实它是一种不被提倡使用的语法(我初Python学习时,就提过)。主要是当要格式化的参数很多时,
# 可读性很差,还容易出错(数错占位符的数量),也不灵活,举个例子,name这个变量要在格式化时用2次,就要传入2次。
\方法2: str-format
# 从 Python 2.6开始,新增了一种格式化字符串的函数 str.format(),基本语法是通过 {}和: 来代替以前的 %。format函数支持通过位置、关键字、对象属性和下标等多种方式使用,
# 不仅参数可以不按顺序,也可以不用参数或者一个参数使用多次。并且可以通过对要转换为字符串的对象的 __format __方法进行扩展。
通过{}来代替:
In: name ='Xiaoming'
In: 'Hello {}'.format(name)
Out: 'Hello Xiaoming'
通过位置访问:
In: '{0},{1},{2}'.format('a','b','c')
Out: 'a,b,c'
In: '{2},{1},{0}'.format('a','b','c')
Out: 'c,b,a'
In: '{1},{1},{0}'.format('a','b','c')
Out: 'b, b, a'
通过关键字访问:
In: 'Hello {name}'.format(name='Xiaoming')
Out: 'Hello Xiaoming'
通过对象属性访问:
class Person():
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return 'my name is {self.name},age is {self.age} years old'.format(self=self)
print(Person('xiaodeng',28)) # my name is xiaodeng,age is 28 old
通过下标访问:
In: coord = (3, 5)
In: 'X: {0[0]};Y:{0[1]}'.format(coord)
Out: 'X: 3;Y: 5
# 左中右对齐及位数补全
(1)< (默认)左对齐、
> 右对齐、
^ 中间对齐、
= (只用于数字)在小数点后进行补齐
(2)取位数“{:4s}”、"{:.2f}"等
print('{} and {}'.format('hello','world')) # 默认左对齐
hello and world
print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左对齐,取10位右对齐
hello and world
print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中间对齐
hello and world
print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
1.123 is 1.12
print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位
1.123 is 1.12
>>> '{:<30}'.format('left aligned') # 左对齐
'left aligned '
>>> '{:>30}'.format('right aligned') # 右对齐
' right aligned'
>>> '{:^30}'.format('centered') # 中间对齐
' centered '
>>> '{:*^30}'.format('centered') # 使用“*”填充
'***********centered***********'
>>>'{:0=30}'.format(11) # 还有“=”只能应用于数字,这种方法可用“>”代替
'000000000000000000000000000011'
总结:
# 可以感受到format函数极大的扩展了格式化功能。但是当处理多个参数和更长的字符串时,str.format() 的内容仍然可能非常冗长,除了定义参数变量,需要把这些变量写进format方法里面。
\方法3: f-Strings
# 现在好了,Python 3.6新增了f-strings,这个特性叫做 字面量格式化字符串,F字符串是开头有一个f的字符串文字,Python会计算其中的用大括号包起来的表达式,并将计算后的值替换进去。
In: name='Xiaoming'
In: f'Hello {name}'
Out: 'Hello Xiaoming'
In: f'Hello {name.upper()}'
Out: 'Hello XIAOMING'
In: d={'id':123,'name':'Xiaoming'}
In: f'User[{d["id"]}]: {d["name"]}'
Out: 'User[123]: Xiaoming'
\和format用法比:
1、通过位置
data = ['data1', 'data2']
# format
print("data1: {0}, data2: {1}".format(*data))
# f-strings
print(f"data1: {data[0]}, data2: {data[1]}")
2、通过关键字
personal = {"name": "Json", "age": 12, "sex": "M"}
# format
print("Name: {name}, age: {age}, sex: {sex}".format(**personal))
# f-strings
print(f"Name: {personal['name']}, age: {personal['age']}, sex: {personal['sex']}")
3、数据精度和类型
num = 23234.76686566
# 保留两位小数
print(f"{num:.2f}")
# 保留两位小数,十个占位符,不足的使用0补充
prinf(f"{num:010.2f}")
4、填充和对齐经常是一起使用的
^、<、>: 分别是居中、左对齐、右对齐,后面带宽度。
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充(一般不指定)。
personal = {"name": "Json", "age": 12, "sex": "M"}
# format
print("Name: {name:>5}, age: {age:>5}, sex: {sex:>5}".format(**personal))
# f-strings
print(f"Name: {personal['name']:^10}, age: {personal['age']:^10}, sex: {personal['sex']:^10}")
5、使用 !r可以给字符串添加引号
a = "abc"
b = "hjk"
# format
c = "{!r} -- {!r}".format(a, b) # "'abc' -- 'hjk'"
# f-string
c = f"{a!r} -- {b!r}" # "'abc' -- 'hjk'"
# 如果你学过Ruby,ES6,你会非常容易接受这样的语法。另外在速度上,f-strings是三种方案中最快的:
In: import timeit
In: timeit.timeit("""name = "Xiaoming"...: 'Hello is %s.' % name""",number =10000)
Out: 0.0023188740001387487
In: 'Hello is %s.'%name
Out: 'Hello is Xiaoming.'
In: timeit.timeit("""name = "Xiaoming"...: 'Hello is {}.'.format(name)""",number=10000)
Out: 0.0038487229999191186
In: timeit.timeit("""name = "Xiaoming"...: f'Hello is {name}.'""",number=10000)
Out: 0.0011758640002881293
# 可以侧面感受到,str.format最慢,%s的稍快一点,F-string是最快的!
# f-string是格式化字符串的新语法。与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快!
\注意事项
1、{}内不能包含反斜杠\,但可以使用不同的引号,或使用三引号。使用引号是将不再表示一个变量,而是当作了字符串来处理。
2、如何插入大括号?
print(f"{{ 10 * 8 }}")
'{ 10 * 8 }'
print(f"{{ {10 * 8} }}")
'{ 80 }'
|
5820ff5bb76804493f7f56159ef6c27cffb3fb09 | cuitianfeng/Python | /python3基础/8.Python修炼第八层/面向对象/面向对象的软件开发.py | 3,944 | 4.21875 | 4 | 很多人在学完了python的class机制之后,遇到一个生产中的问题,还是会懵逼,这其实太正常了,因为任何程序的开发都是先设计后编程,python的class机制只不过是一种编程方式,
如果你硬要拿着class去和你的问题死磕,变得更加懵逼都是分分钟的事,在以前,软件的开发相对简单,从任务的分析到编写程序,再到程序的调试,可以由一个人或一个小组去完成。
但是随着软件规模的迅速增大,软件任意面临的问题十分复杂,需要考虑的因素太多,在一个软件中所产生的错误和隐藏的错误、未知的错误可能达到惊人的程度,这也不是在设计阶段就完全解决的。
所以软件的开发其实一整套规范,我们所学的只是其中的一小部分,一个完整的开发过程,需要明确每个阶段的任务,在保证一个阶段正确的前提下再进行下一个阶段的工作,称之为软件工程
\面向对象的软件工程包括下面几个部:
1.面向对象分析(object oriented analysis ,OOA)
软件工程中的系统分析阶段,要求分析员和用户结合在一起,对用户的需求做出精确的分析和明确的表述,从大的方面解析软件系统应该做什么,而不是怎么去做。
面向对象的分析要按照面向对象的概念和方法,在对任务的分析中,从客观存在的事物和事物之间的关系,贵南出有关的对象(对象的‘特征’和‘技能’)以及对象之间的联系,
并将具有相同属性和行为的对象用一个类class来标识。建立一个能反映这是工作情况的需求模型,此时的模型是粗略的。
2 面向对象设计(object oriented design,OOD)
根据面向对象分析阶段形成的需求模型,对每一部分分别进行具体的设计。
首先是类的设计,类的设计可能包含多个层次(利用继承与派生机制)。然后以这些类为基础提出程序设计的思路和方法,包括对算法的设计。
在设计阶段并不牵涉任何一门具体的计算机语言,而是用一种更通用的描述工具(如伪代码或流程图)来描述
3 面向对象编程(object oriented programming,OOP)
根据面向对象设计的结果,选择一种计算机语言把它写成程序,可以是python
4 面向对象测试(object oriented test,OOT)
在写好程序后交给用户使用前,必须对程序进行严格的测试,测试的目的是发现程序中的错误并修正它。
面向对的测试是用面向对象的方法进行测试,以类作为测试的基本单元。
5 面向对象维护(object oriendted soft maintenance,OOSM)
正如对任何产品都需要进行售后服务和维护一样,软件在使用时也会出现一些问题,或者软件商想改进软件的性能,这就需要修改程序。
由于使用了面向对象的方法开发程序,使用程序的维护比较容易。
因为对象的封装性,修改一个对象对其他的对象影响很小,利用面向对象的方法维护程序,大大提高了软件维护的效率,可扩展性高。
在面向对象方法中,最早发展的肯定是面向对象编程(OOP),那时OOA和OOD都还没有发展起来,因此程序设计者为了写出面向对象的程序,还必须深入到分析和设计领域,
尤其是设计领域,那时的OOP实际上包含了现在的OOD和OOP两个阶段,这对程序设计者要求比较高,许多人感到很难掌握。
现在设计一个大的软件,是严格按照面向对象软件工程的5个阶段进行的,这个5个阶段的工作不是由一个人从头到尾完成的,而是由不同的人分别完成,
这样OOP阶段的任务就比较简单了。程序编写者只需要根据OOd提出的思路,用面向对象语言编写出程序既可。 |
0337d060f3182b1ade5abbf2b96ca02bb83a2f34 | cuitianfeng/Python | /python3基础/7.Python修炼第七层/6.组合(面向对象的一种功能-两个类).py | 3,023 | 4.71875 | 5 | \ 组合 —— 面向对象的一种功能
# 组合 - 是两个类之间的事儿
# 描述的是一种所属关系
\ 组合例一:
# 组合表达的是:什么有什么的关系,比如每个人都有生日,生日是由年月日组成。
class Birthday:
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
class Person:
def __init__(self,name):
self.name = name
alex_birth = Birthday(1968,1,1)
print(alex_birth.year)
alex = Person('alex')
alex.birth = alex_birth # Birthday类的对象是alex的birth属性,这就是组合。
print(alex.birth.year)
print(alex.__dict__) # {'name': 'alex', 'birth': <__main__.Birthday object at 0x1036201d0>}
或者
class Birthday:
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
class Person:
def __init__(self,name,birth):
self.name = name
self.birthday = birth
alex_birth = Birthday(1968,1,1) # Birthday类的对象
print(alex_birth.year)
alex = Person('alex',alex_birth) # Birthday类的对象alex_birth是Person类对象alex的birth属性,这也是组合。
print(alex.birthday.year)
print(alex.__dict__) # {'name': 'alex', 'birthday': <__main__.Birthday object at 0x103c201d0>}
\ 组合例二:
# 人狗大战
# 人:人有武器,人和武器之间就是组合关系。
# 武器:伤害、属性
class Weapon: # 武器类
def __init__(self,aggr,name,money):
self.aggr = aggr
self.name = name
self.money = money
def kill(self,dog_obj):
# 属性的变化
print('%s武器暴击%s,伤害%s'%(self.name,dog_obj.name,self.aggr))
dog_obj.life_value -= self.aggr
class Dog: # 狗类
def __init__(self, name, type, aggr):
self.name = name
self.dog_type = type
self.aggr = aggr
self.life_value = 2000
def bite(self, person_obj): # self==egg,person_obj=alex
# 属性的变化
print('%s咬了%s' % (self.name, person_obj.name))
person_obj.life_value -= self.aggr
class Person: # 人类
rol = '人' # 数据属性、静态属性、类属性
country = '中国'
def __init__(self, name, age, life_value): # 初始化方法
self.name = name # 属性、对象属性
self.theage = age
self.life_value = life_value
self.aggr = 1
def attack(self, dog_obj): # 函数属性、动态属性、方法
# 属性的变化
print('%s攻击了%s' % (self.name, dog_obj.name))
dog_obj.life_value -= self.aggr
knife = Weapon(200,'杀猪刀',1900)
alex = Person('alex',38,500)
egg = Dog('egon','二哈',20)
alex.money = 2000
if alex.money > knife.money:
alex.money -= knife.money
alex.weapon = knife
print(egg.life_value)
alex.weapon.kill(egg) # 组合。 也可以写成 alex.knife.kill(egg)
print(egg.life_value)
|
42eaa6d75c90eed3e67e024dd3ec18421c52aa0e | Mattherix/social-road | /templates_fichier/fonction.py | 582 | 3.859375 | 4 | """Fichier d'exemple"""
def add(a, b):
"""Description rapide de la fonction
Description plus long. Quand faut il utilisé votre fonction ...
:Example:
>>> add(1, 1)
2
:param a: Paramètre 1
:type a: float/int
:param b: Paramètre 2
:type b: float/int
:return: Valeur de retour
:rtype: float/int
:raise TypeError: Si a ou b n'est pas un float/int
"""
# Verification des arguments
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError
# Calcul
c = a + b
return c
|
b1ef56664cbdec7cf4fa86731e65a8551e4118fa | caser789/libcollection | /lib_collection/graph/undirected_graph_connectivity_non_recur.py | 2,402 | 3.875 | 4 | class Node(object):
def __init__(self, v):
self.next = None
self.v = v
class LinkedList(object):
def __init__(self):
self.root = None
self.n = 0
def put(self, v):
node = Node(v)
node.next = self.root
self.root = node
self.n += 1
def __len__(self):
return self.n
def __iter__(self):
h = self.root
while h:
yield h.v
h = h.next
class UndirectedGraph(object):
def __init__(self, v):
self.v = v
self.e = 0
self.adjs = [LinkedList() for _ in range(v)]
def add_edge(self, v, w):
self.adjs[v].put(w)
self.adjs[w].put(v)
self.e += 1
def get_adjs(self, v):
for e in self.adjs[v]:
yield e
def get_degree(self, v):
return len(self.adjs[v])
def pprint(self):
print("{} vertices, {} edges".format(self.v, self.e))
for i, adjs in enumerate(self.adjs):
print("{}:".format(i), end="")
for e in adjs:
print(" {}".format(e), end="")
print("")
class Connectivity(object):
def __init__(self, graph, s):
self.marked = [False for _ in range(graph.v)]
self.count = 0
stack = [s]
while stack:
v = stack.pop()
self.marked[v] = True
self.count += 1
for w in graph.get_adjs(v):
if self.marked[w]:
continue
stack.append(w)
def is_connected(self, d):
return self.marked[d]
if __name__ == '__main__':
g = UndirectedGraph(13)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(0, 6)
g.add_edge(0, 5)
g.add_edge(3, 5)
g.add_edge(3, 4)
g.add_edge(4, 5)
g.add_edge(4, 6)
g.add_edge(7, 8)
g.add_edge(9, 10)
g.add_edge(9, 11)
g.add_edge(9, 12)
g.add_edge(11, 12)
g.pprint()
s = Connectivity(g, 0)
for v in range(g.v):
if s.marked[v]:
print("{} ".format(v), end="")
print("")
if s.count != g.v:
print("NOT CONNECTED")
else:
print("CONNECTED")
s = Connectivity(g, 9)
for v in range(g.v):
if s.marked[v]:
print("{} ".format(v), end="")
print("")
if s.count != g.v:
print("NOT CONNECTED")
else:
print("CONNECTED")
|
e07aa3cfccd437cd9053640983cc7e233b3d2936 | caser789/libcollection | /lib_collection/graph/bipartite.py | 1,366 | 3.640625 | 4 | class Bipartite(object):
def __init__(self, graph):
self.is_bipartite = True
self.color = [False for _ in range(graph.v)]
self.marked = [False for _ in range(graph.v)]
self.edge_to = [0 for _ in range(graph.v)]
self.odd_length_cycle = []
for v in range(graph.v):
if not self.marked[v]:
self.dfs(graph, v)
def dfs(self, graph, v):
self.marked[v] = True
for w in graph.get_siblings(v):
# short circuit if odd-length cycle found
if self.odd_length_cycle:
return
# found uncolored vertex, so recur
if not self.marked[w]:
self.edge_to[w] = v
self.color[w] = not self.color[v]
self.dfs[graph, w]
# if v-w create an odd-length cycle, find it
elif self.color[w] == self.color[v]:
self.is_bipartite = False
self.odd_length_cycle.append(w)
x = v
while x != w:
self.odd_length_cycle.append(x)
x = self.edge_to[x]
self.odd_length_cycle.append(w)
def is_bipartite(self):
return self.is_bipartite
def get_color(self, v):
if not self.is_bipartite:
raise
return self.color[v]
|
937651553d2878d75c6a2297ad44f053ecd8ba4b | caser789/libcollection | /lib_collection/union_find/quick_union_union_find.py | 1,211 | 3.765625 | 4 | class QuickUnionUnionFind(object):
def __init__(self, n):
self.n = n
self.parents = range(n)
def __len__(self):
return self.n
def union(self, p, q):
"""
>>> uf = QuickUnionUnionFind(5)
>>> uf.parents = [0, 1, 1, 2, 4]
>>> uf.union(1, 3)
>>> uf.parents
[0, 1, 1, 2, 4]
>>> uf.union(1, 4)
>>> uf.parents
[0, 1, 1, 2, 1]
"""
p_parent = self.find(p)
q_parent = self.find(q)
if p_parent == q_parent:
return
self.parents[q] = p_parent
self.n -= 1
def find(self, p):
"""
>>> uf = QuickUnionUnionFind(3)
>>> uf.find(1)
1
>>> uf = QuickUnionUnionFind(5)
>>> uf.parents = [0, 1, 1, 2, 4]
>>> uf.find(3)
1
"""
while p != self.parents[p]:
p = self.parents[p]
return p
def is_connected(self, p, q):
"""
>>> uf = QuickUnionUnionFind(5)
>>> uf.parents = [0, 1, 1, 2, 4]
>>> uf.is_connected(1, 3)
True
>>> uf.is_connected(1, 4)
False
"""
return self.find(p) == self.find(q)
|
99e1fb425290754da3793e2149cba60b1fb0b84d | caser789/libcollection | /lib_collection/node.py | 322 | 3.6875 | 4 | class Node(object):
def __init__(self, v):
self.v = v
self.next = None
def __str__(self):
"""
>>> n = Node('a')
>>> n
Node('a')
>>> n = Node(1)
>>> n
Node(1)
"""
return 'Node({})'.format(repr(self.v))
__repr__ = __str__
|
41bf8bd388294f7a5a4a5e11633c9841e7e61ebf | caser789/libcollection | /lib_collection/tree/list_of_lists_representation.py | 2,095 | 3.859375 | 4 | def get_binary_tree(r):
return [r, [], []]
def insert_left(root, subtree):
left_node = root.pop(1)
if len(left_node) > 1:
root.insert(1, [subtree, left_node, []])
else:
root.insert(1, [subtree, [], []])
return root
def insert_right(root, subtree):
right_node = root.pop(2)
if len(right_node) > 1:
root.insert(2, [subtree, [], right_node])
else:
root.insert(2, [subtree, [], []])
return root
def get_root_value(root):
return root[0]
def set_root_value(root, value):
root[0] = value
def get_left_child(root):
return root[1]
def get_right_child(root):
return root[2]
r = get_binary_tree(3)
insert_left(r, 4)
insert_left(r, 5)
insert_right(r, 6)
insert_right(r, 7)
left = get_left_child(r)
print left
set_root_value(left, 9)
print r
insert_left(left, 11)
print r
print get_right_child(get_right_child(r))
class Tree(object):
def __init__(self, v):
self.lst = [v, [], []]
def __len__(self):
return 1 + len(self.lst[1]) + len(self.lst[2])
def insert_left(self, v):
t = Tree(v)
if len(self.lst[1]) == 0:
self.lst[1] = t
return
t.insert_left(self.lst[1])
self.lst[1] = t
def insert_right(self, v):
t = Tree(v)
if len(self.lst[2]) == 0:
self.lst[2] = t
return
t.insert_right(self.lst[2])
self.lst[2] = t
@property
def root_value(self):
return self.lst[0]
@root_value.setter
def root_value(self, v):
self.lst[0] = v
@property
def left_tree(self):
return self.lst[1] if self.lst[1] else None
@property
def right_tree(self):
return self.lst[2] if self.lst[2] else None
def __repr__(self):
return 'Tree({}, {}, {})'.format(self.root_value, self.left_tree, self.right_tree)
r = Tree(3)
r.insert_left(4)
r.insert_left(5)
r.insert_right(6)
r.insert_right(7)
print r.left_tree
r.left_tree.root_value = 9
print r
r.left_tree.insert_left(11)
print r
print r.right_tree.right_tree
|
88db75ade64067b482ce9da5d99ae2e9c5c50119 | caser789/libcollection | /lib_collection/graph/depth_first_search.py | 1,187 | 3.625 | 4 | from undirected_graph import Graph
class DepthFirstSearch(object):
def __init__(self, graph, v):
self.marked = [False] * graph.v
self.count = 0
self.dfs(graph, v)
def dfs(self, graph, v):
self.count += 1
self.marked[v] = True
for e in graph.get_siblings(v):
if not self.marked[e]:
self.dfs(graph, e)
if __name__ == '__main__':
g = Graph(13)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(0, 5)
g.add_edge(0, 6)
g.add_edge(3, 4)
g.add_edge(3, 5)
g.add_edge(4, 5)
g.add_edge(4, 6)
g.add_edge(7, 8)
g.add_edge(9, 10)
g.add_edge(9, 11)
g.add_edge(9, 12)
g.add_edge(11, 12)
g.pprint()
s = DepthFirstSearch(g, 0)
for v in range(g.v):
if s.marked[v]:
print("{} ".format(v), end="")
print("")
if s.count != g.v:
print("NOT CONNECTED")
else:
print("CONNECTED")
s = DepthFirstSearch(g, 9)
for v in range(g.v):
if s.marked[v]:
print("{} ".format(v), end="")
print("")
if s.count != g.v:
print("NOT CONNECTED")
else:
print("CONNECTED")
|
5820bbbaf45b48883bf01f33998c8fcdf79484c3 | Crazyblob/Crazy-scripts | /NewBrute.py | 1,153 | 3.671875 | 4 | char = 'abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ1234567890@#$&!-_'
class creation:
def make_my_own():
return input('password here: ')
def random_password():
try:
length = int(input('lengh of randomly generated password: '))
except:
length = 4
print("You didn't put a number. Pretty uncool you know, so it'll automatically be 4")
y = ''
import random
for x in range(length):
y += random.choice(char)
return y
def choice():
passwordchoice = input('random or your own [random]/[own]: ')
if passwordchoice == 'random':
return creation.random_password()
elif passwordchoice == 'own':
return creation.make_my_own()
else:
print('invalid choice')
password = choice()
def brute():
guesspass = ' '
listgp = list(guesspass)
position = 0
charamount =
print(listgp)
while guesspass != password:
for x in range(len(char)):
listgp[positionamount] = char[position]
print('test',listgp)
position += 1
|
b720f24465dda89e7ff7e6dd6f0fdde60fdb297d | vpreethamkashyap/plinux | /7-Python/3.py | 1,594 | 4.21875 | 4 | #!/usr/bin/python3
import sys
import time
import shutil
import os
import subprocess
print ("\nThis Python script help you to understand Types of Operator \r\n")
print ("Python language supports the following types of operators. \r\n")
print ("Arithmetic Operators \r\n")
print ("Comparison (Relational) Operators \r\n")
print ("Assignment Operators \r\n")
print ("Logical Operators \r\n")
print ("Bitwise Operators \r\n")
print ("Membership Operators \r\n")
print ("Identity Operators \r\n")
print ("Let us have a look on all operators one by one. \r\n")
raw_input("Press enter to see how to aithrmetic operations occurs\n")
var a = 50
var b = 20
var c
c = a+b
print("Addition of a & b is %d \r\n" %c)
c = a-b
print("Subtraction of a & b is %d \r\n" %c)
c = a*b
print("Multiplication of a & b is %d \r\n"%c)
c = a/b
print("Division of a & b is %d \r\n"%c)
c = a%b
print("Modulus of a & b is %d \r\n" %c)
c = a**b
print("Exponent of a & b is %d \r\n" %c)
c = a//b
print("Floor Division of a & b is %d \r\n" %c)
raw_input("Press enter to see how to aithrmetic operations occurs\n")
print("Python Comparison Operators\r\n")
if(a == b):
print(" a & b are same \r\n")
if(a != b):
print("a & b are not same\r\n")
if(a > b):
print("a is greater than b\r\n")
if(a < b):
print("b is greater than a\r\n")
raw_input("Press enter to see how to Bitwise operations occurs\n")
print ("\r\n Bit wise operator a&b %b \r\n" % (a&b))
print ("\r\n Bit wise operator a|b %b \r\n" % (a|b))
print ("\r\n Bit wise operator a^b %b \r\n" % (a^b))
print ("\r\n Bit wise operator ~a %b \r\n" % (~a))
|
213305b2d73beb39b932102d9bc47dab1edcd413 | python10101/wanderlust | /tableof10.py | 132 | 3.53125 | 4 | for i in range(1,11,1):
for j in range(1,11,1):
print("{:4d}".format(i*j),end=' ')
print()
|
3c1c68f19976f4d838ad647f22ff4a86508fa50b | mcteo/handwritten-numbers | /neuralnetwork/number_trainer.py | 3,424 | 3.703125 | 4 | #!/usr/bin/env python
import cPickle
from trainer import Trainer
class NumberTrainer(Trainer):
"""
This uses the abstract `Trainer` class to train an MLP
specificially on the dataset we want.
We can optionally pickle and save the trained MLP for later use.
"""
def __init__(self, num_hidden, file_path):
# this tells the trainer to only train on a random
# 80% of the input data, so we can use the remaining
# 20% to get an idea of the networks performance
# against completely unseen data.
test_ratio = 0.8
super(NumberTrainer, self).__init__(num_hidden, file_path, test_ratio)
def convert_to_network(self, line):
"""
Each line of data contains 256 floats followed by 10 ints.
E.g. 1.00 0.00 1.00 0.00 ... 0 0 0 0 0 1 0
The first 256 floats represent the pixels of the image.
1 being a black pixel, 0 being white.
The 10 ints are flags with the correct output being 1.
e.g. 0 0 0 1 0 0 0 -> 3, because the 3rd (zero indexed)
value is 1.
"""
line = map(lambda x: int(float(x)), line.strip().split(" "))
return (line[:256], line[256:],)
def convert_from_network(self, data):
"""
Ideally, the output of the network should be nine zeros,
with a single one, but alas, we get ten floats instead.
These kind of represent the "best guess" of the network,
so will often have many numbers < 0.01, and one > 0.5.
We take the largest overall number as the final answer
of the network.
"""
return data.index(max(data))
def error_against_unseen_data(self):
"""
The `testcase_ratio` defines how the input data is split between
the training data, and the testing data.
Here we count how many of the unseen testcases are correctly
determined to get an idea of the performance of the neural network.
"""
if self.testcase_ratio == 1.0:
raise Exception("Cannot calculate the error against unseen "
"data when the test ratio == 1.0.")
slice_index = int(len(self.testcases) * self.testcase_ratio)
testcases_slice = self.testcases[slice_index:]
incorrect_count = 0
for (input_data, output_data) in testcases_slice:
self.network.forward(input_data)
predicted = self.convert_from_network(self.network.output_layer)
actual = self.convert_from_network(output_data)
if predicted != actual:
incorrect_count += 1
return 100.0 * incorrect_count / len(testcases_slice)
if __name__ == '__main__':
number_trainer = NumberTrainer(50, "letter_data.in")
learning_rate = 0.1
untrained_accuracy = 100.0 - number_trainer.error_against_unseen_data()
print "Before training, the MLP has an accuracy of %.2f%%" % (untrained_accuracy)
number_trainer.train(learning_rate, max_timesteps=20)
# number_trainer.train(learning_rate, error_threshold=50) # slow
trained_accuracy = 100.0 - number_trainer.error_against_unseen_data()
print "After training, the MLP has an accuracy of %.2f%%" % (trained_accuracy)
# dump trained network for copying to webpage folder
with open("trained_network.pickle", "w") as fout:
cPickle.dump(number_trainer.network, fout)
|
8229a7bb8970bdbad21073af229b25993a81904c | rlawjd34/python | /Test01/ch02/test01.py | 230 | 3.546875 | 4 | #-*- coding: utf-8 -*-
import numpy as np
# branch 테스트 하기 주석
x = np.array([1.0, 2.0, 3.0])
y = np.array([3.0, 4.0, 5.0])
print(x * y)
A = np.array([[1, 2], [3,4]])
print(A)
print(A[0])
print(type(A)) |
6fdbd42b6d7e1f5e0653cfc123dde0a7a753d82b | jenny-jt/Coding-Challenges | /Solutions/Trees.py | 7,992 | 4.3125 | 4 | # Define a tree structure - start with a tree with two nodes.
# For an extra challenge, ask yourself how the implementation would
# change if there are more than two branches per node. An example of this would be a Trie.
# These are very useful for autocomplete and the like
# Tree and Node classes
class Node():
"""node in tree"""
def __init__(self, value, children):
self.value = value
self.children = children or []
def __repr__(self):
return f'<Node={self.value}>'
class Tree():
"""tree class"""
def __init__(self, root):
self.root = root
def __repr__(self):
return f'<Tree={self.root}>'
node_vals = ["A", "B"]
nodes = []
for val in node_vals:
nodes.append(Node(val))
Node_A.children.append(Node_B)
{"A":["B", "C", "D"], "B":[]}
# Write a function that returns the lowest common ancestor of two nodes.
# the lowest node in T that has both n1 and n2 as descendants
# This is a common problem, however when we master this + (depth + breadth)
# first search tree problems will become second nature as the traversal is the same
# and the only conditions that usually change are which direction you take when
def lowest_common_ancestor(node, v1, v2):
target = [v1,v2]
def dfs(node, target):
if not node:
return
# if node is either p or q, will return node
if node.val in target:
return node
# otherwise, search to left and right of node
left = dfs(node.left, target)
right = dfs(node.right, target)
# p and q are in left and right branches, LCA is the node
if left and right:
return node
# if only L or R branch, will find first node that is p or q (child of itself)
return left or right
return dfs(root, target)
#Instead of 2 nodes, what if we had a list of nodes.
def challenge_lowest_common_ancestor(node, alon):
alon = [v1,v2, v3, v4]
def dfs(node, target, children):
if not node:
return
# if node is in alon, will return node
if node.val in alon:
return node
# otherwise, search children of node
for child in node.children:
child_found = dfs(child, target)
if child_found:
children.append(child_found)
if len(children) == len(alon):
return node
return dfs(root, target, [])
class Node():
"""node in tree"""
def __init__(self, value, children):
self.value = value
self.children = children or []
def __repr__(self):
return f'<Node={self.value}>'
class Tree():
"""tree class"""
def __init__(self, root):
self.root = root
def __repr__(self):
return f'<Tree={self.root}>'
1
2 3
4 5
6 8
3 5
1
3 2
6 5 4
8 9
# node.right, add that value to an existing ds
# reach leaf node(right is none) stop
# result = [7, 17, 14]
# d = {1:3, 2:5, 4:none, 3:6, 5:8, 6:none, 8:none, 9:none}
def invert_tree(node):
"""given binary tree, invert the tree"""
# start at root
if node:
temp = node.left
node.left = node.right
node.right = temp
dfs(node.left)
dfs(node.right)
return node
# using dict
def diagonal_sum():
"""given binary tree, calculate diagonal sum"""
# initialize dict
d = defaultdict(int)
d[0] = root.val
# traverse tree
i = 0
def dfs(node, d, i):
if not node:
return
# if R child
if node.right:
d[i] += node.right
# if L child
if node.left:
d[i+1] += node.left
dfs(node.right, d, i)
dfs(node.left, d, i+1)
# unsure if I should put d = dfs(root, d, 0)
dfs(root, d, 0)
# should be list of integer sums [7, 17, 14]
return d.values()
# tried using q and sum array, order of q summing up diagonals in L direction, not R direction
def diagonal_sum():
"""given binary tree, calculate diagonal sum"""
i = 0
def dfs(node, q, sum_, i):
if not node:
return
# if R child
sum_[i] += node.right
# if L child
q.append(node.left)
dfs(node.right, q, sum_, i)
dfs(node.left, q, sum_, i+1)
# add node.right until node.right == None
# add node.left to q
dfs(root, [], [], 0)
# pop from q and add all up until hit none, then start new entry in result array
j = 0
while q:
next_l = q.pop()
if next_l:
sum_[j] += next_l
j += 1
class TrieNode:
def __init__(self):
# staring from 0, diff with A
self.children = [None] * 26
# each node has a boolean, changed to True after finish insert
self.isEnd = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
# insert each char in correct posititon and then move my curr
current = self.root
for char in word:
print("INSERT char", char)
if not current.children[ord(char) - ord('a')]:
# make new node if node does not exist
current.children[ord(char) - ord('a')] = TrieNode()
# move my current to that charcter
current = current.children[ord(char) - ord('a')]
current.isEnd = True # end insert True meaning the word is in tree
# print("current after INSERT", current.children, current.isEnd)
# Search for a char if not there then return False or if there move my curr
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
current = self.root
for char in word:
# print("SEARCH char", char)
if not current.children[ord(char) - ord('a')]:
return False # that character is not present in that children
# moving along to child node
current = current.children[ord(char) - ord('a')]
# if the last node isEnd is true, then it has been inserted before
return current.isEnd
# Search for a prefix if not there then return False or if there move my curr till my prefix ends and return True
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
current = self.root
for i in range(len(prefix)):
char = prefix[i]
# if the char is not a child, then it's not in the trie
if not current.children[ord(char) - ord('a')]:
return False
current = current.children[ord(char) - ord('a')]
num_children = [x for x in current.children if x]
return len(num_children)
# Escape Room Keypads- supposed to use Trie, using sets here
def numKeypadSolutions(wordlist, keypads):
"""input of 2 string arrays, output int array with num of words for each keypad"""
# initialize ans array that contains num of words for each keypad
ans = [0] * len(keypads)
# convert each word in wordlist to a set
words = [set(word) for word in wordlist if len(set(word)) <= 7]
# for each keypad, check if word is subset of keypad and if key in word
for i, keypad in enumerate(keypads):
key = keypad[0]
for word in words:
if key in word and word.issubset(set(keypad)):
ans[i] += 1
return ans
print(numKeypadSolutions(['APPLE', 'PLEAS', 'PLEASE', 'DOG'], ['PBNEDAL', 'OESADLP', 'MOTLAJF', 'GBLKORD'])) |
79a06e1e8bcbba083133a6e3aa3114ecb7115bfa | nizmitz/modul_python | /day_1/test9.py | 137 | 3.5 | 4 | def addition(*args):
total = 0
for i in args:
total += i
return total
answer = addition(20, 10, 5, 1)
print(answer)
|
80594a4a5895376523925999c47afa6a1ee0c040 | opnmind/kurse_python_cleancoding | /Teilnehmer/tn02/Tag2/reader3/reader3.py | 3,293 | 3.671875 | 4 | """
This is a test-reader to get ip-addresses out of a log-file and print the
addresses found to stdout, one address per line.
"""
import re
import sys
from pathlib import Path
from itertools import starmap
from typing import Union, List, AnyStr
IP_SEARCH_PATTERN = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
class LogFile:
"""Represents a log file from which lines are read lazily
"""
def __init__(self, log_file_path: Union[Path, str] = None):
"""Initializes a logfile with a file path to the file on local filesystem
Args:
log_file_path (str or Path-like): representing the path to the log-file to be read.
"""
self._log_file_path = log_file_path
def read_lines(self):
"""Reads the text-based log-file as initialized on class creation and returns its contents
Returns:
log_file_content: yields data from log-file line by line
"""
if self._log_file_path is not None:
try:
with open(self._log_file_path, 'r') as log_file_reader:
for line in log_file_reader:
yield line
except OSError as file_exception:
print(f'File {self._log_file_path} could not be opened. {file_exception}')
sys.exit(2)
class IPAdressManager:
"""Encapsulate ip address extraction """
def get_ip_addresses(self, content_line: str = None, search_pattern: str = IP_SEARCH_PATTERN):
"""Extracts a list of ip-addesses as string from a line of text (usually from a log-file)
Args:
content_line (str): input line read from text file, which will be searched for ip addresses
search_pattern (str): regex search pattern matching ip adresses, defaults to standard search pattern
Returns:
list of ip addresses or None if no address was found
"""
return re.findall( search_pattern, content_line, re.MULTILINE)
class IPAddressPrinter:
"""Encapsulate ip address printing function"""
def print_ip_addresses(self, ip_addresses: List[str] = None, counter: int = 0):
"""Prints a list of ip addresses if ip addresses where foun in the given line
Args:
ip_addresses (List(str)): List of ip addresses as string
counter (int): current ip address counter status
Returns:
counter (int): counter updated with the number of ip addresses printed
"""
if ip_addresses is not None and len(ip_addresses) > 0:
formatted_lines_for_print = starmap(lambda _counter, item: f'{_counter}: {item}', enumerate(ip_addresses, counter))
print('\n'.join(formatted_lines_for_print))
return counter + len(ip_addresses)
else:
return counter
if __name__ == "__main__":
LOG_FILE = '/home/coder/Workspace/kurse_python_cleancoding/Materialien/Sample.log'
counter = 1
log_file = LogFile(LOG_FILE)
ip_address_manager = IPAdressManager()
ip_address_printer = IPAddressPrinter()
for content_line in log_file.read_lines():
ip_addresses = ip_address_manager.get_ip_addresses(content_line)
counter = ip_address_printer.print_ip_addresses(ip_addresses=ip_addresses, counter=counter)
|
b65327aba82d99c3912ad29f91cf07e8c07830d4 | opnmind/kurse_python_cleancoding | /Teilnehmer/tn08/Tag2/reader1.py | 414 | 3.5625 | 4 | #!/usr/bin/env python3
"""
Find IP addresses in a file
"""
import re
LOGFILE = "/home/coder/Workspace/kurse_python_cleancoding/Materialien/Sample.log"
REGEX = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
with open(LOGFILE, "r") as file_descriptor:
log = file_descriptor.read()
ip_addresses = []
matches = re.finditer(REGEX, log)
for match in matches:
ip_addresses.append(match.group())
print(ip_addresses)
|
fa229f35fe33c9046e3fc6ee87a0797302bced9e | opnmind/kurse_python_cleancoding | /Teilnehmer/tn08/Tag3/lotto.py | 927 | 3.734375 | 4 |
class Lotto:
"""Lotto Klasse"""
TIPFILE = "/home/coder/Workspace/kurse_python_cleancoding/Teilnehmer/tn08/Tag3/lotto_tip.txt"
def __init__(self, tip_file = None):
self.tip_file = tip_file if tip_file else self.TIPFILE
self.my_tip = []
self.drawing_tip = []
def enter_tip(self):
with open(self.tip_file) as file_descriptor:
for line in file_descriptor:
tip = int(line)
self.my_tip.append(tip)
return self
def check_tip(self):
print(len(self.my_tip))
print(self.my_tip)
assert len(self.my_tip) == 6
assert all(isinstance(n, int) for n in self.my_tip)
return self
def generate_drawing(self):
pass
def compare_tip_to_drawing(self):
pass
def show_result(self):
return
if __name__ == "__main__":
print(Lotto().enter_tip().check_tip())
|
6abdd864703be9b9d7c1eec4d95ad8be554c74de | 4others/MIT_6.01.1x | /paying_debt_in_year.py | 1,527 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 20:16:57 2018
@author: xxx
"""
#Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.
#
#The following variables contain values as described below:
#
#balance - the outstanding balance on the credit card
#
#annualInterestRate - annual interest rate as a decimal
#
#monthlyPaymentRate - minimum monthly payment rate as a decimal
#
#For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print
#
#Remaining balance: 813.41
#instead of
#
#Remaining balance: 813.4141998135
#So your program only prints out one thing: the remaining balance at the end of the year in the format:
#
#Remaining balance: 4784.0
#A summary of the required math is found below:
#
#Monthly interest rate= (Annual interest rate) / 12.0
#Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
#Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
#Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
month = 1
while month <= 12:
balance -= monthlyPaymentRate*balance
balance = round(balance + annualInterestRate/12.0 * balance, 2)
month += 1
print ("Remaining balance: " +str(balance)) |
63ab49d58ae25ae72e2e6670d932afe5159b2c96 | froggengoing/LeetCodeInPython | /20210819[503]Next Greater Element II.py | 1,802 | 3.515625 | 4 | # Given a circular integer array nums (i.e., the next element of nums[nums.lengt
# h - 1] is nums[0]), return the next greater number for every element in nums.
#
# The next greater number of a number x is the first greater number to its trav
# ersing-order next in the array, which means you could search circularly to find
# its next greater number. If it doesn't exist, return -1 for this number.
#
#
# Example 1:
#
#
# Input: nums = [1,2,1]
# Output: [2,-1,2]
# Explanation: The first 1's next greater number is 2;
# The number 2 can't find next greater number.
# The second 1's next greater number needs to search circularly, which is also 2
# .
#
#
# Example 2:
#
#
# Input: nums = [1,2,3,4,3]
# Output: [2,3,4,-1,4]
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 104
# -109 <= nums[i] <= 109
#
# Related Topics Array Stack Monotonic Stack
# 👍 3065 👎 103
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
stack = []
result = [-1] * len(nums)
i = 0
is_second = False
# 优化 是 2* len(nums) -1
# 下表为i%len(nums)取模
# 即作为[2n-1]的数组
while i < len(nums):
while stack and nums[i] > nums[stack[-1]]:
result[stack.pop()] = nums[i]
stack.append(i)
i += 1
if i == len(nums) and not is_second:
i = 0
is_second = True
return result
# leetcode submit region end(Prohibit modification and deletion)
print(Solution().nextGreaterElements([1, 2, 3, 4, 3, 2]))
print(Solution().nextGreaterElements([1, 2, 1]))
|
10cff008bcffdaef972ebb163badad70d69b2f7c | froggengoing/LeetCodeInPython | /20210729-[189]Rotate Array.py | 2,954 | 3.890625 | 4 | # Given an array, rotate the array to the right by k steps, where k is non-negat
# ive.
#
#
# Example 1:
#
#
# Input: nums = [1,2,3,4,5,6,7], k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
# [1,2,3,4,5,6,7,8,9]
#
# Example 2:
#
#
# Input: nums = [-1,-100,3,99], k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 105
# -231 <= nums[i] <= 231 - 1
# 0 <= k <= 105
#
#
#
# Follow up:
#
#
# Try to come up with as many solutions as you can. There are at least three di
# fferent ways to solve this problem.
# Could you do it in-place with O(1) extra space?
# [123456] 2
# [561234]
# Related Topics Array Math Two Pointers
# 👍 5166 👎 970
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
'''
相较于前一种,有点取巧的意思,但思路也很新奇
'''
def rotate(self, nums, k):
mid = k % len(nums)
self.reverse(nums, 0, len(nums) - 1)
self.reverse(nums, 0, mid - 1)
self.reverse(nums, mid, len(nums) - 1)
def reverse(self, nums, start, end):
index = start
while index <= (start + end) / 2:
tmp = nums[index]
nums[index] = nums[end + start - index]
nums[end + start - index] = tmp
index += 1
'''
秒啊,自己的思路和这个有点类似,但有一点点不通,所以没算出来
非常有意思的题目,真正让数组闭环在移动位置
'''
def rotate2(self, nums, k):
k = k % len(nums)
count = 0
start = 0
while count < len(nums):
current = start
prev = nums[start]
while True:
nxt = (current + k) % len(nums)
temp = nums[nxt]
nums[nxt] = prev
prev = temp
current = nxt
count += 1
if start == current:
break
start += 1
def rotate1(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
'''
暴力两个循环
'''
size = len(nums)
for index in range(k):
tmp = nums[index]
nums[index] = nums[size - 1]
for cur in range(index + 1, size):
sec = nums[cur]
nums[cur] = tmp
tmp = sec
# leetcode submit region end(Prohibit modification and deletion)
# s1 = Solution()
# # n1 = [1, 2, 3, 4 , 5, 6, 7]
# n1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# s1.rotate(n1, 3)
# print(n1)
|
e2b78904361009583f6ddfce67bea0d6838af113 | froggengoing/LeetCodeInPython | /20210825-20-[1025]Divisor Game.py | 2,810 | 3.828125 | 4 | # Alice and Bob take turns playing a game, with Alice starting first.
#
# Initially, there is a number n on the chalkboard. On each player's turn, that
# player makes a move consisting of:
#
#
# Choosing any x with 0 < x < n and n % x == 0.
# Replacing the number n on the chalkboard with n - x.
#
#
# Also, if a player cannot make a move, they lose the game.
#
# Return true if and only if Alice wins the game, assuming both players play op
# timally.
#
#
# Example 1:
#
#
# Input: n = 2
# Output: true
# Explanation: Alice chooses 1, and Bob has no more moves.
#
#
# Example 2:
#
#
# Input: n = 3
# Output: false
# Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
#
# n = 4
# Alice choose f(1), !f(4-1)
# return true
# Alice choose f(2), !f(2)
# return false
#
# n = 5
# Alice choose f(1), !f(5-1)
# return false
# n =6
# Alice choose f(1), !f(6-1)
# return True
# Alice choose f(2), !f(6-2)
# return false
# Alice choose f(3), !f(6-3)
# return true
#
#
#
# Constraints:
#
#
# 1 <= n <= 1000
#
# Related Topics Math Dynamic Programming Brainteaser Game Theory
# 👍 975 👎 2502
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def divisorGame(self, n):
'''
:param n:
:return:
'''
return n % 2 == 0
def divisorGame3(self, n):
res = [None] * n
self.def3(res, 0)
return res[n - 1]
def def3(self, res, i):
if i >= len(res):
return False
if i == 0:
res[0] = False
elif i == 1:
res[1] = True
elif i == 2:
res[2] = False
elif res[i] == False:
return res[i]
else:
tmp = 1
while tmp < i:
if (i + 1) % tmp == 0 and res[i - tmp] == False:
res[i] = True
break
tmp += 1
if res[i] == None:
res[i] = False
self.def3(res, i + 1)
def divisorGame2(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1: return False
if n == 2: return True
if n == 3: return False
res = [None] * n
res[0] = False
res[1] = True
res[2] = False
i = 3
while i < n:
self.dfs2(res, i)
i += 1
return res[n - 1]
def dfs2(self, res, i):
tmp = 1
while tmp < i:
if (i + 1) % tmp == 0 and res[i - tmp] == False:
res[i] = True
return
tmp += 1
res[i] = False
# leetcode submit region end(Prohibit modification and deletion)
for i in range(1, 10):
print(Solution().divisorGame(i))
|
d52ae7db99b0b953fea2ef772a06dd0df0a44609 | Mar19Test/Hate-Speech-Classification | /src/utils/get_tweets_by_id.py | 1,893 | 3.71875 | 4 | import tweepy
import pandas as pd
def load_data(file_path):
'''
Load a csv data set in a pandas dataframe.
Parameters
----------
file_path: String
The path to the csv data set.
Returns
-------
df: Pandas dataframe
The dataframe containing the data from the csv file.
'''
df = pd.read_csv(file_path,
sep = ',',
header = None,
names = ['tweet_id', 'label'])
return df
def get_tweets_by_id(config, file_path):
'''
Get the text from all available tweets with IDs in annotated dataset and
save it in the dataframe.
Parameters
----------
config: JSON-object
The object contains necessary authorization details to get
access to the twitter API.
file_path: String
The path to the annotated csv data set.
Returns
-------
df: Pandas dataframe
The dataframe containing the data from the csv file and the
texts of the tweets if available.
'''
# load authorization details from config-file and send request to api
auth = tweepy.OAuthHandler(config['CONSUMER_KEY'], config['CONSUMER_SECRET'])
auth.set_access_token(config['OAUTH_TOKEN'], config['OAUTH_TOKEN_SECRET'])
api = tweepy.API(auth)
# load annotated data set with read_data()
df = load_data(file_path)
### TRY OUT, else via loop -> api.get_status(tweet_id).text
### FIXME, what happens if tweet is no longer available? -> count?
df['text'] = df.tweet_id.apply(api.get_status).text
### TODO: can get information about geolocation (if available),
# have a look at examples when authorization works
return df
|
cf907309891594e83d7e7c99e9604a90ecb80ba7 | xixolio/Mazhine | /proyecto/normalize.py | 293 | 3.75 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 1 11:14:08 2016
@author: ignacio
"""
def normalize(data):
max_values = data.max(0)
min_values = data.min(0)
norm_data = (data-min_values)/(max_values-min_values)
return norm_data,max_values,min_values |
bb07b4d8192ef78b7dd5d4af1b5ef100f5fe909b | showiproute/python_data_structure | /search.py | 1,547 | 3.75 | 4 | #!/usr/bin/env python
#coding:utf-8
number_list=[0,1,2,3,4,5,6,7]
def linear_search(value,iterable):
for index,val in enumerate(iterable):
if val==value:
return index
return -1
assert linear_search(5,number_list) == 5
def liner_search_v2(predicate,iterable):
for index,val in enumerate(iterable):
if predicate(val):
return index
return -1
assert liner_search_v2(lambda x:x==5,number_list) == 5
def linear_search_recusive(array,value):
if len(array)==0:
return -1
index=len(array)-1
if array[index]==value:
return index
return linear_search_recusive(array[0:index],value)
assert linear_search_recusive(number_list, 5) == 5
assert linear_search_recusive(number_list, 8) == -1
assert linear_search_recusive(number_list, 7) == 7
assert linear_search_recusive(number_list, 0) == 0
def binary_search_recursive(sorted_array,beg,end,val):
if beg>=end:
return -1
mid=int((beg+end)/2)
if sorted_array[mid]==val:
return mid
elif sorted_array[mid]>val:
return binary_search_recursive(sorted_array,beg,mid,val)
else:
return binary_search_recursive(sorted_array,mid+1,end,val)
def test_binary_search_recursive():
# 我们测试所有值和边界条件
a = list(range(10))
for i in a:
assert binary_search_recursive(a, 0, len(a), i) == i
assert binary_search_recursive(a, 0, len(a), -1) == -1
assert binary_search_recursive(a, 0, len(a), 10) == -1
test_binary_search_recursive() |
bc81038ababe2f98c95e6992cf7c8cda8f45d0a8 | showiproute/python_data_structure | /merge_sort.py | 989 | 3.9375 | 4 | #!/usr/bin/env python
#coding:utf-8
def merge_sort(seq):
if len(seq)<=1:
return seq
else:
mid=int(len(seq)/2)
left_half=merge_sort(seq[:mid])
right_half=merge_sort(seq[mid:])
new_seq=merge_sort_list(left_half,right_half)
return new_seq
def merge_sort_list(sorted_a,sorted_b):
a=b=0
new_sorted_list=list()
while a<len(sorted_a) and b<len(sorted_b):
if sorted_a[a]<sorted_b[b]:
new_sorted_list.append(sorted_a[a])
a+=1
else:
new_sorted_list.append(sorted_b[b])
b+=1
while a<len(sorted_a):
new_sorted_list.append(sorted_a[a])
a+=1
while b<len(sorted_b):
new_sorted_list.append(sorted_b[b])
b+=1
return new_sorted_list
def test_merge_sort():
import random
seq = list(range(10))
random.shuffle(seq)
assert merge_sort(seq) == sorted(seq)
if __name__=='__main__':
test_merge_sort()
|
f140a8c262dba9eba22626c5a297fbeef6116978 | partha101/SaaS | /ampm.py | 259 | 3.5625 | 4 | x=raw_input()
list1=x.split(":")
list2=list(list1[2])
if list2[2]=="p" or list2[2]=="P":
a=int(list1[0])+12
if a==24:
a=0
else :
print list1[0]+":"+list1[1]+":"+list1[2][0]+list1[2][1]
print str(a)+":"+list1[1]+":"+str((int(list2[0])*10)+int(list2[1]))
|
aed583549442c818d26b48de62882049c5f4d15f | zahirparker/LearnPy | /reduce.py | 1,932 | 3.6875 | 4 | def reduce_ex_1():
# --------------------------------------
# Print the sum of 1 - 100
# --------------------------------------
sum = reduce(lambda x, y: x + y, range(1,101))
print sum
print
def reduce_ex_2():
# --------------------------------------
# Find the Max number in the list
# --------------------------------------
max = reduce(lambda x, y: x if x > y else y, [1, 4, 31, 103, 201, 45, 6, 9])
print max
print
def reduce_ex_3():
# --------------------------------------
# Concatenate a list of strings to make a sentence
# --------------------------------------
L = ['Testing ', 'shows ', 'the ', 'presence', ', ','not ', 'the ', 'absence ', 'of ', 'bugs']
print reduce( (lambda x,y:x+y), L)
# We get the same using join
print ''.join(L)
print
def reduce_ex_4():
# --------------------------------------
# Sum of Squares of 1 - 100
# --------------------------------------
sum_of_squares = reduce(lambda x, y: x + y, map(lambda x: x ** 2, range(1,101)))
print 'Sum of squares of 1-100 is ', sum_of_squares
print
# The function reduce(func, seq) continually applies the function func() to the sequence seq.
# It returns a single value.
# If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq) works like this:
# At first the first two elements of seq will be applied to func, i.e. func(s1,s2) The list on which reduce() works looks now like this: [ func(s1, s2), s3, ... , sn ]
# In the next step func will be applied on the previous result and the third element of the list, i.e. func(func(s1, s2),s3)
# The list looks like this now: [ func(func(s1, s2),s3), ... , sn ]
# Continue like this until just one element is left and return this element as the result of reduce()
reduce_ex_1()
reduce_ex_2()
reduce_ex_3()
reduce_ex_4()
'''Reference: http://www.python-course.eu/lambda.php'''
'''http://www.bogotobogo.com/python/python_fncs_map_filter_reduce.php'''
|
b6874788c2092e89b63632c6eb6f41ad93ff29e0 | AlgorithmOnline/jaeeun | /2_2021011.py | 673 | 3.703125 | 4 | import sys
input = sys.stdin.readline
mm={}
def find_parent(x):
if mm[x]==x:
return x
else:
return find_parent(mm[x])
def get_parent(x):
if mm[x]==x:
return x
else:
mm[x]=get_parent(mm[x])
return mm[x]
def union(x,y):
x=get_parent(x)
y=get_parent(y)
if x!=y:
mm[y]=x
n,m = map(int, input().split())
for i in range(n+1):
mm[i]=i
for _ in range(m):
try:
v,a,b=map(int, input().split())
if not v:
union(a,b)
elif find_parent(a)==find_parent(b):
print("YES")
else:
print("NO")
except:
pass
|
8efb77dc605a7c4f9d05d9ca63b95f5a88c0834b | AlgorithmOnline/jaeeun | /1_20200907.py | 913 | 3.609375 | 4 | dict_group=dict()
g_answer =0
def solution(n, results):
results+=sorted(results, reverse=True
)
answer = 0
global group
global dict_group
for i in range(1, n+1):
dict_group[i]={
'big':set(),
'small':set(),
}
for result in results:
dict_group[result[0]]['small'].add(result[1])
dict_group[result[1]]['big'].add(result[0])
""""""
for result in results:
for bigger in dict_group[result[1]]['big']:
dict_group[result[1]]['big']=dict_group[result[1]]['big']|dict_group[bigger]['big']
for smaller in dict_group[result[0]]['small']:
dict_group[result[0]]['small']=dict_group[result[0]]['small']|dict_group[smaller]['small']
""""""
""""""
for i in dict_group:
if len(dict_group[i]['big']) + len(dict_group[i]['small']) == n-1:
answer+=1
return answer
|
ee121f38c3915ce3b0d6361f9b2d2719538c381e | AlgorithmOnline/jaeeun | /2_202010119.py | 167 | 3.828125 | 4 | x=int(input())
y=int(input())
if x*y>0:
if x<0:
print(3)
else:
print(1)
else:
if x<0:
print(2)
else:
print(4)
|
a84deac6307de458af9c4bb3430a2c0bceb7e543 | AlgorithmOnline/jaeeun | /1_20210216.py | 973 | 3.578125 | 4 | import copy
def solution(n):
dp=[None,[[1,3]],[ [1,2], [1,3], [2,3] ]]
if n==1:
return dp[1]
elif n==2:
return dp[2]
while len(dp)<n+1:
row =[]
first_step=copy.deepcopy(dp[-1])
for i in range(len(first_step)):
for k in range(len(first_step[i])):
if first_step[i][k]==2:
first_step[i][k]=3
elif first_step[i][k]==3:
first_step[i][k]=2
second_step=[[1,3]]
third_step=copy.deepcopy(first_step)
for i in range(len(third_step)):
for k in range(len(third_step[i])):
if third_step[i][k]==2:
third_step[i][k]=3
elif third_step[i][k]==3:
third_step[i][k]=1
elif third_step[i][k]==1:
third_step[i][k]=2
row=first_step+second_step+third_step
dp.append(row)
return dp[n]
|
6818db794d79fd40e15ff0ffcf8c04a962f4d79d | AlgorithmOnline/jaeeun | /20210323/2751.py | 992 | 3.59375 | 4 | """
퀵정렬을 구현해 문제풀이를 진행했다.
퀵정렬은 피봇을 기준으로 왼쪽에는 작은 값, 오른쪽에는 큰값을 오게 만들어 재귀를 통해 정렬하는 것이다.
"""
import sys
arr=[]
n = int(input())
for i in range(n):
arr.append(int(input()))
def quickSort(left, right,arr):
# left 가 클 경우 종료
if left>=right:
return
i = left
j = right
pivot = arr[(lrft+right)//2]
# i,j 가 교차하면 종료한다.
while(i<=j):
# i 가 작은거라면 통과, 아니라면 멈춘다. -> 교환해야함.
while(arr[i]<pivot):
i+=1
# j가 큰거라면 통과 아니라면 멈춘다-> 교환
while(arr[j]>pivot):
j-=1
if(i<=j):
temp=arr[i]
arr[i]=arr[j]
arr[j]=temp
i+=1
j-=1
quickSort(left, j,arr)
quickSort(i,right,arr)
quickSort(0,n-1,arr)
for i in range(n):
print(arr[i])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.