text stringlengths 37 1.41M |
|---|
# /usr/bin/env python
# coding:utf-8
from collections import Counter
#将对象x转换为表达式字符串
'''
b = {"name":"apple","age":18}
str_b = repr(b)
print(str_b[0:3])
#用来计算在字符串中的有效Python表达式,并返回一个对象
a = "[1,2,3]"
list_a = eval(a)
print(list_a[0])
'''
#for year in range(1,100):
# print("我活了"+str(year)+"年")
str1 = 'abcdefgh'
for... |
# /usr/bin/env python
# coding:utf-8
'''
一般用open方法
1.file_instance.read(): 一次性读取文件全部内容
2.file_instance.readline(): 执行一次这个函数读取一行
3.ile_instance.readlines(): 一次性读取文件全部内容,并放到一个列表里面,每行是一个列表元素
4.file_instance.write(): 写入内容到文件,不换行
5.file_instance.writelines(): 把一个列表里面所有元素写入到文件,不换行
6.file_instance.flush(): 即时把缓存中的数据输... |
'''
题目描述:找出单链表中的倒数第k个元素,例如给定单链表:1->2->3->4->5->6->7
则单链表的倒数第k=3的元素为5
方法为快慢指针法,从头到尾进行遍历查找,在查找过程中,设置二个指针,让其中的一个指针比另一个指针先移动k步,
然后二个指针同时向前移动,循环直到先行指针为None时,另一个指针所指就是需要的值
'''
class LNode():
def _new_(self,x):
self.data = x
self.next = None
#构造一个单链表
def ConstructList(number):
i = 1
... |
"""
题目描述:LRU是指Least Recently Used 的缩写,它的意思是“最近最少使用”,LRU缓存就是使用这种原理。
即缓存一定量的数据,当超过设定的阈值,就把一些过期的数据删除掉
思路分析:
需要二个数据结构实现一个LRU缓存
1、使用双向链表实现的队列,队列最大容量为缓存的大小,使用过程中,把最近使用的页面移动到队列头,最近没有使用的页面放到队列尾
2、使用一个哈希表,把页号作为键,把缓存在队列中的结点的地址作为值。
当引用一个页面时,如果页面在内存中,只需要把这个页对应的结点移动到队列的前面。
如果所需的页面不在内存中,需要把这个页面加载到内存中
"""
from collections import dequ... |
"""
题目描述:
已知二个链表各自有序,head1、head2
请合并,合并后有序
思路:
分别用指针head1、head2来遍历二个链表,当前head1指向的数据小于head2指向的数据,则将head1指向的结点归入合并后链表中
否则,将head2指向的结点归入合并后的链表,
当有一个链表遍历结束,则把未结束的链表连接到合并后的链表尾部
"""
class LNode:
def _new_(self, x):
self.data = x
self.next = None
# 构造链表
def construct_list(number):
i = 1
head = ... |
from tkinter import *
root = Tk()
def sayhello():
print('hello')
mb = Menubutton(root, text='Menubutton的测试项', relief=RAISED)
mb.pack()
menu1 = Menu(mb, tearoff=False)
menu1.add_command(label='删除', command=sayhello)
menu1.add_command(label='重命名', command=sayhello)
mb.config(menu=menu1)
mainloop()
|
from tkinter import *
root = Tk()
def sayhello():
print('触发菜单栏选项')
def nothing():
print('无事发生')
#初始化一个菜单
menu1 = Menu(root)
#初始化一个菜单的子选项菜单
filemenu = Menu(menu1, tearoff=False)
filemenu.add_command(label='打开', command=sayhello)
filemenu.add_command(label='保存', command=nothing)
filemenu.add_separator()
fi... |
from tkinter import *
root = Tk()
def showinfo():
print('账号为: %s' % inputLabel1.get())
print('密码为: %s' % inputLabel2.get())
v1 = StringVar()
v2 = StringVar()
#设置按钮
button1 = Button(root, text='提交信息', width=10, command=showinfo)
button2 = Button(root, text='退出界面', width=10, command=root.quit)
label1 = L... |
def tax(cent=None, income=None):
value = cent / 100 * income
return round(value)
def calculate_tax(income=None):
if 0 <= income <= 15527:
percent = 0
calculated_tax = tax(percent, income)
elif 15528 <= income <= 42707:
percent = 15
calculated_tax = tax(percent, income)
... |
r1 = range(10)
r2 = range(10,50)
r3 = range(10,50,5)
r4 = range(10)
print(type(r1)) # <class'range'>
print(r1) # range(0,10)
print(list(r1)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(r3)) # [10, 15, 20, 25, 30, 35, 40, 45]
print(len(r1)) # 10
print(r1[1]) # 1
print(r1==r2) # False
print(r1==r4) # True
for i in ra... |
import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
for i in range(1,30):
brad.forward(20)
brad.circle(30)
for j in range(1,5):
brad.stamp()
brad.forward(... |
"""
Given a string, find the length of the longest substring
without repeating characters.
"""
def lengthOfLongestSubstring(s: str) -> int:
if len(s) <= 1:
return len(s)
seen = set(s[0])
l, r, cnt = 0, 1, 1
while r < len(s):
if s[l] == s[r]:
l += 1
r += 1
... |
"""
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
"""
def longestPalindrome(s: str) -> str:
pal = ""
for i in range(len(s)):
possible = find_palindrome(s, i, i)
pal = possible if len(possible) > len(pal) else pal
pos... |
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, AveragePooling2D, Dropout
from keras.models import models
def createGoogLeNet():
# Our shape is 3 for the RGB, 224 for number of pixels in the width, 224 for the number of pixels in the height.
input = Input(shape=(3, 224, 224) )
# First convolut... |
#!/usr/bin/env python
"""Communicate with an Arduino over I2C
(Take care of the voltage levels!)
Use the following sketch for the Arduino:
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
int number = 0;
void setup()
{
pinMode(13, OUTPUT);
Serial.begin(9600);
Wire.begin(SLAVE_ADDR... |
import random
import unittest
from recursion import get_fib, recursive_factorial
from searching import binary_search
from sorting import bubble_sort
class BinarySearchTest(unittest.TestCase):
def setUp(self):
self.test_list = [1, 3, 9, 11, 15, 19, 29]
def tearDown(self):
del self.test_list
... |
def sorted_words(s):
words = s.split()
words = [i.lower() + i for i in words]
return " ".join([i[-(len(i)//2):] for i in sorted(words)])
|
import matplotlib.pyplot as plt
import networkx as nx
import random
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]\
for row in range(vertices)]
# A utility function to check if the current color assignment
... |
# https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/
# 540/week-2-june-8th-june-14th/3357/
# Given an array with n objects colored red, white or blue, sort them
# in-place so that objects of the same color are adjacent, with
# the colors in the order red, white and blue.
# Here, we will use t... |
# https://leetcode.com/problems/find-the-difference/
# given two strings s and t which consist of only lowercase letters.
# string t is generated by random shuffling string s
# and then add one more letter at a random position.
# find the letter that was added in t
def findTheDifference(s: str, t: str):
result = 0
f... |
# https://leetcode.com/problems/roman-to-integer/
# function to take a Roman number and return an integer
# equal to that number
# assume the number is no greater than 3,999
def roman_to_int_1(roman: str) -> int:
result = 0
if "IV" in roman: result -= 2 # IV is 4, not 6
if "IX" in roman: result -= 2 # IX is 9, not... |
# https://leetcode.com/problems/counting-bits/
# given a non negative integer number num
# for every i in the range 0 ≤ i ≤ num calculate the number of 1's
# in their binary representation and return them as an array
# Input: 5 Output: [0, 1, 1, 2, 1, 2]
def countBits(num):
bits_array = []
for i in range(num + 1):
... |
# https://leetcode.com/problems/add-digits/
# Given a non-negative integer num, repeatedly add all its digits until
# the result has only one digit.
class Solution:
def addDigits1(self, num: int) -> int:
while num > 9:
sum_n = 0
for digit in str(num):
sum_n += int(di... |
# https://leetcode.com/problems/island-perimeter/
# You are given a map in form of a two-dimensional integer grid
# where 1 represents land and 0 represents water.
# Grid cells are connected horizontally/vertically (not diagonally).
# The grid is completely surrounded by water, and there is exactly
# one island (i.e., ... |
# compute and return the square root of x,
# where x is guaranteed to be a non-negative integer.
# since the return type is an integer,
# the decimal digits are truncated and
# only the integer part of the result is returned.
def mySqrt(x: int) -> int:
i = 0
while i * i < x:
i += 1
... |
from typing import List
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
l = len(nums)
for i in range(l):
while nums[nums[i]-1] != nums[i]:
tmp = nums[nums[i]-1]
nums[nums[i]-1] = nums[i]
nums[i] = t... |
# https://leetcode.com/problems/count-number-of-teams/
# There are n soldiers standing in a line. Each soldier is assigned
# a unique rating value.
# You have to form a team of 3 soldiers amongst them under the following rules:
# Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
# A ... |
# https://leetcode.com/problems/squares-of-a-sorted-array/
# Given an array of integers A sorted in non-decreasing order,
# return an array of the squares of each number, also in sorted
# non-decreasing order.
from typing import List
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
retu... |
class Solution:
powers_of_2 = {2**n for n in range(64)}
def isPowerOfTwo(self, n: int) -> bool:
if n in self.powers_of_2:
return True
else:
return False
####################
### TESTING ONLY ###
####################
solution = Solution()
for number in ran... |
# https://leetcode.com/problems/add-strings/
# Given two non-negative integers num1 and num2
# represented as string, return the sum of num1 and num2.
# you must not use any built-in BigInteger library
# or convert the inputs to integer directly.
def addStrings_1(num1: str, num2: str) -> str:
# much slower than metho... |
# https://leetcode.com/problems/prison-cells-after-n-days/
# There are 8 prison cells in a row, and each cell is either occupied
# or vacant. Each day, whether the cell is occupied or vacant changes
# according to the following rules:
# If a cell has two adjacent neighbors that are both occupied or both
# vacant, then... |
import os
balance = 10000
try:
CardNo = int(input("Please Enter your card Number\n"))
Pin = int(input("\nPlease Enter your Pin\n"))
except ValueError:
print("Please Enter a number")
while True:
try:
Operation = input(
"\nWhat do you want to do??\ni) Cash-Withdrawl\t Enter 1\nii... |
import numpy as np
def change(chosen_number: int, other_loser_number: int, box_num: int):
"""
箱を変えない戦略
:param chosen_number: 初めに選んだ箱
:param other_loser_number: 残った箱で外れのほうの箱
:param box_num:箱の数
:return:
"""
box_set = np.array([number for number in range(box_num)
i... |
#!/usr/bin/env python
"""Class Object for School."""
class School(object):
"""Class Object for School."""
def __init__(self):
"""Initializing the School Object."""
self._name = None
self._school_type = None
@property
def name(self):
"""Name property of the School Obje... |
from os import listdir
# Gets file from user
def file():
while 1:
print(listdir("Input Files"))
f = input("Please Select a File: ")
if f in listdir("Input Files"):
return f
else:
print("Please select one of the listed files")
# Used to print/verify file c... |
word='attack'
word1=word.encode('ascii')
def NRZ(word):
#word = "0111000110011"
word_in_list= list(word)
print(word_in_list)
NRZ_of_word=[]
for i in word_in_list:
if i == '0':
flip_the_bit= i.replace("0","1")
elif i == '1':
flip_the_bit = i.replace("1","0")
... |
from sys import argv
import csv
from cs50 import SQL
# check for input arguments
if len(argv) != 2:
print("Usage: import.py <file.csv>")
exit(1)
# connect to database
db = SQL("sqlite:///students.db")
# open csv file and write into db
with open(argv[1], "r") as file:
for p in csv.DictReader(file):
... |
class Contact:
"""Represents a contact object.
:ivar int id: id of the contact
:ivar str address: the email address of the contact
:ivar str display_name: the display name of the contact
"""
def __init__(self, id, address, display_name):
if display_name == None:
display_name... |
# Mock allows you to replace a part of your application with a dummy at
# test time. Depending on usage, it will even provide a context "with" that
# limits the scope of the dummy function to within the context only.
#
# Instead of calling the actual function, it calls the substitute function.
# It is useful in the f... |
from bfs import bfs
from a_star import a_star
from nodes import objects
import time
class Search:
def __init__(self):
self.intro()
playing = True
while playing:
print('\n')
prompt = str(input('Please input a letter or node you would like to start the search from: ... |
#!/usr/bin/env python
import RPi.GPIO as GPIO
pin = 14
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin,GPIO.IN,pull_up_down = GPIO.PUD_DOWN)
GPIO.setwarnings(False)
print 'status of the sensor is ', GPIO.input(pin)
raw_input("Press Enter to continue...")
print 'lower solenoid to down position and adjust sensor until progr... |
# CodingTest3-1 거스름돈 (array 활용)
while True:
N = int(input("거스름 돈을 입력하세요 : ")) # 입력 받는 거스름 돈
Coin_Count = 0 # 거슬러 주어야 할 동전의 개수
Coin_Value = [500,100,50,10] # 함수에서 사용 할 동전의 가격 리스트
if N > 0 and N % 10 == 0:
for coin in Coin_Value:
Coin_Count += int(N/coin) # int로 선언하여 정수부분만 사용
... |
data = [1, 2, 3]
new_data = []
for x in data:
new_data.append(x * 10)
print(new_data)
|
#Brute forcing the center points for all of the hexagons
import math
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
side_length = 69.28
radius = 60 #Radius is defined as distance from center to midpoint of edge
i = math.pi / 2
increment = 0
inner = 1
outer = 8
point_dic = {}
... |
"""
Напишите функцию которая принимает на вход список.
* Функция создает из этого списка новый список из квадратных корней чисел
(если число положительное) и самих чисел (если число отрицательное)
и возвращает результат (желательно применить генератор и тернарный оператор
при необходимости).
* В результате работы... |
'''
Day-11
'''
# File handling
# opening a file
file = open('files_data.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
# Creating a file
file = open('hello.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particu... |
'''
Day 2 :-
Assignment
Create a small program
1. Take variables with values of different types
2. Print these in different lines and with appropriate messages (use .format())
3. Practice Type conversion functions
(str(), int(), etc)
'''
# Creating Variables
name = "Ayush.v.tejpal"
age = 13
Progr... |
#!/usr/bin/env python3
import os
choices = ['A', 'B', 'C', 'D', 'E']
state = True
global score
score = 0
global turns
turns = 2
os.system('clear')
print("Score: 0 \nTotal Score: 0")
def runGame():
global state
global turns
print("\nTurns Left: {} ...\nChoose!:".format(turns))
print(choices)
var = ... |
from animals import Animal
from movements import Walking
# Designate Goat as a child class by adding (Animal) after the class name
class Goat(Animal, Walking):
# Remove redundant properties from Goat's initialization, and set their values via Animal
def __init__(self, name, species, shift, food, chip_number):
... |
#http://www.i-programmer.info/programming/python/3942-arrays-in-python.html
myList=[1,2,3,4,5,6]
print(myList) #is the entire list.
print(myList[:]) #is the entire list.
print(myList[2]) #will display the third element
myList[2]=100 #change the value
print(myList[2:5]) #is a sublist from the third element to the fifth... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 3 13:27:12 2014
@author: rdevera
"""
# Chapter 1: Exercise 9
# Type in programs and debug them
# Type these short programs in your editor and execute them. When they do not
# work, identify and correct the erroneous statements.
#a) Does sin^2(x)+cos^2(x)=1?
"""
from ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 3 18:59:40 2014
@author: rdevera
"""
# Chapter 7: Problem 6
# The constructor in class Line in Exercise 7.5 takes two points as arguments.
# NOw we want to have more flexibility i the way we specify a straight line:
# we can give two points, a point and a slope, or a s... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 3 18:45:13 2014
@author: rdevera
"""
# Chapter 7: Problem 5
# Make a class Line whose constructor takes two points p1 and p2
# (2-tuples or 2-lists) as input. The line goes through these two points.
# A value(x) method computes a value on the line at point x.
class Li... |
from Quad import Quad
from Point import Point
class Tree:
def __init__(self, size):
self.size = size
self.half_x = size / 2
self.half_y = self.half_x
self.points = []
self.quad = None
def insert(self, x, y):
point = Point(x, y)
if((x > self.size or y > ... |
#solve ricatti equation by iterating algorthm
#R:n*n,Q:k*k,H:k*n,
# A*n*n,B:n*k,P:n*n
import numpy as np
class RicattiEquation:
def __init__(self,beta,A,B,R,Q,H):
print("")
self.beta=beta
self.A=A
self.B=B
self.Q=Q
self.P=0
self.H=H
def check_input(se... |
from random import randint
money = 1000 # 初始资金
while money > 0:
print('你的资金为: %d' % money)
while True:
bet = int(input('请下注')) # 下注金额
# 判断下注金额是否合法
if 0 < bet <= money:
break
else:
print('下注失败')
# 开始摇色子
first = randint(1, 6) + randint(1, 6)
... |
"""
The Collatz Conjecture
"""
def main():
print("This programme shows the Collatz conjecture \n")
num = eval(input("Please entre the starting value you wish to use: "))
while (num != 1):
if (num % 2) == 0 and num > 0:
num = num / 2
print(num)
else:
... |
#!/usr/bin/python3
def func(*args):
sum=0
for i in range(0,len(args)):
sum+=args[i]
return sum
print(func(1,2,3,4,5))
print(func(4,6,3))
print(func(1,2)) |
#!/usr/bin/python3
def pattern1(type='*', limit=10):
for i in range(1, limit+1):
for j in range(1, i+1):
print(type, end=" ")
print(end="\n")
# function call
pattern1()
pattern1(type='+')
pattern1(type='+', limit=50) |
#!/usr/bin/python3
from functools import partial
def func(a,b,c,x):
return 1000*a+100*b+10*c+x
g=partial(func,3,1,4)
#Calling partial function
print(g(5))
def func1(a,b,c):
return 100*a+10*b+c
g1=partial(func1,c=2,b=5)
print(g1(8))
|
#!/usr/bin/python3
num1 = int(input("Number 1? "))
num2 = int(input("Number 2? "))
print(num1 + num2) |
list=[1,2,3,4]
list.append(5)
print(list)
from sys import argv
print(argv[0])
list=[1,2,3,4,5,6]
print(list)
print(list[::-1]) |
#!/usr/bin/python
def count_digit(limit,digit):
count=0
for var in range(0,limit+1):
if var>9:
list=chop_digit(var)
print(list)
for i in list:
if list[i]==digit:
count+=1
else:
count+=1
return count
def chop_digit(digit):
list=[]
while(digit>0):
list.append(digit%10)
digit//=10
re... |
#!/usr/bin/python
import numpy
#Create a multidimensional array
arr=numpy.array([[1,2,3],[4,5,6]])
print(type(arr))
print(arr.ndim) #number of dimensions
print(arr.shape)
print(arr.size)
print(arr.dtype)
ar=numpy.array([[1,2,4],[5,7,6]] , dtype='float' )
print(ar)
arzeros=numpy.zeros([3,5])
print(arzeros)
arfull=n... |
moves = list(input())
cups = [1, 2, 3]
temp = 0
for move in moves:
if move == "A":
temp = cups[0]
cups[0] = cups[1]
cups[1] = temp
if move == "B":
temp = cups[1]
cups[1] = cups[2]
cups[2] = temp
if move == "C":
temp = cups[0]
cups[0] = cups[2]... |
lines = []
for i in range(5):
lines.append(input())
count = 0
for i in range(len(lines)):
if "FBI" not in lines[i]:
count += 1
if count == 5:
print("HE GOT AWAY!")
else:
for i in range(len(lines)):
if "FBI" in lines[i]:
if i == 4:
print(i+1)
else... |
times = int(input())
for i in range(times):
r, e, c = input().split()
r = int(r)
e = int(e)
c = int(c)
if r + c == e:
print("does not matter")
elif r + c < e:
print("advertise")
elif r + c > e:
print("do not advertise") |
people, chicken = [int(x) for x in input().split()]
if chicken - people < 0:
if abs(chicken - people) == 1:
print("Dr. Chaz needs", str(abs(chicken-people)), "more piece of chicken!")
else:
print("Dr. Chaz needs", str(abs(chicken-people)), "more pieces of chicken!")
elif chicken - people > 0:
... |
times = int(input())
for i in range(times):
num = int(input())
if num % 2 == 0:
print(num, " is even")
elif num % 2 != 0:
print(num, " is odd") |
matrix = [[0 for i in range(4)] for j in range(5)]
for y in range(5):
matrix[y] = input().split()
for y in range(5):
for x in range(4):
matrix[y][x] = int(matrix[y][x])
sums = []
sum = 0
for y in range(5):
for x in range(4):
sum += matrix[y][x]
sums.append(sum)
sum = 0
num = ma... |
from typing import Dict
class Video:
""" The Video class is modelled after the DataGym.io Video
DataGym.io Videos fetched from the DataGym API will be parsed
into Video objects.
"""
def __init__(self, data: Dict):
""" Initializes DataGym Video instance
:param Dict data: Respons... |
# Prompt user for a radius
radius = eval(input("Enter a value for radius: "))
# Compute area
area = radius * radius * 3.14159
# Display results
print("The area for the circle of radius", radius, "is", area)
|
print("Ejercicio 01.06. Escribir un programa que reciba un número n por parámetro e imprima los primeros números triangulares, junto con su índice. \nLos números triangulares se obtienen mediante la suma de los números naturales desde 1 hasta n. Es decir, si se piden los primeros 5 números triangulares, el programa deb... |
print("Ejercicio 01. Escribir dos funciones que permitan calcular:\n-La cantidad de segundos en un tiempo dado en horas, minutos y segundos.\n-La cantidad de horas, minutos y segundos de un tiempo dado en segundos.")
def HoraMinutoXSeg(h,m,s):
return ((h*60)+m)*60+s
h=2
m=30
s=3
segundos=9003
print("La can... |
# -*- coding: utf-8 -*-
#author Marcelo Santos
from descontos import Desconto_por_dois_itens, Desconto_por_cinco_itens, Desconto_por_mais_de_quinhentos_reais, Sem_desconto
class Calculador_de_descontos(object):
def calcula(self, orcamento):
desconto = Desconto_por_dois_itens(
Desconto_por_cinco_itens(
Des... |
def replace_all(original,to_replace,replace_with):
for index in range(len(original)):
if original[index] == to_replace:
original[index] = replace_with
a = [1,2,1,3,5,1]
replace_all(a,1,"d")
print(a)
|
seconds = input("Enter Seconds: ")
#sec = int(seconds) / 60
x_seconds = int(seconds) % 60
y = int(seconds) - x_seconds
minutes = y / 60
c = int(minutes) % 60
hour= int(minutes) - c
print (str(seconds) + " seconds is " + str(hour) + " hours, " + str(minutes) + " minute, and " + str(x_seconds) + " seconds")
|
# Netanel Bashan, 323056077, netanebashan12@gmail.com
# Elyasaf Dimant, 204006415, elyasafdi@gmail.com
import random
columns = []
number_of_iterations = 1
# Let's setup one iteration of the British Museum algorithm-- we'll put down "size" queens randomly.
def place_n_queens(size):
columns.clear()
row = 0
... |
import numpy as np
def DFT(data):
"""
important concept learned here is if Nmn is a function of two variables m and n,
create m (N X 1) and n (1 X N) array then apply function using these two array
to obtain vectorized result.
data could be list or array type object
"""
data = np.asarr... |
import sqlite3
(lst,item,k,sub,sub1,sub2,sub3,sub4,sub5,sub6,sub7,sub8,sub9,sub10,sub11,sub12,sub13,name)=([],[],0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,'')
def subcalc(subcode):
if subcode=="301" : subname="English Core"
if subcode=="042" : subname="Physics"
if subcode=="043" : subnam... |
# Basic hours to seconds program
# Name: Raul Costa
# Date: 11/10/2021
# Version: 1.0
hours = 2 # number of hours
seconds = 3600 # number of seconds in 1 hour
print("Hours: ", hours) # printing the number of hours
print("Seconds in Hours: ", hours * seconds) # printing the number of seconds in a given number of hours... |
'''
Name: Raul Costa
Date: 04/10/2021
'''
pound = 0.74
euro = 0.86
amount = float(input("How many USD do you want convert to Pounds? "))
usd_eur = amount * euro
usd_pound = amount * pound
print(f'You can convert the {amount}USD into {usd_eur:.2f}EUR or to {usd_pound:.2f}GBP if you prefer!')
|
#!/usr/bin/env python
# coding:utf-8
# https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431752945034eb82ac80a3e64b9bb4929b16eeed1eb9000
# 默认参数很有用,但使用不当,也会掉坑里。默认参数有个最大的坑
# 定义默认参数要牢记一点:默认参数必须指向不变对象
def add_end(L=[]):
L.append('END')
print(L)
return L
def add_end_r(L=... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2019-05-09 11:09'
"""
斐波那契数列
F(n) = F(n-1) + F(n-2)
返回斐波那契数列之和
"""
def f(n):
if n==1 or n==2:
return 1
else:
return f(n-1) + f(n-2)
print(f(10)) |
# coding=utf-8
"""
DATE: 2021/8/13
AUTHOR: TesterCC
"""
# 基于进程的并行 https://docs.python.org/zh-cn/3/library/multiprocessing.html
from multiprocessing import Pool
def f(x):
return x*x*x
if __name__ == '__main__':
# 最基本的使用
with Pool(4) as p:
print(p.map(f,[1,2,3,4,5])) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2019-07-15 11:32'
"""
lesson 4
线性结构:
1.内存连续
2.下标访问
cd ~/Python3Demo/pw_python/algorithm
pytest array_and_list.py
ref:
https://pegasuswang.github.io/python_data_structures_and_algorithms/02_%E6%95%B0%E7%BB%84%E5%92%8C%E5%88%97%E8%A1%A8/arra... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'TesterCC'
# __time__ = '17/11/13 22:54'
"""
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014318650247930b1b21d7d3c64fe38c4b5a80d4469ad7000
访问限制
"""
# 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,
# 在Python中,实例的变量名如果以__开头,就变成了一... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2019-07-11 13:34'
"""
P29 状态模式
"""
from abc import ABCMeta, abstractmethod
class State(metaclass=ABCMeta):
"""
State abstract class
"""
def __init__(self, name):
self.__name = name
def getName(self):
re... |
# coding=utf-8
'''
DATE: 2020/09/03
AUTHOR: Yanxi Li
'''
"""
1.11 命名切片
问题:
你的程序已经出现一大堆已无法直视的硬编码切片下标,然后你想清理下代码。
解决方案1:命名切片
内置的 slice() 函数创建了一个切片对象,可以被用在任何切片允许使用的地方
"""
record = '..........100...........513.25...........'
# 内置的 slice() 函数创建了一个切片对象,可以被用在任何切片允许使用的地方
SHARES = slice(10, 13)
PRICE = slice(24, 30)
cos... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2020-01-13 17:52'
import collections
"""
4-1 Python内置数据结构算法常考
collections主要的:
namedtuple()
deque
Counter
OrderedDict
defaultdict
建议看源码了解底层结构和实现原理,面试问得深会问到。
举个例子:OrderedDict如何实现有序的?
使用循环双端链表保存key进入的顺序。
"""
print("*"*30 + " namedtuple " + "*... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2019-03-21 22:03'
TmpStr = input("")
if eval(TmpStr) == 0:
print("Hello World")
elif eval(TmpStr) > 0:
st = ''
string = "Hello World"
for i in range(len("Hello World")):
if (i + 1) % 2 != 0:
st = st + strin... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'TesterCC'
# __time__ = '17/11/27 19:03'
"""
要求是把列表里的重复元素删除,只保留没有重复的元素。
例如:
a=['a','b','c','d','a','a']
如何变成:
a=['b','c','d']
level easy
"""
# Method 1 -- 只保留没有重复的元素
a = ['a', 'b', 'c', 'd', 'a', 'a']
b = [x for x in a if a.count(x) == 1]
print(b)
# Meth... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'TesterCC'
# __time__ = '17/9/29 15:39'
'''
题目描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
数组 二维数组中的查找
'''
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
f... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/6/5 22:32'
"""
14章 Pythonic与Python杂记
"""
def get_sunday():
return 'Sunday'
def get_monday():
return 'Monday'
def get_tuesday():
return 'Tuesday'
def get_default():
return 'Unknown'
switcher = {
0: get_sunday, ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2020-01-14 15:51'
"""
4-1 Python内置数据结构算法常考
什么是LRUCache?
Least-Recently-Used 替换掉最近最少使用的对象
1.缓存剔除策略,当缓存空间不够用的时候需要一种方式剔除key
2.常见的有:LRU(Least-Recently-Used,替换掉最近最少使用的对象),LFU(Least-Frequently-Used,根据数据的历史访问频率来淘汰数据)
3.LRU通过使用一个循环双端队列不断把最新访问的ke... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/5/5 13:44'
"""
4-5 类变量和实例变量
"""
class A:
aa = 1 # 类变量
def __init__(self, x, y): # self代表实例
self.x = x # 实例变量
self.y = y
a = A(2, 3)
A.aa = 11 # 改变类变量
a.aa = 100 # 给实例a增加了一个实例变量aa
print(a.x, a.y, a.aa)
prin... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/4/26 11:10'
"""
最基础的敏感词屏蔽
https://blog.csdn.net/qq_35793358/article/details/77947078
"""
user_input = input("Please input your words: \n")
def filter_sensitive_words(user_text=user_input):
"""
filter sensitive word in user input ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/6/27 10:26'
"""
round() 方法返回浮点数x的四舍五入值
以下是 round() 方法的语法:
round( x [, n] )
参数
x -- 数字表达式。
n -- 表示从小数点位数,其中 x 需要四舍五入,默认值为 0。
返回值
返回浮点数x的四舍五入值。
http://www.runoob.com/python3/python3-func-number-round.html
"""
print("round(70.23456) : ",... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'TesterCC'
# __time__ = '17/11/16 21:07'
"""
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143191235886950998592cd3e426e91687cdae696e64b000
使用枚举类
为这样的枚举类型定义一个class类型,每个常量都是class的一个唯一实例
Python提供了Enum类来实现这个功能
如果需要更精确地... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'TesterCC'
# __time__ = '17/10/31 14:52'
"""
Python网络爬虫--从入门到实践 P17-18 2.2.5 面向对象编程
"""
class Person(object):
def __init__(self, name, age): # __init__()为类的构造方法
self.name = name
self.age = age
def detail(self): # 通过self调用被... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.