text
stringlengths
37
1.41M
#!/usr/bin/env python __author__ = 'Ned Udomkesmalee' #Find the sum of all the primes below two million. def primes_up_to(n): #Sieve of Eratosthenes Implementation to create Prime Numbers up to n if n <= 2: return [] sieve = [True] * (n+1) for x in range(3, int(n ** 0.5) + 1, 2): for...
from PIL import Image img = Image.open('UWHat_no1.jpeg') img = img.convert("RGBA") pixels = img.getdata() newData = [] for item in pixels: if item[0] >= 200 and item[1] >= 200 and item[2] >= 200: # make it transparent by setting alpha to 1 newData.append((0, 0, 0, 0)) else: newData.app...
# Given a string, write a program to check if it is palindrome or not. A string is said to be a palindrome if the reverse of the string is the same as string. def isPalindrome(s): return s == s[::-1] s = input() ans = isPalindrome(s) if ans: print("YES") else: print("NO")
# In this assignment, you have to write a program to print a pattern of numbers. # The input should be the number of rows. # Your program should print this pattern where the first row contains only one element i.e 1. # The second row should contain two elements i.e. 1 and 2 separated by a space. # The third row should ...
# Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. s = input() count1 = 0 count2 = 0 for i in s: if(i.isupper()): count1 += 1 elif(i.islower()): count2 += 1 print(count1, count2)
num1=int(input("enter your first number:")) num2=int(input("enter your second number:")) operator=str(input("enter your operator:")) if operator=='+': print("Addition of two numbers is:") print(num1+num2) elif operator=='-': print("Subtraction of two numbers is:") print(num1-num2) elif operator=='*': ...
def ascii_sum(s): sum=0 for i in range(len(strinput)): sum = sum + ord(strinput[i]) return sum def ascii_sum_odd(s): oddsum=0 for i in range(len(strinput)): if ord(strinput[i])%2!=0: oddsum=oddsum+ ord(strinput[i]) return oddsum def ascii_sum_even(s): evensum=0 ...
# -*- coding: utf-8 -*- # @Time : 2021/1/4 09:32 # @Author : ooooo from typing import * class Solution: def fib(self, n: int) -> int: if n == 0 or n == 1: return n a, b = 0, 1 for i in range(n - 1): a, b = b, a + b return b
# -*- coding: utf-8 -*- # @Time : 2020/12/1 09:44 # @Author : ooooo from typing import * class Solution: def binary_search_right(self, target): l, r = 0, len(self.nums) - 1 while l < r: mid = l + (r - l + 1) // 2 if self.nums[mid] > target: r = mid - 1...
# -*- coding: utf-8 -*- # @Time : 2020/10/19 06:52 # @Author : ooooo from typing import * class Solution: def backspaceCompare(self, S: str, T: str) -> bool: stack1, stack2 = [], [] for x in S: if x == '#': if len(stack1) != 0: stack1.pop() ...
# -*- coding: utf-8 -*- # @Time : 2020/10/20 16:30 # @Author : ooooo # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return...
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two numbers such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ n = len(input_list) # Build a max-heap - O(n) for i in range(n, -1, -1): ...
# -*- coding: utf-8 -*- """ Created on Tue Dec 12 21:48:36 2017 @author: Dmitry Stafeev """ from random import randint k = 10 A = [randint(-10,100) for x in range(k)] print('Unsorted:',A) def merge_sort(A): if len(A) <= 1: return A middle = int(len(A)/2) left = merge_sort(A[:midd...
from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer """ 这个文件是 tf-idf 的实现, tf(term frequency), idf(inverse document frequency) 这个函数的功能就是如何将文档中的term normalize。将文档中大量重复的单词的权重降低的一种方式。 这里的代码是来自下面这个链接, 稍有改动, 适应python3和最新的sklearn版本,链接中有详细的解释: http://blog.ch...
# Global module imports import os import json import sys # Function to iterate over files in a given path # Determines if file, directory, or a child directory, and size of tile, in bytes def path_listing(path): p = {'name': (path)} if os.path.isdir(path): p['type'] = "directory" p['child'] = [...
""" example of importing modules """ def sumNumbers(theList): """sums up the numbers input: list of numbers output: the sum """ theSum = 0 n = len(theList) for i in range(n): theSum = theSum + theList[i] return(theSum) def avgNumbers(theList): n = len(theList) retu...
import tensorflow as tf from tensorflow.keras.layers.experimental.preprocessing import Rescaling def SIMPLEST_PIPELINE(): """ This is the simples pipeline, it simply loads the image from disk """ return lambda image_path, label: ( tf.image.decode_jpeg(tf.io.read_file(image_path), channels=3), ...
""" http://www.spoj.com/problems/PRIME1/ 2. Prime Generator Problem code: PRIME1 Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers! Input The input begins with the number t of test cases in a single line (t<=10). In eac...
# pip install essential_generators # ^ remember to install this in order to fetch random sentences ^ # get random values of sentances from essential_generators import DocumentGenerator gen = DocumentGenerator() # measure elapsed time import time # standarize the length of sentence to prevent anomalies sentence_to_...
def calculate(min, max): sum = 0 for x in range(min, max+1): sum = sum+x print(sum) calculate(1, 3) calculate(4, 8) def avg(data): num = data['count'] sal = data['employees'] total = 0 for i in sal: sal = i['salary'] total += sal avg = total/...
from graphics import * from time import sleep from random import randint SIZE = 1000 color_list = ['red', 'purple', 'yellow', 'green', 'blue', 'cyan', 'orange', 'maroon', 'magenta', 'pink', 'violet'] class QuadrantRenderer(object): def __init__(self, n, init_deficiency): """initializes the quadrant rende...
#!/usr/bin/env python import urllib2 import crypt import getpass print("Getting a random salt from random.org...") salt = urllib2.urlopen( "https://www.random.org/strings/?num=1&len=20&digits=on&upperalpha=on&loweralpha=on&unique=on&format=plain&rnd=new").read() hs = crypt.crypt(getpass.getpass(), "$6${}".format...
# coding: utf-8 import string #简单类型 print type(1234) print type(12.123) print type(123.) print type('abc') print type("abc") #容器 print type([1,23,4]) print type((12,2,3)) print type(set([1,2,2,3])) print type({'a':1,'b':2}) #函数 def func(a,b,c): return a + b + c pass afunc = func print type(func) print type(afunc) #模...
class Estudiante(object): def __init__(self, nombre_r, edad_r): self.nombre = nombre_r self.edad = edad_r def hola(self): return "Mi nombre es %s y tengo %s"%(self.nombre, self.edad) e = Estudiante("jesus",26) s = e.hola() lista = [] for estudiante in range(10): nombre = "Estudiante %s"% estudiante e = Estud...
class StatsGenerator: """ All statistic related calculation should go here """ _data = None _statistics = None def __init__(self, data): self._data = data self._statistics = {} def calculate_average_working_time(self): """ Calculate average working time for...
A="so good" if A == ' ' or A == " ": print(0) else: word_count = 1 for i in range(1,len(A)-1): if A[i]==' ': word_count += 1 print(word_count)
#변수명 = {key1:value1 , key2:value2 , . . .} dic_val ={1:'a',3:'c'} print(dic_val) #변수명 [key1]=value1 dic_val[2]='b' print(dic_val) # p=0 p={} p[1]='apple' print(p)
oddCount=0 evenCount=0 num=0 # 1. 반복문 : while True: while True: # 2. 정수입력 , input -> int num = int(input("정수 입력")) # 3. 0이 입력되면 if -> break if num == 0: break #4. 짝수 홀수 판별 if num % 2 ==0: evenCount=evenCount+1 else: oddCount=oddCount+1 print(evenCount) print(oddC...
def add(): x=4 y=2 add_res=x+y#6 print(add_res) def add1(): x=1 y=3 add_res=x+y#6 print(add_res) add() add1()
a = {'name': 'pey', 'phone': '0119993323', 'birth': '1118','email':"naver"} isNameExist='name' in a isEmailExist='email' in a print(isNameExist,isEmailExist) if isNameExist: val =a['name'] print(val) if isEmailExist: val =a['email'] print(val)
#2개의 값을 입력받아서 4칙연산을 해서 결과값 4개를 리턴 def calculate(x,y): sum=x+y sub=x-y div=x/y mul=x*y return (sum, sub, div, mul) x=1 y=10 sum=sub=div=mul=0 sum, sub, div, mul=calculate(x,y)#11 -9 0.1 10 print(sum, sub, div, mul)
num=0 sum=0 # 1. 입력 num=int(input("정수입력")) # 2. 반복문 for range for i in range(1,num+1,1): # 3. 변수 체크 -> 5의 배수면 누적합 더하기 if i%5==0: sum=sum+i # 4. 누적합 을 출력 print(sum)
from .exceptions.over_draft_error import OverdraftError class Account: def __init__(self, acc_no, acc_type, acc_balance): self.acc_no = acc_no self.acc_type = acc_type self.acc_balance = acc_balance def deposit(self, amt): self.acc_balance += amt return self.acc_balance def withdraw(self, a...
path = '/Users/mehul.chopra/Documents/professor.py' fp = open(path) # print(type(fp)) # print(fp) # soomething with fp # read line by line '''print('Read first time from the file') for line in fp: print(line.rstrip()) # strips out the \n from the end of the line print('Read second time from the file') for line in ...
# variable numbers of arguments (0 to n) def myadd(*args): # all the arguments passed, get packed into the args tuple object # print(args) # tuple sum = 0 for item in args: sum += item return sum # positional arguments packing print(myadd()) print(myadd(4, 5)) print(myadd(5, 6, 3, 4, 10)) def perimeter(...
#Jogo adivinhe a palavra import random lines = open("palavras.txt").readlines() line = lines[0] palavras = line.split() #Introdução print("") print("Jogo: Adivinhe a palavra") print("*"*50) print("Você recebera dicas e terá 3 chances para acertar a palavra.") print("") print("Vamos começar") pri...
#the function 'not' combines two situations for eg x=true.....if we check the #variable in x and it is 'not true', then it is false def is_odd(x): if not x % 2 == 0: return False else: return True print(is_odd(5)) print (" ") def is_evens(): #function name numbers = [1,56,234,87,4,76,24,69,90,135] #li...
import time rootnode = None class Node(object): def __init__(self, name, description): self.name = name self.description = description self.children= [] def addChild(self, child): self.children.append(child) child.parent = self.name def get_children(self): #lists...
import random print("\n***** HANGMAN GAME *******") HANGMAN = (''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | ...
import requests import json import os #OWM website and API key OWM_BASE = 'http://api.openweathermap.org/data/2.5/weather' OWM_API_KEY = os.environ.get('OWM_API_KEY') #set parameters for Json call def get_city_temp(city): r = requests.get( OWM_BASE, params={ 'q': city, 'uni...
"""token = [1,2,3,3,5,6,7] new_trigrams = [] c = 0 while c < len(token) - 2: new_trigrams.append((token[c], token[c+1], token[c+2])) c += 1 print new_trigrams""" pairs = [("narendra","modi"),("controversial","minister"),("temple","mosque"),("speech","commentary"),("chanting","crowd"),("indian","foreign")...
def palindrome_chain_length(n): s = 0 while True: if str(n) == str(n)[::-1]: return s else: n = n+int(str(n)[::-1]) s += 1
#str(lst).replace("[", "").replace("]", "") patt = re.findall("[0-9]", str(lst)) return sum([int(i) for i in patt]) import re def sum_nested(lst): patt = re.findall("[0-9]+", str(lst)) return sum([int(i) for i in patt]) """ def sum_nested(lst): return sum(sum_nested(x) if isinstance(x,list) else x for ...
""" https://www.codewars.com/kata/simple-string-reversal/train/python In this Kata, we are going to reverse a string while maintaining spaces. For example: solve("our code") = "edo cruo" -- Normal reversal without spaces is "edocruo". -- However, there is a space after the first three characters, hence "edo cruo" ...
a, b = "ESTATE", "DUELED" e, f, g, h = [], 0, [], 0 for i in a: if i not in e: print(i, "not in") e.append(i) e.append(f) f += 1 elif i in e: print(i, "in") e.append(i) e.append(e.index(i)//2) print(e) ...
def pyramid(n): pyr = "" for i,j in enumerate(range(n, 0, -1)): if j == 1: pyr = pyr + ("/" + "_"*(i*2) + "\\\n") else: pyr = pyr + (" "*(j-1) + "/" + " "*(i*2) + "\\"+ "\n") return pyr ' /\\ \n / \\ \n / \\ \n/______\\\n' should equal ' /\\\n / \\\n /...
#LIBRERIAS USADAS import matplotlib.pyplot as plt import numpy as np #FUNCIONES DADA UNA LISTA CON NUMEROS PSEUDOALEATORIOS DEL 0 AL 36 COMO PARAMETRO NOS DEVUELVE SU ESTADISTICO def relativefrequency(numero,data): count = 0 rf = [] for x in range(len(data)): if data[x] == numero: count...
# -*- coding: utf-8 -*- """ Created on Mon May 31 20:29:35 2021 @author: JuanCHerreraPro """ #Binarization """ Binarization is used to convert numerical values into Boolean values. Let's use an inbuilt method to binarize input_data and using 2.1 as the threshold value. """ import numpy as np from sklearn impor...
def validni_brojevi(x, y) : if not x.isnumeric()or not y.isnumeric() : return False else: return True korisnik_uneo_prvi = input("Unesite prvi broj: ") korisnik_uneo_drugi = input("Unesite drugi broj: ") if not validni_brojevi(korisnik_uneo_prvi, korisnik_uneo_drugi) : quit ("Brojevi nisu...
import math def Isprime(x): if x == 2: return True if x % 2 == 0: return False s = int(math.sqrt(x)) for i in range(3,s+1,2): if x % i == 0: return False return True class Hashtable: def __init__(self,expected_size): size =...
import time import random import sys import math # creates a random list at any length def RandomDubplicate(List_Length): A = [] for i in range(List_Length): # use underscore (for _ in range() if i gives trouble r = random.randrange(0, List_Length) A.append(r) return A c...
slownik = {'kefir':'szt', 'chleb':'szt', 'ziemniaki':'kg', 'ser':'kg'} A = [key for key, value in slownik.items() if value == 'szt'] print(slownik, A)
import sys str = raw_input("Enter the string: ") spaces = 0 for i in range(0,len(str)): if str[i] == ' ': spaces += 1 newlen = len(str) + (spaces*2) newstr = str newstr += ' ' * (spaces * 2) j = newlen - 1 for i in range(len(str)-1,-1,-1): if newstr[i] != ' ': newstr = newstr[0:j] + newstr[i] + newstr[j+1:] ...
import sys class Node: def __init__(self, value = None, left = None, right = None): self.value = value self.left = left self.right = right class Tree: def __init__(self): self.root = None def insert(self, x): if self.root == None: self.root = Node(x) else: current = self.root while current ...
import sys word1 = raw_input("Enter the first word: ") word2 = raw_input("Enter the second word: ") len1 = len(word1) len2 = len(word2) diff = abs(len1 - len2) if(diff > 1): print "Not one edit away" exit() # Check for replace, delete or insert edit = 0 if(diff == 0): i = 0 for letter in word1: if letter != ...
#!/usr/bin/env python3 from string import ascii_lowercase as asl from itertools import product for s in product(asl, repeat=5): if ''.join(s).startswith('o'): print(''.join(s))
import random import string def search_seed_for_word(word): letters = string.ascii_lowercase for i in range(0, 100000000): random.seed(i) rand_letters = [] for j, letter in enumerate(word): rand_letter = random.choice(letters) rand_letters.append(rand_letter) ...
# 蟒蛇实例 # import turtle # # # def drawSnake(rad, angle, len, neckrad): # for i in range(len): # turtle.circle(rad, angle) # turtle.circle(-rad, angle) # turtle.circle(rad, angle / 2) # turtle.fd(rad) # turtle.circle(neckrad + 1, 180) # turtle.fd(rad * 2 / 3) # # # def main(): # tu...
import requests from bs4 import BeautifulSoup # Here,we're just importing both Beautiful Soup and the Requests library res = requests.get('https://guidestarindia.org/List_of_NGOs.aspx') #its a url that I already determined is safe and legal to scrape from. html_text = res.text # Here we are taking the entire text fr...
import urllib, json try: # test if it's Python 3 from urllib.request import Request, urlopen except: from urllib2 import Request, urlopen VERIFY_SERVER="www.google.com" class RecaptchaResponse(object): def __init__(self, is_valid, error_code=None): self.is_valid = is_valid self.error...
my_dict = {'1/2': {'-1/3': 'Strange Quark', '2/3': 'Charm Quark', '-1': 'Electron Lepton', '0': 'Muon Lepton'}, '1': {'0': 'Photon Boson'}} spin = input() el_ch = input() print(my_dict[spin][el_ch])
def fact(n): if n >= 0: n * fact(n) n = n-1 # print(fact(4)) a = [3,7,8,11,21,39,40,100,101] b = [2,3,4,5] #collate def collate(listA, listB): c = [] for a in listA: for b in listB: if a < b: c.append(a) return c def collate_ans(listA, listB): listC = [] num = len(listA) + len(listB) A = 0...
''' tensorflow的特点: 使用图(graph)来表示计算任务 在被称为 会话(session)的上下文(context)中执行图 使用tensor表示数据 通过变量(variable)维护状态 使用feed和fetch可以为任意的操作(arbitrary operation)赋值或者从其中获取数据 ''' import tensorflow as tf #创建一个常量节点op #加到默认图中 #构造器的返回值代表该常量op的返回值 matrix1=tf.constant([[3.,3.]]) #创建另一常量op,产生一个2*1矩阵 matrix2=tf.constant([[...
import tensorflow as tf import matplotlib.pyplot as plt import numpy as np x=np.linspace(-5,5,200) y_relu=tf.nn.relu(x) y_sigmoid=tf.nn.sigmoid(x) y_tanh=tf.nn.tanh(x) y_softplus=tf.nn.softplus(x) y_softmax=tf.nn.softmax(x) sess=tf.Session() y_relu,y_sigmoid,y_tanh,y_softplus=sess.run([y_relu,y_sigmoid,y_tanh,y_soft...
#!/usr/bin/env python total = 0 all_num = {} found = False firstRun = True while not found: for lines in open("input1.txt"): if lines[0] == "+": total += int(lines[1:]) else: total -= int(lines[1:]) if total in all_num: if not found: print("twice:", total) found = True else: all_num[total...
#to print the nodes of a binary tree from root to bottom as visible fro left side of tree a=[] n=int(input("enter the height of binary tree: ")) h=(2**n)-1 for i in range(h): node=int(input("enter the element of binary tree: ")) a.append(node) print a k=0 for item in a: i=a.index(item) if(i+1==(2**k) and item!=-...
def binarysearch(arr,low,high,x): mid=0 if x<=arr[low]: return low if x>arr[high]: return -1 mid=(low+high)/2 if arr[mid]<x: if mid+1<=high and x<=arr[mid+1]: return mid+1 else: return binarysearch(arr,mid+1,high,x) else: if mid-1>=low and x>arr[mid-1]: return mid else: return binarysearch...
import sys def binarysearchfloor(arr,low,high,x): mid=0 while low<=high: if low>high: return -1 if x>=arr[high]: return high mid=(low+high)/2 if arr[mid]==x: return mid if mid>0 and arr[mid-1]<=x and x<arr[mid]: return mid-1 if x<arr[mid]: high=mid-1 if x>arr[mid]: low=mid+1 return -1...
def product(arr,n,K): count=0 for x in range(1,2**n): prod=1 for k in range(n): z=1 z=z<<k if x & z: prod=prod*arr[k] if prod<=K: count+=1 return count t=13 for m in range(13): N,K=map(int,raw_input().split()) arr=map(int,raw_input().split()) print product(arr,N,K)
def sumofdigits(i): t=0 while i>0: t+=i%10 i=i/10 return t def binarysearchfloor(low,high,x): while high-low>1: mid=(low+high)/2 if mid-sumofdigits(mid)<=x: low=mid else: high=mid if low+1-sumofdigits(low+1)<x: return low+1 return low n,s=map(int,raw_input().split()) count=0 if s>=n: count=n el...
import time start=time.clock() def sieve(MAX,all_primes): prime=[True for i in range(MAX+1)] p=2 while p*p<=MAX: if prime[p]==True: for i in range(p*2,MAX+1,p): prime[i]=False p+=1 for p in range(2,MAX): if prime[p]==True: all_primes.append(p) def binarysearch(arr,low,high,x): if x>arr[high]: re...
## check if number is divisible by 3 without modulus function def check_divisible_by_3(num): if(num==3 or num==6 or num==9 or num==0): return True else: string_num=str(num) sum_digits=0 for i in range(0,len(string_num)): if(string_num[i]!='-'): digit_num = int(string_num[i]) sum_digits...
## This is an interview question where in a row wise and col wise sorted matrix we find number of negative integers A=[[-3,-2,-1,1],[-2,2,3,4],[4,5,7,8]] B=[[-7,-3,-2],[-3,-2,5],[-1,1,7]] def findOccurenceOfFirstNegativeInteger(aSortedListOfNumberLists): dictToStoreFirstOccurence={} for i in range(0,len(aSortedLis...
# Task # Given sets of integers, M and N, print their symmetric difference in ascending order. # The term symmetric difference indicates those values that exist in either M or N but do not # exist in both. # # Input Format # The first line of input contains an integer, M. # The second line contains M space-separated i...
#!/bin/python3 # NOT PASSING LAST TEST CASE # IMPLEMENT SIEVE OF ERATOSTHENES import sys def isPrime(p): # assume list primes is populated up to sqrt(n). If not, we should check all odds. i = 0 q=primes[0] while q**2 <= p: if p % q == 0: return False i += 1 q = pri...
print('hello this is yongduek') mystring = 'this is a string.' print(mystring) # print one char by one char for char in mystring: print(char, ' --- ') for darcy in mystring: print(darcy, ' darcy ') length_of_mystring = len(mystring) print('length of my string is ', length_of_mystring) for i in range(len...
# filename: float-image-type.py # image pixel data is represented normally by uint8 # but float32 is also a popular representation. # Use TIF format to save a float32 RGB image # Image Viewer for TIF float32 is ImageMagick/display import imageio import matplotlib.pyplot as plt import numpy as np im = imageio.imrea...
import pygame import numpy as np def Rmat(deg): """ deg: angle in degree """ radian = np.deg2rad(deg) c = np.cos(radian) s = np.sin(radian) m = np.eye(3) m[0,0] = m[1,1] = c m[1,0] = s m[0,1] = -s return m def Tmat(tx, ty): m = np.eye(3) m[0,2] = tx m[1,2] = ty ...
# -*- coding: utf-8 -*- import pygame import numpy as np # 게임 윈도우 크기 WINDOW_WIDTH = 800 WINDOW_HEIGHT = 600 # 색 정의 WHITE = (255, 255, 255) BLUE = (0, 0, 255) # Pygame 초기화 pygame.init() # 윈도우 제목 pygame.display.set_caption("Ball") # 윈도우 생성 screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) # 게임 화면 업데...
def dna_to_rna(dna): """ dna: string varaible """ listdna = list(dna) print(listdna) listrna = [] for c in listdna: if c == 'T': listrna.append('U') # elif c == 'X': # else if else: listrna.append(c) # rna = ''.join(listrna) return...
import pygame import numpy as np def Rmat(deg): """ deg: angle in degree """ radian = np.deg2rad(deg) c = np.cos(radian) s = np.sin(radian) m = np.eye(3) m[0,0] = m[1,1] = c m[1,0] = s m[0,1] = -s return m def Tmat(tx, ty): m = np.eye(3) m[0,2] = tx m[1,2] = ty ...
def printStr(inputStr): print(inputStr) def printList(inputList): print(inputList) def dataPlus(num1, num2): print(num1 + num2) return num1 + num2 def dataLess(num1, num2): print(num1 - num2) return num1 - num2 def dataMultiply(num1, num2): print(num1 * num2) return num1 * num2 def...
name = raw_input("Enter file: ") if len(name) < 1 : name = "mbox-short.txt" handle = open(name,'r') #text = handle.read() counts = dict() for line in handle: line = line.rstrip() if line == '' : continue # want to keep non blank lines words = line.split() if words[0] != 'From' : continue # continue to ...
import urllib from BeautifulSoup import * # http://python-data.dr-chuck.net/known_by_Evelyn.html url = raw_input('Enter - ') html = urllib.urlopen(url).read() soup = BeautifulSoup(html) # Retrieve all of the anchor tags tags = soup('a') # Find position 3 print tags[17] #for tag in tags: #print tag.get('href', No...
import numpy as np def conv_nested(image, kernel): """A naive implementation of convolution filter. This is a naive implementation of convolution using 4 nested for-loops. This function computes convolution of an image with a kernel and outputs the result that has the same shape as the input image. ...
#!/usr/bin/env python3 input = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,9,19,1,19,5,23,2,23,13,27,1,10,27, 31,2,31,6,35,1,5,35,39,1,39,10,43,2,9,43,47,1,47,5,51,2,51,9,55,1,13,55,59, 1,13,59,63,1,6,63,67,2,13,67,71,1,10,71,75,2,13,75,79,1,5,79,83,2,83,9,87, 2,87,13,91,1,91,5,95,2,9,95,99,1,99,5,103,...
import pygame from pygame.locals import * from random import shuffle, choice, randint pygame.init() """ similar to amazer.py, an exploration of procedural maze generation the same but with the addition of up and down this time the syntax will be Never Eat Soggy Waffles Unless Dared [N, E, S, W, U, D] """ PW = 32 W, H...
# 爬虫前奏(原生爬虫) # #1.明确抓取的目的 # 2.找到数据对应的网页 # 3分析网页结构,找到数据所在的标签位置 # # 模拟http请求,向服务器发送个请求,获取服务器返回给我们的html # 用正则表达式提取我们的数据(名字,人气) from urllib import request #断点调试 class spider(): url = "https://www.baidu.com" def __fetch_content(self): #私有函数 r = request.urlopen(spider.url) #读取类变量的方法spider.url html...
print('1.---------------------如果不希望字符串中的\表示转义,我们可以通过在字符串的最前面加上字母r来加以说明------------------') # s1 = r'\'hello, world!\'' # s2 = r'\n\\hello, world!\\\n' # print(s1, s2, end='') s1 = 'hello ' * 3 print(s1) # hello hello hello s2 = 'world' s1 += s2 print(s1) # hello hello hello world print('ll' in s1) # True print('good'...
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import random # create some random data ptx1 = [random.randint(0,100) for x in range(20)] pty1 = [random.randint(0,100) for x in range(20)] fig = plt.figure() ax = fig.add_subplot(111) def animate(i): # use i-th elements from data ...
def division(): apple = int(input("输入苹果数量:")) child = int(input("输入人数:")) # if (child > apple): # raise ValueError("苹果不够分") assert child <= apple, "苹果不够分" res = apple // child print("一人几个:" + str(res) + "剩余:" + str(apple % child)) if __name__ == '__main__': try: division...
def demo(obj): obj += obj def bmi(weight, height, name='佚名'): bmi = weight / (height * height) print(name, bmi) def obj_var(obj=[]): print(obj) obj.append(1) def obj_val(obj=None): if obj == None: obj = [] print(obj) obj.append(1) if __name__ == '__main__': obj = 'gu' ...
class Space: def attach_to_board(self, board): pass def play(self, player): raise NotImplementedError( 'Must implement what happens when the player lands on this space.' ) class Go(Space): name = 'go' def play(self, player): player.money += 200 class T...
''' Write a Python program to find if a given string starts with a given character using Lambda. ''' s='abhi' p=lambda a: True if a[0]=='x' else False print(p('knbdf'))
# Python, Introduction, Loops # https://www.hackerrank.com/challenges/python-loops a = int(raw_input()) i = 0 for i in range(a): print(i*i)
''' Converts array of integers into a matrix of its bianry number with each bit in a separate cell Converts integer to binary string, strips header and counts total number of bits (MSB) Creates padded matrix of 0's based on length of data array and MSB Fills bits with 1 by coutning from LSB to MSB ''' import nump...
#!/usr/bin/python2 """ Statement: Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20x20 grid? """ from unittest import TestCase, main class Problem15(object): def...
class Node: def __init__(self, key): self.key = key self.left = None self.right = None class AVLTree: def __init__(self, node=None): self.node = node # init height to -1 because of 0-indexing self.height = -1 self.balance = 0 def display(self, level...
class node: def __init__(self,data): self.data = data self.left = None self.right = None def addToTree(self,data): new_node = node(data) while True: if new_node.data <= self.data: if self.left == None: self.left = new_node ...
# INORDER TRAVERSAL def printTree(root): if (root.left)!=None: printTree(root.left) print(root.data,end = ' ') if root.right: printTree(root.right)