text
stringlengths
37
1.41M
""" 1052.爱生气的老板 今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。 在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。 书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。 请你返回这一天营业下来,最多有多少客户能够感到满意的数量。 来源:力扣(LeetCode) 链接:https://leetcod...
""" 95.不同的二叉搜索树II 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树 """ class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def generateTrees(n): if n == 0: return def solve(l, r): res =[] if l > r: res.append(None)...
import unittest from attribute_injection import MinimalClass class TestMinimalClass(unittest.TestCase): __uut = None def setUp(self): self.__uut = MinimalClass() def test_get_the_list_fails_when_it_doesnt_exist(self): try: theList = self.__uut.theList except Exceptio...
from Book import Book from datetime import datetime def create_book(year): if year == 1: return Book("Harry Potter e la pietra filosofale","J. K. Rowling","Salani Editore",1997, 294, 8877827025) elif year == 2: return Book("Harry Potter e la camera dei segreti","J. K. Rowling","Salani Editore",...
from bs4 import BeautifulSoup import requests, json, time, re, csv, time def subtitle_clean(str_input): str_input = str(str_input) str_input = str_input.strip('<span class="subtitle">') str_input = str_input.strip('</span>') return str_input #create empty list for books subtitle_info_list = [] #create empty li...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Genre, Base, Movie, User engine = create_engine('sqlite:///movieswithusers.db') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metad...
""" >>> parser0.print_help() # doctest: +ELLIPSIS usage: PROG [-h] [--foo FOO] ... optional arguments: -h, --help show this help message and exit --foo FOO foo help >>> parser1.print_help() # doctest: +ELLIPSIS usage: PROG [--foo FOO] ... optional arguments: --foo FOO foo help >>> parser2.print_help() # ...
# Abra una imagen y aplíquele diferentes tipos de filtros pasa bajos. Visualice el resultado # y observe qué ocurre cuando se modifican los coeficientes (kernel 3x3) import cv2 import matplotlib.pyplot as plt import numpy as np import tkinter as tk from tkinter import filedialog def file_read(): ''' Abro una...
import sys if __name__=="__main__": n=input("Enter an number: ") n=int(n) i=0 sum=0 for i in range (0,n+1): sum+=i print("Sum of first "+ str(n) +" numbers is: "+ str(sum)) else: print("Something does not work. :/")
class Solution: def twoSum(self, nums, target): num_set = {} for index,num in enumerate(nums): if target-num in num_set: return [num_set[target-num],index] num_set[num]=index print(num_set)
class Solution: def isPalindrome(self, s): string = [] for char in s: if char.isalnum(): string.append(char.lower()) lens = len(string) for i in range(lens): lens = lens - 1 if string[i] != string[lens]: return Fal...
def solution(array, commands): answer = [] for i in commands: # [2, 5, 3] -> [4, 4, 1] -> [1, 7, 3] temp_arr = [] for j in range(i[0] - 1, i[1]): # temp_arr 만들기 temp_arr.append(array[j]) # temp_arr 채우기 temp_arr.sort() answer.append(temp_...
loop = [1,2,3] for item in loop: print(item) tuple = [(1,2), (3,4), (5,6)] for a, b in tuple: print(a, b) dict = {'k1':1, 'k2':2, 'k3':3} for key, value in dict.items(): print(key) x = 1 while x < 5: print('this is True') x+=1 else: print('this is False') word = 'hello' for index, char in en...
class Node: def __init__(self, value): self.value = value self.nextnode = None def reverse(head): current = head prev = None next = None while current: nextnode = current.nextnode current.nextnode = prev prev = current current = next return prev...
unsorted_array = [99,88,33,11,4,6,77] def insertion_sort(arr): for i in range(0, len(arr)): j = i while j != 0 and arr[j] < arr[j - 1]: arr[j], arr[j - 1] = arr[j - 1], arr[j] j -= 1 return arr print(insertion_sort(unsorted_array))
av = 3 x=int(input("enter no of candies you want :")) i=1 while i<=x: if i>av: print("out of stock") break print("candy") i=i+1 print("Bye")
import math # simple program practicing methods of Number a = 120 b = 20.5 #checking type of a and b print(type(a)) print(type(b)) # type conversion c = int(b) print(c) # some functions print(abs(-40)) print(math.ceil(b)) print(math.floor(b)) print(math.log(a)) print(math.log10(a)) print(max(2,4,10,20,4.5)) print(mi...
# Largest sublist with 0 sum list = [15,-2,2,-8,1,7,10,23] def subList(list) : sum = 0 len = 0 dict = {} for item in list : sum = sum + item if sum == 0 and len == 0 : len = 1 if sum == 0 : len = list.index(item) + 1 if sum not in dict : ...
''' count all the triplets such that sum of two elements equals the third element. ''' #taking input list_input = [] no_of_element = int(input("Enter no. of element in list\n")) i = 0 while i < no_of_element : element = int(input("Enter number\n")) list_input.append(element) i+=1 def countTriplet(list) : ...
# tWo strings are anagram or not ''' task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. ''' str1 = input("Enter 1st string\n") str2 = input("Enter 2nd string\n") def ...
# Program to chcek You are underWeight overWeight or fit ''' Formula to calculate BMI : weight (kg) / [height (m)]2 ''' def takeInput() : #function to take input from users weight = float(input('Enter your weight in kg\n')) height_in_feet = float(input("Enter Your height in feet\n")) calculateBMI(weigh...
class Student: """ Student class contains student id, first name and last name""" def __init__(self, f_name, l_name, id_num): """Create a new Student """ self.firstName = f_name self.lastName = l_name self.idNum = id_num def getFirst(self): """get the fi...
class Rational(): """Rational class holds rational numbers with a top number/ numerator and a bottom number/ denominatior""" def __init__(self): self.top = 0 self.bottom = 1 def display(self): if(int(self.bottom) > int(self.top)): print("{}/{}".format(int(s...
""" File: rock.py Author: Ali Cope Contains Rock class and three derived Rocks to be used as asteroids: LargeRock, MediumRock and SmallRock """ import arcade import math import random from flying import Flying # These are Global constants to use throughout the game SCREEN_WIDTH = 800 SCREEN_HEIGHT = ...
""" File: ds07.py Author: Ali Cope This purpose of this program is to use recursion to calculate the fibonacci number. The function will take just the nth number that we are looking for in fibonacci and return the result """ #first fibonacci number def fib(nth): """ fib function takes an index and...
import unittest from tests.system_tests.code_runner import run_code class VariablesTester(unittest.TestCase): def test_simple_var_declaration(self): code = """ void main() { int x; } """ target_output = "" scc_output = run_code(code) self.assertEqual...
from unittest import TestCase from main import GameEngine game = GameEngine() class TestGameEngine(TestCase): def test_is_invalid_letter_is_numeric(self): self.assertTrue(game.is_invalid_letter("1")) def test_is_invalid_letter_is_special(self): self.assertTrue(game.is_invalid_letter("!"))...
import numpy as np import matplotlib.pyplot as plt from matplotlib.image import imread """ How to use Matplotlib ver. python3.5 author y-ok """ # データ準備 x = np.arange(0, 6, 0.1) # 0から6まで0.1刻みでデータ生成 y1 = np.sin(x) y2 = np.cos(x) # グラフ描画 plt.subplot(2, 1, 1) plt.plot(x, y1, label="$\sin$") plt.plot(x, y2, linestyle =...
fileLines = open("input.txt", "r") freq = 0 for line in fileLines: print (line) freq = freq + int(line) print(freq)
from tkinter import * root = Tk() my_label = Label(root, text = 'I am l label') my_button = Button(root, text = 'I am a button') my_label.pack() my_button.pack() root.mainloop()
import numpy as np import matplotlib.pylab as plt def my_gaussian(x_points, mu, sigma): """ from: https://github.com/NeuromatchAcademy/course-content/blob/master/tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_aeeeaedf.py Returns normalized Gaussian estimated at points `x_points`, with...
# Complete the solution so that it reverses the string value passed into it. # # solution('world') # returns 'dlrow' # This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off # and specifying a step of -1, it reverses a string. def solution(string): return string[::-1]
# IMPORTEER BELANGRIJKE BIBLIOTHEKEN import simpleaudio as sa import time import random """ An example project in which a rhythmical sequence (one measure, 1 sample) is played. - Sixteenth note is the smallest used note duration. - One meassure, time signature: 3 / 4 Instead of using steps to iterate through a seq...
import sys # Algoritmo tradicional de fibonacci def fibonacci_recursivo(n): if n == 0 or n == 1: return 1 return fibonacci_recursivo( n - 1 ) + fibonacci_recursivo( n - 2 ) # Algoritmo fibonacci pero inyectado con programación dinámica. En esta ocasión, guardamos en # valores en memoria los cálculos ...
idades = 0 dividir = 0 while(True): idade = int(input()) if idade<0: break else: idades+=idade dividir+=1 media = float(idades/dividir) print("{:.2f}".format(media))
x = int(input()) b = x z = int(input()) if z <= x: while True: z = int(input()) if z>x: break cont = 1 while True: cont+=1 a = x b+=1 x = a+b if x >z: break print(cont)
n = float(input()) if n > 100.01: print('Fora de intervalo') elif n >= 0 and n <= 25.00: print('Intervalo [0,25]') elif n >= 25.01 and n <= 50.00 : print('Intervalo (25,50]') elif n >= 50.01 and n <= 75.00: print('Intervalo (50,75]') elif n >= 75.01 and n <= 100.00: print('Intervalo (75...
quant = int(input()) for quantidade in range(1,quant+1): s,r = input().split() #1 if s == "tesoura" and r == "papel": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "tesoura" and s == "papel": print("Caso #{}: Raj trapaceou!".format(quantidade)) #2 elif s == "pape...
n = int(input()) if n % 2 == 0: n = n + 1 else: n = n print("%d"% n) for i in range(1,6): n += 2 print("%d"% n)
ho = int(input()) lista = [] for i in range(ho): lista.append("Ho") lista[-1] = "Ho!" print(" ".join(lista))
# A list is a collection which is ordered and changeable. In Python lists are written with square brackets. thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist) # You access the list items by referring to the index number # Print the second item of the list print("The second e...
a = """This is a multi line string example"""; print(a); # Strings are Arrays a = "Hello, World!" print('The character at position 2 is ' + a[1]) # Slicing # we can return a range of characters by using the slice syntax. b = "Hello, World!" print("The characters of string b from position 2 - 5 excluding 5th position...
''' Exercise 5.1: Fill lists with function values ''' import matplotlib.pyplot as plt from math import exp, pi,sqrt def f(x): y=(1/sqrt(2*pi))*exp(-0.5*x**2) return y initial=-4 h=8./40 xlist=[initial+i*h for i in range(41)] ylist=[f(x) for x in xlist] for x,y in zip(xlist,ylist): print(round(x,2),"\t",round(y,2)) ...
import re from datetime import datetime class Average(object): def __init__(self, lst): self.lst = lst def average(self): """ Function calculates the average of numbers stored in list lst """ # average avg = float(sum(self.lst)) / len(self.lst) if avg < 6: p...
""" Bar and Tick Chart ------------------ How to layer a tick chart on top of a bar chart. """ # category: bar charts import altair as alt source = alt.pd.DataFrame( { "project": ["a", "b", "c", "d", "e", "f", "g"], "score": [25, 57, 23, 19, 8, 47, 8], "goal": [25, 47, 30, 27, 38, 19, 4], ...
# -*- coding: utf-8 -*- """ Created on Tue Oct 17 21:14:09 2017 @author: Isik """ class Reader_Writer(): """ A helper class that contains all the necessary tools for reading and writing text or binary files. Attributes: ifs: Input File Stream. ofs: Output File Stream. ...
import numpy as np a = np.array([1,2,3,4,5,6]) print(a) print("*************************") print(a.ndim) print("*************************") #making an matrix with dtype = int16 b = np.array([[1,2,3],[11,33,55], [88,99,66],[45,55,77]],dtype='int16') #Dimensions of array print(b,b.ndim) print("**********************...
''' Tic Tac Toe is a game for two players, X and O, who take turns marking the spaces in a 3x3 grid. The player who succeds in placing three of their marks in a horizontal, vetical, or diagonal row wins the game. ''' positons = ['0', '1', '2', '3', '4', '5', '6', '7', '8'] print ("Player 1 insert your name") player01...
import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web style.use('ggplot') #validate the date #validate the symbol company_name = input ('please enter the company\'s symbol: ') startdate_entry = input('please choose your start da...
# Comment print "Okay" # YaCmnt print "Test" print 25 + 30 / 6 print 100 - 25 * 3 % 4 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print 3 + 2 < 5 - 7 print "" cars = 100 space_in_a_car = 4.0 drivers = 30 passangers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_c...
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] fruit = set(basket) print(fruit) a = set('abracadabra') print(a) b = set('alacazam') res1 = a - b # letters in a but not in b print(res1) res2 = a | b # letters in either a or b print(res2) res3 = a & b # letters in both a and b print(res3) res...
class Queue: def __init__(self): self.queue = list() def enqueue(self, value): self.queue.append(value) def dequeue(self): return self.queue.pop(0) def isEmpty(self): return len(self.queue) == 0 def size(self): return len(self.queue) #...
''' Leetcode problem 3 : Longest Substring Without Repeating Characters difficulty level : medium Given a string s, find the length of the longest substring without repeating characters. Example 1: # Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "b...
""""""""""""""""""""""""""" 여러 줄 문자열 """"""""""""""""""""""""""" number = int(input("정수 입력> ")) # if 조건문과 여러 줄 문자열(1) if number % 2 == 0: print("""\ 입력한 문자열은 {}입니다. {}는 짝수입니다.""".format(number, number)) else: print("""\ 입력한 문자열은 {}입니다. {}는 홀수입니다.""".format(number, number)) # ...
""""""""""""""""""""""" 복합 대입 연산자 """"""""""""""""""""""" # 숫자 복합 대입 연산자 number = 100 number += 10 # number = number + 10 number += 20 number += 30 print("number:", number) # 숫자 계산 후 대입 # 문자열 복합 대입 연산자 string = "안녕하세요" string += "!" string += "?" print("string:", string) # 문자열 연결 후 대입 string = "...
""""""""""""""""""""""""""" 코드에 이름 붙이기 """"""""""""""""""""""""""" # 주석이 붙어 있는 코드 number_input = input("숫자 입력> ") radius = float(number_input) print(2 * 3.14 * radius) # 원의 둘레 print(3.14 * radius * radius) # 원의 넓이 # 함수를 횔용한 코드 PI = 3.14 def number_input(): output = input("숫자 입력> ") return float(output) ...
""""""""""""""""""""""" while 반복문 """"""""""""""""""""""" # for i in range(10) i = 0 while i < 10: print("{}번째 반복입니다.".format(i)) i += 1 # 해당하는 값 모두 제거하기 ls = [1, 2, 1, 2, 5, 8, 9] value = 2 # list 내부에 value 가 있다면 반복 while value in ls: ls.remove(value) print(ls) # 시간을 기반으로 반복하기 import time unix_time = ...
list1 = [12,-75, 64,-14] for i in list1: if i > 0: print (i) list2 =[ 12,14,-95, 3] for i in list2: if i <=0: list2.remove(i) print (list2)
#!/bin/python3 import sys def designerPdfViewer(h, word): #Calculate the ASCII value of character in the word. For [a - z], the ASCII value is [97 - 122]. Subtract 97 from the obtained ##value and substitute it as the index of array h stating height of each character alphabetically. ##Calculate t...
#!/bin/python3 import sys def findDigits(n): numberString = str(n) result = 0 for i in range(0, len(numberString), 1): digit = int(numberString[i]) if digit!= 0: if n % digit == 0: result = result + 1 return(result) if __name__ == "__main__": t = ...
print('DAY 4 TASK') a=b=c=300 print('data type of a,b,c :',type(a)) print('divide a value by 10') print(a,'/','10','=',a/10) print('multiply b value by 50') print(b,'*','50','=',b*50) print('add c value by 60') print(c,'+','60','=',c+60) code='143js' print('Sting:',code) print('length of the string:',len(cod...
from utils import morse_dict, get_morse_key from morse_functions import morse_to_audio def text_to_morse(text): morse_text = '' text = text.upper() for char in text: if morse_dict.get(char) == None and char != ' ' and char != '\n': print('Caracter \"' + char + '\" eh invalido. ...
def evaluate_tests(func, tests): '''Evaluate func against tests. Test example: tests = [{'input': {'nums': [34, 1]}, 'output': 1}] ''' print('Evaluating tests') for i in range(len(tests)): if func(tests[i]['input']['nums']) == tests[i]['output']: result = 'PASS' else: ...
import abc class PacketPayload(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def bytes(self) -> bytes: """Get packet payload in bytes format""" @abc.abstractmethod def __len__(self): """Get packet payload length""" @staticmethod @abc.abstractmethod def par...
import sys class Graph(object): """ A simple undirected, weighted graph """ def __init__(self): self.nodes = set() self.edges = {} self.distances = {} def add_node(self, value): self.nodes.add(value) def add_edge(self, from_node, to_node, distance): s...
from display import Display import font from keyboard import Keyboard from linked_list import LinkedList from memory import Memory from random import randint from typing import List SPEED = 10 class Cpu: def __init__(self, memory: Memory, display: Display, keyboard: Keyboard): self.memory = memory ...
# -*- coding: utf-8 -*- from config import * import showing as sh from random import randrange as rndt class Barrier: """ этот класс связан со всем, что связано с преградами """ def __init__(self, name, race, health, force, x, y): self.x = x self.y = y self.health = health ...
n=int(input()) while (n != 0): px=input() py=input() while (n): x=input() y=input() if (x == px or y == py): print("divisa") elif (x < px and y > py): print("NO") elif (x > px and y > py): print("NE") elif (x > ...
# Implement a class to hold room information. This should have name and # description attributes. class Room: def __init__(self, name, desc, items): self.name = name self.desc = desc self.items = items def __str__(self): return f"\nYou are here -> {self.name}\n\n {self.desc}...
from abc import ABC class Weapon(ABC): def __init__(self, name): self.name = name class Bow(Weapon): def __init__(self): super().__init__(name='bow') self.arrows = 5 class Sword(Weapon): def __init__(self): super().__init__(name='sword')
import click from flask.cli import with_appcontext def register_commands(app): """Add commands to the line command input. Parameters: app (flask.app.Flask): The application instance. """ app.cli.add_command(add_user_command) @click.command('user') @click.argument('username') @click.arg...
# __author__ = 'Vlad' # l = [] # a = 1,2,"3",4,"5" # for item in a: # l.append(int(item)*3) # print l[int(item)-1]+10 largest = 0 smallest = 0 while True: try: num = (raw_input("Enter a number: ")) if num == "done": break elif num == 'a': raise ValueError ...
# -*- coding: utf-8 -*- """ Utilises the power of matplotlib / seaborn to visualise data sets @author: A00209408 """ import matplotlib.pyplot as plt import matplotlib.dates as mdates import calculationFunctions as stat def apply_boxplot(ax: plt.Axes, data: [], title, y_label) -> plt.Axes: """ Creates and r...
import copy def find_empty_cell(board: list): # self-explanatory? for y in range(9): for x in range(9): if board[y][x] == 0: return x, y return -1 def print_board(board: list): # print-board in console print(" ", end="") for i in range(9): prin...
from datetime import datetime import csv,EmpObject def writeToFile(startDate,endDate): ''' Reads the data from Employee table based on the inputs (startDate & endDate), writes to the CSV file. ''' empf=open('Employee_'+ datetime.now().strftime("%y%m%d%H%M%S") + '.csv','w') writer=csv.writer(empf) ...
# -*- coding: utf-8 -*- """ Created on Thu Jun 29 11:50:30 2017 @author: Moondra """ import threading import time total = 4 def creates_items(): global total for i in range(10): time.sleep(2) print('added item') total += 1 print('creation is done') def crea...
#juan gines ramis vivancos practica 2 ejercicio 3 #saber si un numero es par o inpar print('introduce tu numero') numero = int (input()) mod = numero%2 if mod == 1: print('tu numero es inpar') else: print('tu numero es par')
#Escribe un programa que lea el nombre de una persona y un carácter, le pase estos # datos a una función que comprobará si dicho carácter está en su nombre. # El resultado de dicha función lo imprimirá el programa principal por pantalla. def contar(nombre,carater): if carater in nombre: return(caracter, '...
#juan gines ramis vivancos #Escribe un programa que te pida palabras y las guarde en una lista. #Para terminar de introducir palabras, simplemente pulsa Enter. #El programa termina escribiendo la lista de palabras. palabras=[] print('introduce una palabra') palabra=str(input()) palabras.append(palabra) while palabra !=...
#juan gines ramis vivancos p6ej2 #Escribe un programa que te pida números #y los guarde en una lista. Para terminar de introducir número,simplemente #escribe “Salir”.El programa termina escribiendo la lista de números. print('introduce un numero') numero=int(input()) numeros=[] numeros.append(numero) while numero!=('sa...
print('introduce el dia') dia = int(input()) print('introduce el mes') mes = int(input()) print('introduce el año') año = int(input()) if año>=0: if 0<mes<=12: if mes == 1 or 3 or 5 or 7 or 8 or 10 or 12: if 0<dia<=31: print('fecha correcta') else: pr...
#Escribe un programa que lea una frase, y la pase como parámetro a un procedimiento. #El procedimiento contará el número de vocales (de cada una) que aparecen, #y lo imprimirá por pantalla. def contar_vocal(frase): vocales=['a','e','i','o','u'] contador=[0,0,0,0,0] for i in range(len(vocales)): for...
#juan gines ramis vivancos P4ej5 #Pida al usuario un importe en euros y diga si el cajero automático le #puede dar dicho importe utilizando el mismo billete y el más grande print('introduce la cantidad que quieres sacar') cantidad = int(input()) if cantidad%500 == 0: (billete) = cantidad/500 print('te doy' ,bil...
import turtle as t n = 50 t.bgcolor("black") t.color("green") t.speed(0) for x in range(n): t.circle(80) t.lt(360/n)
print ("Today we will start the installation fase.") answer = input ("Starting the installation. Do you confirm?") if answer == " start": print ("OK! Starting installation.") else: quit() print ("0%...................100%") "/n" print("Installing questions...") "/n" print("Installing question 1/6...") "/...
import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument("--x", type=int, help="the base") parser.add_argument("--y", type=int, help="the exponent") args = parser.parse_args() print(args.x**args.y) print(args.x + args.y) if __name__ == "__main__": main()
# -*- coding: utf-8-*- import xlrd def readExcel(filename,sheetname=''): #文件位置 ExcelFile=xlrd.open_workbook(filename) #获取目标EXCEL文件sheet名 # print(ExcelFile.sheet_names()) #若有多个sheet,则需要指定读取目标sheet例如读取sheet2 #sheet2_name=ExcelFile.sheet_names()[1] #获取sheet内容【1.根...
answer = input("How old are you?") print(answer, "years old!") for i in (a, b, c, d, e): print(i)
poem=("Roses are red, violets are blue, I am really cute, but you look like poo;)") no=("idc", poem) answer = input("Hello!") player = 1 WW = 1 power = "Yes" or "No" choice = "Yes" or "No" op=input("How are you?") if not op.isnumeric(): print("Interesting!") elif op.isnumeric(): print("Wow") response=in...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Use Twitter API to grab user information from list of organizations; export text file Uses Twython module to access Twitter API """ import csv import sys import string import simplejson from twython import Twython #WE WILL USE THE VARIABLES DAY, MONTH, AND YEAR FOR O...
#!/usr/bin/env python #-*-coding:utf-8-*- ''' 给定一个整数数组 nums 和一个目标值 target, 请你在该数组中找出和为目标值的那 两个 整数, 并返回他们的数组下标 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] ''' #解法一 #解题思路:用字典模拟哈希求解,把索引序列添加到字典里["value":"index"] class Solution(): def twoSum(self,nums,target): dic = dict() for in...
from pychallenge.sort.bubble import bubble_sort def test_bubble_sort(): assert bubble_sort([]) == [] assert bubble_sort([0]) == [0] assert bubble_sort([-1, 0, 1]) == [-1, 0, 1] assert bubble_sort([1, 0, -1]) == [-1, 0, 1] assert bubble_sort(["a", "c", "b"]) == ["a", "b", "c"] assert bubble_sor...
from enum import Enum from random import random, randrange class PrimeTest(Enum): TRIAL_DIVISION = 0 MILLER_RABIN = 1 class PrimeGenerator: def __init__(self): pass def __del__(self): pass @staticmethod def is_prime(number: int, algorithm: PrimeTest = PrimeTest.MILLER_RABIN...
#包含一个学生类 #一个sayhello的函数 #一个打印语句 class Student(): def __init__(self, name='NoName', age=18): self.name = name self.age = age def say(self): print("hello,my name is '{}'".format(self.name)) def sayHello(): print("非常高兴遇见你") # 此判断语句建议一直作为程序的入口 if __name__ == '__main__': print(...
#1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. #Об окончании ввода данных свидетельствует пустая строка. def __userinfo__(): global u_inf u_inf = [] while True: u_inp = input("Print in what you think about Python: ") u_inf.appe...
# -*- coding: utf-8 -*- """ Created on Fri Jun 9 14:15:48 2017 Script that runs a query on actors and genres tables and stores the result in a json format. @author: Jaya """ import json hostname = 'localhost' username = 'postgres' password = '******' database = 'movie' def doQuery( conn ) : #connect to Postgres ...
class Dog: species = "mammal" def __init__(self,the_sound): self.sound_made = the_sound def sound(self): print(self.sound_made) def bite (self): self.sound() print("Bite") def identify_yourself(self): print("I am a" + self.species) class Bull...
# Herencia y poliformismo class Figura: # #atributos def __init__(self, lado, tamanio): self.nLados = lado self.tLado = tamanio # metodos def mostarNlados(self): print('El numero de ', type, ' es:', self.nLados) def mostrarTlados(self): ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): if root == None: return 0 if root.left == None and root.right == None: return...
types_of_people = 10 x = f"There are {types_of_people} types of people" binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}" print(x) print(y) hilarious = False joke_evaluation = "Isnt the joke funny {} {}" print(joke_evaluation.format(hilarious, "Wooahh")) # the other way of prin...