text
stringlengths
37
1.41M
# 第八章:类与对象 # 8.1 改变对象的字符串显示 # 要改变一个实例的字符串表示,可重新定义它的 __str__() 和 __repr__() 方法。例如: class Pair: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return 'Pair({0.x!r}, {0.y!r})'.format(self) def __str__(self): return '({0.x!s}, {0.y!s})'.format(self) # __rep...
# 第四章:迭代器与生成器 # 4.1 手动遍历迭代器 def manual_iter(): with open('/etc/passwd') as f: try: while True: line = next(f) print(line, end='') except StopIteration: pass items = [1, 2, 3] it = iter(items) print(next(it)) # 4.2 代理迭代 # 你构建了一个自定义容器对象,里面包含有列表...
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self,new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def middleelement(self): ...
ar = [2,1,3,5,6] n = len(ar) x = n+1 ar1 = [] for i in range(x): ar1.append(i)
import random # TODO: How to specify seed def random_group(members, seed=None): """ Parameters ---------- members: list<any> seed: hashable Returns ------- list<list<any>> """ random.seed(seed) # If there are less than GROUP_MAX_SIZE (which is 5) people, just get one t...
''' 给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。 示例 1: 输入: "2-1-1" 输出: [0, 2] 解释: ((2-1)-1) = 0 (2-(1-1)) = 2 示例 2: 输入: "2*3-4*5" 输出: [-34, -14, -10, -10, 10] 解释: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 ''' class So...
''' 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 来源:力扣(LeetCode) 链接:https://leetcode-cn.co...
def find(s1,s2): #以 i j 结尾的最长子串,必须包括 ij if s1 == '' or s2 == '': return 0 count = 0 dp = [ [ 0 for j in range(len(s2)+1) ] for i in range(len(s1)+1) ] for i in range(1,len(s1)+1): for j in range(1,len(s2)+1): dp[i][j] = dp[i-1][j-1]+1 if s1[i-1] == s2[j-1] else 0 ...
class MyHashMap: def __init__(self): """ Initialize your data structure here. """ self.size=1000000 self.table=[None]*self.size def calculate_hash_value(self, key): return key%self.size def put(self, key: int, value: int) -> None: """ va...
""" Jake Stephens Class: CS 677 - Summer 2 Date: 7/13/2021 Homework #2 Description: This program makes many different calculations to analyze the stock data for 2 tickers, SUN and SPY. """ import pandas as pd import os import math import ast import matplotlib.pyplot as plt # Ticker file location ticker_file_sun = r"da...
# map_reduce.py '''"'Defines a.txt single function, map_reduce, which takes an input dictionary i and applies the user-defined function mapper to each (input_key,input_value) pair, producing a.txt list of intermediate keys and intermediate values. Repeated intermediate keys then have their values grouped into a.txt li...
male = input("are you male? True/False") tall = input("are you tall? True/False") if male == "True": print("you are a male ") else: print("you aren't a male ") if tall == "True": print("and you're tall") else: print("and you aren't tall")
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ guessit(self,0,n) def guessit(self...
# exercise 2 def email_check(string): for letter in string: if '@' and '.' in string: return True else: return False email=input("Enter your e-mail: ") print("This email is",email_check(email))
#!/usr/bin/env python # coding: utf-8 # # Coursework 2 for Cardiac MR Image Segmentation (2020-2021) # # After you have gone through the coursework description, this tutorial is designed to further helps you understand the problem and therefore enable you to propose a good solution for this coursework. You will learn...
#Find out the maximum sub-array of non negative numbers from an array. #The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping the third element is invalid. # #Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A ...
import json import os import time from urllib import request def locationinput(): with open('history.city.list.json') as f: data = json.load(f) city_list = [] id_list = [] for i in data: city_list.append(i["city"]["name"]) id_list.append(i["id"]) while True: location = input("please enter a valid city nam...
# 1.6.1 単純なグラフの描画 import numpy as np import matplotlib.pyplot as plt # create data x = np.arange(0, 6, 0.1) y = np.sin(x) # draw graph plt.plot(x, y) plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @_ambonilla 2014 Using cocos & piglet libraries, is a small counter program where when you push the up key it will add a number to the displayed value, and the down key will substract one """ import cocos import sys from cocos.actions import * import pyglet from...
''' This is an implementation of the k-Nearest Neighbor classification algorithm. For a given test point, it finds the k nearest neighbors and assigns to the test point the most common classification of those neighbors. In the case of a tie it picks randomly from the classifications most represented. ''' import ran...
""" #Search Algorithms - Uninformed Author: Sebastian C. """ from collections import namedtuple,deque city = { 's':{ 'a':7, 'b':2, 'c':3 }, 'a':{ 's':7, 'b':3, 'd':4 }, 'b':{ 's':2, 'a':3, 'd':4, 'h...
""" @drmorales4 Programacion Funcional: Funciones Puras Efectos Secundarios """ import csv def lineas(archivo): return csv.reader(archivo, delimiter=";") with open("data/data-estudiantes.csv") as midata: print(list(lineas(midata))) # midata = open("data/data-eestudiantes.csv") # uso de grandes volumenes de...
import random # random.randint(x,y) 生成一个指定范围内的整数 num = random.randint(0,20) # 统计用户猜测的次数 count = 1 # 用户猜的数字 print("please guess a number < 20") # python3里面input()默认接收到的是str类型 x = int(input(">")) while x != num and count < 10: if x > num: print("bigger,please guess once more") x = int(in...
import sqlite3 def insertAccount(ID, FIRSTNAME, LAST, USERNAME, PASSWORD, EMAIL, PHONENUMBER): dbase = sqlite3.connect("Accounts (2).db") act = dbase.cursor() act.execute("INSERT INTO Accountinfo (ID, FIRSTNAME, LAST, USERNAME, PASSWORD, EMAIL, PHONENUMBER) VALUES (?,?,?,?,?,?,?)", (9, "hello", "world", "this", "is...
def function1(ransomNote, magazine): ''' for letter in ransomNote: if ransomNote.count(letter)>magazine.count(letter): return False return True ''' buf_dict = {} for each in magazine: if each in buf_dict: buf_dict[each]+=1 else:buf_dict[each]=1 ...
def function1(grid): perimeter = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]==1: perimeter+=count(grid,i,j) return perimeter def count(grid,i,j): counter=0 if i-1< 0 or grid[i-1][j] == 0:counter+=1 if j+1>= len(grid[0]) or grid[i]...
#import itertools def function1(A,B): if len(A)!=len(B):return False if A==B: seen = set() for each in A: if each in seen:return True seen.add(each) return False else: pairs = [] for a,b in zip(A,B): if a!=b: pairs.a...
def function1(a,b): buf_dict = {} output = [] for each in a.split(): if each in buf_dict: buf_dict[each]+=1 else: buf_dict[each]=1 for each in b.split(): if each in buf_dict: buf_dict[each]+=1 else: buf_dict[each]=1 prin...
def function1(number): ans = "" while number: number -= 1 unitsdigit = number%26 ans = chr(ord('A')+unitsdigit)+ans number=number//26 return ans print(function1(701))
def function1(string,k): #print(len(string)) for each in range(0,len(string),2): #print(each) print(string[each-1]) function1('pradeep',2)
def test(x): print(x) if x%3==0:return test(x/3) if x%2==1:return x return test(2*x+1) test(100)
def function1(array): min_element = min(array) return sum([x-min_element for x in array]) print(function1([1,1,3]))
''' def func1(string1,string2): if len(string1)!=len(string2):return False elif sorted(string1)==sorted(string2):return True return False print(func1('god','dog')) ''' def func2(string1,string2): array = [0]*128 if len(string1)!=len(string2):return False for each in string1: array[ord(e...
def permutations(items): if len(items) == 0: yield [] else: pi = items[:] for i in range(len(pi)): pi[0], pi[i] = pi[i], pi[0] for p in permutations(pi[1:]): yield [pi[0]] + p a = [1, 3, 4, 2, 23] for i in permutations(a): print(i)
def _range(start: int, end=None, step=1) -> iter: if end is None: end = start start = 0 if step < 0: while end < start: yield start start += step elif step > 0: while start < end: yield start start += step print([i for i in...
""" In this chapter, you will learn about condition statement conditionStatement = " if ", " elif ", "else" """ statement1 = True statement2 = False if statement1 is True: # do something pass elif statement2 is True: # do something pass else: # do something pass # usage of if else statement ...
def get_base_counts(dna): counts = {'A': 0, 'T': 0, 'G': 0, 'C': 0} for base in dna: counts[base] += 1 return counts def get_base_frequencies_v1(dna): counts = get_base_counts(dna) return {base: count*1.0/len(dna) for base, count in counts.items()} def get_base_frequencies_v2(dna...
""" author: Aslesha """ import numpy as np from numpy.random import uniform def f(r): """ Return 1 if the squared norm of r is less than or equal to 1 and 0 otherwise. """ # generalize the check x^2+y^2 <= 1 to n dim squared_norm = np.dot(r, r) if squared_norm <= 1: ...
from math import sqrt,exp from numpy import empty from random import random,randrange,seed import matplotlib.pyplot as plt from matplotlib import rc font = {'family': 'DejaVu Sans', 'size': 14} # adjust fonts rc('font', **font) seed(10) N = 25 R = 0.02 Tmax = 10.0 Tmin = 1e-3 tau = 1e5 # Function ...
import numpy as np def distance(xi, yi, xj, yj): """ Return the distance between i and j particles """ return np.sqrt((xj - xi)**2 + (yj - yi)**2) # acceleration found in part (a) def acceleration(xi, yi, xj, yj): """ Return the aceleration in r direction. To get the x-com...
# Author: Utkarsh Mali # Adapted from Prof Nicolas import numpy as np import matplotlib.pyplot as plt import random as random # Combine function in to defenition. print('[STATUS] Initializing...') random.seed(10) def Markov_Simluation(temp): # Initialize constants steps = int(1e5) N = 20 J = 1.0 ...
""" Given an array of integers. Find the Inversion Count in the array. Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then the inversion count is 0. If an array is sorted in the reverse order then the inversion count is the maximum...
def singleoccur(arr): d={} for i in range(len(arr)): if arr[i] in d: d[arr[i]]+=1 else: d[arr[i]]=1 return d if __name__=='__main__': arr=[3,4,4,5,5] m=singleoccur(arr) for i in m: if m[i]!=2: print(i)
class Node: def __init__(self,data): self.data=data self.right=None self.left=None def height(root): if root is None: return 0 lh=height(root.left) rh=height(root.right) if lh>rh: return lh+1 else: return rh+1 def PrintGivenlevel(root...
""" First make the inorder traversal of the tree and add it in array and then make a DLL and then add the data at the end of DLL. """ class LinkedListNode: def __init__(self,data): self.data=data self.prev=None self.next=None class LinkedList: def __init__(self): s...
class Node: def __init__(self,data): self.data=data self.left=None self.right=None def insert(root,data): if root is None: return Node(data) if root.data==data: return if root.data<data: root.right=insert(root.right,data) if root.data>data:...
def ispowerof2(n): if n&(n-1)==0: print("Yes") else: print("No") if __name__ == '__main__': ispowerof2(16) ispowerof2(20)
def createStack(): s=[] return s def isEmpty(s): return len(s)==0 def push(s,x): s.append(x) return s def pop(s): if isEmpty(s): print("No element") else: return s.pop() def isgreater(arr): s=createStack() next=0 element=0 push(s,arr[0]) ...
""" This is a Program for reversing a array or string """ def reverse(A,start,end): while(start<end): temp=A[start] A[start]=A[end] A[end]=temp start=start+1 end=end-1 A=[] size=int(input()) for i in range(size+1): A.append(input()) print(A) reverse(A,0,size) print(A)
""" In this we need to find a cycle and if cycle exists it means that job is not possible and vice versa. """ from collections import defaultdict class Graph: def __init__(self,vertices): self.vertices=vertices self.graph=defaultdict(list) def addEdge(self,u,v): self.graph[u].ap...
""" Arithmetic Number Easy Accuracy: 19.06% Submissions: 4803 Points: 2 Given three integers 'A' denoting the first term of an arithmetic sequence , 'C' denoting the common difference of an arithmetic sequence and an integer 'B'. you need to tell whether 'B' exists in the arithmetic sequence or not. Example 1: ...
""" Given a sequence of N (1 ≤ N ≤ 34) numbers S1, ..., SN (-20,000,000 ≤ Si ≤ 20,000,000), determine how many subsets of S (including the empty one) have a sum between A and B (-500,000,000 ≤ A ≤ B ≤ 500,000,000), inclusive. Input=We are given an array and we are given a range we have to count the number of subset...
""" 344. Reverse String Easy 1938 744 Add to List Share Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Input: ["h","e","l","l","o"] Out...
def heapify(arr,n,i): largest=i l=2*i+1 r=2*i+2 if l<n and arr[largest]<arr[l]: largest=l if r<n and arr[largest]<arr[r]: largest=r if largest!=i: arr[i],arr[largest]=arr[largest],arr[i], heapify(arr,n,largest) def heapsort(arr,n): start=n//2-1...
def redundant(exp): stack=[] for i in range(len(exp)): print(stack) if exp[i]=='(' or exp[i]=='+' or exp[i]=='-' or exp[i]=='*'or exp[i]=='/': stack.append(exp[i]) elif exp[i]== ')': if stack.pop()=='(': return True stack.pop()...
class Node: def __init__(self,data): self.data=data self.left=None self.right=None def height(root): if root==None: return -1 else: lh=height(root.left) rh=height(root.right) if lh>rh: return lh+1 else: ret...
def dictionarycon(word): dictionary = {"mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "love", "ice", "cream"} return word in dictionary def wordbb(s): wordbbutil(s,len(s),"") def wordbbutil(s,n,result): for i in range(1,n+1): prefix=s[...
""" Program to print the leaf nodes of the tree. We will have the root and then we will check that the root is not non we will go to it's left then we will check that at present node the node.left and node.right is None.If None then we will print the data """ class Node: def __init__(self,data): sel...
class TreeNode: def __init__(self,data): self.data=data self.left=None self.right=None def inorder(self,root): if root is None: return self.inorder(root.left) print(root.data,end=" ") self.inorder(root.right) if __name__ == '__main...
class Node: def __init__(self,data): self.data=data self.left=None self.right=None def insert(root,data): if root is None: return Node(data) if root.data<data: root.right=insert(root.right,data) if root.data>data: root.left=insert(root.left,data...
class Graph: def __init__(self,vertices): self.vertices=vertices self.adj_list={} for node in self.vertices: self.adj_list[node]=[] def addedge(self,source,destination): self.adj_list[source].append(destination) self.adj_list[destination].append(sour...
class Node: def __init__(self,data): self.data=data self.left=None self.right=None def inorder(root,arr): if root: inorder(root.left,arr) arr.append(root.data) inorder(root.right,arr) def buildTreeutil(arr,start,end): if start>end: return N...
""" Kth element in Matrix Medium Accuracy: 47.64% Submissions: 9554 Points: 4 Given a N x N matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest element in the matrix. Example 1: Input: N = 4 mat[][] = {{16, 28, 60, 64}, {22, 41, 63, 91}, ...
from queue import Queue def PrintQueue(queue): while(not queue.empty()): print(queue.queue[0],end=" ") queue.get() def reverseaQueue(q): stack=[] while(not q.empty()): stack.append(q.queue[0]) q.get() while(len(stack)!=0): q.put(stack[-1]) st...
class Graph: def __init__(self,vertices): self.vertices=vertices self.graph=[[] for i in range(vertices)] def addEdge(self,u,v,w): self.graph[u].append([v,w]) self.graph[v].append([u,w]) def pathmorethank(self,source,k): path=[False]*(self.vertices) p...
# 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, # количества слов в каждой строке. word_number = [] with open("text.txt") as f_obj: count = sum(1 for _ in f_obj) # Считаем кол-во строк f_obj.seek(0, 0) for str_number i...
def fibonacci(n): if n<2: return n prev,curr = 0,1 for i in range(n-1): prev, curr = curr, (curr+prev)%10 return curr def sum_squares_period60(): square_digits = [0] * 10 for i in range(10): square_digits[i] = (i * i) % 10 square_digits = dict(zip(list(ra...
from functools import reduce def main(): numberlist = [] output = '' for x in range(0, 1000): if x % 3 == 0 or x % 5 == 0: numberlist.append(x) output = reduce(lambda x, y: x + y, numberlist) print(output) if __name__== "__main__": main()
# .-"-. # /|6 6|\ # {/(_0_)\} # _/ ^ \_ # (/ /^\ \)-' # ""' '"" 하늘 # written by # @author Wolverine 왕경민 # File Name : Chanukah Challenge.py # Date Created : 28/1/2020 import math N = int(input()) for i in range (N): case, days = map(int, input().split()) total = days if (days % 2 == 0): ...
satnica = input('zarada po satu: ') satnica = int(satnica) A = input('broj dana rada Ante: ') A = int(A) J = input('broj dana rada Jurica: ') J = int(J) M = input('broj dana rada Miro: ') M = int(M) res=A*satnica*8+J*satnica*4+M*satnica*10 print(int(res))
ime = input('Unesite ime: ') prezime = input('Unesite prezime: ') datum_rodjenja = input ('Unesite datum rodjenja: ') print('Bok '+ime+'!') print('Drago mi je što smo se upoznali!') print('I ja sam rođen' +datum_rodjenja)
a = int(input("Cantidad de numeros a evaluar: ")) datos = [] numeros = [] for i in range (0,a): x = int(input("Ingrese numero: ")) datos.append(x) datos.append(0) for i in range (0,a-1): if datos[i+1] > datos[i]: y = datos[i+1] numeros.append(y) elif datos[i+1] < datos[i]: z ...
# import csv # import time # from random import * # # with open("추천도서리스트.csv") as file: # reader = csv.reader(file) # booklist = list(reader) # # def recomment_book(): # print("3초 뒤 책을 추천해드립니다.\n") # time.sleep(1) # print("당신에게 추천해드릴 도서는") # time.sleep(1) # print("바로") # time.sleep(1) # ...
import csv class Student: math = [] eng = [] kor = [] count = 0 def __init__(self, name, num, dept, math, eng, kor): self.name = name self.num = num self.dept = dept self.math = math self.eng = eng self.kor = kor Student.math.append(math) ...
#01 a = [0,1,2,3,4] print(a[:3], a[:-3]) #02 a = [0,1,2,3,4] print(a[::-1]) #03 first = ["egg", "salad", "bread", "soup", "canafe"] second = ["fish", "lamb", "pork", "beef", "chicken"] third = ["apple", "banana", "orange", "grape", "mango"] order = [first, second, third] john = [order[0][:-2], second[1::3], third[0]...
n = int ( input() ) for i in range (1, n+1): for j in range (n-i): print(" ", end="") for h in range(i): print("*", end="") print()
name = "이정윤" student_ID = 2018112197 department = "건설환경공학과" print("*"*50) print("2020년 2학기 파이썬프로그래밍 기말고사 답안지") print("*"*50,"\n") print("*"*30) print("{:<7}: {:<6}".format("이름",name)) print("{:<7}: {:<6}".format("학번(ID)",student_ID)) print("{:<7}: {:<6}".format("학과",department)) print("*"*30) #2 tu = (1, 2, 5,...
instruction = int(input()) queue = [] ins = {} for i in range(instruction): ins[i] = input().split(' ') for i in range(instruction): if ins[i][0] == 'push': queue.append(int(ins[i][1])) elif ins[i][0] == 'pop': if len(queue) != 0: print(queue.pop(0)) else: print(-1) ...
print('Задача 3. Число наоборот 2') # Пользователь вводит два числа — N и K. # Напишите программу, # которая заменяет каждое число на число, # которое получается из исходного записью его цифр в обратном порядке, # затем складывает их, # снова переворачивает и выводит ответ на экран. # Пример: # Введите первое числ...
""" Tic Tac Toe Player """ import copy import math X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who ha...
#It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice # a square. #9 = 7 + 2×1^2 #15 = 7 + 2×2^2 #21 = 3 + 2×3^2 #25 = 7 + 2×3^2 #27 = 19 + 2×2^2 #33 = 31 + 2×1^2 #It turns out that the conjecture was false. #What is the smallest odd composite that cann...
#The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. #Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. #(Please note that the palindromic number, in either base, may not include leading zeros.) def isStringPal(input): for it in range(len(i...
""" File: subtract_numbers.py ------------------------- This program gets two real-values from the user and prints the first number minus the second number. """ def main(): """ Since Part 1-A asks us to use real numbers (float), assuming the user always inputs a decimal point number we can wrap input() in...
from random import randrange import time import sys from os import system, name from time import sleep def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux else: _ = system('clear') class color: PURPLE = '\033[95m' CYAN = '\033...
""" CREATED BY: Benjamin Hamlin Chapter 4 Question 5 "Validate BST" PROMPT: Implement a function to check if a binary tree is a BST DATE: 12/12/2019 """ import unittest from ch4.btree import BTNode, BinaryTree def __p5(node: BTNode): if node.left is not None: if node.left.data < node.data: ...
""" CREATED BY: Benjamin Hamlin Chapter 1 Question 2 "Check Permutation" PROMPT: Given two stings, write a method to decide if one is a permutation of the other DATE: 11/14/2019 """ import unittest # O(N) where N is the length of str1 # O(1) when strings are not the same length def p2(str1, str2): if len(s...
""" CREATED BY: Benjamin Hamlin Chapter 1 Question 8 "Zero Matrix" PROMPT: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. DATE: 11/18/2019 """ import unittest import numpy # O(N*M) def p8(arr): zeros = [] rows = len(arr) cols = len(arr[0]) ...
""" CREATED BY: Benjamin Hamlin Chapter 1 Question 4 "Palindrom Permutation" PROMPT: Given a string, write a function to check if it is a permutation of a palindrome. a palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not nee...
""" CREATED BY: Benjamin Hamlin Chapter 4 Question 2 "Minimal Tree" PROMPT: Given a sorted ascending array with unique integer elements, write an algorithm to create a binary search tree with minimal height DATE: 12/11/2019 """ import unittest from ch4.btree import BTNode, BinaryTree import sys sys.setrecursio...
# -*- coding: utf-8 -*- class Fib(object): def __init__(self): self.a, self.b = 0, 1 # 初始化两个计数器a, b def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 def __next__(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 100000: # 退出循环的条件 raise StopIteration() return self.a # 返回下一个值 ...
def tail(sequence, n): """Returns the last n items of a given sequence.""" if n <= 0: return [] return list(sequence[-n:])
from pessoa import Pessoa, contar_numero_beneficiados as contar, beneficiarios_por_valor, valor_total_beneficio, beneficiarios_por_tempo from datetime import date lista_pessoa = [] fim = False while not fim: pessoa = Pessoa() print('Bem Vindo') pessoa.nome = input('Informe seu nome completo') pessoa.da...
str=input("Enter a String:") str2=str[::-1] print(str2) if(str==str2): print("palindrome") else: print("not palindrome") #second method mid=len(str)//2 s=l=0 flag=False for i in range(mid+1): if(str[s]==str[l]): l-=1 s+=1 else: flag=True break if(flag!=True): print("n...
n=int(input("Enter the number of element:")) lis=[] for i in range(n): val=int(input("Enter value:")) lis.append(val) print(lis) #first method total=0 for i in lis: total+=i print(total) #Second method usinng built in function sum print(sum(lis))
# # A simple script to download images within a chosen radius of a target # from urllib.request import urlopen import json #API details observer_id = 1 api_key = "xyz" #Target name target = "M82" #Search radius (degs) radius=0.2 #SIMBAD URL to get decimal coordinates from target name simbadURL = ...
class LiveDataFeed(object): """ A simple "live data feed" abstraction that allows a reader to read the most recent data and find out whether it was updated since the last read. Interface to data writer: add_data(data): Add new data to the feed...
# Parallelizing CPU-bound code with threading and multiprocessing. # # Tested with Python 2.7 and 3.4 # # Eli Bendersky [http://eli.thegreenplace.net] # This code is in the public domain. from __future__ import print_function import math import multiprocessing import random import threading import time class Timer(ob...
# Simple client used to interact with concurrent servers. # # Launches N concurrent client connections, each executing a pre-set sequence of # sends to the server, and logs what was received back. # # Tested with Python 3.6 # # Eli Bendersky [http://eli.thegreenplace.net] # This code is in the public domain. import arg...
from collections import defaultdict from math import sqrt class GridMap(object): """ Represents a rectangular grid map. The map consists of nrows X ncols coordinates (squares). Some of the squares can be blocked (by obstacles). """ def __init__(self, nrows, ncols): """ Create a new...
# Face Eye Detection Example # # This script uses the built-in frontalface detector to find a face and then # the eyes within the face. If you want to determine the eye gaze please see the # iris_detection script for an example on how to do that. import sensor import time import image # Reset sensor sensor.reset() #...