text
stringlengths
37
1.41M
# Enter your code here. Read input from STDIN. Print output to STDOUT if __name__ == '__main__': N = int(input()) X = list(map(int, input().split())) W = list(map(int, input().split())) weighted_mean = round(float(sum([x * w for x, w in zip(X, W)])) / sum(W), 1) print(weighted_mean)
def add(a,b): print "ADDING %d + %d" % (a,b) return a+b def substract(a,b): print "SUBSTRACTING %d - %d" % (a,b) return a-b def divide(a,b): print "DIVIDING %d / %d" % (a,b) return a/b def multiply(a,b): print "MULTUPLYING %d * %d" % (a,b) return a*b result = add(24, substract(divide(34,100),1023)) pri...
import tkinter window = tkinter.Tk() window.title('My first gui program') window.minsize(width=500, height=300) # label my_label = tkinter.Label(text='I am a label', font=('Arial', 24, "bold")) my_label.pack() # places it on the screen, centered # button def button_clicked(): print('I got clicked.') if len...
from turtle import Turtle, Screen import random race = False screen = Screen() screen.setup(width = 500, height = 400) bet = screen.textinput("Make your bet", 'Which turtle will win the race? Enter a color: ') colors = ['red','orange','yellow','green','blue','purple'] turtles = [] for num, color in enumerate(colors):...
from turtle import Screen, Turtle import pandas as pd from map import Map from map_game import Game df = pd.read_csv('50_states.csv') df['state'] = df['state'].apply(lambda x: x.lower()) map = Map() game = True while game: answer_state = map.user_input() if answer_state in df['state'].values: map.upd...
##################### Extra Hard Starting Project ######################] import smtplib import datetime as dt import pandas as pd import random # 1. Update the birthdays.csv now = dt.datetime.now() month = now.month day = now.day df = pd.read_csv('birthdays.csv') # 2. Check if today matches a birthday in the birthda...
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #First *fork* your copy. Then copy-paste your code below this line 👇 #Finally click "Run" to execute the tests true = ['t','r...
inicio=0 while(inicio<=100): if(inicio%3==0): print("Numeros Divisibles por 3") inicio+=1
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' Sum of Left Leaves 題目: 加總整棵樹左邊的子葉 想法: - 沒有樹回傳0 - 判斷是不是葉 - 左葉回傳原本的值,右葉回傳零 - 並在方入葉的時,紀錄是不是左邊 - 遞迴 Time: O(n) Space: O() ''' class Solution(objec...
''' Kth Largest Element in an Array 題目: 找出第 k 個最大的元素 想法: - 利用 Heap 回傳最小並且不改變父類別最小的特性 - 每個數變負數後,原本最大的數,會被先返回 - 跑 k 次迴圈取出,最後一個取出的就是第 k 個最大的元素 - 還原成正數 Time: O() Space: O() ''' import heapq class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int ...
''' 513. Find Bottom Left Tree Value [題目] 在樹中找最深且最左邊的值 [思考] 最深優先權最高,依樣深選最左邊 DFS 我要記住目前最深的,還要知道我是該層最左邊的 BFS 由右至左,一層一層下去,最後一個值就是我們的答案 ''' from Queue import Queue class Solution(object): def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype int """ queue = Queue...
def bruter(lis, maximum, num_max): err = 0 shouldpass = 0 while len(lis) <= maximum: try: bruterhand(lis) except NameError: print("[!]you should define a func called bruterhand() to use the output of this func[!]") err = 1 if err == 1: ...
""" These are the unit tests for the calculator library """ import calculator class TestCalculator: def test_addition(self): assert 40 == calculator.addition(20, 20) def test_subtraction(self): assert 2 == calculator.subtraction(4, 2) def test_multiplication(self): assert 16 ==...
def main(): x = eval(input("Unesite 1: ")) y = eval(input("Unesite 2: ")) c = x+y print(c) main() # Programi # Programi
"""Importamos la libreria math, para poder llevar a cabo operaciones matematicas""" import math """Valor al que sacaremos su raiz cuadrada, se ha identificado con una x""" x = 100 """Se ocupa la funcion math.sqrt, la cual nos permite obtener la raiz cuadrada de un numero""" print(math.sqrt(x)) """Definimos el obj...
class node: def __init__(self,power,prefix): self.power=power self.prefix=prefix self.nextNode=None class linked: def __init__(self): self.head=None def printer(self): search=self.head while(True): if search==None: break ...
counter = 0 sum = 0 while True: inputNumber = input() # Integer input try: number = int(inputNumber) isPrime = True canDivideby10 = False if number%10 == 0: canDivideby10 = True else: if number < 2: isPrime = False ...
#Write a function to print "hello_USERNAME!" USERNAME is the input of the function. #The first line of the code has been defined as below. def hello_username (username): return username=str(input("enter username : ")) print(f"Hello " + str(username))
# -*- coding: utf-8 -*- """ Created on Mon Nov 30 22:52:19 2020 @author: convi """ #11.Crie um programa para ler uma string fornecida pelo usuário. Informe se essa stringforma um palíndromo. palavra = input("") for i in range(int(len(palavra)/2)): if(palavra[i] != palavra[-i - 1]): print("não é palindro...
import networkx as nx import matplotlib.pyplot as plt U=nx.Graph() #undirected graph G=nx.DiGraph() #Directed graph print(G.nodes()) G.add_nodes_from([i for i in range(10)]) print(G.edges()) #by default show outgoing edges G.add_edge(1,2) G.add_edge(0,2) G.add_edge(1,3) G.add_edge(3,1) G.a...
#输入三角形的三个变长,求三角形的周长和面积 #注意两边之和大于第三边,两边之差小于第三边 #注意三角形三边的面积公式 def is_angle(a,b,c): if a + b > c and a + c >b and b + c > a and a - b< c and a - c < b and b - c < a: return True else: return False def perm_angle(a,b,c): if is_angle(a,b,c): return a + b + c else: return 0 def aera_angle(a,b,c): if is_a...
#将输入的话是温度转换成摄氏温度 #公式是:c = (f - 32) / 1.8 # # f = float(input("请输入华氏温度:")) c = (f -32) / 1.8 print('%.1f 华氏度 = %1.f 摄氏度'%(f,c))
# 使用变量保存数据,并进行算术运算 # a = 123 b = 321 print(a + b) print(a * b) print(a - b) print(a / b) #取整数运算 print(a // b) #取模运算 print(a % b) #指数运算 print(a ** 2) print('*'*20) # 使用type() 检查变量类型 # a = 123 b = 12.345 # 1 + 5j 和 1 + 5J 是一样的 c = 1 + 5J d = 'hello world' e = True #注意首字母大小写的问题 print (type(a)) print (typ...
#使用while循环 #while 循环使用时候,可以不用知道循环次数,while True: #可以使用break,终止循环 #可以使用continue,结束本次循环,进入下一次循环 # #猜数游戏 # import random answer = random.randint(1,100) count = 0 while True: value = float(input('请输入结果:')) if value > answer: print('答案偏大,需要小一点') count += 1 elif value < answer: print('答案偏小,需要大一点') count += 1 ...
class Node: def __init__(self, value): self.value = value self.next = None class Slist: def __init__(self, value): node = Node(value) self.head = node def addNode(self, value): node = Node(value) runner = self.head while (runner.next != None): ...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ p = t = ListNode(0) c...
import turtle import random kucha = random.randint(5, 25) #kucha = 10 radius = 15 win = turtle.Screen() alex = turtle.Turtle() alex.speed("fastest") row_count = 1 max_in_kucha = 1 while kucha > max_in_kucha: row_count = row_count + 1 max_in_kucha = max_in_kucha + row_count alex.write(str(kucha)) alex.penup()...
n = int(input()) cub = 3 ** n fact = 1 for i in range(1, n + 1): fact = fact * i print(cub, fact)
# Dynamic Function def get_func_mult_by_num(num): def mult_by(value): return num * value return mult_by generated_func = get_func_mult_by_num(5) print("5 * 10 = ", generated_func(10)) def testing_function(number1): def inner_func(number2): return number1, number2 return inner_func ...
# -*- coding: utf-8 -*- """ Created on Mon Jun 25 19:51:43 2018 @author: joshu """ import math import random # Recursive Factorial def factorial(num): if num <= 1: return 1 else: result = num * factorial(num - 1) return result print(factorial(4)) def recursive_factorial(num): if nu...
# -*- coding: utf-8 -*- """ Created on Mon Jun 25 09:38:48 2018 @author: joshu """ import random def bubble_sort(unsorted_list): i = len(unsorted_list) - 1 while i > 1: j = 0 while j < i: #print("\nIs {} > {}".format(unsorted_list[j], unsorted_list[j + 1])) if uns...
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 11:27:53 2018 @author: joshu """ # Will provide different outputs based on age # 1-18 -> Important # 21, 50, or > 65 -> Important # All others -> Not Important # age = eval(input("Please enter your age: ")) if ((age >= 1) and (age <= 18)): print("IMPORTANT") el...
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 20:31:22 2018 @author: joshu """ import random import math # 1. An outer loop decreases in size each time # 2. The goal is to have the largest number at the end of the list # when the outer loop completes 1 cycle # 3. The inner loop starts comparing indexes at...
# Prime number generator def isPrime(num): for i in range(2, num): if (num % i == 0): return False return True def gen_Primes(max_number): for num1 in range(2, max_number): if isPrime(num1): yield num1 prime = gen_Primes(50) print("Prime :", next(prime)) print("Pr...
import random try: aList = [1,2,3] print(aList[3]) except (IndexError,NameError): print("Sorry that index doesnt exist") except: print("An unknown error occurred") class DogNameError(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) try: dogNa...
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 12:10:26 2018 @author: joshu """ # Have the user enter their investment amount and expected interest # Each year their investment will increase by their investment + their # investment * interest rate # Print out the earnings after a 10 year period money, inte...
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 15:18:15 2018 @author: joshu """ from decimal import Decimal as D sum = D(0) sum += D("0.1") sum += D("0.1") sum += D("0.1") sum -= D("0.3") print("Sum = ", sum) print("0.1 + 0.1 + 0.1 - 0.3 = ", (0.1 + 0.1 + 0.1 - 0.3))
# Given list of ints, return True if any two nums in list sum to 0. # Given the wording of our problem, a zero in the list will always make this true, # since “any two numbers” could include that same zero for both numbers, and they sum to zero # This function isn’t implemented, though, so when we run addtozero.py, we...
import datetime # 1) Write me Python code that generates all prime numbers between 0 and 100 for num in range(1,101): count = 0 for i in range (2, num//2+1): if num % i == 0: count=+1 break if count == 0 and num != 1: print('%d' %num, end = ' ',) # 2) take a list of ...
#! python3 # Chapter 10 Project - Use Transposition Ecryption and Decryption on files import time, os, sys, TranspositionDecrypt, TranspositionEncrypt def main(): #inputFilename = 'frankenstein.txt' inputFilename = 'frankenstein_encrypted.txt' outputFilename = 'frankenstein_decrypted.txt' key = 10 ...
''' 1. 按照经验将不同的变量储存为不同类型的数据 2. 验证这些数据是何种类型 ''' # int--整型 a = 1 print(type(a)) # float--浮点型 b = 1.1 print(type(b)) # str--字符型 c = 'trash' print(type(c)) # bool--布尔型(逻辑判断--True&False) d = False print(type(d)) # list--列表 e = [10,20,30] print(type(e)) # tuple--元组 f = (10,20,30) print(type(f...
a = 10 a += 1 # a = a + 1 print(a) a = 10 a = a + 1 print(a) b = 9 b -= 1 # b = b - 1 print(b) # 相似的,还有*=, /=, //=, %=, **= 等等 c=8 c /= 4 print(c) c **= 5 print(c) # 扩展 d = 10 d += 1 + 2 # 是先算1+2=3,然后是d += 3? 还是先算d += 1 再加2? print(d) e = 10 e *= 2 + 3 print(e) # 注意:从加法没法看出来,但从乘法赋值可以看出...
from math import trunc n = float(input('Digite um número:')) int = trunc(n) print('O número {} tem a parte inteira {}'.format(n, int))
print('DESCONTO') p = int(input('Qual o preço do produto?')) d = int(input('Quanto de desconto será dado?')) de = (d*p)/100 f = p-de print('O preço do produto com {}% de desconto fica por {} reais.'.format(d, f))
# apis_tb.py # Creator: Alejandro Balseiro # Last review: 22/01/2021 by Javier Olcoz import pandas as pd import numpy as np import json import requests class Apis: def checker(self, url_complete): """ @Alex Function that helps us to make the call to the server to recieve the appropiate ...
import guiatv import guiatv guiatv.opciones() numero = input('') print('elegiste la opción',numero) if numero == '1': print('¿cuantos canales deseas listar?') cantidad = input('') aenterocantidad = int(cantidadentero) guiatv.listar((cantidadentero+1)) elif numero == '2': guiatv.agregar() elif ...
def check(a, b, c): if (a + b <= c) or (b + c <= a) or (c + a <= b): return False else: return True n = int(input("Enter number of test cases: ")) for i in range(n): a, b, r = [int(x) for x in input("Enter a, b, r: ").split()] num = int(input("Enter number of chopsticks in jar: ")) leng = list(map(int, input...
from turtle import right, left, forward, shape, exitonclick a = int(input("napis hodnotu:")) for d in range(a): for i in range(1): for j in range(2): forward(50) left(60) forward(50) left(60) forward(50) right(60) forward(5...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
#To check whether the string contains all 26 letters. s='Quick zephyrs blow, vexing daft Jim' temp=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] s=s.lower() flag=0 for i in temp: if i not in s: flag=1 break if flag==0: print("Pangram...
def sum(num): if num!=0: return num+sum(num-1) else: return num num=10 print(sum(num))
# Numbers which have repeating Aliquot sequence of length 1 are called Perfect Numbers. For example 6, sum of its proper divisors is 6. # Numbers which have repeating Aliquot sequence of length 2 are called Amicable numbers. For example 220 is a Amicable Number. # Numbers which have repeating Aliquot sequence of length...
#Given three positive numbers a, b and m. Compute a/b under modulo m. #The task is basically to find a number c such that (b * c) % m = a % m. import math def modinverse(b,m): temp=math.gcd(b,m); if temp!=1: return -1 else: return b**(m-2)%m def modular_division(a,b,m): a=a%m inv...
def root(arr,i): while i!=arr[i] : i=arr[i] return arr[i] def find(arr,u,v): if root(arr,u)==root(arr,v): return 1 else: return 0 def weight_union(arr,size,u,v): rootu=root(arr,u) rootv=root(arr,v) if(size[rootu]<size[rootv]): arr[rootu]=arr[rootv] ...
def noOfdigits(num): count=0 while num: num=int(num/10) count+=1 return count num=34545 temp=num revnum=0 digits=noOfdigits(num)-1 while(temp): revnum+=(temp%10)*(10**digits) temp=int(temp/10) digits-=1 print(revnum)
class Empresa: ventas = {0, 0, 0, 0, 0, 0, 0} def __init__(self, name, id): self.name = name self.id = id self.ventas = {} def ventas_totales(self): ventasTotales = 0 for i in self.ventas: ventasTotales += int(i) return ventasTotales def __s...
class Pieza: pass class Tuberia(Pieza): def __init__(self, longitud): self.longitud = longitud def __str__(self): return "Tuberia " + str(self.longitud) + "mm" class Tuerca(Pieza): def __init__(self, diametro): self.diametro = diametro def __str__(self): return ...
# -*- coding: utf-8 -*- """ Created on Sat Aug 1 17:38:24 2020 @author: stuar """ import random class Card(object): ''' Creates the class card, which contains the suit (either Spade, Heart, Club or Diamond) and a value (J,Q,K and A are represented as 11, 12, 13 and 14). ''' def __init__(sel...
# understandiing cryptography problem 2.l import string alphabet = string.ascii_lowercase # ALPHABET_LIST = [alphabet[i] for i in range(len(alphabet))] def create_alphabet_dict(alphabet_list=ALPHABET_LIST): # alphabetを数値かする output_dict = {} for i in range(len(alphabet_list)): output_dict[alphabet_...
a=int(input('Enter the first value')) print(a) b=int(input('Enter the second value')) print(b) temp=a a=b b=temp print("After swapping Your first value is",a,"and Your second value is",b)
# example of program that calculates the total number of times each word has been tweeted. import numpy as np # read text file file = open('tweet_input/tweets.txt','r') #print(file) allWords = np.empty(shape=(0,0)) #print(allWords) # write words in a text file to single array for line in file: # read words in ea...
# non-web GUI's (YAY!) # remember, with WSL you need to launch xming import tkinter # GUI development mainWindow = tkinter.Tk() mainWindow.title("Hello World") # screen resolution # offsets (Where window appears on screen) represented by +/- mainWindow.geometry('640x480+8+400') # GUI design label = tkinter.Label(ma...
# Time Basics # import time # # prints start of epoch as tuple # print(time.gmtime(0)) # # produces current locatime as a tuple # time_here = time.localtime() # print(time_here) # # two ways of outputting the data (via tuple index, or through built in # # methods) # print("Year:", time_here[0], time_here.tm_year) # ...
val=int(input("enter a value") if(val%400==0): print(val,"is leap year") else print(val,"is not a leap year")
"""Pixelflut is a TCP server screen inspired by the pixelflut project of the CCC Göttingen (https://cccgoe.de/wiki/Pixelflut). It uses the core python libraries and will not rely on other libraries. There is a server and a client component in this package. The server listens for packets with commands as content. The f...
import pprint from collections import defaultdict from google.cloud import translate def statement_request(): entry = input("Enter a phrase for us to deconstruct:\n").lower() return entry def deconstruct(entry): """ Function to create a deconstructed list of the statement letters :param entry: T...
#The python program String to MD5 hash method #Ajith R B import hashlib; string=input ("Enter the String to MD5 hash:") result = hashlib.md5(string.encode()) print("The hexadecimal equivalent of hash is : ", result.hexdigest())
a=int(input("enter the 1st num")) b=int(input("enter the 2nd num")) c=input("enter operation") if(c=="add"): print(a,"+",b,"=",a+b) elif(c=="sub"): print(a,"-",b,"=",a-b) elif(c=="mul"): print(a,"*",b,"=",a*b) elif(c=="div"): print(a,"/",b,"=",a/b) else: print("enter any operators like a...
def checkio(text): text=text.lower() y=0 for i in text: if ord(i)>=97 and ord(i)<=122: if text.count(i)>y: y=text.count(i) z=i if text.count(i)==y: if ord(z)>ord(i): z=i return z print chec...
from abc import abstractmethod, ABC class Beverage(ABC): description: str = "Unknown beverage" def get_description(self): return self.description @abstractmethod def cost(self): pass
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right numbers = [] class Solution: def recoverTree(self, root: TreeNode) -> None: """ Do not return anyth...
import sqlite3 def connect(): conn = sqlite3.connect("bookstore.db") cur = conn.cursor() cur.execute( "CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)") conn.commit() conn.close() connect() def insert(title, author, year, isb...
# https://leetcode.com/problems/power-of-three def isPowerOfThree(n): """ :type n: int :rtype: bool """ if n < 1: return False while n % 3 == 0: n /= 3 return n == 1
# -*- coding: utf-8 -*- """ Created on Wed Apr 12 15:32:09 2017 @author: Artem Los """ nums = {} # REMOVE LATER def popWithSquares(a, b, p): for x in range(p): #y2 =( x*x*x+a*x+b )% p if x**2%p in nums: nums[x**2 % p].append(x) else: nums[x**2 % p] = [x] ...
class Assignments: def __init__(self, name, max_score, grade): self.name = name self.max_score = max_score self.grade = grade def Assignment(self, name, max_score): self.name = name self.max_score = max_score self.grade = None def assign_grade(self, grade):...
def is_isogram(string: str) -> bool: """Checks if a given string is an Isogram (ie. no repeated chars) Parameters: string the given string Retunrs: ======== True, if string is an isogram False, otherwise """ # Controls whether a char has already appeared or not char_...
### Chapter 6: Python 101 :Jimmy Moore ### # Ex. 6.1 fruit = 'banana' index = len(fruit)-1 while index >=0: letter = fruit[index] print letter, index = index-1 # Ex. 6.2 # fruit[:] is a slice of the full string. full slice? # Ex. 6.3 def counter(string,index): count =0 for letter in string: ...
produto1 = int(input('digite o preço de um produto: ')) produto2 = int(input('digite o preço de um produto: ')) produto3 = int(input('digite o preço de um produto: ')) menor = min(produto1, produto2, produto3) print('compre o de R$' + str(menor) + ' por que é mais barato ')
import math h = input("Podaj wysokosc do uderzenia(m): ") a = 9.8 l = input("Podaj odleglosc do upadku(m): ") tx = math.sqrt(2*l/a) vz = math.sqrt(l*a/2) if vz**2 - 2*a*h < 0 : print "Wprowadzono bledne dane!" else : vo = math.sqrt(vz**2 - 2*a*h); print "Predkosc poczatkowa:",\ vo,\ ...
import random want_more = 'хочу' while want_more == 'хочу': answer = random.randint(1, 10) guess = -1 while answer != guess: guess = input('Введите число: ') try: guess = int(guess) except ValueError: print('Где у вас башка? Я вам сказала введите ЧИСЛО! Вы с...
#!/usr/bin/python def split_numal(val): """Split, for example, '1a' into (1, 'a') >>> split_numal("11a") (11, 'a') >>> split_numal("99") (99, '') >>> split_numal("a") (0, 'a') >>> split_numal("") (0, '') """ if not val: return 0, '' for i in range(len(val)): if not val[i].isdigit(): ...
# DDP LAB-4 # Nama: Evry Nazyli Ciptanto # NIM: 0110220045 # SOAL 1 - Mencetak nama # Tuliskan program untuk Soal 1 di bawah ini print("SOAL 1 - Mencetak nama") nama = input("Masukkan nama: ") # mendapatkan input pengguna i = 0 # set awalan variabel i ke 0 while i < len(nama): # melakukan perulangan sebanyak panjang ...
#! /usr/local/bin/python # -*- coding: utf-8 -*- # 关于字符和字符串的用法几乎都在这里了 print "Hello World!" print 'Hello Again' print "I'd much rather you 'not', or \"not\"" print 'I "said" do not touch this, notice the word \'said\'' print "They are John", "Jack", "Philip" print "What is 3 + 2?", 3 + 2 print "This is first line.", p...
# We are going to create a program where the user is able to enter a magic number however if they pick the number then they win def magic_number(): user_value = input("Enter your magic number beteen 0 - 10: ") if user_value < "10": print ("this is your magic number {} ".format(int(user_value))) elif user_val...
# draw regular polygons with the sparki # # written by Jeremy Eglen # Created: September 13, 2012 (originally for the Scribbler 2 / Fluke) # Last Modified: July 19, 2016 from __future__ import division,print_function from sparki_learning import * def getInteriorAngle(numSides): """ Calculates the interior angle...
"""A class representing a car, with a dependency on an engine""" class Car: """A car that can be turned off and can be inspected""" def __init__(self, engine): self.engine = engine def is_on(self): return self.engine.on def turn_off(self): return self.engine.turn_of...
from Book import Book from BookStore import BookStore case =0 test_case = int(input()) ## 테스트케이스를 받는다. while case<test_case: ## 테스크케이스만큼 반복한다 book = input() ##책의 수와 서점 수를 입력받는다 book_number = int(book[0]) book_store_number = int(book[2]) Book_Store = [0]*book_store_number ## 서점 수만큼의 배열을 만든다 for...
__author__ = 'yihanjiang' import numpy import scipy.optimize as opt def sigmoid(X): return 1 / (1 + numpy.exp(- X)) def cost(theta, X, y): p_1 = sigmoid(numpy.dot(X, theta)) # predicted probability of label 1 log_l = (-y)*numpy.log(p_1) - (1-y)*numpy.log(1-p_1) # log-likelihood vector return log_l.me...
from datetime import timedelta from block_core.blocked import Blocked class DataCache: """ This class represents a time-limited cache of blocked traffic data. By default, it stores the last 10 seconds of data. This cache is approximate, in that each time new data is added, all data older than 10...
import string def format(text, limit, justify): separator = ' ' slice_start = 0 formatted_text = str() #substitui os caracteres que quebra de linha para que o algoritmo possa identificá-los como palavras separadas text_without_line_break = text.replace('\n', ' \n ') #separa o texto inserido usando e...
""" Simple text based progress indicator """ from __future__ import print_function class TextProgress: def track(self, name, at, end, points): print("Fetching track {:s} [{:d}/{:d}] with {:d} points".format(name, at, end, points)) def point(self, at, end): if at % 100 == 0: print...
''' Problem:Remove Nth Node From End of List Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: 1.Given n will always be valid. 2.Try...
''' Problem:Single Number II Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? ''' class Solution(object): def singleNumber(self, nums): """ ...
""" Þú átt að útfæra clasann DiceThrower í honum á að vera Constructor sem skilgreinir hversu marga tenginga notandinn hefur, breytu sem kallar í Dice classan throw fall sem kastar öllum teningunum í lista rethow fall kastar völdum tenginum aftur Einnig áttu að búa til 2 föll Main_menu sem býr prentar út upphafið á le...
lower = int(input("lower: ")) higer = int(input("higher: ")) between = 0 while True: between = int(input("enter number between " + str(lower) + " and " + str(higer) + ":")) if(lower <= between <= higer): print("Gotham city is safe … for now") break
size = int(input("Input size: ")) arr = [] for i in range(size): arr.append(int(input("Enter value {}:".format(i + 1)))) target = int(input("Input target")) # Demo 1 if target in arr: print("{} is in the list.".format(target)) else: print("{} is not in the list.".format(target)) # Demo 2 found = 0 for a ...
def get_file(file_name): try: with open(file_name, "r", encoding="utf-8") as data_file: data_list = [] # start with an empty list for line_str in data_file: data_list.append(line_str.strip().split()) return sorted(data_list) except FileNotFoundError: ...
def lowest_value(nums): return min(nums) def check(length, l): return len(length) == l def main(): for x in range(2, 5): i = [int(ss) for ss in input("Enter " + str(x) + " numbers: ").split(',')] if x == 4: print(lowest_value(i)) else: if check(i, x): ...
def get_value(): val = int(input("Input table size: ")) if 0 < val > 8: print("Invalid size!") exit(0) return val def main(val): for x in range(1, val + 1): print("{}|".format(x), end="") for y in range(1, val + 1): print("{}".format("\t" + str((x*y))), end=...
a = int(input("Integer one: ")) b = int(input("Integer two: ")) print(a + b)