text stringlengths 37 1.41M |
|---|
class Calculadora():
def __init__(self):
self.bateria = Bateria()
self.entrada = TeclasCalculadora()
self.operacoes = Operacoes()
self.display = Display()
def novaOperacao(self, valor1, valor2):
self.entrada.valorEntrada(valor1, valor2)
self.bateria.uso()
d... |
class Rectangle:
def __init__(self,width,height):
self.height = height
self.width = width
def __str__(self):
return f"Rectangle(width={self.width}, height={self.height})"
def set_height(self,height):
self.height = height
return None
def set_width(self,width... |
import keras
from keras import backend as K
from gym import Env, spaces
import numpy as np
from Model import Model
class KerasModel(Model):
"""
An implementation of Model that approximates the action-value function using a neural network implemented with
Keras. The Keras model used has to be provided on... |
#_*_coding:utf-8_*_
count = 0
while count <= 100:
print("loop ", count)
if count == 5:
continue
count += 1
print('---out of the loop ---') |
#_*_coding:utf-8_*_
def range2(n):
count = 0
while count < n:
print('count',count)
count += 1
sign = yield count # return
if sign == 'stop':
print("---sign", sign)
break
print('sin...',sign)
return 3333
new_range = range2(3)
# n1=next(ne... |
#1、新式类
#2、经典类
#在python2中-》经典类:没有继承object的类,以及它的子类都称之为经典类
#
# class Foo:
# pass
#
# class Bar(Foo):
# pass
#
#
# #在python2中-》新式类:继承object的类,以及它的子类都称之为新式类
# class Foo(object):
# pass
#
# class Bar(Foo):
# pass
#在python3中-》新式类:一个类没有继承object类,默认就继承object
# class Foo():
# pass
# print(Foo.__bases__)... |
#多态:同一类事物的多种形态
import abc
class Animal(metaclass=abc.ABCMeta): #同一类事物:动物
@abc.abstractmethod
def talk(self):
pass
class People(Animal): #动物的形态之一:人
def talk(self):
print('say hello')
class Dog(Animal): #动物的形态之二:狗
def talk(self):
print('say wangwang')
class Pig(Animal): #动物的形态之三... |
>>>
>>> L2 = ['a','b','c','d','a','e',1,2]
>>>
>>> L2[2] #通过索引取值
'c'
>>> L2[-1] #通过索引从列表右边开始取值
2
>>> L2[-2]
1
>>> L2.index('a') #返回指定元素的索引值,从左右查找,找到第一个匹配值 则返回
0
>>> L2.count('a') #统计指定元素的个数
2
>>>
>>> L2
['a', 'b', 'c', 'd', 'a', 'e', 1, 2]
>>>
>>> L2[0:3] #返回从索引0至3的元素,不包括3,顾头不顾尾
['a', 'b', 'c']
>>> L2[0:-1] #返... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Date: 2017/6/15
"""
#练习一:
if True or False and False:
print('yes')
else:
print('no')
#输出结果为?为什么?
if (True or False) and False:
print('yes')
else:
print('no')
#输出结果为?为什么?
"""
# if True or False and False:
# print('yes')
# else:... |
'''
练习1:编写一个学生类,产生一堆学生对象, (5分钟)
要求:
有一个计数器(属性),统计总共实例了多少个对象
'''
class Student:
school='luffycity'
count=0
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
# self.count+=1
Student.count+=1
def learn(self):
print('%s is learing'... |
#并发执行
import time
def producer():
g=consumer()
next(g)
for i in range(10000000):
g.send(i)
def consumer():
while True:
res=yield
start_time=time.time()
producer()
stop_time=time.time()
print(stop_time-start_time)
#串行
import time
def producer():
res=[]
for i in range(100... |
# -*- coding:utf-8 -*-
# __author__="X1gang"
# Date:2018/12/8
# 组合 :对象1的属性是对象2,对象1就拥有了对象2的数据和函数属性,这就是组合
'''
# A类型和B类型没有共性,不可以继承,但是A有B的特性,比如A是人,B是家,A和B没有继承关系,但是人有家,A有B的关系,那么就可以把B的属性都给A用
class people:
def __init__(self,name,age):
self.name = name
self.age = age
def say_hi(self):
print("... |
'''
Write a program to handle the following exceptions in you program.
a) KeyboardInterrupt,
b) NameError
c) ArithmeticError
Note : make use of Try, except, else: statements.
'''
#a
import time
try:
while(True):
time.sleep(1)
print(1)
except KeyboardInterrupt... |
# 求一个字符串 list 中,字符串长度大于2,且首尾字符相同的元素个数
# [‘a’, ‘xy’, ‘alabama’, ‘101’]
# 2
l = ['a','xy','alabama','101']
num = list(filter(lambda s:isinstance(s,str) and len(s) >= 2,l))
print(num) |
# 定义函数,把一个list的元素去重,返回新的List
ids = [1,2,3,3,4,2,3,4,5,6,1]
news_ids = []
for id in ids:
if id not in news_ids:
news_ids.append(id)
print (news_ids) |
import logging
import time
import InputHandler
from ComputerAgent import ComputerAgent
from Game import Game
def list_of_zeroes(n):
return [0] * n
def ask_player_cnt():
while True:
player_cnt = InputHandler.handleInput("How many players?: ", type_cast=int)
if player_cnt < 1:
print("Too small player count!... |
class Stack():
def __init__(self):
self.stack=[]
def IsEmpty(self):
return self.stack==[]
def push(self,element):
self.stack=self.stack+[element]
def peek(self):
return self.stack[-1]
def pop(self):
a=self.stack[-1]
self.stack=self.stack[0:-1]
... |
global a
a=0
def is_palindromes(s):
'''
:param s: a string
:return: whether it is palindromes(ignore non-letter and case)
'''
def toChars(s):
global a
s=s.lower()
letters=""
for c in s:
a+=1
if c in "qazxswedcvfrtgbnhyujmkiolp":
... |
import unittest
import random
import itertools
# Given a string (e.g. "What the hell?"), returns a list of the following pattern
# ['What the hell?', 'What the hell', 'What the hel', 'What the he', 'What the h', 'What the ',
# 'What the', 'What th', 'What t', 'What ', 'What', 'Wha', 'Wh', 'W']
def input_nput_put_ut_t(... |
def Domain(R):
#Takes a relation as a set of pairs and returns the domain
#Domain({(1,2),(2,3)})={1,2}
answer=set()
for p in R:
answer.add(p[0])
return answer
def Range(R):
#Take a relation as a set of pairs and returns the range
#Range({(1,2),(2,3)})={2,3}
answer=set()
for ... |
def cal_balance_12(b,a,m):
'''
:param b: balance
:param a: annualInterestRate
:param m: monthlyPaymentRate
:return:balance remained after 12 months
'''
for i in range(12):
b=(b-b*m)+(b-b*m)*a/12
return round(b,2)
print(cal_balance_12(42,0.2,0.04))
print(cal_balance_12(484,0.2,0.0... |
'''
Source codes for Python Machine Learning By Example 2nd Edition (Packt Publishing)
Chapter 9: Stock Price Prediction with Regression Algorithms
Author: Yuxi (Hayden) Liu
'''
import pandas as pd
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class PetCat(object):
"""家猫类"""
def __init__(self, name, age):
"""
构造方法
参数 name: 猫的名称
参数 age: 猫的年龄
"""
self.name = name
# 私有属性,不能随意改变
self.__age = age
@property
def age(self):
retur... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def pow():
yield 1
yield 2
yield 3
yield 4
def pow_num1():
return (x * x for x in [1, 2, 3, 4, 5])
def pow_num2():
for x in [1, 2, 3, 4, 5]:
yield x * x
if __name__ == '__main__':
# rest = pow()
# print(next(rest))
# prin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 21:55:12 2019
@author: superallen
"""
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 3, 5, 6, 3, 4, 5, 2, 5, 7]
plt.scatter(x, y, label='ssssss')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sc')
plt.legend()
plt.sho... |
class Iter2D:
def __init__(self, two_d):
self.two_d = two_d
self.i = 0
self.j = 0
def next(self):
ret = self.two_d[self.i][self.j]
self.j += 1
while self.has_next() and self.j == len(self.two_d[self.i]):
self.j = 0
self.i += 1
retu... |
class Tree:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def solve(tree):
return list(reversed(helper(tree)[0]))
def helper(tree):
if tree is None:
return [], 0
if tree.left is None and tree.right is None:
... |
def solve(s, k):
substring_start = 0
current_index = 0
current_substring = ''
chars = set()
longest_substring = ''
while substring_start < len(s):
current_char = s[current_index]
chars.add(current_char)
if len(chars) > k or current_index > len(s) - 2:
... |
def zigzag(s, k):
mat = [[' ' for _ in s] for _ in range(k)]
row = 0
step = 1
for i, c in enumerate(s):
mat[row][i] = c
row += step
if row == 0 or row == k - 1:
step = -step
return '\n'.join(''.join(row) for row in mat)
if __name__ == "__main__":
print(zigza... |
# O(|s|^2 * |chars|)
def brute(s, chars):
return min(
filter(
lambda s: not (chars - set(s)),
(s[i:j] for i in range(len(s) - len(chars) + 1) for j in
range(i + len(chars), len(s) + 1))
),
key=len)
# O(|s| * |chars|)
# could impro... |
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_leaf(tree):
return [tree.left, tree.right] == [None] * 2
def same_value(tree):
return len({
tree.value,
tree.left.value if t... |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left:
self.left.insert(value)
else:
self.left = Node(value)
... |
def solve(arr):
"""
Horrible, quadratic complexity, no extra space though
"""
return [
len([y for y in arr[i+1:] if y < x])
for i, x in enumerate(arr)
]
def _solve(arr):
"""
Slightly faster, O(n log n) time complexity, but O(n) extra space
Also, not valid Python, we are... |
def do_swaps(arr, color, start=0):
first_diff = start
while arr[first_diff] == color:
first_diff += 1
color_i = first_diff
for i in range(first_diff + 1, len(arr)):
if arr[i] == color:
arr[color_i], arr[i] = arr[i], arr[color_i]
color_i += 1
return color_i
# ... |
def operation(a,b,operation): #operationmath(a=1, b=22, operation="mul")
if False:
return a+b
elif True:
return a-b
elif True:
return a*b
else :
return a+b
temp = operation(1,2,"add")
print(temp)
temp = operation(11,2,"sub")
print(temp)
temp = operation(1,22,"mu... |
""" A Functional Breakfast """
num ='2345'
name='aishwaryaadsfasdfasdfasdf'
fruits = ['banana', 'apple', 'mango', 'strawberry']
def test():
print('2')
print('3')
print('4')
print('5')
print(num)
def getname():
print(name)
def getcity():
print('fremont')
def forloopsample():
for let... |
#Helen Ye, Jennifer Zhang
#SoftDev1 pd7
#HW03 -- StI/O: Divine your Destiny!
#2017-09-15
import random
def read_occupations():
# Read the file
# 'U' is the universal newline (in case the csv file was made in Windows)
source = open('occupations.csv', 'rU')
# Strip of newlines at the beginning of end of ... |
import random
rnumber = [random.randint(10, 99) for x in range (100)]
mult_five = []
mult_three = []
for number in rnumber:
if number%5==0:
mult_five.append(number)
elif number%3==0:
mult_three.append(number)
print(mult_five)
print(mult_three)
print(sum(mult_five+mult_three))
... |
""" Denne python fil er en eksempel løsning på opgaverne fra
lektion 1. Der kan være andre varianter at løse opgaverne på, men dette
er mit bud"""
#opgave 1
print("Opgave 1 løsning:")
print("Hello world")
#Opgave 2
print("Opgave 2 løsning")
navn = "Hej, mit navn er Martin"
print(navn)
navn = "Ny besked!"
print(navn... |
""" Denne indeholder eksempel kode fra lektion 4 - bruger input og while"""
navn = input("Hvad er dit navn: ")
print("Hej "+navn +"!")
alder = int(input("Hvad er din alder, "+navn+"? "))
if alder<18:
print("Du er meget ung!")
elif alder>80:
print("Du er meget gammel")
else:
print("Du er hverken ung elle... |
""""
GLLAguilar
DATALOG Lab04
FEB. 12, 2020
I have neither received nor provided any help
on this (lab) activity, nor have I concealed
any violation of the Honor Code.
"""
from abc import ABC, abstractmethod
class Polygon(ABC):
def __init__(self, lengths_sides):
self.number_sides = le... |
""""GLLAguilar
DATALOG Lab02
FEB. 5, 2020
I have neither received nor provided any help
on this (lab) activity, nor have I concealed
any violation of the Honor Code.
"""
print("'+' ADDITION")
print("'-' SUBTRACTION")
print("'/' = DIVISION")
print("'*' MULTIPLICATION")
a = float(input()) #to input t... |
#Create_a_list
areas=list([hall,kit,liv,bed,bath])
print(areas)
#Create list with different types
areas = ['hallway',hall,'kitchen', kit, "living room", liv,'bedroom', bed, "bathroom", bath]
print(areas)
#List of lists
house = [["hallway", hall],
["kitchen", kit],
["living room", liv],
[... |
loop = 1
op = 0
while loop == 1:
print("welcom calculator")
print("options:")
print("")
print("1:addtion")
print("2:subtraction")
print("3:multiplication")
print("4:division")
print("5:quit")
print("")
op =int(input("select option:"))
try:
if op == 1:
... |
#1.program to loop through a list of number
z=[4,3,2,6]
for i in z:
print(i,i+2) #add +2 value for each element
#2.write a program
for i in range(1,6):
for j in range(5,i-1,-1):
print(j,end="")
print("\n")
#3.print the fibonacci sequence
def fib(n):
a=0
b=1
if n == 1... |
print ("Problem 1: arithmetic operations")
def operation():
number1 = int (input("Enter number #1: "))
number2 = int(input("Enter number #2: "))
operation = int(input("Enter the operation number (1 for addition, 2 for subtraction, 3 for multiplication and 4 for division: "))
print ("number1: ", number1)
... |
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set init... |
import datetime
class Memory():
def __init__(self, title, contributor, story, date, charity, id=None):
self.title = title
self.contributor = contributor
self.story = story
self.date = date
self.charity = charity
self.id = id
def convert_date(self):
... |
class Robot:
name = ""
speed = 0
pollution = 0
def __init__(self, name="War Machine", speed=8.5):
self.speed = speed
self.name = name
self.distance = 0
def walk(self,time):
""" Multiply the speed with the time to obtain the distace and pollution """
self.di... |
# -*- coding: utf-8 -*-
class Sample:
# コンストラクタ
def __init__(self, name, age):
self.name = name
self.age = age
# 成人かチェックする関数
def judge(self):
if self.age >= 20:
print(self.name + 'さんは' + '成人です')
else:
print(self.name + 'さんは' + '成人ではありません')
# リスト... |
import pygame
import sys
# -- Initialization --
pygame.init()
# -- Constants --
SCREEN_WIDTH, SCREEN_HEIGHT = 600, 600
SQUARE_SIZE = 75
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
LIGHT_BROWN = (237, 201, 175)
DARK_BROWN = (159, 129, 112)
# -- Functions --
# As the name suggests this dra... |
#1.1 정수
print((999).bit_length()) #int는 불변형 4바이트 bit_lenth 를 이용하여 바이트수 확인 가능
print()
s = '11'
d = int(s)#casting
print('\'11\'을 정수로 변환:', d)
b = int(s, 2) # 10진수로 변환하기 --> int(문자열, 밑)
print('\'11\'을 밑이 2인 10진법으로 변환:', b)
print('====================================')
# 1.2 부동소수점
# 1.2.1 부동소수점끼리 비교
# 32비트 부동소수점에서 1비트=... |
class Card:
def __init__(self, value, pos):
self.value = value
self.is_reveal = False
self.pos = pos
# Special Methods
def __str__(self):
return f"{ str(self.value) + ('' if self.value > 9 else ' ')}"
def __eq__(self, other):
return self.value == other.value
... |
"""
This script asks for an augmentation factor from user
and augments the original data with TGAN generated data
Augmentation Factor = 1 is when no of males = no of females
"""
import pandas as pd
from sklearn.utils import shuffle
def number_of_synthetic_data(aug_fact, data):
"""
This function finds the numbe... |
import os
import sys
import time
from random import randint
class itemsClass():
def __init__(self, value, inventory):
self.name = name
self.value = value
class Talisman_of_Truth(itemsClass):
value = 100
def add_tali(self):
player.inventory.append('Talisman_of_Truth')
player... |
teta = PI/3
R = 200 #comprimento
g = 980.0 #aceleração da gravidade
vt = 0.01
h = R-R*cos(teta)
EM = g*h+(vt**2)/2
oldt = millis()/1000.0
ver = 1.0
def setup():
size(800,800)
def draw():
global oldt, teta, R, vt, g, h, EM, ver
t = millis()/1000.00
dt = t - oldt
oldt = t
omega = ve... |
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def predict(data, root, sample):
split = root[0]
col = split[0]
pivot = split[1]
confidences = root[1]
confidences_smaller = confidences[0]
confidences_larger = confidences[1... |
#countdown
newlist = []
def Countdown (num):
for i in range (num,-1,-1):
newlist.append(i)
return newlist
print(Countdown (5))
#print and return
def print_and_return (list):
print (list[0])
return list[1]
print ( print_and_return ([1,2]))
#First Plus Length
def First_Plus_Length (arr):
firstv... |
def findComments():
file = open('code.txt','r')
counter = 0
for line in file:
if line.find('#') != -1:
counter = counter + 1
print(counter)
findComments()
|
'''
Created on Jan 21, 2019
@author: Aaron
'''
print("math homework.py")
problom=input("enter a MATH problom or 'q' to quit")
while(problom!="q"):
print("the answer to ",problom,"is",eval(problom))
problom=input("enter another math problom or 'q' to quit") ... |
'''
Created on Feb 1, 2019
@author: Aaron
'''
# -*- coding: utf-8 -*-
star=input("how many stars you haw? ")
print(star)
if star>=(5):
print("your good! give one kiss")
elif star == (4):
print("your great give one hug")
elif star == (3):
print("saylove")
else:
print("scream out or hurt b... |
class LinkedListNode:
"""linked list node"""
def __init__(self, item, next=None):
self.item = item
self.next = next
class LinkedList:
"""linked list"""
def __init__(self):
# sentinel
self._nil = LinkedListNode(item=None)
self._nil.next = self._nil
self.t... |
from math import inf
from .keyed_item import KeyedItem
from .linked_list import LinkedList, LinkedListNode
from .doubly_linked_list import DoublyLinkedList, DoublyLinkedListNode
from .binary_search_tree import BinarySearchTree
class BaseDictionnary:
def search(self, key) -> KeyedItem:
"""Given a search k... |
import rps,tic,double_card_game_X,raja_vajeer,sys,time,os
def start():
print('1-rock paper scissors\n2-double card game\n3-tic tac toe\n4-raja vajeer')
i=int(input('enter your choise\n'))
if(i==1):
rps.start()
elif(i==2):
double_card_game_X.start()
elif(i==3):
... |
'''
Реализуйте программу, которая будет вычислять количество различных объектов в списке.
Два объекта a и b считаются различными, если a is b равно False.
Вашей программе доступна переменная с названием objects, которая ссылается на список,
содержащий не более 100 объектов. Выведите количество различных объектов в эт... |
'''
Напишите программу, которая выводит на экран текст «I***like***Python» (без кавычек).
'''
print('I','like','Python',sep='***')
'''
Напишите программу, которая считывает строку-разделитель и три строки,
а затем выводит указанные строки через разделитель.
'''
sep = input()
one = input()
two = input()
three = input()... |
# fibonacci series
num=int(input("Enter the last number up to which series creates : "))
a=0
b=1
c=0
while(True):
print(c, end=",")
a=b
b=c
c=a+b
if(c>num):
break |
num=int(input("enter the number of rows: "))
c=1
for i in range(1,num+1):
for j in range(1,num-i+2):
print(c," ",end='')
c=c+1
print()
|
"""
@file
@brief Measures speed.
"""
import sys
from timeit import Timer
import numpy
def measure_time(stmt, context, repeat=10, number=50, div_by_number=True):
"""
Measures a statement and returns the results as a dictionary.
:param stmt: string
:param context: variable to know in a dictionary
:... |
# find the score of the runner-up(second maximum score)
n = 5
arr = 2, 3, 6, 6, 5
arr2 = list(map(int, arr))
arr2.sort(reverse=True)
last_element = arr2[0]
for x in arr2:
if x < last_element:
break
print(x)
|
#! usr/bin/python3
# ABS_10_debugCoinToss.py -> A coin toss guessing game where the player gets two guesses
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.disable(logging.CRITICAL)
logging.debug('Start of program.')
import random
guess = []
while g... |
#AWS_10_practiceProblems
"""1. Write an assert statement that triggers an AssertionError
if the variable spam is an integer less than 10."""
assert spam >= 10, "The spam variable is less than 10!"
# Learning: Make sure to understand the task correctly & fully.
"""2. Write an assert statement that triggers an Asserti... |
#! /usr/bin/python3
# ABS_15_countdown.py > a simple countdown script
import subprocess
import time
timeLeft = 10
while timeLeft > 0:
print(timeLeft)
time.sleep(1)
timeLeft = timeLeft - 1
# At the end of the countdown, play a sound file
subprocess.Popen(['open','231-freelancing.mp3'])
'''
Question:
-... |
#! /usr/bin/env python3
# printTable.py - A program that takes a list of lists of strings and
# displays it in a table with each column right-justified.
# Each inner list is displayed in a column, organized from top to bottom,
# with the first inner list at the leftmost column.
# Assumes that all the inner lists contai... |
# 具名元组: 有字段名的元组
# 普通元组是一条没有字段名的记录
# 1. 定义和使用具名元组
from collections import namedtuple
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', '1m', (35.689722, 139.87654))
print(tokyo)
print('tokyo 所在国家: %s'%tokyo.country)
print('tokyo 人口: %s'%tokyo.population)
print('tokyo 经纬度: %f, %... |
# -*- coding:utf-8 -*-
a = 10
def func1():
b = 20
def func2():
c = 30
return a + b + c
return func2()
print(func1())
|
index = {'ab':[1,2,3], 'cd':[5,6,7,8]}
ll = [('ab', 8), ('cd', 0), ('ef', 9)]
# 普通的方法将 ll 插入 index
# 需要经过两次 hash 查询
for tp in ll:
index_l = index.get(tp[0], []) # 从 index 中找到 tp[0] 对应的映射,没有则返回 []
index_l.append(tp[1]) # 将新的 tp[0] 映射关系,加入到原先的映射关系
index[tp[0]] = index_l
print(index)
# 使用setdefault
for tp... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 11:04:27 2019
@author: comnet
"""
class Node():
def __init__(self,nextnode = None,val = None):
self.nextnode = nextnode
self.val = val
head = Node(Node(Node(Node(Node(Node(None,6),5),4),3),2),1)
#while 1:
# print(head.val)
# head = head.nextn... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 9 19:34:12 2019
@author: comnet
"""
"""
二分查找
"""
def binary_search(lis, num):
left = 0
right = len(lis) - 1
while left <= right: #循环条件
mid = (left + right) // 2 #获取中间位置,数字的索引(序列前提是有序的)
if num < lis[mid]: #如果查询数字比中间数字小... |
x=input();
y=x.split("=")
left=len(y[0])-1
right=len(y[1])
if left!=right:
print("Impossible")
else:
|
'''
Write a Python program to remove the first occurrence of a specified element from an array.
'''
from array import *
c=array('i',[1,2,3,4,5,1,1])
c.remove(1)
print(c)
|
from board import *
print('''
Hello! Welcome to the Connect 4 game.
Rules:
Each player will choose a color (red or yellow) and then take turns dropping colored discs into a seven-column,
six-row vertically suspended grid. The pieces fall straight down, occupying the lowest available space within
the column. The obje... |
import requests as req
import json
handle=input("Enter handle : ")
count=input("Enter the number of submissions : ")
r1=req.get("https://codeforces.com/api/user.status?handle="+handle+"&from=1&count="+count)
data=json.loads(r1.text)
cnt=0
sum=0
if(data["status"]!="OK"):
print("Something went wrong")
exit(... |
print('我在pk01文件下')
class Student():
def __init__(self, name='NoName', age = 18):
self.name = name
self.age = age
def say(self):
print('My name is {}'.format(self.name))
def sayHello():
print('WELCOME to pk01') |
# 多线程使用
import time
import _thread as thread
def loop1():
# ctime 得到当前时间点
print('Start loop ce1 at :', time.ctime())
# 睡眠多长时间,单位是秒
time.sleep(4)
print('End loop1 ce1 at:',time.ctime())
def loop2():
print('Start loop 2 at:', time.ctime())
time.sleep(2)
print('End loop 2 at :', time.... |
import numpy as np
randomList = np.random.randint(100, size=100)
# print(np.random.seed(0))
# To check how many times number is being repeating..
# using Dictionary
randomList1 = np.random.randint(100, size=100)
print(randomList1)
print("")
listDict = {}
for i in range(len(randomList1)):
if listDict.get(randomLis... |
from tkinter import *
#########################################################################################################################
# python notebook for Make Your Own Neural Network
# code for a 3-layer neural network, and code for learning the MNIST dataset
# (c) Tariq Rashid, 2016
# license is GPL... |
def swap(str,a, b):
str=list(str)
temp = str[a]
str[a] = str[b]
str[b] = temp
str1 = ''.join(str)
return str1
def permutation(str,i,n):
if i==n:
print(str)
else:
for x in range(i,n+1):
str=swap(str,i,x)
permutation(str,i+1,n)
str=swap(... |
dic = {
"rojo": 1,
"manzana": ("roja", "chica"),
"clave": "valor"
}
print "rojo:", dic["rojo"]
print "manzana:", dic["manzana"]
print "clave:", dic["clave"]
#print "foo:", dic["foo"] # Error: la clave no existe en el dic
dic["foo"] = 12.34
print "foo:", dic["foo"]
for k in dic:
print... |
def min_max(arreglo):
if len(arreglo) < 1:
return (None, None)
min = arreglo[0]
max = arreglo[0]
for x in arreglo:
if x < min:
min = x
elif x > max:
max = x
return (min, max)
print min_max([3, 5, 2, 4])
a = range(4, 79, 5)
print min_max(a)
print... |
def rainfall_statistics(*rainfall_months): #using the star to pass in the multiple values of a list (it takes in 12 arguments for the months of the year)
total_rainfall = 0
highest = rainfall_months[0] #set highest to element zero of rainfall_months
lowest = rainfall_months[0] #set lowest to element zero... |
#!/usr/bin/python
#birthday.py
#A script to tell you who's birthday it is
#Author: paul-louis
#TODO: Wish the lucky guy a wonderful birthday!
#
from time import strftime
import xlrd, csv
import os, sys
import gspread
import getpass
import smtplib
def init():
if len(sys.argv) != 2:
usage()
username = s... |
class patterns():
#creates an array of 0s corresponding to the chromosome length and detects the postion of the regulated ORF and places the integer 1 in its position whereby the code can extract their positions
def __init__(self):
self.s = 0
def chrom(self, gene_names, gene):
count = ... |
class 里面的 __slots__
__slots__ 本质上是一个类变量,变量的值可以是元组、列表、任何可迭代对象,当然也可以是一个字符串,但那就意味着该类只有一个成员变量。
由于每次实例化一个类都要分配一个新的 __dict__,存在空间的浪费,因此有了 __slots__ 。它包括了当前能访问到的属性。
当定义了slots后,slots中定义的变量变成了类的描述符。类的实例只能拥有slots中定义的变量,不能再增加新的变量。
注意:定义了 __slots__ 后,就不再有 __dict__。
1.限制 class 的属性
class Student(object):
__slo... |
利用 Python 搭建一个简单的 Web 服务器,快速实现局域网内文件共享。
1. cd 到准备做服务器根目录的路径下(这目录下的文件将会被共享)
2. 运行命令:
python -m Web服务器模块[端口号,默认8000]
这里的“Web服务器模块”有如下三种:
BaseHTTPServer: 提供基本的Web服务和处理器类,分别是 HTTPServer 和 BaseHTTPRequestHandler 。
SimpleHTTPServer: 包含执行GET和HEAD请求的 SimpleHTTPRequestHan... |
python 前面版本没有原生的 枚举, 需要自己封装一个。(Python 3.4+ 开始有枚举了)
新版本的枚举写法(python 3.4)
# 写法1
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
# 写法2
class Animals(Enum):
ant = 1
bee = 2
cat = 3
dog = 4
旧版Python用户可以充分发挥动态语言的优越性来构造枚举:
# 示例... |
一、数据库操作
1. 导入模块
import redis
print(redis.VERSION) # 显示 python 的 redis 模块版本号
2. 数据库连接
r = redis.Redis(host='localhost', port=6379, db=0) # 直接连接
pool = redis.ConnectionPool(host='localhost', port=6379, db=0) # 建立连接池
r = redis.Redis(connection_pool=pool) # 池连接
3. 设... |
创建Greenlets
=============================
gevent 对 Greenlet 初始化提供了一些封装,最常用的使用模板之一有
# 示例
import gevent
from gevent import Greenlet
def foo(message, n):
"""
Each thread will be passed the message, and n arguments in its initialization.
每个线程初始化时都需要传递 message 和 n 参数
... |
Python 内建函数之 —— filter, map, reduce, zip
1、 filter(bool_func, seq):
此函数的功能相当于过滤器。
调用一个布尔函数 bool_func 来迭代遍历每个 seq 中的元素;返回一个使 bool_seq 返回值为 True 的元素的序列。
例如:
li = filter(lambda x : x%2 == 0, [1,2,3,4,5])
print(li) # 打印: [2, 4]
print(list(li)) # py3.x时需要这样打印
l2 = filter(lambda x :... |
反射(自省)
dir([obj]) # 调用这个方法将返回包含obj大多数属性名的列表(会有一些特殊的属性不包含在内,连父类的属性也包含在内)。obj的默认值是当前的模块对象。
vars([obj]) # 这个方法将返回obj当前属性及其值的字典(不包含父类的属性及静态属性)。 obj默认值是当前模块对象,即没有参数是返回 local()。
type(obj) # 返回对象的类型。返回值是一个类型对象。
hasattr(obj, attr) # 这个方法用于检查obj是否有一个名为attr的值的属性,返回一个布尔值。
getattr(obj, attr[, default... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.