text
stringlengths
37
1.41M
print "Hello World!" print "Hello Again" print "I like typing this." print "This is fun." print 'Yay! Printing.' print "I'd much rather you 'not'." print 'I "said" do not touch this.' print "Arithemetics" print 2+4 print 8/2 print 8%2 print 6>8 rate = 12 tax = 24 total = rate + tax /100 print tax rate = 12 tax = 24 tot...
def solution(s): answer = [] for i in range(len(s)): for j in range(1, len(s) + 1): if s[i:j] and str(s[i:j]) == str(s[i:j])[::-1]: answer.append(s[i:j]) elif s[j:i] and str(s[j:i]) == str(s[j:i])[::-1]: answer.append(s[j:i]) return max(answer)...
answer = 0 def dfs(begin, target, words, visited): global answer stacks = [begin] while stacks: stacks.pop() stack = stacks.pop() if begin == target: return answer for w in range(len(words)): if [] == 1: answer += 1 def solution(begin,...
A = list(input()) B = list(input()) count = 0 intersection = set(A) & set(B) symmetric_difference = set(A) ^ set(B) for x in symmetric_difference: count += A.count(x) + B.count(x) for x in intersection: count += abs(A.count(x) - B.count(x)) print(count)
num1 = input("Enter number sequences seperated by comma :").split(',') # Given tuple num_tuple = tuple((num1)) print("Given list is ", num_tuple) # Print elements that are divisible by 5 print("Elements that are divisible by 5:") for num in num_tuple: if (int(num) % 5 == 0): print(num)
class DictList(dict): """A dictionnary of lists of same size. Dictionnary items can be accessed using `.` notation and list items using `[]` notation. Example: >>> d = DictList({"a": [[1, 2], [3, 4]], "b": [[5], [6]]}) >>> d.a [[1, 2], [3, 4]] >>> d[0] DictList({"a":...
def quartiles(arr): # Write your code here arr = sorted(arr) n = len(arr) if n % 2 == 0: median = (arr[n//2] + arr[n//2 - 1]) / 2 arr1 = arr[:n//2] arr2 = arr[n//2:] else: median = arr[n//2] arr1 = arr[:n//2] arr2 = arr[n//2 + 1:] l = len(arr1...
def getNumber(string): for i in range (0,len(string)): if string[i].isdigit()==True or string[i]=='.': for j in range (i,len(string)+1): if j>len(string)-1: val=string[i:j+1] return float(val) if string[j].isdigit()==True or string[j]=='.': j+=1 else: ...
from .peekable import Peekable def sequence(*iterables, by=None, compare=None): if compare is not None: compare = compare elif by is not None: compare = lambda i1, i2: by(i1) <= by(i2) else: compare = lambda i1, i2: i1 <= i2 iterables = [Peekable(it) for it in iterables] ...
#!usr/bin/env python3 def timeConversion(s): if s.endswith("AM"): s=s.strip("AM") x=s.split(':') if x[0]=='12': x[0]='00' result=':'.join(x) return result else: result=':'.join(x) return result elif s.endswith("PM"): ...
#program to understand the multi-line comments in python ''' Since python will ignore string literals which are not assigned to a variable,you can add a multi-;ine string (Triple quotes) in your code, and place your comments inside it. ''' ''' As long as the string is not assigned to a variable, python read the code,...
""" Author: Kristofer Stensland Last Updated: October, 2012 Description: Sends search queries to Ask.com and harvests the top ten most relevant documents, storing all of their URLS in a sqlite database. Then Removes all of the HTML tags leaving only the tokens. Then cleans up the ...
"""Provides helper utilities for formatting""" import ast def safe_determine_type(string): """ Determine the python type of the given literal, for use in docstrings Args: string (str): The string to evaluate Returns: ``str``: The type, or "TYPE" if the type could not be determined ...
import collections class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ squares = [1] i = 2 while squares[len(squares)-1] < n: squares.append(i*i) i += 1 print squares result = ...
# a/b def add(x, y): a = True while a: a = x & y b = x ^ y x = a << 1 y = b return b def mult(a, b): r = 0 for i in xrange(b): r = add(r, a) return r def division(a, b, precission=0.001): prev_guess = 0 guess = a while abs(a - mult(guess, b...
""" You are the main character in a game where you have to defeat a number of enemies in order. The player has a strength value and an initial amount of money. Each enemy also has a strength value, plus a price. When facing each enemy you can either: 1) Fight him (if your strength is enough). You keep your money...
""" You are given a text file that has list of dependencies between (any) two projects in the source code repository. Write an algorithm to determine the build order ie. which project needs to be build first, followed by which project..based on the dependencies. Bonus point: If you can detect any circular dependencies...
def is_pal(str_to_check): for i in xrange(len(str_to_check) / 2): if str_to_check[i] != str_to_check[-(i+1)]: return False return True print is_pal("hello") print is_pal("romaamor") print is_pal("romamor") # Could be: Manacher's algorithm, but not... this is almost the same def get_all_pa...
""" Given a start position and an target position on the grid. You can move up,down,left,right from one node to another adjacent one on the grid. However there are some walls on the grid that you cannot pass. Now find the shortest path from the start to the target. """ from collections import defaultdict class Gam...
def intersec_sorted(arr1, arr2): p1 = 0 p2 = 0 result = [] while p1 < len(arr1) and p2 < len(arr2): if arr1[p1] == arr2[p2]: result.append(arr1[p1]) p1 += 1 p2 += 1 elif arr1[p1] < arr2[p2]: p1 += 1 else: p2 += 1 r...
""" Given an arraylist of N integers, (1) find a non-empty subset whose sum is a multiple of N. (2) find a non-empty subset whose sum is a multiple of 2N. Compare the solutions of the two questions. """ class IntArray(object): def __init__(self, int_arr): self._int_arr = int_arr def sum_mult_n(self...
fib = lambda x: x if x <= 1 else fib(x-1) + fib(x-2) print fib(6) class Fibonacci(object): def __init__(self): self.__cache = [1, 1] def fib(self, pos): pos -= 1 if pos >= len(self.__cache): last_pos = len(self.__cache) - 1 while last_pos != pos: ...
import pandas as pd import numpy as np def create_data(): """ This function loads price data from an Excel document. WARNING : Pay attention to the Excel document's directory path and name. :return: a DataFrame of the prices of the assets. :rtype: DataFrame """ data = pd.read_excel( ...
a={'Name':'Fatima'} try: with open('data.csv','w'): pass print('I am after open file') print(a['Name']) except KeyError: print('This key does not exist in this ADT') except FileNotFoundError as e: print(e) print('File does not exist') except Exception: print('This is unknown e...
def add_something(x): return x + 8 a = add_something(6) #인자가 2개인 함수 def plus_two_times(a, b): return a + b + b c = plus_two_times(3, 4) print(c) #문자열을 인자로 받는 함수 def hello_someone(someone): return 'Hello ~ ' + someone print(hello_someone('조재성'))
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% #Universidad Autónoma de Chihuahua # Facultad de Ingeniería # Sistemas de Búsqueda y Razonamiento # Equipo: # Carlos García # Alejandro Aguirre # Ericka Bermúdez # referencias: https://www.educative.io/edpresso/how-to-im...
a, b = input().split() print('Yes') if (int(a+b)**0.5).is_integer() == True else print('No')
A = int(input()) print((A // 2) ** 2 if A % 2 == 0 else A // 2 * (A // 2 + 1))
"""un/comment to de/activate ########################### a = 10 b = 10 print( a == b ) print( a != b ) print( a > b ) print( a < b ) print( a >= b ) print( a <= b ) #######################################################""" # """un/comment to de/activate ########################### # evaluation / execution # data...
"""un/comment to de/activate ########################### # types # int, float # bool # None # str # *tuples # list # dictionaries # *sets # abstraction # variables # functions # control flow # if elif else # iteration # for # while # map text = ''' Whose w...
"""un/comment to de/activate ########################### # len # Input # some collection ie a list or string or tuple # Process # Output # int representing the lenght of the input lst = [ 44, 33, 55, 44] # list # append # pop # len # len(lst) # sum # sorted # max # min # count # lst.count(44) # index ...
import numpy as np xa_high = np.loadtxt('data/xa_high_food.csv', comments='#') xa_low = np.loadtxt('data/xa_low_food.csv', comments='#') def xa_to_diameter(xa): """ Convert an array of cross_sectional areas to diameters with commuensurate units """ # Compute diameter from area # A = pi * d^2 / 4 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 from array import array alph = list('абвгдежзийклмнопрстуфхцчшщъыьэюя') new_alph = list() keyword = list(str(input('Введите ключевое слово:\n'))) text = list(str(input('Введите текст:\n'))) b=-1 new_text=list() my_keyword=list() for i in keyword...
# FILL TABLES THAT ALREADY CREATED IN SQL # setup from __future__ import unicode_literals import sqlite3 import csv connection = None cursor = None cursor2 = None tab_delimited_file = None tweet_reader = None tweet_counter = -1 field_count = -1 current_tweet_row = None # variables to hold fields tweet_timestamp = "...
import math def is_prime(x): if x <= 1: return False if x <= 3: return True i = 2 while (i <= math.sqrt(x)): if (x % i == 0): return False i+= 1 return True def main(): count = 0 index = 0 primes = list() while (index < 10001): ...
#program to resize the image import cv2 img = cv2.imread("image.png") #resize the image using row and column values newImage = cv2.resize(img, (550, 350)) #display the image cv2.imshow('Resized Image', newImage) cv2.waitKey(0)
# Word Genetic Algorithm [init, points, selection, crossover, mutation] # Point Granting # correct letter 1 points # correct letter in posistion 2 points # correct length 4 points # word properties # - length # - letters import string import random # Properties target_word = "to be or not to be" showEvery = 5 Popul...
#An apparel shop wants to manage the items which it sells #OOPR-Assgn-24 #Start writing your code here class Apparel: counter = 100 def __init__(self,price,item_type): Apparel.counter+=1 self.__item_id=item_type[0].upper()+str(Apparel.counter) self.__price = price self.__item_ty...
# This application renames files based on a user input directory, word that needs to be changed, and word that it will be changed to. # It also has optional capabilities to add a date stamp to a .txt file that has been renamed import os import datetime as dt def file_renamer(path, original, new, datestamp = False): ...
a = input() b = input() def similar(a, b): if len(a)-1 != len(b): return False offset = 0 for bindex in range(len(b)): if a[bindex + offset] != b[bindex]: if offset == 0: offset += 1 else: return False return True print('TAK' if s...
height = int(input()) n = int(input()) for segment in range(0, n): for i in range(1, height+1): print(' '.join(['*'] * i)) height += 1
n = int(input()) word = '' for i in range(n): word += input()[i] print(word)
from typing import Optional from githubmarkdownui.constants import HEADING_MAX_LEVEL, HEADING_MIN_LEVEL def thematic_break() -> str: """Returns a <hr> tag, used to create a thematic break. Equivalent to --- in Markdown.""" return '<hr>' def code_block(text: str, language: Optional[str] = None) -> str: ...
def bold(text: str) -> str: """Alternative name for strong_emphasis. :param text: The text to be bolded """ return strong_emphasis(text) def code_span(text: str) -> str: """Returns the text surrounded by <code> tags. :param text: The text that should appear as a code span """ return ...
''' Problem Either strand of a DNA double helix can serve as the coding strand for RNA transcription. Hence, a given DNA string implies six total reading frames, or ways in which the same region of DNA can be translated into amino acids: three reading frames result from reading the string itself, whereas three more res...
def reversecomplement(s): nucl_replace={'A':'T','T':'A','C':'G','G':'C'} revcom='' for nucl in s.strip('\n')[::-1]: revcom = revcom + nucl_replace[nucl] return revcom with open('rosalind_revc.txt') as file: DNAsequence = file.read() fh=open('rosalind_revc_output.txt', 'w+') fh.write(reversecomplement(DNAse...
def Fibonacci(n,k): F1=0 F2=1 if n==0: return F1 elif n==1: return F2 else: for i in range(1,n): Fib=F2 + k*F1 F1=F2 F2=Fib return Fib print(Fibonacci(50,3)) with open('Fibonacci/rosalind_fib.txt', 'r') as file: value=list(m...
class MOD(object): """ A Class for any MOD Statements in the Assembly Code """ def __init__(self, code, memory, cpu): self.code = code self.opcode = code[0: 3] self.operand = code[3: len(self.code)].replace(" ", "").split(",") self.value = self.getValue(memory) ...
#!/usr/bin/env python # coding: utf-8 # # Algoritmos Computacionais em Grafos - Trabalho Final # # **PUC Minas** # # **Engenharia de Software** # # **Prof Joyce Christina de Paiva Carvalho** # # * Bruno Armanelli # * Douglas Domingues # * Henrique Freire # * Luiz Antunes # ## 0) Imports # # A grande parte do cód...
class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.level = None class BST: def __init__(self): self.root = None def create(self, val): if self.root == None: self.root = Node(val) else: ...
# Uses error to determine significant digits to display data in # Usage: r'$(%.0f \pm %.0f)x10^{%i}$' % sigfigs(value, error) def sigfigs(value, error): sigfigs = 0 if error >= 1.: e = str(int(error)) for i in range(len(e),0,-1): if int(e[i-1]) != 0: sigfigs = len(e)...
#Heap Sort #Function to create max heap def max_heapify(arr, n, i): largest = i left = 2*i+1 right = 2*i+2 if left < n and arr[i] < arr[left]: largest = left if right < n and arr[largest] < arr[right]: largest = right if largest != i: arr[i]...
#Shell Sort import numpy as np #Function to sort input array to ascending order def Ashellsort(A): print(A) n = len(A) gap = int(np.floor(n/2)) while gap > 0: for i in range(n-gap): if A[i] >= A[i+gap]: A[i], A[i+gap] = A[i+gap], A[i] j ...
""" Wave Array Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it. In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order). Input Format: The first line contains an integer T, dep...
def func(ch,st,n): if(n == len(st)): print(ch) return func(ch+st[n],st,n+1) func(ch,st,n+1) st = input() print(func("",st,0))
def reverseWords(s): ans="" l=[] for x in s: ans+=x if(x=='.'): l.append(ans) ans="" continue l.append(ans) answer="" for x in range(len(l)-1,-1,-1): answer+=l[x] if(x==len(l)-1): answer+='.' print(answer[0:-1],e...
""" Digital Root You are given a number n. You need to find the digital root of n. DigitalRoot of a number is the recursive sum of its digits until we get a single digit number. Eg.DigitalRoot(191)=1+9+1=>11=>1+1=>2 Input: The first line of input contains T denoting the number of testcases. T testcases follow. Each te...
""" Multiply the matrices When dealing with matrices, you may, sooner or later, run into the elusive task of matrix multiplication. Here, we will try to multiply two matrices and hope to understand the process. Two matrices A[][] and B[][] can only be multiplied if A's column size is equal to B's row size. The resulta...
""" Digits In Factorial Given an integer N. The task is to find the number of digits that appear in its factorial, where factorial is defined as, factorial(n) = 1*2*3*4……..*N and factorial(0) = 1. Input: The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Ea...
""" Minimum Number in a sorted rotated array Given an array A which is sorted and contains N distinct elements. Also, this array is rotated at some unknown point. The task is to find the minimum element in it. Note: Expected time complexity is O(logN). Input: The first line of input contains an integer T denoting th...
""" Minimum Platforms Given arrival and departure times of all trains that reach a railway station. Your task is to find the minimum number of platforms required for the railway station so that no train waits. Note: Consider that all the trains arrive on the same day and leave on the same day. Also, arrival and departu...
""" Rotate Array Given an unsorted array arr[] of size N, rotate it by D elements (counter-clockwise). Input: The first line of the input contains T denoting the number of testcases. First line of eacg test case contains two space separated elements, N denoting the size of the array and an integer D denoting the num...
""" Modular Multiplicative Inverse Given two integers ‘a’ and ‘m’. The task is to find modular multiplicative inverse of ‘a’ under modulo ‘m’. Note: Print the smallest modular multiplicative inverse. Input: First line consists of T test cases. Only line of every test case consists of 2 integers 'a' and 'm'. Output: F...
""" Interchanging the rows of a Matrix You are given a matrix A of dimensions n1 x m1. You have to interchange the rows(first row becomes last row and so on). Input: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase two lines of input. The first line contains dimens...
""" Binary Array Sorting Given a binary array A[] of size N. The task is to arrange array in increasing order. Note: The binary array contains only 0 and 1. Input: The first line of input contains an integer T, denoting the testcases. Every test case contains two lines, first line is N(size of array) and second line ...
temp = head fast = head while(temp!=None and fast.next!=None and fast.next.next!=None): temp = temp.next fast = fast.next.next if temp==fast: return('True') return('False')
""" Possible Words From Phone Digits Given a keypad as shown in diagram, and an N digit number. List all words which are possible by pressing these numbers. Input: The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains two lines of input. The first l...
""" Merge Without Extra Space Given two sorted arrays arr1[] and arr2[] in non-decreasing order with size n and m. The task is to merge the two sorted arrays in place, i. e., we need to consider all n + m elements in sorted order, then we need to put first n elements of these sorted in first array and remaining m eleme...
""" Find first set bit Given an integer an N. The task is to print the position of first set bit found from right side in the binary representation of the number. Input: The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The only line of the each test case c...
N = int(input()) result = [] for i in range(N): result.append(2**i) print(result,end=' ')
inch = float(input()) cm = inch * 2.54 print('{:.2f} inch => {:.2f} cm '.format(inch, cm))
# 런타임에러 N = int(input()) nums = list(map(int, input().split())) compare_in = nums[0] compare_de = nums[0] length_in = 1 length_de = 1 result = [] for i in range(1, len(nums)): if nums[i] >= compare_in: compare_in = nums[i] length_in += 1 result.append(length_in) else: ...
T = int(input()) for t in range(1, T+1): str1 = str(input()) str2 = str(input()) if str1 in str2: result = 1 else: result = 0 print('#{} {}'.format(t, result))
T = int(input()) for tc in range(1, T+1): words = [0]*5 maxlen = 0 for i in range(5): words[i] = list(input()) if len(words[i]) > maxlen: maxlen = len(words[i]) print('#{}'.format(tc), end=' ') for i in range(maxlen): for j in range(5): if len(words[j]...
n = int(input()) for i in range(1,n+1): print(f"{'*' * i}") for i in range(n-1,0,-1): print(f"{'*' * i}")
# arr = [0] * 5 # for i in range(5): # arr[i] = list(map(int,input().split())) # print(arr[0]) # print(arr) # print(arr[0][1]) # arr = [[0] * 5] * 5 # 이렇게 초기화하지 않는다!! # arr[1][0] # print(arr) # arr = [[0] * 5 for _ in range(5)] # 이렇게 초기화 해준다! # arr[1][0] = -1 # print(arr) 10101 => [1, 2, 3, 1,]
#!/bin/env python import numpy as np import integ_Romberg def NaivTrap(f,a,b,eps): """变步长梯形积分 :f: TODO :a: TODO :b: TODO :eps: TODO :returns: TODO """ n = 1 h = (b-a)/n I1 = 0.5*h*(f(a)+f(b)) tol=1; while tol>eps: I0 = I1 n = 2*n h = (b-a)/n ...
import numpy as np from scipy import optimize def newton(f,df,p0,epsilon=10**-6,maxi=1000): """solve nonlinear eqution by newton iterative method :f: func :df: First derivative of f :p0: initial value :returns: solve """ x=p0 res=f(x) i=0 while abs(res)>= epsilon: x1 ...
from random import random def GetGuess(): tmp = int(input("Please input your guess\n")) return tmp key = int(random()*100) print("guess the number in (0,100])") guess = GetGuess() while guess != key: if guess > key: print("Too large!") if guess < key: print("Too small!") guess ...
import numpy as np # from scipy.optimize import curve_fit import matplotlib.pyplot as plt from linalg_gauss_jordan import gauss_jordan def multifit(x,y,m): """TODO: Docstring for multifit. :arg1: TODO :returns: TODO """ n = len(x) if m > n : print("warning: m >n") S = np.zeros((m...
caps = list(range(65, 91)) lower = list(range(97, 123)) everything = list(range(33, 127)) def hey(str): str = str.strip() if says_nothing(str): return "Fine. Be that way!" elif question(str): return "Sure." elif yell(str): return "Whoa, chill out!" else: return "Whatever." def question(str): ord_list = ...
def distance(str1, str2): str1, str2 = str1.upper().strip(), str2.upper().strip() if len(str1) != len(str2): raise ValueError("Input strings are of unequal length") for item in str1+str2: if item not in 'GCTAU': raise ValueError("At least one input strings was invalid") diffs, i = 0, 0 while i < len(str1): ...
# Storing elements in a list / tuple in variables for easy accessibility numbers = (2, 3, 4, 5) a = numbers[0] b = numbers[1] c = numbers[2] d = numbers[3] print(a) print(b) print(c) print(d) print() # Unpacking makes the above easier j, k, l, m = numbers print(j) print(k) print(l) print(m) print() # In lists, mile...
# Dictionaries - used for storing unique key-value pairs # user = { # "first_name": "Ian", # "second_name": "Roberts", # "email": "ianroberts@mail.co.uk", # "country": "UK", # "is_registered": True, # "user_code": 23409 # } # # # availab...
first_name = "Dean" mid_name = "van" last_name = "Thompson" multiply_string = "good " print(first_name, last_name) print(first_name.isprintable()) print(first_name.upper()) print(mid_name.capitalize()) print(first_name.lower()) print(len(last_name)) print(last_name.find("s")) print(mid_name.isdigit()) print(mid_name.i...
import random import time name=input("enter your name : ") tar=50 play=0 comp=0 def player(play,val): input("press enter to roll the dice") dice=random.randint(1,6) if val==1: print("entry value : ",dice) return dice print(dice) if play+dice<=tar: if play==tar-6 and dice==6: ...
################################################################################ # 'SNAKEY' GAME ## Adapted by George Deeks from https://gist.github.com/sanchitgangwar/2158089 ## Use ARROW KEYS to play and Esc Key to exit ################################################################################ # Import helper ...
from code.algoritmes.dumbsolver import dumbsolver from code.algoritmes.dannystra import dannystra from code.algoritmes.breadth import breadth from code.helper.play import play from code.helper.play_2 import play_2 from code.helper.draw_2 import begin from code.helper.compare import compare def main(): ''' Mai...
import logging import operator import copy from logs.setup_logs import init_logs from readers.file_reader import FileReader logger = init_logs(__name__) HALT = 99 ADD = 1 MULT = 2 def operate(operand, code_position, register): """ This method will modify the register with the requested operation :param ...
from operator import methodcaller from readers import FileReader COM = "COM" def main(): raw_orbits = list(map(methodcaller("split", ")"), map(str.strip, FileReader.read_input_as_list()))) orbits = {o[1]: o[0] for o in raw_orbits} total_orbits = 0 for planet in orbits.keys(): print(f"Gettin...
import random n = random.randrange(1, 20, 2) print("I am thinking of a number between 1 and 20. Take a guess.") def inputnum(): a = int(input()) return a def GuessGame(): b = inputnum() for i in range(1, 6): if n == b: print("Good job! You guessed my number in " + str...
str1='abcsadfadsfgfegegegea' j = 0 dict1={} for i in str1: j+=1 dict1.update({i:j}) print (dict1)
# -*- coding: utf-8 -*- # @Time : 2019/1/7 20:36 # @Author : for # @File : 01_copy_test.py # @Software: PyCharm import copy a = [1,2,3,4,[5,6,7]] b = a print('a 的 id : %s ,b 的 Id %s '%(id(a),id(b))) #深copy d = copy.deepcopy(a) print('d 的 id',id(d)) #浅copy c = copy.copy(a) print(id(c)) a.append(8) a[4].append(9) ...
n=int(input('请输入递归数')) result=1 i=1 while i<=n: result = result*i i+=1 print(result)
""" @File : 2_简单的绘图实例.py @Time : 2020/4/15 3:31 下午 @Author : FeiLong @Software: PyCharm """ import numpy from matplotlib import pyplot # 定义x轴的坐标 x=numpy.arange(1,11) # 定义y轴的坐标 y=2*x+5 # 坐标图的标题 pyplot.title('Matplotlib Demo') # x轴的名称 pyplot.xlabel('x axes') # y轴的名称 pyplot.ylabel('y axes') # 设置坐标参数 xp=[1,2,3,4] y...
a=[1,2,3,5,7,2,9,6,3,5,4] for i in a: if i==max(a): print('最大值是%d'%i) elif i==min(a): print('最小值是%d'%i)
''' 对象:万物皆对象,就是事实存在的事物 类: 是对事物的划分,当我们在描述的时候用到类,就是在描述一系列的事物的共性特征,比如:鸟类,我们想要说的是所有鸟的共性比如:卵生,羽毛 实例: 从类当中具体映射出来的个体,比如鸟类当中的鸵鸟 类和实例都有自己独立的内存空间,相互独立互不影响,实例来源于类但是比类更具有个性 ''' ''' 域: 属于类或者实例的变量,一些名词,例如name,age…… 方法:属于类或者实例的功能(函数),一般来说是函数。一些动词,吃,喝…… 属性: 域和方法的统称 类方法:属于类的功能 类属性:属于类的属性 实例方法:属于实例的功能 实例属性:属于实例的属性 ''' #####面向对象:在编程过程...
# 导入套接字 import socket # 创建一个套接字 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 绑定端口,参数为元组,''代表本地所有的IP sock.bind(('',8080)) # 监听最大的端口为5 sock.listen(5) #接收连接请求 #conntent 用来接收请求用户的消息和发送对该用户的的消息功能 #address 是请求用户的身份(ip,port) conntent,address=sock.accept() print('%s:%s id connectent...'%address) # 发送数据,encode()编码 co...
#####常规继承 # class Admin(): # def eat(self): # print('吃。。。') # def drink(self): # print('喝。。。') # class Dog(Admin): # def eat(self): # print('狗在吃') # def call(self): # print('狗在喝') # class Cat(Admin): # def catch(self): # print('猫抓老鼠') # # # 将类实例为对象 # d=Dog() #...
#####获取异常的信息 # def func(): # try: # print(a) # except Exception as e: # print(e) # func() #####没有捕捉到异常就会执行else中的代码 # def func(): # a='我是你爸爸' # try: # print(a) # except Exception as e: # print(e) # else: # print('没有捕捉到异常就执行else中的代码') # func() #####finally...