text
stringlengths
37
1.41M
#####函数作用域: ''' L local局部作用域,本地作用域 E enclosing嵌套作用域 G global全局作用域 B built-in内建作用域 for,if,while这些流程控制不会形成自己的作用域 ''' #####得到所有模块的方法,内建作用域 # import sys # print(dir(sys)) #####全局变量 # 全局变量name name = 'while' def outer(): # name = 'for'#嵌套作用域 def inner(): #本地作用域 # name = 'django' age = 18 ...
""" Each ListNode holds a reference to its previous node as well as its next node in the List. """ class ListNode: def __init__(self, value, prev=None, next=None): self.prev = prev self.value = value self.next = next """ Our doubly-linked list class. It holds references to the list's he...
import sys import re if len(sys.argv) is not 2: print "Invalid number of arguments. Usage: 'python part3_worldcup1.py worldcup.txt'" file = open(sys.argv[1], 'r') current_line = "" for line in file: junk_match = re.match(r"^\|-|!|\|\d*\|\||\|\}", line) country_match = re.match(r"^.*\{\{fb\|([A-Z]*).*$", line)...
#!/usr/bin/python print("Welcome to word counter!") fileInput = input("Enter a file name: ") numWords = 0 with open(fileInput,"r") as doc: for words in doc: wordList = words.split() numWords += len(wordList) print("Number of words: %i" % numWords)
#!/usr/bin/env python3 def merge(l1, l2): i = j = 0 l = [] while i < len(l1) and j < len(l2): if l1[i] <= l2[j]: l.append(l1[i]) i += 1 else: l.append(l2[j]) j += 1 l.extend(l1[i:]) l.extend(l2[j:]) return l if __name__ == '__main...
""" CAP4640/5605 Project 1 - Python Basics Author: Paul Firaza Version: 1/15/2018 Email: n01388082@ospreys.unf.edu """ import csv class State: """ State class contains: - __init__ creates a State object with 6 different datas( State Name, City,Abrv,Population,Region and House Seats ) - ...
# import libraries import urllib2 from bs4 import BeautifulSoup # specify the url quote_page = 'https://projects.fivethirtyeight.com/soccer-predictions/mls/' req = urllib2.Request(quote_page) response = urllib2.urlopen(req) # query the website and return the html to the variable page page = response pr...
# a < b < c # a**2 + b**2 = c**2 # a + b + c = 1000. # a*b*c = ? import traceback for a in range(3,1000): for b in range(a+1, 999-a): c = 1000 - a - b traceback.print_exc() if c**2 == a**2 + b**2: print(a,b,c) print(a*b*c)
import urllib2 ## There's also urllib. response = urllib2.urlopen ('http://api.wunderground.com/api/063bc5d3a98d95bf/conditions/q/DC/Washington.json') ## Note the very end of the URL. It's a query about weather in DC. ## I created a weather underground account and got a key. Did I need it to do the above? import json f...
class Stack: def __init__(self): self.stack=[] def pop(self): return self.stack.pop() def push(self,item): self.stack.append(item) def peek(self): return self.stack[-1] def isEmpty(self): return len(self.stack)==0 def size(self): return len(self.st...
def insertionSort(aList): for i in range(1,len(aList)): currentvalue=aList[i] position=i while currentvalue<aList[position-1] and position>0: aList[position]=aList[position-1] position-=1 aList[position]=currentvalue return aList alist = [54,26,93,17,77,3...
# Assignment Number...: 1 # Student Name........: 오승환 # File Name...........: hw1_오승환 # Program Description.: 기본적인 자료형과 input 함수를 활용하는 법을 익히는 과제입니다. season = input("What is your favorite season? ") #input 함수를 사용하여 값을 입력받아 변수에 할당한다. print(season) ...
# Computes approximate solutions to differential equations of the form dy/dx = f(y) using Euler's method # (also known as autonomous or time-invariant systems) import matplotlib.pyplot as plt import numpy as np def calculate_next_point(last_point, delta, derivative_function): '''Calculates the next point given th...
import datetime import time start_time = time.time() # options date res = [] def next_weekday(d, weekday): days_ahead = weekday - d.weekday() if days_ahead <= 0: # Target day already happened this week days_ahead += 7 return d + datetime.timedelta(days_ahead) for i in range(0,28,7): x = next_w...
__author__ = 'elpython3' import pygame # The module to make games. import sys # To close the game without error output. from pygame.font import SysFont # Initialize Pygame pygame.init() # This game is open-sourced. If you wish to mod this and make it public, please reference me. # If you are using this file and w...
from flask import Flask,render_template,session,url_for,request,redirect from datetime import timedelta ''' tutorial on sessions''' app = Flask(__name__) app.permanent_session_lifetime = timedelta(minutes=5) app.secret_key = "jana" @app.route('/home') def home(): return render_template('child.html') @app.route('/...
#数字列から■で構成された文字に変換する def numprint(numlist): numchars =[ """ ■■■■■■■■ ■ ■ ■ ■ ■ ■ ■■■■■■■■ """, """ ■ ■ ■ ■ ■ """, """ ■■■■■■■■ ■ ■■■■■■■■ ■ ■■■■■■■■ """, """ ■■■■■■■■ ■ ■■■■■■■■ ■ ■■■■■■■■ """, """ ■ ■...
# # Global Centering # # Global Centering: Calculating and subtracting the mean pixel value across color channels. # Local Centering: Calculating and subtracting the mean pixel value per color channel. from PIL import Image from numpy.core._asarray import asarray image = Image.open('sydney_bridge.jpeg') pixels = asa...
def man(): d_1 = "\n Enter 1 - to see list of all workers\n" d_2 = "Enter 2 - to see 'to-do list'\n" d_3 = "Enter 3 - list of instructions to employees\n" d_4 = "Enter 4 - show a list of all coverage for specific areas\n" d_5 = "Enter 5 - show the amount for real estate, for sale, for rent\n" ...
def quick_sort(arr): n=len(arr) if n<=1: return arr else: pivot = arr.pop(0) # creating 2 empty lists to segregate greater than pivot elements and less than pivot elements lesser_than_pivot = [] greater_than_pivot = [] for item in arr: if item<pivot: lesser_than_pivot.append(item) ...
import abc from typing import Dict from .const import SecurityType from .date import Date, RDate from . import cashflow as cf class Index: """ This represents price of equity and FX or value of rates To be differentiated with asset, which is traded on the market and thus holds market value directly. ...
class Machine: ingredient = ["water", "milk", "coffee beans", "disposable cups", "money"] metrics = ["ml", "ml", "grams ", "pieces"] in_machine_info = [400, 540, 120, 9, 550] menu_names = ['espresso', 'latte', 'cappuccino'] menu = [[250, 0, 16, 1, -4], [350, 75, 20, 1, -7], [200, 100, 12, 1, -6]] ...
# Convolutional Neural Network # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # pip install tensorflow # Installing Keras # pip install --upgrade keras # Have distinct data structure for training and test set # Part 1 - Building the CNN # Impor...
'''Python Mad Libs''' print "Mad Libs Start!" name = raw_input("Please input your name: ") print "We need 3 adjectives for the game." adj1 = raw_input("Please input the 1st adjective: ") adj2 = raw_input("Please input the 2nd adjective: ") adj3 = raw_input("Please input the 3rd adjective: ") print "We need 3 verbs...
Question 1 Which Python keyword indicates the start of a function definition? help rad break def Answer: def Question 2 In Python, how do you indicate the end of the block of code that makes up the function? You put a # character at the end of the last line of the function You de-indent a line of code to the same ind...
# class Solution: # def __init__(self): # self.dp = {} # def tribonacci(self, n): # if n == 0: # return 0 # if n == 1 or n == 2: # return 1 # try: # return self.dp[n] # except: # self.dp[n] = self.tribonacci(n-1) + ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # 方法更快 class Solution(object): # 类函数 def binaryTreePaths(self, root): """ :type root: TreeNode ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode "...
class Solution(object): def reformatDate(self, date): """ :type date: str :rtype: str """ day, mon, year = date.split(" ") month_map = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", ...
class Solution(object): # 回溯算法 和46题思路一样 # 不同地方是消除重复 写下两个例子就能明白了 def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # 先排序 nums.sort() n = len(nums) res = [] def helper(li, tmp_li, cnt): if cn...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def nextLargerNodes(self, head): """ :type head: ListNode :rtype: List[int] """ # 栈中存放未找到更大值的...
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. """ f = {} def find(p): # 如果p不在dict里 那么p的value设置为p f.setdefault(p, p) if f[p] != p:...
class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if nums == []: return [-1,-1] # 第一次二分查找需要找到最左边的target left = 0 right = len(nums)-1 ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtyp...
# class Solution(object): # def searchMatrix(self, matrix, target): # """ # :type matrix: List[List[int]] # :type target: int # :rtype: bool # """ # if len(matrix) == 0 or len(matrix[0]) == 0: # return False # 考虑左下角或者右上角的两个点 # 左下角 # ...
""" # Definition for a Node. class Node(object): def __init__(self, val=None, children=None): self.val = val self.children = children """ # 递归1 class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def findDuplicateSubtrees(self, root): """ :type root: TreeNode :rty...
from random import choice class RandomizedSet(): def __init__(self): """ Initialize your data structure here. """ self.dic = {} self.li = [] def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain th...
class Solution(object): # 自己解法超时 def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ if len(A) < 3: return False for i in range(1, len(A)-1): if all(A[m] > A[m-1] for m in range(1, i+1)) and all(A[n] > A[n+1] for n in r...
class Solution(object): # 参考网上答案 单调栈 def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ stack = [] cnt = collections.Counter(s) for char in s: if char not in stack: while stack and stack[-1] > char and cnt[s...
class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ i = 0 n = len(A) while i < n: if A[i] % 2 == 0: i += 1 else: temp = A.pop(i) A.append(t...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # dict储存节点和节点个数 class Solution(object): def pseudoPalindromicPaths (self, root): """ :type root: Tre...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): # 东哥解法 def isValidBST(self, root): """ :type root: TreeNode :rty...
# cspmodel.py # Author: Sébastien Combéfis # Version: April 12, 2020 from abc import ABC, abstractmethod class Variable: '''Class representing a named variable with its associated domain.''' def __init__(self, name, domain): self.name = name self.domain = domain self.value...
import functools import time def timer(func): """Print the runtime of the decoreted function Arguments: func {[object]} -- The function to be decorated """ @functools.wraps(func) def wrapper_timer(*arg, **kwargs): start_time = time.perf_counter() print(f"Function {func.__n...
#TUNG, DONIA #SoftDev2 pd7 #K15 -- Do You Even List? #2018-04-25 UC_LETTERS = "ABCDEFGHIJKLNOPQRSTUVWXYZ" NUMS = "1234567890" NONALPHNUM = ".?!&#,;:-_*" def threshold(password): return checkNumbers(password) & checkLetters(password) def checkNumbers(password): word = [1 if x in NUMS else 0 for x in password]...
def fun(): str1 = input("Enter string 1: ") str2 = input("Enter string 2: ") s1 = len(str1) s2 = len(str2) if s1>s2: print(str1) elif s2>s1: print(str2) elif s1==s2: print(str1) print(str2) fun()
counter = 1 while counter <= 5: number = int(input("Guess the " + str(counter) + ". number ")) if number != 5: print("Try again.") counter = counter +1 elif number ==5: print("Good guess!") break counter = counter +1 else: print ("Sorry but that was not very succe...
def unique(list1): list_set = set(list1) unique_list = (list(list_set)) for x in unique_list: print(x) list1 = [10, 20, 10, 30, 40, 40] print("the unique values from 1st list is") unique(list1)
def showNumber(limit): for i in range(0,limit+1): if i%2 == 0: x = print(i,'EVEN') else: x = print(i,'ODD') return x showNumber(5)
print 'Welcome to a crease/section of folded paper calculator!' print 'Input the number of creases before the number of folds that you want to find out.' print 'However, it does round down to the nearest non-float.' preCrease = float(raw_input('> ')) nowCrease = int(preCrease * 2 + 1) nowSect = int(nowCrease + 1) print...
#!usr/bin/env python def my_range(stop): i = 0 lista = [] while i < stop: lista.append(i) i += 1 return lista def my_range2(stop, start = 0, krok = 1): i = 0 lista = [] while i < stop: lista.append(i) i += krok return lista def my_range3(*arg): ...
def trianglemath(num): return num ** num num = int(input("Please input a number: ")) print(trianglemath(num))
def romanToInt(s): mapping = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, } min_ = None total = 0 for c in s: val = mapping[c] print(min_, "Min at start") if min_ and val > min_: print(...
def filter_list(l): nlist = [] for filter in l: #print(filter) if isinstance(filter, int) == True: if filter > 0: nlist.append(filter) return nlist l = [1, 'a', 'b', 0, 15] print(filter_list(l))
# abre um novo arquivo file = open("compras.txt", "w") # adiciona itens ao arquivo file.write('Agua\n') file.write('Arroz\n') file.write('Detergente\n') # fecha arquivo file.close() # abre arquivo novamente file = open("compras.txt", "r") # ler arquivo print(file.read()) # ler primeira linha print(file.readline())...
# lacos de repeticao # while contador = 0 # while contador != 100: # nome = input('Digite um nome: ') # contador = contador + 1 # while com else while contador < 3: print("Dentro do loop") contador = contador + 1 else: print('Dentro do else') # for capitais = ['Recife','Maceio','Salvador','Ara...
#!/usr/bin/env python def std(): std_dict = {('Valid', 'Unknown'): 0, ('Valid', 'Invalid'): 0, ('Unknown', 'Valid'): 0, ('Unknown', 'Invalid'): 0, ('Invalid', 'Valid'): 0, ('Invalid', 'Unknown'): 0} with open('result.txt', 'r') as rfile: lines = rfile.readlines() for line in lines: content = line.str...
from MyTwoThreeNode import MyTwoThreeNode class MyTwoThreeTree: def __init__(self): self.root = None def insert(self, new_data): if self.root is None: self.root = MyTwoThreeNode(new_data) else: current_node = self.root found_empty_spot = False ...
from MyTreeNode import MyTreeNode class MyAVLTree: def __init__(self): self.root = None def print_tree(self): pre_order_print(self.root) def insert(self, new_data): self.root = self.insert_and_fix_tree(self.root, new_data) def insert_and_fix_tree(self, node, new_data): ...
##Author: Michael Shiferaw ##Date: 8/5/2017 - 8/5/2017 ##Program Description: Maximize Profits for Raw Material Provider ##Key Components: List competitive pricing. Allow users to update price/amount. Be user friendly. Return results quickly. import company def main(): company_dictionary = read_and_stor...
# FUNCIONES DE MANIPULACION DE CADENA 1: msg="EL FIN DEL MUNDO SE ACERCA" # Mostrar el nro de ocurrencias de la palabra FIN print("FIN",msg.count("FIN")) print("A ->", msg.count("A")) # FUNCIONES DE MANIPULACION DE CADENA 2: cadena1="LOS VENGADORES FIN DE LA GUERRA" # Transformar el texto en minusculas mensaje=caden...
#MANIPULACION DE TEXTOS # 10 # 01234567890123456789 cadena="HOY TE IRÁ MUY BIEN" #manipulador de texto nro 1 print(cadena[5],cadena[6],cadena[12]) #me imprime los caracteres "E I" que ocupa los indice 5 6 12 #manipulador de texto nro 2 print(cadena[2],cadena[9]) #me imprime los caractere...
""" // Time Complexity : o(m*n) // Space Complexity : o(m*n) // Did this code successfully run on Leetcode : not on leetcode // Any problem you faced while coding this : no """ class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 r = len(matri...
a = {'john', 'josh', 'joe', 'james'} b = {'joe', 'george', 'james', 'jack'} print(a.intersection(b))
# this program will rename photos to the following file-name format # example: IMG_2015015_233016.jpg import os import pyexiv2 import datetime i = 0 # remove spaces from file names old_list = os.listdir(os.getcwd()) for old_name in old_list: file_name = old_name.replace(' ', '_') file_name = old_name....
# Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) count=0 num=0 total=0 for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue count=count+1 num = float(line[21:]) total=num+total avg=total/count print("Average...
import pickle import string from collections import Counter from .utils import parse_into_words class WordFrequency: def __init__(self): self._dictionary = Counter() self._total_words = 0 self._unique_words = 0 self._letters = set() self._longest_word_length = 0 s...
class Bike(object): """docstring for Bike.""" def __init__(self, price, max_speed, miles = 0): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print self.price, self.max_speed, self.miles def ride(self): print "Riding" self.miles += 10 return self def revers...
print("") print("This prints out a list of all the divisors of the number you input.") print("") print("Enter a number:") num = int(input("--> ")) list_of_num = [] list_range = list(range(1,num+1)) for elem in list_range: if num % elem == 0: list_of_num.append(elem) print(list_of_num)
import unittest import os import testLib class TestNilUser(testLib.RestTestCase): """Test adding user with empty Username""" def assertResponse(self, respData, errCode = testLib.RestTestCase.ERR_BAD_USERNAME): """ Check that the response data dictionary matches the expected values """ ...
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) arr.sort(reverse=True) max_num = arr[0] runner = 0 for num in arr: if num != max_num: runner = num break print(runner)
# This file assumes a reference input for z (named x in the lectures) variable # and plots the z reference and z, as well as, the theta value over time. # It should not need to be changed by the students import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np plt.ion() # enable inte...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'lyl' # 使用元类 # 可以使用type()函数创建新的类型 def fn(self, name = 'world'): print('Hello, %s' % name) Hello = type('Hello', (object, ), dict(hello = fn)) # 创建Hello class h = Hello() print('Hello类型是:', type(Hello)) print('类的实例对象类型是:', type(h))
# Gets the Conversation (based on the is reply to Key of the libraries timeline) of each tweet and returns the conversation as a LoD with following keys: # # u'hours_to_answer', u'is_follower', u'follower_local', u'original_is_question', u'original_screen_name', # u'original_status_id', u'original_text', u'original_...
# # Creating the Twitter CSV files # # Write new csv files with all the libraries with Twitter handles # # - 1 file for the National libraries (3 libraries) # - 1 file for university libraries (27 libraries) # - 1 file for public libraries (21 libraries) import csv import json #import & export CSV def impCSV(inp...
import time class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ x_str = str(abs(x)) #先取絕對值 reversed_x = x_str[::-1] if x >= 0: ans_int = int(reversed_x) else: ...
import sqlite3 conn = sqlite3.connect('Database.db') c = conn.cursor() def createTables(c): c.execute('''CREATE TABLE USERS ([uid] INTEGER PRIMARY KEY, [username] VARCHAR(30) NOT NULL UNIQUE, [password] VARBINARY(100) NOT NULL, [role] VARCHAR(20)) ''') conn.commit() def populateTabl...
hungry = input("Are you hungry?") if hungry == "yes": print("Eat pasta.") else: print("Go to your work")
# You are given a string.Your task is to print only the consonants present in the string without affecting the sentence spacings if present. If no consonants are present print -1 # Input Description: # You are given a string ‘s’. # Output Description: # Print only consonants. # Sample Input : # I am shrey # Sam...
### Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. n=input() print(n) print(len(n)) b="ing" j=len(n)-1 print(j) if(n.endswith(...
##real armstrong no n1=int(input()) sum=0 temp=n1 while(temp>0): digit=temp%10 sum+=digit**3 temp//=10 if(sum==n1): print("armstrong") else: print("not armstrong")
###Write a Python program to swap comma and dot in a string. Go to the editor ###Sample string: "32.054,23" ###Expected Output: "32,054.23" S = input() k = "" for i in S: if i == ",": k = k + "." continue if i == ".": k = k + "," continue else: k = k + i print(k)
### Write a Python program to count repeated characters in a string. Go to the editor ##Sample string: 'thequickbrownfoxjumpsoverthelazydog' ##Expected output : ##o 4 ##e 3 ##u 2 ##h 2 ###r 2 ##t 2### s=(input()) print(s) dic={} for i in s: if(not dic.get(i)): dic[i]=1 else: dic[i]+=1 print(dic...
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> ##decimal to binary >>> import math num=int(input()) print(num%2) rem="" while num>=1: rem+=str(num%2) num=math.floor(num/2) binary=""...
##Write a Python program to find the first non-repeating character in given string. ##input:ammartamizh ##output:['a', 'm', 'm', 'a', 'r', 't', 'a', 'm', 'i', 'z', 'h'] ##{'a': 3, 'm': 3, 'r': 1, 't': 1, 'i': 1, 'z': 1, 'h': 1} ##r s=list(input()) print(s) dic={} for i in s: if(not dic.get(i)): dic[i]=1 ...
class FileParser(object): """This class reads the file input and returns appropriate data to caller""" def __init__(self, path_to_file): self.path_to_file = path_to_file def read_file(self): """Read file contents and return a list""" # ipdb.set_trace(context=1) list_alloca...
""" Author: Pruthvi Suryadevara Email: pruthvi.suryadevara@tifr.res.in Code to plot Mass as a function of radius """ import numpy as np import scipy.integrate as area import matplotlib.pyplot as plt ### Using Cartesian cootdinates def fz(y,x,r): return(area.quad(lambda z:1,-np.sqrt(r**2 -x**2 -y**2),np.sqrt(r**...
str1 = str(input()) str2 = str(input()) if(str1==str2): print(-1) else: print(max(len(str1),len(str2)))
import torch import torch.functional as F from torch.autograd import Variable import numpy as np #created multiple layers for a neural network using a logistic optimizer xy = np.loadtxt('/Users/elliottchoi/Desktop/Code_Repository/data-03-diabetes.csv', delimiter=',', dtype=np.float32) x_data=Variable(torch.from_num...
from socket import * s = socket(AF_INET,SOCK_STREAM) server = input('Server u want to Connect :-') def pscan(port): try: s.connect((server,port)) return True except: return False for x in range(1,25): if pscan(x): print('Port {0} is open!!!!!!!!!!!!!!!'.format(x)) else: print('Port {0} is closed'.forma...
from graphics import * class Computer(object): def __init__(self, x, y, color, win): self.x = x self.y = y self.color = color self.drawComp(x, y, color, win) # place points and color here def drawComp(self, x, y, color, win): comp = Rectangle(Point(self.x, sel...
# http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab5.html # Упражнение №2. Задачи посложнее # ================================= # Переставьте соседние элементы в списке. Задача решается в три строки. s = "1 2" s = "1" s = "1 2 3 4 5 6 7" s = "" s = "1 2 3 4 5 6" L = s.split() last = len(L) - 1 if le...
# http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab5.html#o9 # Упражнение № 9 # =============== hours = int(input()) data = list(map(int, input().split())) k = int(input()) maximum = max([sum(data[i:i + k]) for i in range(hours - k + 1)]) print(maximum)
# http://judge.mipt.ru/mipt_cs_on_python3/labs/lab1.html#o5 # http://cs.mipt.ru/python/lessons/lab2.html#o5 # Упражнение №5: больше квадратов import turtle import turtle_helper def paint_square(turtle, side, x = 0, y = 0, angle = 0): turtle_helper.move(turtle, x, y) turtle.left(angle) for i in...
import unittest from A import find_two_equal class FindTwoEqual(unittest.TestCase): def test_find_two_equal(self): self.assertEqual(find_two_equal([8, 3, 5, 4, 5, 1]), 5) self.assertEqual(find_two_equal([5, 5, 1, 4, 2, 3]), 5) self.assertEqual(find_two_equal([1, 4, 2, 3, 5, 5]), ...
""" http://judge.mipt.ru/mipt_cs_on_python3_2015/labs/lab6.html#a Задача A ========= В массиве ровно два элемента равны. Найдите эти элементы. Программа получает на вход число N, в следующей строке заданы N элементов списка через пробел. Выведите значение совпадающих элементов. """ def find_two_equal(a...
# http://judge.mipt.ru/mipt_cs_on_python3/labs/lab1.html#o10 # http://cs.mipt.ru/python/lessons/lab2.html#o10 # Упражнение № 10: "цветок" (версия № 2) import turtle import turtle_helper def main(): wn = turtle_helper.make_window("lightgreen", "Flower") t = turtle_helper.make_turtle("red", 2) ...
#K-邻近算法,KNN,当k=1时称为最近临近算法 import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors,datasets,model_selection def load_classfication_data(): digits = datasets.load_digits() X_train = digits.data y_train = digits.target return model_selection.train_test_split(X_train,y_train,test_...
def add(no): sum=int(0) for i in str(no): sum=sum+int(i); return sum def main(): no=int(input("Enter no : ")); print("Sum is: ",add(no)) if __name__=="__main__": main();