text
stringlengths
37
1.41M
# Stack Big O complexity # Push: O(1) - Constant Time # Pop (remove): O(1) - Constant Time # Top (top): O(1) - Constant Time # Is Empty: O(1) - Constant Time # Size: O(1) - Constant Time class Emptiness(Exception): pass class Stack: def __init__(self): self.items = [] def push(self, item): ...
def binary_search(list, item): first_index = 0 last_index = len(list)-1 while first_index <= last_index: middle_index = (first_index + last_index) // 2 if item == list[middle_index]: return True elif item > list[middle_index]: first_index = middle_index + 1 ...
''' https://leetcode.com/problems/judge-route-circle/description/ Example 1: Input: "UD" Output: true Example 2: Input: "LL" Output: false ''' def judge_circle(moves): return moves.count("U") == moves.count("D") and moves.count("R") == moves.count("L") print(judge_circle("UD")) print(judge_circle("LL"))
# # PRACTICE WITH DICTIONARIES # print("") # Step 2 create a dictionary from given table groceryList = { "Chicken":"$1.59", "Beef":"$1.99", "Cheese":"$1.00", "Milk":"$2.50" } # Step 3 create a new variable with a dictionary fruitColors = { "grapes":"purple", "grape fruit":"pink", "st...
def fibo( num ): x = 0 y = 1 for count in range( num ): prevX = x print( x ) x = y y = y + prevX num = int( input( "How many terms? " ) ) fibo( num )
class Foo: def __init__( self, n ): print( 'Init Foo with', n) self.n = 2 * n def bar( self, x ): print( 'Barred:', x ) print( x * self.n ) return x + self.n def getN( self ): return self.n def main(): print('Starting up') f1 = Foo( 3 ) f2 = Foo(...
message = input('Enter the message to encrypt: ') key = int(input('Enter the shift key: ')) outputFileName = input('Enter the name of the file to write the encrypted message to: ') alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" shiftedAlphabetStart = alphabet[len(alphabet) - key:] shiftedAlphabetEn...
## Arthur Twiss (AJ) List = [1,2,3,4,[5,8,9,10]] result = [] def makeArray(myList): for i in myList: print('{} this is i'.format(i)) # checking in i is a list if isinstance(i, list): #hits second array and makes it to int that will hit the else and append to results ...
from HTMLParser import HTMLParser class HTMLTagsStripper(HTMLParser): def __init__(self): HTMLParser() HTMLParser.reset(self) # a list of the data within a text self.fed = [] def handle_data(self, d): # we only care about the data inside not the tags self.fed....
n1 = input("Digite o nome de um carro velho: ") n2 = input("Digite o nome outro carro velho: ") carros_velhos = [n1, n2] todos_os_carros = carros_velhos.copy() todos_os_carros.append("Fusca") print(todos_os_carros)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Jul 18 09:32:37 2019 @author: Jaime Duque Domingo (UVA) Esta clase se encarga de implementar los métodos de extracción de los ángulos de los vectores que devuelve OpenPose así como de obtener las longitudes de los vectores necesarios. Dicha lista de va...
import math import sumpf import nlsp import common import collections class HammersteinModel(object): """ A class to construct a Hammerstein model. The simple Hammerstein model consists of a nonlinear block followed by the linear filter block. The nonlinear block can be defined by power series or some...
import random def create_phone_numbers(alist): mask = '(xxx) xxx-xxxx' for x in alist: x = random.choice(alist) mask = mask.replace('x', str(x)) return mask print(create_phone_numbers([1,2,3,4,5,6,7,8,9,0]))
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ This script contains diverse utility funs Created on Tue Mar 20 11:21:34 2018 @author: haroonr """ #%% def create_pdf_from_pdf_list(file_list, savefilename): ''' combine pdfs ''' from PyPDF2 import PdfFileMerger, PdfFileReader merger = PdfFileMerger() ...
#! python3 # Python3 utility to take clipboard contents and extract contact information # exercise from Automate the Boring Stuff with Python import re # noinspection PyUnresolvedReferences import pyperclip # phone number pattern. using the verbose method to make it more readable phonepattern = re.compile(r''' ( (\...
# # # imie = input ('wpisz swoje imie: ') # # print( 'witaj', imie) # # wiek = int (input ('ile masz lat?')) # # print(' za dawa lata bedziesz miał(a):, wiek +2') # # # operatory porównania< > <= >= == != takie znaki mozna # if wiek >= 18: # print('zapraszam na piwo!') # else: # print('zapraszamy na cole') m...
zestaw = [] liczba = input('podaj liczbe:') while liczba != '' and len(zestaw) <10: zestaw.append (int(liczba)) liczba = input('podaj liczbę: ') print (f'średnia to {sum (zestaw) / len }')
# Copyright (c) 2021, srowanphys # All rights reserved. # This source code is licensed under the Apache 2.0 license found in the # LICENSE.md file in the root directory of this source tree. # The following code constructs an basic program for calculating average acceleration # The program is written in the Python lan...
from HashTable import HashTable H = HashTable() H.insert('hello', 'goodbye') H.insert('f', 'g') hello = H.get('hello') g = H.get('f') print(hello) print(g) H.remove('hello') hello = H.get('hello') print(hello)
from Vertice import Vertice from Edge import Edge class Graph: # Receive nothing def __init__(self): self.list_vertices = [] self.list_edges = [] # Receive an integer def add_vertice(self, identifier): self.list_vertices.append(Vertice(identifier)) #...
from pymongo import MongoClient import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["test"] mycol = mydb["Datos Personales"] while True: print("\n Ingrese el numero del menu que desee acceder \n") menuOpt = int(input(" 1 Agregar una palabra nueva \n 2 Edi...
#!/usr/bin/python """ This script will merge one of the output CSV files with its corresponding data from the labeled data CSV. """ def buildLabelDictionary(labelFileName): """ buildLabelDictionary(labelFileName) -> dictionary Build a dictionary where the key is the PID and the value is the list of v...
a = 0 b = 1 r = raw_input("ENTER THE RANGE : ") print str(a)+"\n" print str(b)+"\n" sum = 0 for i in range(2,int(r)): sum = a + b print str(sum)+"\n" a = b b = sum
import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split, cross_val_score dataset = pd.read_csv("dataset.csv") x = dataset[['x', 'y']].values y = dataset['label'].values means_values = {} scores = np.zero...
def hello(): print('Hello, World!') hello() print("hello \" salman ahmad \"") print("""helo lerm ipsim sdl oolasm sasollqw""") print (1+2) a = input("Your name") # concatination print (a + " hello how are you") print('spam'*3) print('2' + '2') print(int('2')+int('2'))
'''1. Create a list of given structure and get the Access list as provided below''' '''x=[100,200,300,400,500,[1,2,3,4,5,[10,20,30,40,50],6,7,8,9],600,700,800] Access list: [1, 2, 3, 4]Access list: [600, 700] Access list: [100, 300, 500, 600, 800] Access list: [[800, 700, 600, [1, 2, 3, 4, 5, [10, 20, 30, 40, 50], 6, 7...
""" -- instruction menu file -- class: instruction_menu() functions: __init__() on_show() on_draw() on_key_press() """ import random import arcade from arcade.gui import UIManager from data import constants class instruction_menu(arcade.View): """ this class creates the inst...
class Customer: # capitalisation of the start of the class name and its pascal camel case helps to differenciate between methods and functions def __init__(self, name, cash): # every __init__ needs a self, as the first declaration. Think of this as a function with the parameters name nd...
import sqlite3 import datetime import random def table_creator (): try: p.execute('create table '+tableName+'(Id integer primary key, Temperture integer, Date datetime);') db.commit() except: print dbName,'has been already created with the table %s \n'%(tableName) ...
def counter(func): """ Декоратор, считающий и выводящий количество вызовов декорируемой функции. """ func.__invocation_count__ = 0 def wrap(*args, **kwargs): func.__invocation_count__ += 1 res = func(*args, **kwargs) print("{0} была вызвана: {1}x".format(func.__name__...
""" You are given a digital number written down on a sheet of paper. Your task is to figure out if you rotate the given sheet of paper by 180 degrees would the number still look exactly the same. input: "1" output: false input: "29562" output: true input: "77" output: false """ def digital_number(number): ...
list1=[1,2,4,5,1,1,4,1,56] #Type 1 indices=[] for i in range(len(list1)): if list1[i]==1: indices.append(i) print(indices) #Type 2 indices=[i for i in range(len(list1)) if list1[i]==1] print(indices) #Type 3 indices=[index for index,value in enumerate(list1) if value==1] print(indices) #Type 4 indices=...
# Transpose of student details students = [['priya','muki','Dhana','mani'],['CSE','Civil','ECE','IT'],[1999,1998,2000,1997]] print("The given list is",students) print("The transpose is",[[nested_list[i] for nested_list in students] for i in range(len(students))]) # check even or odd in list number = int(input("Ent...
tup=("www","hackerrank","com","domains","python") url="" for i in range(len(tup)): if i==1 or i==2 : url=(url+"."+tup[i]) else: url=(url+"/"+tup[i]) print(url)
port1={21:"FTP",22:"SSH",23:"Telnet",80:"http"} port2=dict() for key in port1.keys(): port2[port1[key]]=key print(port1) print(port2)
import sqlite3 def is_ascii(s): return all(ord(c) < 128 for c in s) def GetCustomer(): conn = sqlite3.connect("northwind.sqlite") cur = conn.cursor() query = "SELECT ContactName FROM Customer;" cur.execute(query) return [r[0] for r in cur.fetchall()] names_to_check = [] for name in GetCustom...
import numpy as np import time import matplotlib.pyplot as plt #planet Mercury = [57*10**9 ,9116.4] Venus = [108*10**9 , 2611.0] Earth = [150*10**9 , 1366.1] Mars = [227*10**9 , 588.6] Jupiter = [778*10**9 , 50.5] Saturn = [1426*10**9 , 15.04] Uranus = [2868*10**9 , 3.72] Neptune = [4497*10**9 , 1.51] Pluto = [...
# Template for using the 'unittest.py' module for testing python code # documentation can be found here: https://docs.python.org/3/library/unittest.html # Note that there are many other functions available, see the docs import unittest # Replace 'MyClass' with the name of your class # and write your constructor and m...
import random chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP123456789#!@" while 1: password_len = int(input('how many characters would you like your password to have: ')) password_count = int(input('how many passwords would you like : ')) #a for loop for number of passwords and assigning an empty strin...
# Use snake cases from now on instead of camel cases when writing python # PROTOTYPE VERSION import random import time class Accounts: # Defining Account instance variables. def __init__(self, pin, balance, annualInterestRate=3.4): self.pin = pin self.balance = balance sel...
import math # author Valeria def f(x): # function return ((math.log((math.pow((math.sin(x)), 2)) + 1)) - (0.5)) #bisection method def bisection(a, b, iterations, tolerance): x0 = 0 y0 = 0 i = 1 xm = (a + b) / 2 result = f(xm) #Method data input control if iterations < 1: ...
def ascending(l): if len(l) < 2: return True for i in range(2, len(l)): if l[i - 1] > l[i]: return False return True def valley(l): n = len(l) small = l[0] vp = 0 if n < 3: return False for i in range(n): if small > l[i]: ...
##Program Name: OfficeStatus.py ##Purpose: Use python datetime module to determine whether a business branch ## in different timezones open or closed based on current time. ##Program Language: Python ##Language Version: 2.7.9 ##Platform Tested: Windows 8.1 on x86 ##Author: Matt ...
# -*- coding: utf-8-spanish -*- # Autor: Abdias Alvarado # Fecha: 28/Oct/2017 # Script: 5. Contando Domingos.py from datetime import datetime from datetime import timedelta import time def DomingosInicioMes(fechaInicio, fechaFinal): ''' Retorna la cantidad de veces que un mes comenzó con un do...
''' This module created by Tom Lester for the Full Stack Nano Degree.''' import webbrowser class Movie(object): ''' Movie class creates a data structure for movie information. The Movie class takes in four arguments: movie_tite: The Title of the movie. movie_storyline: A synopsis of the ...
class Employee: # accessible as the same variable to all instances. Similar to a static attribute raise_amount = 1.04 num_of_emps = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first+"."+last+"@gmail.com" ...
#产生网格坐标 import numpy as np import matplotlib.pyplot as plt import create_data as cd #产生[[600,600],[600,600]]的点,而且xx,yy 不相同 xx, yy = np.mgrid[-3:3:.01, -3:3:.01] print(xx.shape) print(xx,yy) print(xx.ravel().shape) #把xx拉成(36000,) print(xx.ravel()) #组成(36000,2) grid = np.c_[xx.ravel(), yy.ravel()] print(grid.shape) pri...
# This module provides a single method, is_valid(), # which returns True or False to indicate whether a given cpf # is valid according with Ministério da Fazenda specification. from constant import BLOCKLIST def is_valid(cpf): if not isinstance(cpf, str): return False if cpf in BLOCKLIST or not cpf....
a=raw_input("Minu nimi on: ") print ('{:<40}'.format(a)).swapcase() + ('{:>40}'.format(a)).upper()
from typing import List import functools class Solution: #先把nums中的所有数字转化为字符串,形成字符串数组 nums_str #比较两个字符串x,y的拼接结果x+y和y+x哪个更大,从而确定x和y谁排在前面;将nums_str降序排序 #把整个数组排序的结果拼接成一个字符串,并且返回 def largestNumber(self, nums: List[int]) -> str: nums_str=list(map(str,nums)) compare=lambda x,y: 1 if x+y<y+x els...
class Solution(object): def isValidSerialization(self, preorder): # 核心:二叉树入度和出度是相等的。 nodes = preorder.split(',') diff = 1 for node in nodes: diff -= 1 if diff < 0: return False if node != '#': diff += 2 retu...
import bisect from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: M, N = len(matrix), len(matrix[0]) t_list = [x[0] for x in matrix] target_row = bisect.bisect_right(t_list, target) - 1 if target_row == 0: return F...
""" Takes an unsolved Sudoku puzzle and returns it solved. """ import re from collections import Counter NUM_SEARCHES = 0 # Define some helpful global variables def cross(A, B): """ Cross product of elements in A and elements in B. """ return [a + b for a in A for b in B] rows = 'ABCDEFGHI' cols = ...
import sys import os class ArgumentsErrors(ValueError): pass def get_input_files(arguments): if len(arguments) == 3: return arguments[1], arguments[2] else: raise ArgumentsErrors("Invalid Argurments.") def read_file(filename): with open (filename, "r") as fd : line = fd.readl...
# -*- coding: utf-8 -*- """ Created on Sat Nov 17 09:47:49 2018 @author: Nomula Dheeraj Kumar """ from goto import goto, label print('Choose between "X" and "O"') player=input() if(player=='X'): computer='O' current=player else: computer='X' current=computer def is_full(board):...
x=int(input('Введите год: ')) if x%4==0 and x%100!=0: print ('год високосный') elif x%400==0: print ('год високосный') else: print ('год не високосый')
def fib(number): if number == 1 or number == 2: return 1 return fib(number - 1) + fib(number-2) number = int(input()) print (fib(number))
#Программа должна прочитать текст, создать частотный список слов в этом тексте, #используя слова в качестве ключей словаря, а частотность в качестве значений. #После этого нужно распечатать самое частотное слово в тексте. # Найти среднее значение частотности слов в тексте. with open ('anna.txt', 'r', encoding = 'utf...
Counter = int(input ("How many numbers")) def average(a): sum = 0 for i in range(a): number = int(input("What is your number")) sum = sum + number Avg = (sum / a) return Avg,sum print(average(Counter)) print(Counter) print(sum)
class binary_search(object): ''' * a method to find the given target in the given array. if the * target is found, then return the index of it. Otherwise None * @param arr: an array to be searched * @param target: an element the program looks for ''' def find(arr, target): # set min...
from Min_heap.minheap import Minheap ''' * Author: Tomoya Tokunaga(mailto: ttokunag@ucsd.edu) * * About this file: * This file implements Dijkstra's shortest path algorithm with a binary MIN-HEAP * Complexity: O((V + E)*logV) time | O(1) space (this stores node & distance pair * to a list, so it takes a space) ''' cla...
# Class for storing Movie information class Movie(): """ A Movie object with common attributes trailer, poster, etc""" def __init__(self, title, poster, trailer, rating, genre): # constructor self.trailer_youtube_url = trailer self.title = title self.poster_image_url = poster s...
"""Extendable JSON is an extendable drop in replacement of Python's JSON library. By using @json_serialize and @json_deserialize decorators to enable custom objects not normally serializable by default. This library includes the ability to serialize Exceptions, Objects, and Datetime objects by default. ==============...
""" Given a linked list, remove the nth node from the end of list and return its head. """ class ListNode: def __init__(self, v): self.val = v self.next = None def main(): head = ListNode(0) n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n5 = ListNode(5...
""" Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, Given input array A = [1,1,2], Your function should return length = 2, and A is now...
class Node: def __init__(self,v,l,r): self.val = v self.left = l self.right = r global max_sum def main(): max_sum = [0] n3 = Node(3, None, None) n4 = Node(4, None, None) root = Node(5, n3, n4) MaxSum(root, max_sum) print max_sum[0] def MaxSum(root, max_sum): i...
# Python program to find the factorial of a number provided by the user. # function to print factorial of given number def isOddEven(number): factorial = 1 if number < 0: print("Sorry, factorial does not exist for negative numbers") elif number == 0: print("The factorial of 0 is 1") else: ...
#reverse a string manually reverse = "reverse" reverse_manually = "serever" print(reverse_manually) #reverse a string using an empty string user_entry = input('Please enter your favorite number: ') reverse_user_entry = "" for each_word in user_entry: reverse_user_entry = each_word + reverse_user_entry print(re...
# https://leetcode.com/problems/hamming-distance/ class Solution: def hammingDistance(self, x: int, y: int) -> int: x_bin = bin(x)[2:] y_bin = bin(y)[2:] digits = max(len(x_bin), len(y_bin)) if len(x_bin) > len(y_bin): y_bin = "0"*(len(x_bin)-len(y_bin)) + y_bin ...
#This program is used to find twin from 0 to 100 import math as m def isPrime(value): """Checks wheather the given number is prime or not""" x=int(sqrt(value)) for i in range (2,x+1): if(value%i==0): return False return True for i in range (3,1000,2): if(i%2!=0): ...
#Определить четверть координатной плоскости по координатам x и y. Применить минимум два разных подхода в #указании условий. x = int(input("Координата Х = ")) y = int(input("Координата Y = ")) if not y or not x: print("Точка на оси") else: if y > 0: if x > 0: print("I четверть") els...
#Вывести на экран таблицу умножения на 3 for i in range(1, 11): print(3,' * ', i, ' = ', 3 * i)
#Проверить, что введеные три числа (длины сторон) могут образовать треугольник. a = int(input("Введите первое число ")) b = int(input("Введите второе число ")) c = int(input("Введите третье число ")) if a < b + c and b < a + c and c < a + b: print('Треугольник со сторонами {},{},{} может существовать'.format(a,b...
# sum using while loop total = 0 i=1 while i<=100: total = total+i i = i+1 print(total)
#dictionary exercise def number_cube(n): dic1 = {} for i in range(1,n+1): dic1[i]=i**3 return dic1 print(number_cube(10)) ## dictionary Comprehension number = {num : num**2 for num in range(1,11)} print(number) odd_even = {i:('even'if i%2 == 0 else 'odd') for i in range(1,11)} ...
list1 = [1, 2.3, ' absvs', [1,'cd','23'],7.9] list2 = [i for i in list1 if type(i) == float or type(i) == int] # for i in list1: # if type(i) == float or type(i) == int: # list2.append(i) print(list2)
#word counter using dictionary def word_counter(a): count = {} for i in a: count[i]= a.count(i) return count print(word_counter("MalhAr"))
#funcation practice name = input("enter your name: ") def name_1(abc): return abc[-1] print(name_1(name))
# chapter 1 print 'chapter 1: why should I learn python' x=6 y=x*7 print y # chapter 2 print 'chapter 2: Variables, expressions, and statements' print type('hello') print 1,000,000 input = raw_input("please enter your desire number :") if(int(input)): print 'your number is ' , input words = {'nitesh','...
User_Number = 0 Total = 0 for i in range(0, 10): User_Number = int(input("Enter a number: ")) Total += User_Number print(Total)
# The following program uses selenium to navigate and interact with he instagram platform to follow profiles on the # the users suggested page from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expecte...
import random # The classic string-between def strbet(text, start, end): start_str = text.find(start) if start_str == -1: return None end_str = text.find(end, start_str) if not end_str: return None start_str += len(start) return text[start_str:end_str] def rndk(charset): charset = list(charset) rand...
from SnakeParts import * from enum import Enum import curses import random class Direction(Enum): UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 class Snake: def __init__(self, max_y, max_x, color, color_num): # y and x size of the game field self.max_y, self.max_x = max_y, max_x # i...
raw_input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. open(...) ...
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList:...
def anagramCheck(str1, str2): if (sorted(str1) == sorted(str2)) : return True else : return False str1 = input("Please enter String 1 : ") str2 = input("Please enter String 2 : ") if anagramCheck(str1,str2): print("Anagram") else: print("Not an anagram")
# Given an array of one's and zero's convert the equivalent binary value to an integer. # Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1. def binary_array_to_number(arr): arr.reverse() result = 0 for i in range(0,len(arr)): result += arr[i] * (2**i) return result number ...
''' Set up the tables of the database ''' import sqlite3 as sqlite import os class DBmanager(): def __init__(self, dbname): thisfilepath = os.path.dirname(os.path.realpath(__file__)) dbrelpath = '' self.filepath = os.path.join(thisfilepath, dbrelpath, dbname) # Create tables if do ...
# ------------------------------------------------- # # Title: Listing 15 # Description: A try-catch with manually raised errors # using custom error classes # ChangeLog: (Who, When, What) # RRoot,1.1.2030,Created Script # ------------------------------------------------- # #1:08:30 class CustomError(Exception)...
all_inp = [] file = open("input.txt", "r") for i in file: i = i.strip("\n") all_inp.append(i) final_count = 0 for inp in all_inp: #inp_info1 = inp[0:3] ##inp_info2 = inp[3:-0] #print(inp_info1) #print(inp_info2) inp_split = inp.split(" ") inp_split2 = inp_split[0].split("-") most = ...
# def char2num(s): # return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] # print(char2num('2')) # -*- coding: utf-8 -*- #!/usr/bin/env python3 # -*- coding: utf-8 -*- # from functools import reduce # def str2float(s): # def str2num(str): # return {'0': 0, '1'...
class Queue: def __init__(self): self.list = [] def enqueue(self, val): self.list = self.list + [val] return 0 def dequeue(self): if len(self.list) == 0: return False val = self.list[0] self.list = self.list[1:] return val def empty(self): if len(s...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Lab 2 SI 618: Fetching and parsing structured documents (100 points) # # The utf8 'magic comment' is to tell Python that this source code will # contain unicode literals outside of the ISO-Latin-1 character set. # Some lines of code are taken from Google's Python Class ...
import re from pyspark import SparkConf, SparkContext def normalizeWords(text): return re.compile(r'\W+', re.UNICODE).split(text.lower()) conf = SparkConf().setMaster("local").setAppName("WordCountBetter") sc = SparkContext(conf = conf) rdd = sc.textFile("book.txt") words = rdd.flatMap(normalizeWords) wordsCount = ...
import pygame from pygame.sprite import Sprite class Ship(Sprite): # 关于飞船设置的类 def __init__(self, ai_settings, screen): #设置初始位置 super(Ship, self).__init__() self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load('images/ship.bmp') # 加载飞船图像 self.r...
import matplotlib.pyplot as plt input_values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] plt.plot(input_values, squares, linewidth=5) # 导入列表,linewidth决定线条的粗细 plt.title("Square Numbers", fontsize=24) # 设置图表标题并设置其字号 plt.xlabel("Value", fontsize=14) # 设置X轴上的文本并设置其字号 plt.ylabel("Square of Value", fontsize=14) # 设置Y轴上的...
import pygame from pygame.sprite import Sprite # 通过Sprite类,可将游戏中相关 # 的元素编组,进而同时操作编组中的所有元素 class Bullet(Sprite): # 定义关于子弹的类 def __init__(self, ai_settings, screen, ship): super(Bullet, self).__init__() self.screen = screen # 初始化屏幕 self.rect = pygame.Rect...
def convert_to_c(fahrenheit): '''(number) -> float Returns the number of Celsius degrees equivalent to Fahrenheit degrees >>> convert_to_c(32) 0.0 >>> convert_to_c(212) 100.0 ''' return (fahrenheit - 32) * (5/9)
entrada = int(input("")) contador=0 anterior = 0 fat = 1 def fatorial(n): if n <= 1: return 1 if n > 1: return fatorial(n - 1) * n while True: f=fatorial(fat) if f < entrada: fat+=1 anterior=0 anterior+=f if f > entrada: contador+=1 fat=1 ...
entrada= (raw_input("")) entrada=entrada.split() distanciamaxima=int(entrada[1]) entrada2=(raw_input("")) entrada2= entrada2.split() x = 0 contador = 1 for i in (entrada2): atual=int(i) if atual - x > distanciamaxima: contador+=1 break else: x=atual if contador>1: print('N') els...