text stringlengths 37 1.41M |
|---|
# Queli Serrano
# Classes used in Thomson's Construction.
import argparse
class State:
"""A state with one or two edges, all edges labeled by label. """
# Constructor for the class.
def __init__(self, label=None, edges=[]):
# Every state has 0,1, or 2 edges from it.
self.edges = edges if edges e... |
"""
Класс с расчетом сглаживающих множителей для нереккурсивных фильтров
Каждый метод класса возвращает список со значениями коэффициентов множителей
На данный момент единственная реализация, которую я представляю...
Но как говорится, нет предела совершенству!
"""
# todo: Необходимо добавить расчет множителей Кайзера и... |
# coding: utf-8
def readfile(file):
nums = []
with open(file) as f:
for line in f:
nums.append(line.strip())
return nums
def find3Max(nums):
li = nums[:3]
if li[0] < li[1]:
if li[0] < li[2]:
if li[1] > li[2]:
li[1], li[2] = li[2], li[... |
# -*- coding:utf-8 -*-
from Operation import *
class OperationFactory:
@staticmethod
def CreateOperation(operationType):
if operationType == "+":
return Add()
elif operationType == "-":
return Subtraction()
elif operationType == "*":
return Multiply(... |
#Add item to python list
languages = ['C', 'Kotlin', 'Javascript']
user_input = input('Enter a programming language...')
languages.append(user_input)
for i in languages:
print(i)
#Result
>>Enter a programming language...[ Python| ]
>>'C'
>>'Kotlin'
>>'Javascript'
>>'Python' |
#write a python program to find gcd of two given numbers
#gcd is greatest common divisor
def gcd(a,b):
if (b == 0):
print('the gcd of two numbers:',a)
else:
return gcd(b,a%b)
d1 = int(input("Enter a number:"))
d2 = int(input("Enter another number"))
gcd(d1, d2)
|
#count
print("==============count=================")
str = "Semangat puasa nya all !!!"
sub = "a";
print ("str.count(sub, 4, 16) : ", str.count(sub, 4, 16))
sub = "an";
print ("str.count(sub) : ", str.count(sub))
#center
print("==============center=================")
str = "aku laper tapi puasa";
print ("str.center(... |
import random
print("How many numbers do you want to sort?")
try:
int_input = int(input())
fillArray(int_input)
except Exception as ex:
print("Error: {}".format(type(ex).__name__))
print("Only numbers are allowed.")
def fillArray(int_input):
i = 0
array_number = []
while(i < int_input):... |
'''
Dictionary of ten popular songs (a list of dictionaries)
'''
songs = [
{'title': 'Song 1', 'genre': 'Rock 1', 'artist': 'Artist 1', 'length': 4.70},
{'title': 'Song 2', 'genre': 'Rock 2', 'artist': 'Artist 9', 'length': 4.71},
{'title': 'Song 3', 'genre': 'Rock 1', 'artist': 'Artist 3', 'length'... |
class Person:
def __init__(self, n, a):
self.name = n
self.age = a
print('instance created')
def say_hello(self):
print(f'Hello, my name is {self.name}, and I am {self.age} years old.')
# - classes allow us to create our own data types. 'self' has to be in the __ini... |
import csv
import json
# - Reading a CSV
'''
with open('data/deniro.csv') as csv_file:
file_reader = csv.reader(csv_file)
for row in file_reader:
print(row)
'''
# Read a json file
with open('data/sample.json') as json_file:
data = json.load(json_file)
# print(data['students']... |
x=15
y=3
z = "This"
#Concatenate strings
print(z*y)
#Automated spacing
print(x,y,z)
#For loop
for i in range(0,10):
print(i)
#List
myList = [10,20,30,40]
for i in myList:
print(i.index())
#Function
def myPrint(words):
print(words, ", ok.")
myPrint("are you")
def recFun(vList):
if len(vList) > 0:... |
# --- Day 5: Binary Boarding ---
from typing import List
from utils import read_file
def do_work(boarding_passes: List[str]):
seat_ids = []
for pass_ in boarding_passes:
seat_ids.append(boarding_pass_to_decimal(pass_))
return seat_ids
def boarding_pass_to_decimal(boarding_pass: str):
conver... |
# --- Day 8: Handheld Halting ---
import operator
from typing import List, Tuple
ops = {'+': operator.add, '-': operator.sub}
def do_work(instructions: List[List[str]], part: int) -> int:
if part == 1:
return part1(instructions)[0]
else:
return part2(instructions)
def part1(instructions: Li... |
#This code will calculate number of vowels in a given word
word = input("Enter string: ")
vowels=0
for i in word:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vowels = vowels + 1
print("Number of vowels are: " + str(vowels))
|
"""
Program to take comma separated numbers input, and calculate the value of "Q" for each number
Use the number as "D" for equation
Equation : Q = Square root of ((2*C*D)/H), where C=50 and H=30, round off the result also
Input : 10,23,33
Output : [5,8,10]
"""
import math
# Take input from user
comma_input = input(... |
# Program to count total numbers of trials to get same numbers on 2 dices
import random
count = 1 # number of
# Method to roll dices
def roll():
global count
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print("\nDice 1: ",d1)
print("Dice 2: ",d2)
if d1 != d2:
roll()
coun... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 22 19:55:31 2018
@author: BlairLAdams
"""
print("\033[1;31;40m>>>")
annual_salary = float(input("\033[1;34;40mEnter your starting salary: "))
portion_saved = float(input("\033[1;34;40mEnter the percent of your salary to save, as a decimal: "))
total... |
bits = float(eval(input('How many bits? ')))
prob = 1.0
notprob = 1.0
num = 1
while prob < .5 or num == 1:
#prob = 1 - ((2**bits - num)/(2**bits))
#print float(((bits-num)/bits)), num, bits
#prob = 1.0 - float(prob * float(float(bits - num)/float(bits)))
notprob = notprob * (bits - num)/bits
print( prob, no... |
class Vector:
"""
Represent a vector in a multidimensional space.
"""
def __init__(self, d):
"""Create d-dimensional vector of zeros if d is an integer.
Transform the given data to a vector if d is a list."""
if isinstance(d, int):
self._coords = [0] * d
elif... |
# R-4.6
def harmonic_number(n):
im = 1.0 / n
if n == 1:
return im
elif n > 1:
return im + harmonic_number(n-1)
harmonic_number(1)
harmonic_number(2)
harmonic_number(3)
# R-4.7
def str_2_int(string, index=0):
length = len(string)
if index = length - 1:
return int(string[inde... |
def find_brute(T:str, P:str):
"""Return the lowest index of T at which substring P begins (or elese -1)."""
n, m = len(T), len(P)
for i in range(n-m+1): # try every potential starting index within T
k = 0 # an index into pattern P
while k < m and T[i+k] == P[k]: # kth characte... |
__author__ = 'anthonymcclay'
__project__ = 'LearnSmart1'
__date__ = '7/18/16'
__revision__ = '$'
__revision_date__ = '$'
# Anonmymous FUnctions lambda
print("Example program 1 - Anonmous function Lambda:\n")
total = lambda sub1, sub2, sub3,sub4, sub5: sub1 + sub2 + sub3 + sub4 + sub5
# Now you can call the function... |
word=input("input words: ")
list_word=word.split(",")
list_word.sort()
print(list_word) |
"""def oldest(self,name,age):
ansourted=age#value:14,15,12
age.sort()#12,14,15
for i in range(len(ansourted)):
if age[-1]==ansourted[i]:
x=i
print(name[x]+" "+age[-1])
class Cat:
def __init__(self, name=["kath","cath","kats"], age=[14,15,12]):
self.name = name
sel... |
num1=int(input("enter first number :"))
num2=int(input("enter second number :"))
if num1<num2:
print("num1 is smallest")
else:
print("num2 is smallest") |
print("Hello World")
# Variable store
a = 30
b = 10
c = "rohit"
name = "rohit"
print("Name is",name)
#assiging multiple
a, b, c = 15,20,"rohit"
print(a)
print(b)
print(c)
a, b, c = 10,50,"rohit"
print("value is : ",a)
print("value is : ",b)
print("value is : ",c) |
num1=int(input("enter first number :"))
num2=int(input("enter second number :"))
if num1>num2:
print("num1 is greatest")
elif num1<num2:
print("num2 is greatest")
elif num1==num2:
print("both number is equal") |
def read(filename):
"""
0 -- Tomato
1 -- Mushroom
"""
f = open(filename)
r, c, l, h = tuple([int(parameter) for parameter in f.readline().split()])
pizza = []
used = []
for i in range(r):
pizza.append([0 if char == 'T' else 1 for char in f.readline()][:-1])
used.app... |
"""
Author: Ahmed Bilal
Add Country Code to your iphone contacts file .vcf
Input:
Filename
Prefferred Country Code
Algorithm:
Take all content from the file and load it into memory
Replace All VOICE:0 with Country Code
Replace All pref:0 with Country Code
Reads weather a country code all rea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" File containing simple spacial object definition. """
class spacial_object(object):
o_name = None
o_nr = None
def __init__(self, *args, **kwargs):
"""Constructor."""
if len(args) == 2:
self.o_name = args[0]
self.o_n... |
# -*- coding: utf-8 -*-
"""
基于分支限定法的旅行商问题解法Python源码
Author: Greatpan
Date: 2018.10.3
"""
import math
import time
from queue import Queue
import Greedy
from MyFuncTool import GetData,ResultShow,draw,Node
def get_up(CityNum,Dist):
"""
函数名:get_up(CityNum,Dist)
函数功能: 通过贪心算法求取目标函数的上界
输入 1 CityNum:城市数量
2... |
#Math
from ast import Num
from _ast import And
print("Hello")
# Floating point representation
print(5/2)
# Integer devision or floor devision
print(5//2)
#power of
print(2**3)
# Modulus or remainder
print(5%2)
print("*****************************String*****************************************************... |
#!/usr/bin/python
from itertools import groupby
from operator import itemgetter
import sys
def read_mapper_output(input_file, separator='\t'):
'''
This function read mapper output
:param file: input file
:type file : sys.stdin
:param separator: separator string
:type separator:str
:return... |
from typing import List
def gaussian_elimination(A: List[List[float]], b: List[float]) -> List[float]:
"""solve systems of equation using Gaussian elimination
Parameters
__________
A : matrix A
b : vector b
Returns
_______
x : the solution
x is [] if A is singular
"""
# me... |
import numpy as np
import matplotlib.pyplot as plt
from math import exp, floor
def euler(f, h, t0, y0, tn):
"""use Euler method to solve ODE at tn
Parameters
__________
f : the right hand side of the ODE
h : resolution
t0 : the initial position
y0 : the initial value
tn : the unknown p... |
# -*- coding: utf-8 -*-
import urllib.request
def run_main():
"""
主函数
"""
url = "http://www.cninfo.com.cn/finalpage/2017-10-26/1204071413.PDF"
file_name = url[url.find('/120') + 1:url.find('PDF')+6]
urllib.request.urlretrieve(url, 'C:\\Users\zanderkong\Desktop\PycharmPdf\\' + file_... |
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import urllib.request
def run_main():
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; a... |
# Weekly Challenge 6
# CX Programming Club
# lariasca
# Name Game
sample = ['Goblin', 'Creature', 'Troll', 'King/Queen', 'Witch/Warlock',
'Vampire', 'Guardian', 'Fairy', 'Knight', 'Elf', 'Assasin',
'Sorcerer/Sorceress', 'Giant', 'Warewolf', 'Wizard', 'Ogre',
'Goblin', 'Beast', 'Dragon', ... |
# テストの平均点を出力する処理
# for loopで変数に渡す値を設定
point_list = [50, 75, 91]
# 合計点の変数totalの初期化
total = 0
# for文で合計点を計算
for point in point_list:
total = total + point
# print('Your Point is', total , '.')
#print('End of For Loop')
# 変数point_listのデータの個数(リストの長さ)をlen関数で取得
num_subject = len(point_list)
# 合計点をデータの個数で割って平均点を割り出す
... |
# Project Euler Problem #6
# -----------------------------------------
# The sum of the squares of the first ten natural numbers is:
# 1^2 + 2^2 + ... + 10^2 = 385
#
# The square of the sum of the first ten natural numbers is:
# (1 + 2 + ... + 10)^2 = 55^2 = 3025
# Hence the difference between the sum of the squares
#... |
# Project Euler Problem #9
# -----------------------------------------
# A Pythagorean triplet is a set of three natural numbers,
# a < b < c, for which, a^2 + b^2 = c^2
#
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#
# Find the product abc.
... |
#Q1.Create a numpy array with 10 elements of the shape(10,1) using np.random and find out the mean of the elements using basic numpy functions.
import numpy as np
np_arr=np.random.rand(10,1)
print(np_arr)
print("Mean: ",np.mean(np_arr))
#Q2.Create a numpy array with 20 elements of the shape(20,1) using np.random fin... |
#Q.1 - Create a dataframe with your name , age , mail id and phone number and add your friends’s information to the same.
import pandas as pd
import numpy as np
context = {
'Name':['Ankita','Ajay','Sakshi'],
'Age' :[21,23,21],
'Email_id':['anki@gmail.com','ajay@gmail.com','saks@gmail.com'],
'Phone_no' ... |
import random as rand
'''
Jonathan Elsner
2020
Python module that facilitates asking common types of questions to the user.
Accounts for invalid user responses and reprompts the question. Provides a high
amount of customization for handling edge cases and input sanitization with
straightforward default parameters.
''... |
import random as randint
#def pr1(a,b): # 1
# print((a+4*b)*(a-3*b)+a**2)
#pr1(2,3)
def pr2(): # 2
array=[]
i=0
while i<10:
array.append(randint(1,20))
print(array)
pr2()
#def pr3(a): # 3
# t=0
# y=3
# b=0
# while t!=3:
# t+=1
# if a[t] < a[t-1]:
# ... |
#a=5
#while a>0:
#print(a)
#a-=1
#print("Цикл закончен")
#a=int(input("Введите число\n"))
#b=0
#while a!=0:
# b=b+a
# a=int(input("Введите число\n"))
#print(b)
#for i in range(0,21,2):
# print(i)
#a=int(input("Введите число"))
#for i in range(1,a+1):
# print("*"*a)
#i=0
#while i<5:
# a=int(in... |
oper=str(input("Введите оператор от 1 до 6: \n1 - сложение, \n2 - вычитание, \n3 - деление, \n4 - умножение, \n5 - возведение в степень, \n6 - остаток от деления \n"))
summ=str("1")
subtract=str("2")
division=str("3")
multiply=str("4")
exp=str("5")
remainder=str("6")
if oper == summ:
x=int(input("Введите первое ч... |
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Embedding , LSTM, Input,Conv2D, MaxPool2D, GlobalAveragePooling2D, BatchNormalization, ReLU, MaxPooling2D, Dropout # Embedding 자연어 쪽에서 많이 씀
input1 = Input(shape=(32, 32, 3))
# h = Embedding(input_d... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# author : haymai
if __name__ == '__main__':
"""
你想将 print() 函数的输出重定向到一个文件中去
"""
with open('d:/work/test.txt', 'wt') as f:
print('Hello World!', file=f)
print('ACME', 50, 91.5)
print('ACME', 50, 91.5, sep=',')
print('ACME', 50, 91.5, sep=... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author : haymai
# 通常情况下,你没有办法
# 知道接收数据的线程是什么时候接收到的数据并开始工作的。不过队列对象提供一些
# 基本完成的特性,比如下边这个例子中的 task done() 和 join()
from queue import Queue
from threading import Thread
# A thread that produces data
def producer(out_q):
while running:
# Produce some data
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author : haymai
if __name__ == '__main__':
filename = 'spam.txt'
endswith = filename.endswith('.txt')
print(endswith)
startswith = filename.startswith('file:')
print(startswith)
file_names = ['Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h']
_e... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author : haymai
"""
你写好了一个函数,然后想为这个函数的参数增加一些额外的信息,这样的话其他
使用者就能清楚的知道这个函数应该怎么使用。
"""
def add(x: int, y: int) -> int:
# 123123
return x + y
if __name__ == '__main__':
print(help(add))
print(add.__annotations__)
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author : haymai
"""
你想读写一个 CSV 格式的文件。
"""
import csv
from collections import namedtuple
if __name__ == '__main__':
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
# Process row
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author : haymai
"""
你有一个字符串形式的方法名称,想通过它调用某个对象的对应方法。
"""
import math
import operator
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({!r:},{!r:})'.format(self.x, self.y)
def distance(self... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author : haymai
"""
你想自己去实现一个新的上下文管理器,以便使用 with 语句。
"""
import time
from contextlib import contextmanager
@contextmanager
def timethis(label):
start = time.time()
try:
yield
finally:
end = time.time()
print('{}: {}'.format(label, end -... |
# a modify version of bubble sort.
# this version stops early if it finds that the list has become sorted.
def shortBubbleSort(alist):
exchanges = True
passnum = len(alist)-1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i] > alist[i + 1]... |
s = 'abcdef'
print(s[0])
print(s[0:3])
print(s[0:3:2])
print(s.find('c'))
print(s.replace('d','z'))
print(s.count('e'))
|
def checklimit(limit,colourlength,total):
if limit >= colourlength:
result = colourlength
elif limit < colourlength:
result = total - colourlength +1
return(result)
totalLen = int(input())
redList = []
orangeList = []
yellowList = []
greenList = []
blueList = []
blackList = []
if totalLen... |
#세트
# 순서 없고, 중복 없는 객체 집합
# {} 정의
# in, not in , len
#세트 만들기
a={1, 2 ,3}
print(a, type(a))
#포함 여부의 확인
print(2 in a )
print(3 in a )
print(2 not in a )
print(3 not in a )
#객체 추가 : add(x)
a.add(4)
print("add(4):" , a)
a.add(4) # 이미 있는 값에 추가
print("add(4)", a)
# 객체 제거
a.remove(4)
#a.remove(4) #keyerror
print("remov... |
def greatest(a,b,c):
if a>b and a>c:
return a
elif b>a and b>c:
return b
else:
return c
print (greatest(5,6,7))
print (greatest(5,6,2))
print (greatest(99,1,1003))
|
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
even=0
odd=0
for i in numbers:
if i%2==0:
even=even+1
else:
odd=odd+1
print(even)
print(odd)
|
j=3
for i in range(3):
print(" "*(j-i-1),end="")
print("*"*(2*i+1),end="")
print(" "*(j-i-1)) |
# mydict={
# "ram":"hindi",
# "shyam":"Bengali",
# "Suresh":"english",
# "Rajesh":"French"
# }
# print(mydict.keys())
# a=input("Enter the name:")
# print(mydict.get(a))
mydict=[]
name1=input("please enter the name")
mydict.append(name1)
print(mydict) |
import random
def gameWin(comp,you):
if comp==you:
return None
elif comp=="s":
if you=="g":
return True
else:
return False
elif comp=="w":
if you=="s":
return True
else:
return False
elif comp=="g":
if you=="w"... |
def fraction(n):
if n==1 or n==0:
return 1
else:
return n*fraction(n-1)
print(fraction(11)) |
"""
author: Bhoj Bahadur Karki
Date: 2020-August-12th
Purpose: singleton design pattern: This pattern restricts the instantiation of
a class to one object. It is a type of
creational pattern and involves only one class to create methods and specified objects.
"""
class Singleton:
__instance = None
@staticme... |
"""
purpose: To learn about database programming with mysql and python
date: 2020/July/24th
author:Bhoj bahadur karki
Motivation: To be able to build my own custom ORM with python in near future.
Quote: Those who believe can, will do it.
Tutorial link: https://www.python-course.eu/sql_python.php
"""
import MySQLdb
d... |
"""
purpose: To learn about network and web programming in python.This tutorial
is from david beazley book. Chapter 11.
Topic: creating TCP server using only builtin socket library
date: 2020/July/24th
author:Bhoj bahadur karki
Motivation: To be able to build my own server.
Quote: Those who believe can, will do it.
... |
class Parent():
def __init__(self,last_name,eye_color):
print "Parent Constructor Called"
self.last_name=last_name
self.eye_color=eye_color
class Child(Parent):
def __init__(self,last_name,eye_color,number_of_toys):
print "Child Constructor Called"
Parent.__init__(sel... |
import csv
from Alumno import Alumno
class ManejadorAlumno:
#__lista = []
def __init__(self, ):
self.__listaAlumnos = []
def agregarAlumno(self, unalumno):
self.__listaAlumnos.append(unalumno)
def getALUMNOS(self):
return self.__listaAlumnos
def getAlumnos... |
"""
7. Напишите программу, доказывающую или проверяющую, что для множества
натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2,
где n - любое натуральное число.
Решите через рекурсию. Решение через цикл не принимается.
Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7
"""
b = int(input("... |
"""
3. Сформировать из введенного числа обратное по порядку входящих в него
цифр и вывести на экран. Например, если введено число 3486,
то надо вывести число 6843.
Подсказка:
На каждом шаге вам нужно 'доставать' из числа очередную цифру
Пока все числа не извлечены рекурсивные вызовы продолжаем
Условие завершения реку... |
"""
Tic tac toe game.
TODO:
"""
def generate_blank_locations(GRID_SIZE):
locations = []
for row in range(GRID_SIZE):
locations.append([])
for col in range(GRID_SIZE):
locations[row].append("")
return locations
def display_grid(GRID_SIZE, locations):
grid = ""
for nu... |
def add_time(start, duration, days=None):
meridiem_later = 0
week_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
#Splitting the AM-PM
meridiem = start.split(" ")[1]
initial_meridiem = meridiem
start = start.split(" ")
start.pop(1)
start = ''.join(start)
#Splitting ... |
year = int(input('enter a year'))
#cannot return something outside of function
a = year % 19
b = year % 4
c = year % 7
d = (19*a+24) %30
e = (2*b+4*c+6*d+5)%7
date_of_easter = 22 + d +e
march = 'easter is on march',date_of_easter %32
april = 'easter is on april',date_of_easter %31
if date_of_easter <= 31:
... |
# Tuple unpacking also allows functions to return multiple values in a way that is convenient to the caller.
# The os.path.split() function builds a tuple (path, last_part) from a filesystem path
import os
_, filename = os.path.split('~/Users/thomaskalnik/Desktop/FluentPython-scripts/Path_split.py')
print(_)
print(... |
# -*- coding: utf-8 -*-
"""
Functions for working with dictionaries.
The :func:`dict_hist` function counts the number of discrete occurrences of hashable
items. Similarly :func:`find_duplicates` looks for indices of items that occur more
than `k=1` times.
The :func:`map_keys` and :func:`map_vals` functions are useful... |
'''
实现目录下查找指定文件(包括子目录)
'''
import os
#在路径下查找文件
def findFile2(dirname,filename):
D={};L=[dirname]
while L:
L1=[]
for l in L:
values = [x for x in os.listdir(l) if os.path.isfile(os.path.join(l, x)) and filename in os.path.splitext(x)[0]]
if values: D[l] = values
... |
'''
我们把变量从内存中变成可存储或传输的过程称之为序列化
反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化
如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,
但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,
也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,
而且可以直接在Web页面中读取,非常方便。
JSON表示的对象就是标准的JavaScript语言的对象
'''
import json
d=dict(name='Bob',age=20,score=68)
j=json.dumps(d) ... |
'''
urlopen连接网络时可能会发生异常:
1.网页在服务器上不存在(或者获取页面的时候出现错误)--返回HTTP错误
2.服务器不存在--返回None
调用查询结果时:
如果你想要调用的标签不存在,BeautifulSoup 就会返回 None 对象。不过,
如果再调用这个 None 对象下面的子标签,就会发生 AttributeError 错误。
'''
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup as bfs
try:
ht=urlopen("https:... |
'''
Python对协程的支持是通过generator(生成器yield)实现的。
'''
def consumer():
print('0020')
r = 'xxx'
while True:
print('0021')
#运行周期:[开始...yield r][n=1...yield r][n=2...yield r]...
n = yield r
print('0022', n, r if r else 'None')
if not n:
return
print('[CONSUME... |
from abc import ABCMeta, abstractclassmethod
class Super(metaclass=ABCMeta):
def delegate(self):
self.action()
@abstractclassmethod
def action(self):
pass
# x = Super() #TypeError: Can't instantiate abstract class Super with abstract methods action
class Sub(Super):
pass
# x = Sub() #T... |
'''
relief:设置 Button 的外观效果
FLAT,GROOVE,RAISED,RIDGE,SOLID,SUNKEN
'''
from tkinter import *
r=Tk()
print('flat, groove, raised, ridge, solid, or sunken'.upper())
r.geometry('600x400')
Button(r,text='按钮1',relief=FLAT).pack()
Button(r,text='按钮2',relief=GROOVE).pack()
Button(r,text='按钮3',relief=RAISED).pack()
Button(r,te... |
class A:
def f1(self):
print('abc')
def f2():
print('def')
def f3(self):
print('ghi')
a=A()
a.f1()
A.f2() #用类实例对象调用函数会默认发送给函数一个参数(self),用类对象则不会
f3(a) |
# Program to convert Voltage to Resistance from the TIA
# USAGE:
# Converter is instantiated as an object per Channel.
# Base Conversion Equation is:
# R = (V - Vb) * Rb/Vb
import numpy as np
import math
class Converter:
# Object Delcaration
# @Param:
# Vb - Optional Parameter to override de... |
"""
208. 实现 Trie (前缀树)
"""
class TreeNode:
def __init__(self, val=None, is_end=False):
self.val = val
self.next = {}
self.is_end = is_end
class Trie:
def __init__(self):
self.node = TreeNode()
def insert(self, word: str) -> None:
tmp = self.node
for i in w... |
"""
1122. 数组的相对排序
https://leetcode-cn.com/problems/relative-sort-array/
"""
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
"""
采用计数排序和哈希表,先将arr1中按照arr2的顺序,找出匹配的数字进行按次排列,然后把剩下的数字进行排序
"""
hashmap = {}
for num in arr1: # 将arr1的所有数字进... |
"""
860. 柠檬水找零
在柠檬水摊上,每一杯柠檬水的售价为 5 美元。
顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
注意,一开始你手头没有任何零钱。
如果你能给每位顾客正确找零,返回 true ,否则返回 false 。
"""
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
"""
优先找零大面额的钱币,因为小面额钱币比大面额... |
print('hello,world!')
file = open('E:/学习/file.txt','w')
file.write('hello,world!')
what_he_does = ' plays '
his_instrument = 'guitar'
his_name = 'Robert Johnson'
artist_intro = his_name + what_he_does + his_instrument
print(artist_intro)
seq='strijjj'
print(''.join(reversed(seq)))
num=[[1,2,3],[4,5,6]]
for i in nu... |
class CocaCola:
formula = ['caffeine','sugar','water','soda']
def __init__(self):
for element in self.formula:
print('Coke has {}!'.format(element))
def drink(self):
print('Energy!')
coke = CocaCola()
class TestA:
attr = 1
obj_a = TestA()
TestA.attr = 42
print(obj_a.attr)
c... |
#!/usr/bin/env python3
import sys
from board import AgentBoard
from agent import *
import random
def walk(difficulty, seed):
random.seed(seed)
game = AgentBoard(difficulty) #
agent = Agent()
agent.newGame(game, True)
agent.loadStateMemory()
stop = ""
gameOutput = CONTINUE_TEXT
input... |
# This is an amazing maze game constructed using while loop and if/elif/else loop.
# Actual source code will work in this url => https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Maze&url=worlds%2Ftutorial_en%2Fmaze1.json
'''
Write a program using an if/elif/else... |
# Import required modules
from art import logo, vs
from game_data import data
import random
from replit import clear
def print_data(account):
""" Based on account data return the printable format """
account_name = account["name"]
account_desc = account["description"]
account_country = account["cou... |
import sys
# print(type(sys.argv[1]))
# Takes first name and last name via command
# line arguments and then display them
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([int(j) for j in sys.argv[1].split(",")])
ypoints ... |
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return x**3+5*x
sequence=[1,2,3,4,5,6,7,8,9,10]
x = np.linspace(-10,10, num=100)
y = f(x)
plt.plot(x, y)
plt.show(
|
number = [2, 4, 6, 8, 10]
a = '5'
b = '10'
for i in number:
i = number
if number == a:
print('True')
elif number == b:
print('True')
else:
print('False') |
N = int(input())
num = 1
print('1', end=' ')
for i in range(N):
num = num * 2
print(num, end=' ') |
# a = []
#
# for i in range(10):
# a.append(1)
# print(a)
#
# for i in range(3):
# line = []
# for j in range(2):
# line.append(0)
# a.append(line)
# print(a)
#
# a = [[0 for j in range(2)] for i in range(3)]
# print(a)
#
# a = [[0]*2 for i in range(3)]
# print(a)
#
# a = [3,1,3,2,5]
# b = []
#
... |
LIST = [1, 3, 11, 15, 23, 28, 37, 52, 85, 100]
even = []
for i in LIST:
if i % 2 == 0:
even.append(i)
print(even) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.