text stringlengths 37 1.41M |
|---|
from collections import deque
class Item:
'''
Representation of items in PriorityQueue.
For use internally in PriorityQueue class only.
'''
def __init__(self, label, key):
self.label, self.key = label, key
class PriorityQueue:
'''
Heap-based priority queue implementation.
'''
... |
# ---------------------------------------------------------------------
# JSON normalization routines
from __future__ import annotations
from collections import (
abc,
defaultdict,
)
import copy
from typing import (
TYPE_CHECKING,
Any,
DefaultDict,
)
import numpy as np
from pandas._libs.writers i... |
DAYS: list[str]
MONTH_ALIASES: dict[int, str]
MONTH_NUMBERS: dict[str, int]
MONTHS: list[str]
int_to_weekday: dict[int, str]
def get_firstbday(year: int, month: int) -> int: ...
def get_lastbday(year: int, month: int) -> int: ...
def get_day_of_year(year: int, month: int, day: int) -> int: ...
def get_iso_calendar(yea... |
"""
Reversed Operations not available in the stdlib operator module.
Defining these instead of using lambdas allows us to reference them by name.
"""
from __future__ import annotations
import operator
def radd(left, right):
return right + left
def rsub(left, right):
return right - left
def rmul(left, rig... |
total=0
for days in range(7):
Deliveries=int(input("How many deliveries did you do\n>>>"))
total=Deliveries * 0.1
print("This how much you made in one week\n>>> £" + str(total))
|
from tkinter import *
equalsState=False
def addition(num1, num2):
return num1+num2
def subtraction(num1, num2):
return num1-num2
def multiplication(num1, num2):
return num1*num2
def division(num1, num2):
return num1/num2
def equalsPressed(state):
global equalsState
equalsSt... |
import datetime
person = input('Enter your name: ')
print('Hello', person)
now = datetime.datetime.now()
age = int(input('enter your age: '))
yearsto100 = 100 - age
print("this is when you will be 100: ",yearsto100+now.year)
|
import random
numero = random.randint (0,99)
print ("Intente adivinar el numero")
while True:
while True:
intento = input ("Introduzca un numero entre el 0 y el 99 incluidos ")
try:
initento = int(intento)
except:
pass
else:
... |
"""Dictionaries(hash tables)"""
""" Mappings are a collection of objects that are stored by a key, unlike
a sequence that stored objects by their relative position. This is an
important distinction, since mappings won't retain order since they
have objects defined by a key. """
""" A python dictionary consists of a k... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 函数定义
def hello():
print ("我是李强")
# 函数
def passFunc():
pass
# 函数参数探究
def argFunc01(str):
print (str)
argFunc01("李强")
argFunc01(123)
def argFunc02(str):
print (str + 99)
# argFunc02("liqiang")
argFunc02(66)
def hello2(name, sex = "小哥哥"):
print ("... |
class LongestSubstring():
def getLength(self, s):
if len(s) < 2:
return len(s)
seen = []
maxLength = 0
for char in s:
if char in seen:
index = seen.index(char)
del seen[:index + 1]
seen.append(char)
if le... |
x = 7 * 10
y = 5 * 6
# Jika x sama dengan 70, cetak 'x adalah 70'
if (x == 70):
print('x adalah 70')
# Jika y tidak sama dengan 40, cetak 'y bukan 40'
if (y != 40):
print('y bukan 40')
|
# Node of a generic binary tree
# Extend later to create other tree types like heaps, BST, etc.
class BinaryNode():
left = None
right = None
parent = None
side = None
def __init__(self, data):
self.data = data
def get(self):
return self.data
# Sets parent and tells what si... |
from karel.stanfordkarel import *
def pave_all_hurdles():
"""
This is the master function that gets Karel from one side of the chart to the other and covers the entire chart in a layer of beepers over all the hurdles.
pre-condition: Karel is at (1,1) facing north. To his right is the first hurdle. There... |
print('welcome to my guess game:')
print('you have only 9 turn if you dont guess within 9 you will lost this game')
n = 18
x = int(input('enter your guess number: '))
no_of_guess = 9
while True:
no_of_guess -= 1
if no_of_guess < 1:
print('your turn over: \n GAME OVER \n YOU LOST')
... |
print('---'*20)
print(f'{"CÁLCULO IMC":^60}')
print()
nome = str(input('Informe o seu nome: '))
altura = float(input('Informe a sua altura: '))
peso = float(input('Informe o seu peso: '))
print()
print()
print('--'*20)
print(f'{"DADOS INFORMADOS":^40}')
print(f'Nome: {nome}')
print(f'Altura: {altura}')
print(f'Peso: {... |
""" The purpose of this file is to determine the maximimum value in a list """
# Requirements: "Please write a Python function, max_num_in_list to return the max number of a given list. The first line of the code has been defined as below. def max_num_in_list(a_list):"
def max_num_in_list(a_list):
maximum_var =... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*
import sys
#import os
#import math
###### Read in file
# f = open("test.txt", "r")
f = open("rosalind_ins.txt", "r")
toSort = f.readline().rstrip()
myList = f.readline().rstrip().split()
myList = [int(i) for i in myList]
# print("input:", myList)
# sys.exit()
num_swap = ... |
#!/Users/courtine/anaconda3/bin/python
# -*- coding:utf-8 -*
# k homozygous dominant
# m heterozygous recessive
# n homozygous recessive
#### Better solution from Rosalind
#def firstLaw(k,m,n):
# N = float(k+m+n)
# return 1 - ( m*n + .25*m*(m-1) + n*(n-1) ) / ( N*(N-1) )
####
k, m, n = 20, 21, 23
''' Probabi... |
##This is a Inheritance example with child class does not have parameteres.
##Hence pass is mentioned.
class person:
def __init__(person,fname,lname):
person.fname = fname
person.lname = lname
def printname(self):
print("Hello! "+self.fname+" "+self.lname)
class student(person):
... |
"""
6. Class tree links. In “Namespaces: The Whole Story” in Chapter 29 and in “Multiple
Inheritance: ‘Mix-in’ Classes” in Chapter 31, we learned that classes have a
__bases__ attribute that returns a tuple of their superclass objects (the ones listed
in parentheses in the class header). Use __bases__ to extend the li... |
# Lambda is commonly used to code jump tables
# which are lists/dicts of actions to be performed on demand
L = [lambda x: x ** 2, # Inline function definition
lambda x: x ** 3,
lambda x: x ** 4] # A list of three callable functions
for f in L:
print(f(2)) ... |
X = set('bimri')
Y = {'i', 'm', 'r', 'ii'}
print(X, Y) # A tuple of two sets without parantheses
print(X & Y) # Intersection
print(X | Y) # Union
print(X - Y) # Difference
print(X > Y) # Superset
# Preferrable use cases f... |
'''
Common Python expression statements:
spam(eggs, ham) Function calls
spam.ham(eggs) Method calls
spam Printing variables in the interactive interpreter
print(a, b, c, sep='') Printing operations in Py... |
"Computed Attributes"
class DescSquare:
def __init__(self, start): # Each desc has own state
self.value = start
def __get__(self, instance, owner): # On attr fetch
return self.value ** 2
def __set__(self, instance, value): # On attr a... |
"Scopes and try except Variables"
try:
1/0
except Exception as X:
print(X)
# print(X) # NameError: name 'X' is not defined
'''
Unlike compression loop variables, though, this variable is removed after the except
block exits in 3.X. It does so because it would otherwise retain a ... |
''' 1. The Basics'''
print(2 ** 16) # 2 raised to the power 16
print(2/5, 2/5.0) # Integer / truncates in 2.X, but not 3.X
# Strings
print('spam' + 'eggs') # Concatenation
S = 'ham'
print("eggs " + S)
print... |
"The try/except/else Statement"
'''
Syntactically, the try is a compound, multipart statement. It starts with a try header
line, followed by a block of (usually) indented statements; then one or more except
clauses that identify exceptions to be caught and blocks to process them; and an optional
else clause and block a... |
"Raising Exceptions"
'''
the following two forms are equivalent—both raise an instance of the exception class named,
but the first creates the instance implicitly:
'''
raise IndexError # Class (instance created)
raise IndexError() # Instance (created in statement)
'''
We can also create ... |
'''
fundamental built-in tools such as range, map, dictionary
keys, and even files are now generators
don’t complicate your code with user-defined generators if
they are not warranted. Especially for smaller programs and
data sets
simple lists of results will suffice, will be easier to understand, will be
garbage-c... |
L = [1, 2, 3, 4, 5]
for i in range(len(L)):
L[i] *= 10
print(L)
# List comprehension of above code(not simiilar though for it makes a new list object)
L = [x * 100 for x in L]
print(L)
|
'''The range Iterable'''
R = range(10) # range returns an iterable, not list
print(R)
I = iter(R) # Make an iterator from the range iterable
print(next(I))
print(next(I)) # Advance... |
import sys
print('{1:10} = {1:10}'.format('spam', 123.3456))
print('{0:>10} = {1:<10}'.format('spam', 123.3456))
print('{0.platform} = {1[kind]:<10}'.format(sys, dict(kind='laptop')))
print('{:10} = {:10}'.format('spam', 123.4567))
print('{:>10} = {:<10}'.format('spam', 123.4567))
print('{.platform:>10} = {[kind]:<10... |
# Embedding-based Manager alternative
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
def lastName(self):
return self.name.split()[-1]
def giveRaise(self, percent):
self.pay = int(self.pay * (1 + percent))
de... |
"Metaclasses Versus Class Decorators: Round 3 (and Last)"
# Class decorator factory: apply any decorator to all methods of a class
from types import FunctionType
from decotools import tracer, timer
def decorateAll(decorator):
def DecoDecorate(aClass):
for attr, attrval in aClass.__dict__.items():
... |
"Text and Binary Files"
# File I/O (input and output)
'''
Python now makes a sharp platform-independent distinction between text files and binary files;
~ Text files
When a file is opened in text mode, reading its data automatically decodes its content
and returns it as a str; writing takes a str and automatically... |
"Records Revisited: Classes Versus Dictionaries"
'''
dictionaries, tuples, and lists to record properties
of entities in our programs, generically called records. It turns out that classes can often
serve better in this role—they package information like dictionaries, but can also bundle
processing logic in the form of... |
"__getattribute__ and Descriptors: Attribute Tools"
"""
the __getattribute__ operator overloading
method, available for new-style classes only, allows a class to intercept all attribute
references, not just undefined references. This makes it more potent than its __get
attr__ cousin, but also trickier to use—it’s pron... |
# range allows multiple iterators
R = range(3)
# next(R) # TypeError: range object is not an iterator
I1 = iter(R)
print(next(I1))
print(next(I1))
I2 = iter(R) # Two iterators on one range
print(next(I2))
print(next(I2)) # I1 is at a differ... |
"Encodings converting"
'''
It’s also
possible to convert a string to a different encoding than its original, but we must provide
an explicit encoding name to encode to and decode from. This is true whether the
original text string originated in a file or a literal.
The term conversion may be a misnomer here—it really ... |
"Metaclass Methods Versus Class Methods"
'''
Though they differ in inheritance visibility, much like class methods, metaclass methods
are designed to manage class-level data. In fact, their roles can overlap—much as
metaclasses do in general with class decorators—but metaclass methods are not accessible
except through ... |
'''
keyword-only arguments are coded as named arguments
that may appear after in the arguments list *args
'''
def kwonly(a, *b, c):
print(a, b, c)
kwonly(1, 2, c=3)
kwonly(a=1, c=3)
kwonly(1,2,3,4,5,6,c=9)
"TypeError: kwonly() missing 1 required keyword-only argument: 'c'"
# kwonly(1,2,3)
'''
We can also use a... |
"annotation information"
# arbitrary user-defined data about a function’s
# arguments and result—to a function object
'annotations are completely optional'
#attached to the function object's __annotations__ attribute
# e.g. use annotations in the context of error testing
def func(a, b, c):
return a + b + c
prin... |
class Super:
def hello(self):
self.data1 = 'spam'
class Sub(Super):
def hola(self):
self.data2 = 'eggs'
X = Sub()
print(
X.__dict__ # Instance namespace dict
)
print(
X.__class__ ... |
# sys.stdout is just a normal file object
import sys
x, y, z = 'spam', 12, [12, 23, 45]
temp = sys.stdout # Save for restoring later
sys.stdout = open('log1.txt', 'a') # Redirect prints to a file
print('spam') ... |
"Function Interfaces and Callback-Based Code"
class Callback:
def __init__(self, color): # Function + state information
self.color = color
def __call__(self): # Support calls with no arguments
print('turn', self.color)
if __name... |
"List comprehensions with if clauses can be thought of as analogous to the filter built-in"
lc = [x for x in range(5) if x % 2 == 0]
print("list comprehension", lc)
fltr = list(filter((lambda x: x % 2 == 0), range(5)))
print("filter", fltr)
# Procedural
res = []
for x in range(5):
if x % 2 == 0:
res.appen... |
from __future__ import print_function
from functools import reduce
from timeit import repeat
import math
def fact0(N): # Recursive
if N == 1: ... |
"Listing instance attributes with __dict__"
from listinstance import ListInstance # Get lister tool class # Get lister tool class
class Super:
def __init__(self): # Superclass __init__
self.data1 = 'spam' #... |
"Why You Will Care: Bound Method Callbacks"
'''
Because bound methods automatically pair an instance with a class’s method function,
you can use them anywhere a simple function is expected. One of the most common
places you’ll see this idea put to work is in code that registers methods as event callback
handlers in the... |
'''the built-in dir function is an easy way to grab a list of all the
attributes available inside an object'''
import sys
print(
dir(sys)
)
print(
len(dir(sys)) # Number names in sys
)
print(
len([x for x in dir(sys) if not x.startswith('__')]) # Non __X name... |
'''
In Python:
- All objects have an inherent Boolean true or false value
- Any nonzero number or nonempty object is true
- Zero numbers, empty objects, and the special object None
are considered false
- Comparisons and equality tests are applied recursively to
data structures
- Compar... |
"Runtime Class Changes and super"
'''
Superclass that might be changed at runtime dynamically preclude hardcoding their
names in a subclass’s methods, while super will happily look up the current superclass
dynamically. Still, this case may be too rare in practice to warrant the super model by
itself, and can often be ... |
class Squares: # __iter__ + yield generator
def __init__(self, start, stop): # __next__ is automatic/implied
self.start = start
self.stop = stop
def __iter__(self):
for value in range(self.start, self.stop + 1):
yi... |
"__getattr__ and __getattribute__"
'A First Example'
class Person:
def __init__(self, name): # On [Person()]
self._name = name # Triggers __setattr__!
def __getattr__(self, attr): # On [obj.undefined]
print('get: ' + attr)
if a... |
"Adding Decorator Arguments"
import time
def timer(label='', trace=True): # On decorator args:retain args
class Timer:
def __init__(self, func): # On @: retain decorated func
self.func = func
self.alltime = 0
def __call__(self, *args,... |
def countdown(N):
if N == 0:
print('stop')
else:
print(N, end=' ')
countdown(N-1)
countdown(10)
countdown(90)
# generator-based solution
def countdown2(N): # Generator function, recursive
if N == 0:
yield 'stop'
... |
L = [123, 'spam', 1.23]
print(len(L)) # get length of collection
print(L[0]) # item at offset 0
print(L[:-1]) # all items except last one
print(L + [4, 5, 6]) # concat make new list too
print(L * 2) # repeat make new list too
print(L)... |
"Multiple Context Managers in 3.1, 2.7, and Later"
'''
the with statement may also specify multiple (sometimes
referred to as “nested”) context managers with new comma syntax
'''
with open('data') as fin, open('res', 'w') as fout:
for line in fin:
if 'some key' in line:
fout.write(line)
... |
L = ['loyal', '6lack', 'SONG!']
L.append('fying') # Append method call: add item at end
print(L)
L.sort()
print(L)
L = ['abc', 'ABD', 'aBe']
L.sort() # Sort with mixed case
print(L)
L = ['abc', 'ABD', 'aBe'] # Nor... |
"Object Destruction: __del__"
'''
__init__ constructor is called whenever an instance is generated
the destructor method __del__, is run automatically when an instance’s space is being reclaimed
(i.e., at “garbage collection” time):
'''
class Life:
def __init__(self, name='unknown'):
print('Hello ' + name)
... |
"Example: Default Behavior"
'''
Because the control flow through a program is easier to capture in Python than in
English, let’s run some examples that further illustrate exception basics in the context
of larger code samples in files.
'''
def gobad(x, y):
return x / y
def gosouth(x):
print(gobad(x, 0))
go... |
from firstClass import FirstClass
class SecondClass(FirstClass): # Inherits setdata
"""
SecondClass defines the display method to print with a different format. By defining
an attribute with the same name as an attribute in FirstClass, SecondClass effectively
replaces the ... |
"A First Look at User-Defined Function Decorators"
'''
Because the spam function is run through the tracer decorator, when the original
spam name is called it actually triggers the __call__ method in the class. This method
counts and logs the call, and then dispatches it to the original wrapped function.
'''
class tra... |
def intersect(*args):
res = []
for x in args[0]: # Scan first sequence
if x in res: continue # Skip duplicates
for other in args[1:]: # For all other args
if x not in other: break # Item in each one?
else... |
"Computed Attributes"
# properties do much more—computing the value of an attribute
# dynamically when fetched
class PropSquare:
def __init__(self, start):
self.value = start
def getX(self): # On attr fetch
return self.value ** 2
def setX(self, valu... |
# use this technique to skip items as we go:
S = 'abcdefghijk'
print(
list(range(0, len(S), 2))
)
for i in range(0, len(S), 2): print(S[i], end=' ')
print()
# slice with a stride of 2
for c in S[::2]: print(c, end=' ')
|
# update Person object on database
"prints the database and gives a raise to one of our stored objects each time"
import shelve
db = shelve.open('persondb') # Reopen shelve with same filename
for key in sorted(db): # Iterate to display database object... |
"Coding Exceptions Classes"
class General(Exception): pass
class Specific1(General): pass
class Specific2(General): pass
def raiser0(): raise General()
def raiser1(): raise Specific1()
def raiser2(): raise Specific2()
for func in (raiser0, raiser1, raiser2):
try:
func()
except General as X: ... |
from streams import Processor
class Uppercase(Processor):
def converter(self, data):
return data.upper()
if __name__ == "__main__":
import sys
obj = Uppercase(open('trispam.txt'), sys.stdout)
obj.process(); print()
class HTMLize:
"""
we get both uppercase conversion ... |
"Python 3.X Exception Chaining: raise from"
'''
Exceptions can sometimes be triggered in response to other exceptions—both deliberately
and by new program errors.
Python 3.X allows raise statements to have an optional from clause:
raise newexception from otherexception
'''
try:
1/0
except Exception as E:
... |
'''
filter is an iterable
in 3.X that generates its results on request, a generator expression with an if clause is
operationally equivalent
'''
# generator seems marginally simpler than the filter here
line = 'aa bbb c'
print(
''.join(x for x in line.split() if len(x) > 1) # Generator with 'if
)
print(
'... |
"Reduce function lives in functools module"
# Accepts aan iterable to process, but it's bot an iterable itself
# - it returns a single result.
from functools import reduce # Import in 3.X
# reduce passes the current sum or product. respectively
print(
reduce((lambda x, y: x + y), [1, 2,... |
"""\
JSON存儲文件
"""
import json
str='''[{"name":"bob","age":12},
{"name":"zjb","age":91}]'''
json.loads(str)
with open("data.json",'r') as a:
str=a.read()
jsonData=json.loads(str)
print(jsonData[0]) |
#!/usr/bin/env python
# coding: utf-8
# ## Task 11
# In[ ]:
# In[5]:
number1 = int(input('Enter 1st number: '))
number2 = int(input('Enter 2nd number: '))
ans = int(input('press 1 for addition, 2 for subtraction, 3 for multiplication, 4 for division: '))
def addition(number1,number2):
Jack = number1 + num... |
string = "How can mirrors be real if our eyes aren't real"
def to_jaden_case(string):
ans = []
for n in string.split():
ans.append(n.capitalize())
return " ".join(ans)
print(to_jaden_case(string)) |
'''
Given an n x n snail_map, return the snail_map elements arranged from outermost elements to the middle element, traveling clockwise.
snail_map = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(snail_map) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next snail_map consecut... |
'''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once. Also, i... |
#нарисовать 8
import turtle
import math
sqrt_3 = math.sqrt(3)
rad = sqrt_3 * 100/3
#print (rad)
turtle.left(120)
turtle.forward(200)
turtle.circle(-rad,240)
turtle.forward(200)
turtle.circle(rad,240) |
#funtion below is to check for type-0
def type0(p,lhs):
#n=p*2
for n in range(len(lhs)):
if((lhs[n]=="A")or(lhs[n]=="B")or(lhs[n]=="S")):
return 0
return 9
#function below is to check for type-1
def type1(p,lhs,rhs,l,r):
j=0
k=0
for q in range(len(lhs)):
... |
soma=0
x=int(input())
y=int(input())
if x < y:
for i in range (x,y+1):
if i % 13 != 0:
soma += i
else:
for i in range (y,x+1):
if i % 13 != 0:
soma += i
print(soma)
|
for i in range(1,10,2):
print("I="+str(i),"J=7")
print("I="+str(i),"J=6")
print("I="+str(i),"J=5")
|
x=int(input())
y=int(input())
if x < y:
for i in range (x+1,y):
if i % 5 == 2 or i % 5 == 3:
print(i)
else:
for i in range (y+1,x):
if i % 5 == 2 or i % 5 == 3:
print(i)
|
novoGrenal=1
somaGrenais=0
somaInter=0
somaGremio=0
empate=0
while novoGrenal == 1:
Inter,Gremio=map(int,input().split(" "))
if Inter > Gremio:
somaInter += 1
elif Gremio > Inter:
somaGremio += 1
elif Inter == Gremio:
empate += 1
somaGrenais += 1
print("Novo grenal... |
n=int(input())
line=list(map(int,input().split()))
menorValor=0
posicao=0
for i in range(n):
if int(line[i]) < menorValor or menorValor == 0:
menorValor = int(line[i])
posicao = i
print("Menor valor:",menorValor)
print("Posicao:",posicao)
|
print('Type "qqq" for exit')
while True:
try:
def funk():
if sign == "+":
return a + b
elif sign == "-":
return a - b
elif sign == "*":
return a * b
elif sign == "/":
return a / b
sign = i... |
def sustituye_it(lista_pal, pal_busc, pal_reemp):
""" lista, string, string -> lista
OBJ: Recibe una lista de palabras, busca todas las apariciones de la palabra a buscar(pal_bus) y la sustituye por la palabra a reemplazar (pal_reemp).
Devuelve la lista de palabras con las sustituciones realizadas."""
pal_reemp =... |
# Realice un subprograma que determine si un numero esta dentro de sus limites naturales, los cuales se pasan como argumento al subprograma.
def numero_limite(num, lim_inf, lim_sup):
"""Parameters: int, int, int -> boolean
OBJ: Comprueba si un num esta comprendido entre dos limites
PRE: lim_inf sera menor... |
clientes = {}
opcion = ''
while opcion != '6':
if opcion == '1':
dni = input('Introduce DNI del cliente: ')
nombre = input('Introduce el nombre del cliente: ')
direccion = input('Introduce la dirección del cliente: ')
fecha = input('Introduce la fecha de nacimiento del cliente: ')
... |
#!/usr/bin/env python3
"""Module to store implementation of the normal distribution"""
π = 3.1415926536
e = 2.7182818285
def erf(x, n=4):
"""Compute the Maclaurin approximation of erf up the fifth term"""
return 2/π**0.5*sum([x, -1/3*x**3, 1/10*x**5, -1/42*x**7, 1/216*x**9])
class Normal:
"""Class to re... |
#!/usr/bin/env python3
"""Demonstrate use of element-wise operations on numpy arrays"""
def np_elementwise(mat1, mat2):
"""Peform element-wise addition, subtraction,
multiplication, and division on mat1 and mat2"""
return mat1+mat2, mat1-mat2, mat1*mat2, mat1/mat2
|
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.RandomState(37)
x = rng.rand(200)
y = 3*x**7 + x + rng.randn(200)
y3 = 3*x**7 + x
plt.scatter(x, y)
plt.scatter(x, y3)
def F(x, y, a, c):
e = 0.
for i in range(len(y)):
e = e + (y[i] - ((-a*x**7)[i] + c*x[i]))**2
return e/(2*(len(y... |
import math
def function(x):
return math.exp(-x) - x
def derivative(x):
return -(math.exp(-x)) - 1
def roots_nr(guess, error):
ec = 100
while ec > error:
xn = guess - (function(guess)/derivative(guess))
ec = (guess - xn)/xn * 100
guess = xn
return xn
roots_nr(1, 0)
|
import socket # We need our socket functions
# This is the client function, used for sending the mbr info to the server
class Client:
# Declaring the host and port variables
host = '127.0.0.1'
port = 5000
def __init__(self):
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creating our sock... |
tempc = input('請輸入攝氏C,我來幫你轉成華氏F唷')
tempc = float(tempc)
tempf = tempc * 9 / 5 + 32
tempf = float(tempf)
print('轉成華氏後是',tempf,'度唷!') |
def answers(numbers):
# Create an empty list, to put the pirates as they're met.
pirates = []
# Start at pirate 0.
i = 0
# Keep going until the cycle is found.
while True:
# Check the current pirate matches any existing pirates.
# As they're added sequentially, any previous pi... |
import math
def even(x):
c = math.ceil(x)
f = math.floor(x)
if c%2 == 0:
r = c
else:
r = f
return r |
import datetime
def fact():
'''Get the current day name'''
try:
now = datetime.datetime.now()
current_hour = now.strftime("%H")
except (IOError, OSError):
current_hour = ""
return {'current_hour': current_hour}
if __name__ == '__main__':
print(fact())
|
import datetime
def fact():
'''Get the current day name'''
try:
now = datetime.datetime.now()
dayname = now.strftime("%A")
except (IOError, OSError):
dayname = ""
return {'current_day_name': dayname}
if __name__ == '__main__':
print(fact())
|
a = [6,4,1]
swap = 0
swap1 = 1
while swap1 != 0:
swap1 = 0
for i in range (1,len(a),1):
if a[i-1] > a[i]:
temp = a[i]
a[i] = a[i-1]
a[i-1] = temp
swap1 += 1
print(swap1 ,a)
swap += 1
print(f"Array is sorted in {swap} swaps")
print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.