text
stringlengths
37
1.41M
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ reversed_num = 0 isNegative = False if x < 0: x = abs(x) isNegative = True while x != 0: reversed_num *= 10 reversed_num ...
# -*- coding: utf-8 -*- ''' @author:黄鑫晨 ''' import urllib2 import json def http_post(): url='http://localhost:800/regist' base_nick_name = '小黄人' base_phone_number = '151518586' #for i in range(10, 60): try: nick_name = base_nick_name + str(77) phone_number = base_phone_number + str(...
in_str = input("입력해주세요\n") real_dnjsxmf = "11" real_dnjsxkf = "ab" if real_dnjsxmf == in_str: print("hello!, dnjsxmf") elif real_dnjsxkf == in_str: print("hello!,dnjsxkf") else: print("누구냐")
""" we can! Here's a simple class that adds items to a list only if they are even numbered integers: """ def no_return(): print ("I am about to rain exception ") raise Exception("this is always raised") print ("this line will not execute") return "I won't be returned" def raise_exceptor(): ...
from random import randint c, e = 1, 0 #граница рандома, очки h = [0] def random(h): h[0] = randint(0,c) return #print('В этой игре тебе надо угадать случайное число. С каждым угаданным числом ты получаешь 1 очко, а диапазон увеличивается на 1.') #print() while True: b = int(input('Введи число: ')) ...
## Importing the necessary modules import re import os ## Creating a file path to the source text pyparagraphfile = os.path.join("Resources","paragraph_2.txt") ## Creating an outputfile pyparagraphfile_output = os.path.join("Analysis","parapgraph_analysis.txt") total_letter_count = [] ## Opening and reading the te...
#!/usr/bin/env python3 import argparse import sys from collections import defaultdict def num_paths(start, end, graph): if start == end: return 1 # this final edge is one single path to the end sum_paths = 0 for i, next_vertex_pair in enumerate(graph[start]): next_vertex, paths_from_verte...
#!/usr/bin/env python3 import fileinput if __name__ == "__main__": # Similar to part one, we need to loop over all # the number pairs, calculate the complement, then scan # through the remainder of the list for that complement nums = [int(n) for n in fileinput.input()] for i, num1 in enumerate(nums...
import numpy as np import matplotlib.pyplot as plt def kmeans(data, k=-1): """A function that performs k-means clustering given an mxn input NumPy array.""" if k < 0: print("Please enter a valid k value") else: cluster_labels = np.zeros(data.shape[0], dtype=float) cluster_labels = k...
# 文件的读写 # try: # f = open('read.txt', 'r') # print(f.read()) # finally: # if f: # f.close() # # # with open('read.txt', 'r') as fileReader: # print(fileReader.read()) # # # with open('read.txt', 'r') as fileReader: # for line in fileReader.readlines(): # print(line.strip()) # # w...
#!/usr/bin/env python3 """Module-level comment.""" def main(): bird_weight = float(input("How many ounces of birds are carrying the coconuts? ")) coconut_weight = float(input("How many pounds of coconuts are there? ")) if bird_weight / coconut_weight >= 5.5: print("Yes! Carrying the coconuts is pos...
# Write a Python program to calculate and display the interest on a loan amount (Rupees) using the formula: # interest=(prin cipal * rate of interest * time)/100 principal = 2000 rate_of_interest = 5 time = 5 interest = 0 interest = (principal*rate_of_interest*time)/100 print(interest)
''' Write a python program that displays a message as follows for a given number: If it is a multiple of three, display "Zip" If it is a multiple of five, display "Zap". If it is a multiple of both three and five, display "Zoom". If it does not satisfy any of the above given conditions, display "Invalid". ''' num =...
''' The road transport corporation(RTC) of a city wants to know whether a particular bus-route is running on profit or loss. Assume that the following information are given: Price per litre of fuel = 70 Mileage of the bus in km/litre of fuel = 10 Price(Rs) per ticket = 80 The bus runs on multiple routes having differ...
''' Write a Python function to find all the Strong numbers in a given list of numbers. Write another function to find and return the factorial of a number. Use it to solve the problem. Example: A number is considered to be a Strong number if sum of the factorial of its digits is equal to the number itself. 145 is a St...
# this code will calculate the sum of two numbers using function call def sum(data1, data2): total = data1+data2 return total result = sum(10, 20) print("sum =", result)
# PF-Assgn-39 # This verification is based on string match. # Global variables menu = ('Veg Roll', 'Noodles', 'Fried Rice', 'Soup') quantity_available = [2, 200, 250, 3] '''This method accepts the item followed by the quantity required by a customer in the format item1, quantity_required, item2, quantity_required etc...
#!/usr/bin/env python import threading from time import sleep, ctime loops=[4,2] class ThreadFunc(object): def __init__(self,func,args,name=''): self.name=name self.func=func self.args=args def __call__(self): # apply(self.func,self.args) #self.func(self.args[0],self.a...
""" Author: Zachary Nowak Date:10/31/2017 Program Description: This code can create a passage with random letters, random words, or words from a story """ import random import moduleForCreatingAMatrix def Create(String, length): passage = "" if(String == "Random Letters"): import listOfAllKeys nameDict = list...
def sum(*b): c=0 for i in b: c=c+i print(c) def info(name, **data): print(name) for i,j in data.items(): print(i,":",j) sum(2,3,4,5) info(name='Ankit', age=25, mobile=443434)
# Problema de tipo mochila # Las entradas a usar serán: # PesoMaximo: peso máximo a cargar # PesoElemento: peso de cada elemento # Coeficientes: coeficiente de la funcion objetivo # n: número de variables def ProblemaMochila(PesoMaximo, PesoElemento, Coeficientes, n): # Ya que el problema es de maximización, se ...
#!python2 import json import fresh_tomatoes import media ''' This creates the list of favourite movies. ''' def fetch_from_api(): ''' This reads the json data from file to simulate api call. It should be replace with your own backend api ''' movies = [] try: # Open File to read the m...
#반복문 # for i in range(5): # print("출력") arr=[273,32,103,57,52] for item in arr: print(item) arr2=[1,2,1,3,4,1,5,6,7,8,9] for item in arr2: if(item == 1): arr2.remove(1) print(arr2)
# yield 는 출력하고 다음단계로 넘어감 def test(): print("A 지점 통과") yield 1 print("B 지점 통과") yield 2 print("C 지점 통과") yield 3 # print(list(test())) output= test() print("D 지점 통과") a = next(output) print(a) print("E 지점 통과") b = next(output) print(b) #에러발생 next를 호출할 때 마다 yield값을 할당. 더이상 할당 할 값이 없음 print(...
def factorial(n): output=1 if n==0: return 1 else: return n *factorial(n-1) # for i in range(1,n+1): # output *=i # return output counter = 0 def fibo(n): global counter counter += 1 if(n==1): return 1 if(n==2): return 2 else: ...
import math def euler7(n): count = 3 focus = 5 while(count < n+1): if (isPrime(focus)): count += 1 focus += 2 print(focus-2) def isPrime(x): result = True myList = [i for i in range(3, math.ceil(math.sqrt(x)) + 1, 2)] for n in myList: ...
def euler1(): n = 1000 store = [] for i in range(n): if (i%5 == 0) | (i%3 == 0): store.append(i) total = 0 for x in store: total += x print(total) euler1()
from max_priority_queue import MaxPriorityQueue class Stack: def __init__(self): self.priority_queue = MaxPriorityQueue() self.key = 1 def push(self, val): """ Push an element into the stack. """ self.priority_queue.insert(val, self.key) self.key += 1 def pop(self): """ Remove and return the ele...
class MaxPriorityQueue: def __init__(self): self.heap = [0] self.neg_inf = -9999999 self.inf = 9999999 def is_empty(self): """ Check if a max-priority-queue is empty. >>> q = MaxPriorityQueue() >>> q.is_empty() True >>> q.insert(1, 10) >>> q.is_empty() False """ return self.heap[0] == 0 ...
import random import requests def random_pokemon(): pokemon_number= random.randint(1,151) url='https://pokeapi.co/api/v2/pokemon/{}/'.format(pokemon_number) response=requests.get(url) pokemon = response.json() return { 'name':pokemon['name'], 'id':pokemon['id'], 'height': pokemon['height'], ...
from abc import ABCMeta, abstractmethod from Movement import * ## ## Dit is een abstracte klasse voor alle mogelijke beweging-strategieen. ## class AbstractStrategy : __metaclass__ = ABCMeta ## Constructor bij het vehicle dat deze strategie gebruikt. def __init__(self, vehicle) : self._vehicle = vehicle ## Ge...
""" ### Dice Simulation ### PROBLEM DESCRIPTION We know that a fair S-sided dice would show up one of the numbers 1 through S with equal probability (1/S) at each throw. We also know that a fair coin (a two-sided dice!) would show up heads and tails with equal probability (0.5) at each toss. Note: We may assume...
''' Problem 2 Create a generator that yields "n" random numbers between a low and high number (that are inputs). Note: Use the random library. For example: import random random.randint(1,10) ''' import random def rand_num(low,high,n): for _ in range(n): yield random.randint(low,high) # TEST for n...
''' Exercise 29 - Liquid Volume Calculator Question: Please write a function that calculates liquid volume in a sphere using the following formula. The radius r is always 10, so consider making it a default parameter. Liquid Volume = ((4 * Pi * r**3) / 3) - (Pi * hc**2 * (3 * r - hc) / 3 ) You can then test your...
''' Exercise 27 - Acceleration Calculator Question: Create a function that calculates acceleration given initial velocity v1, final velocity v2, start time t1, and end time t2. The formula for acceleration is: a = (V2 - V1) / (t2 - t1) To test your solution, call the function by inputting values 0, 10, 0, 20 for ...
import time as _time import threading as _threading from time import sleep ''' 多线程 ''' def loop(): print("Thread %s is running ..." % _threading.current_thread().name) n = 0 while n < 5: n += 1 print("Threading %s >>> %s" % (_threading.current_thread().name, n)) _time.sleep(1) ...
#a) cantidad de vocales en la frase #b) cuantas letras en total existen en la frase #c) porcentaje de vocales respecto al total de letras texto = "hoy es un lindo dia para comer un asado" texto += "." cvocal = cletras = 0 print(texto) for i in texto: if i.isalpha(): if i in ("a", "e", "i", "o", "u"): ...
_author_ = 'JORGE NAHUEL AQUINO' #titulo y carga de datos print("Ejercicio nro 11 - Palabra enmascarada") palabra = input("Ingrese una palabra: ") #procesos.. tam = len(palabra) #visualizacion de resultados print(palabra[0]+'X'*(tam - 2)+palabra[tam-1])
_author_ = 'JORGE NAHUEL AQUINO' #titulo general y carga de datos print("Ejercicio nro 2 - Fecha como cadena") date = input("Ingrese una fecha con formato 'dd/mm/aaaa' : ") #procesos.. dia = date[0] + date[1] mes = date[3] + date[4] anio = date[6] + date[7] + date[8] + date[9] #visualizacion de resultados.. print(...
x=float(input("Ingrese el valor de la suma de los angulos alfa + beta : ")) y=float(input("Ingrese el valor de la diferencia de los angulos alfa - beta : ")) alfa=(x+y)/2 beta=x-alfa print("El valor del angulo alfa es : ",alfa,"\nEl valor del angulo beta es: ",beta)
monto_inical=float(input('Ingrese el monto actual del medicamento: ')) Desc=monto_inical*0.35 monto_final=monto_inical-Desc print("El monto inicial del medicamento es: $",monto_inical,"\nEl descuento del 35% es: $ ",round(Desc,2),"\nEl monto final a pagar es: $",round(monto_final,2))
# Desarrollar un programa en phyton que permita cargar por teclado una secuencia de numeros, uno por uno. # Siempre se supone que el usuario cargara un 0 (cero) para indicar el fin del proceso de carga. # El cero no debe considerarse un dato a procesar. El programa debe. # a) Determinar el porcentaje que cantidad de nu...
_author_ = 'JORGE NAHUEL AQUINO' #constantes del programa INC = 0.080 DES = 0.025 CAMPO1 = 'NOMBRE DEL EMPLEADO: ' CAMPO2 = 'NUEVO SALARIO: ' CAMPO3 = 'ÁREA FUNCIONAL: ' CAMPO4 = 'SALARIO ACTUAL: ' #titulo y carga de datos print("Ejercicio nro 6 - Calculo de sueldo ") nom_emp = input("Ingrese el nombre del empleado:...
<<<<<<< HEAD ======= from board import Board >>>>>>> 1c3518085d0112dea8e44579fc08e2aeb4ae406f import pygame pygame.font.init() BLACK = (0, 0, 0) class GuiBoard: def __init__(self, row, col, height, width): """"Intializes the board """ self.row = row self.col = col self.height = ...
while True: try: name = int(input('enter name')) break except: print('error') finally: print('Attemped input')
# import numpy as np # def plus(s1,s2): # return s1+s2 # def minus(s1,s2): # return s1-s2 # def scal(s1,s2): # res = s1*s2 # return [ round(i,3) for i in res] # # return round(s1 * s2,3) # s1 = np.array([8.218,-9.341]) # s2 = np.array([-1.129,2.111]) # print(plus(s1,s2)) # s3 = np.array([7.119,...
class MyClass: name = "RAVI"; contact ="7396625277" def __init__(self, uname): self.name= uname print self.name; def instanceMethod(self): print self.name ,self.contact return self @staticmethod def staticMethod(): print "Im From Static Method" @classmethod ## class method is nothing but alternate...
a = ["sdf" ,"sdfhsk","wry","daasdash"] b = [ x for x in a if x.endswith("y")] print b
def decoreter_fun(fun): def inner(): print("X"*20) fun() print("Y"*20) return inner def say_hellow(): print("hellow World") #Way 1 # decoretor normal Way dec = decoreter_fun(say_hellow) # delete decoreter_fun from memory for closer #del decoreter_fun dec() #Way 2 @decoreter_fun def say_hellow_tow():...
# Lista con multiplos de tres que también son múltiplos de cinco multiplos_tres = [num for num in range( 1, 101) if num % 3 == 0 and num % 5 == 0] print(multiplos_tres)
# Convertir una cadena de caracteres a una lista cadena = 'Una cadena de texto' lista = list(cadena) print(lista) # Convertir una cadena a una listas print(''.join(lista)) # Convertir lista en tupla tupla = tuple(lista) print(tupla) # Diccionarios dict = {1: 'hi', 'a': 'world'} print(list(dict)) # solo hace una ...
import pandas as pd serie1 = pd.Series([6, 12, 3], index=['dia', 'mes', 'año']) print(serie1) serie2 = pd.Series({'dia': 26, 'mes': 5, 'año': 2021}) print(serie2) frame1 = pd.DataFrame({'dia': [25, 26], 'mes': [5, 5], 'año': [2021, 2021]}) print(frame1) frame2 = pd.DataFrame([[65, 25, 87], [45, 67, 57], [ ...
palabra = 'una palabra' # Imprimir cada caracter de la cadena for letra in palabra: print(letra) # Con la funcion enumerate podemos acceder al indice de # cada caracter e imprimirlo for index, letra in enumerate(palabra): print(index, letra)
def calc_three_numbers_average(num_1, num_2, num_3): # num_1 = input("Write the first number: ") # num_2 = input("Write the second number: ") # num_3 = input("Write the third number: ") average = (int(num_1) + int(num_2) + int(num_3)) / 3 message = f"The average is {average}" print(message) ca...
#Write a python program using tkinter interface to write Hello World and a exit button that closes the interface. # from tkinter import * # root=Tk() # b=Button(root,text="hello world") # b.pack() # b1=Button(root,text="exit",command=exit) # b1.pack() # root.mainloop() # Write a python program to in the same interface...
# Q1- Create a database. Create the following tables: # 1. Book # 2. Titles # 3. Publishers # 4. Zipcodes # 5. AuthorsTitles # 6. Authors # Refer to the diagram below import pymysql as py db=py.connect("localhost","root","**","library") book='create table book(book_id char(40),title_id char(40),location char(40),gr...
def Hello(name): print("Hello" + " " +name) x=input("Enter your name: ") y= Hello(x)
import random as random def programa(): count = 1 def generator(): temp="" for i in range(5): temp = (temp + str(random.randint(0,9))) print(temp) return temp num = generator() while num != str("69420"): num = generator() count ...
import unittest from mathgenerator import MathGenerator from repositories.user_repository import user_repository class TestMathgenerator(unittest.TestCase): def setUp(self): self.generator = MathGenerator() def test_check_answer(self): task = self.generator.gen_addition_task() correcta...
import numpy as np class Node: def __init__(self, label, goal_distance): self.label = label self.visitaded = False self.adjacent = [] self.goal_distance = goal_distance def add_adjacent(self, adjacent): self.adjacent.append(adjacent) def show_adjace...
# Authors: Derek Lance # Patrick Farrell # Course: CSC 466 # Assignment: Lab 1 # Term: Fall 2018 # Input: File name (string) to be read into the program # File is expected to be in .csv format with m lines of n entries # Output: An mxn list of frozensets where each frozenset is a ma...
#takes a folder of provided .jpg images and creates base64 copies, placing them in a specified folder def base64creator(): import os, base64 from os import walk from os import listdir from os.path import isfile, join os.chdir("C:/Users/Noble/Pictures/AlbumArt") imgs = [] for name in os.listdir("C:/Users/Noble/Pi...
import colorama from termcolor import cprint # Activates the color in the console without this there would be no colors colorama.init() def yesNo(): """A simple prompt for a yes or no question that returns true or false Returns: boolean: Yes is True, No is False """ print('y for Yes') pri...
import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) if 0 < n < 101: if (n%2 == 1) or (n in range(6,21) and n%2 == 0): n = "Weird" elif (n%2 == 0 and n in range(2,6)) or (n > 20 and n%2 == 0): n = "Not Weird" print(n)
count = int(input()) valores = [int(x) for x in input().split()] valores = valores[(-1)*count::] multiplos = [2,3,4,5] for valor in multiplos: multiplo = [1 for x in valores if x%valor == 0].count(1) print(''.join([str(multiplo), ' Multiplo(s) de ', str(valor)]))
dias = int(input()) anos = int(dias/365) meses = int(dias%365/30) dias = int(dias%365%30) print(str(anos)+' ano(s)') print(str(meses)+' mes(es)') print(str(dias)+' dia(s)')
valor_n = int(input()) valores = [int(x) for x in input().split()] is_nlogonia = 1 base = '' for x in range(valor_n): if x == 0: if valores[x] == valores[x+1]: is_nlogonia = 0 break elif valores[x] < valores[x+1]: base = 'menor' elif valores[x] > valores[x...
valorX, valorY = [int(x) for x in input().split()] valores = [] count = 0 for x in range(1, valorY+1): if len(valores) > 0 and len(valores[count]) == valorX: count += 1 if len(valores) > 0 and (count+1) <= len(valores): valores[count].append(x) else: valores.insert(count, [x]) for ...
def hasDifferentValues(numbers): valorA, valorB = numbers return valorA != valorB listResults = [] while len(listResults) == 0 or hasDifferentValues(listResults[-1]): valorA, valorB = [int(x) for x in input().split()] listResults.append([valorA, valorB]) listResults.pop() for result in listResults: ...
def isTriangle(valorA, valorB, valorC): isAPlusBBiggerThanC = valorA+valorB > valorC isBPlusCBiggerThanA = valorB+valorC > valorA isAPlusCBiggerThanB = valorA+valorC > valorB return isAPlusCBiggerThanB and isBPlusCBiggerThanA and isAPlusBBiggerThanC valorA, valorB, valorC = [float(x) for x in input().s...
print('-'*39) showDecimalTitle = False showOctalTitle = False showHexadecimalTitle = False for x in range(39): if (x+1) in [1, 13, 23, 39]: print('|', end='') elif not showDecimalTitle and x+1 in range(4, 4+len('decimal')): print('decimal', end='') showDecimalTitle = True elif not sh...
number = int(input()) lastNumber = 11 if number%2 == 0: number += 1 for x in range(number, (number+lastNumber), 2): print(x)
numAtletas = int(input()) for x in range(numAtletas): name = str(input()) notaPartida = float(input()) notasJuizes = [float(y) for y in input().split()] notasJuizes.sort() notasJuizes.pop(0) notasJuizes.pop(-1) notaFinal = sum(notasJuizes)*notaPartida print(' '.join([name, '{:.2f}'.form...
valor_a, valor_b, valor_c = [int(x) for x in input().split()] if valor_a > valor_b: if valor_c > valor_b: print(':)') elif valor_b - valor_c < valor_a - valor_b: print(':)') else: print(':(') elif valor_a < valor_b: if valor_c < valor_b: print(':(') elif valor_b - va...
combustivelList = [] while True: combustivel = int(input()) if combustivel == 4: break elif combustivel in [1,2,3]: combustivelList.append(combustivel) countAlcool = len(list( filter(lambda combustivel: combustivel == 1, combustivelList) )) countGasolina = len(list( filter(lambda c...
repeticoes = int(input()) raiz2 = 1 fracao = 1/2 if repeticoes == 0: print('{:.10f}'.format(raiz2)) else: for x in range(repeticoes-1): fracao = 1 / (2+fracao) print('{:.10f}'.format(raiz2 + fracao))
import numpy as np print("PROGRAM MATRIKS") B = int(input("Masukan jumlah baris:")) K = int(input("Masukan jumlah kolom:")) print("Masukan angka isi dari matriks dalam satu baris (pisahkan dengan spasi): ") # User input of entries in a # single line separated by space entri = list(map(int, input().split()...
class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ amount_list = [] amount_list = [-1] * (amount + 1) amount_list[0] = 0 for i in range(amount + 1): for c in co...
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ complements = {} for i in range(len(nums)): if nums[i] in complements: return [complements[nums[i]], i] ...
#Create a function(or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. def even_or_odd(n): return 'Even' if n % 2 == 0 else 'Odd'
""" Simple challenge - eliminate all bugs from the supplied code so that the code runs and outputs the expected value. Output should be the length of the longest word, as a number. There will only be one 'longest' word. """ def find_longest(string): spl = string.split(" ") longest = 0 i=0 while (i < l...
# 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 from collections import deque class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: # if no root...
def factorial(n): num = 1 if n<1: print "the number is less than 1" else: while n >= 1: num = num * n n = n - 1 return num print factorial(6)
# 19. Write a Python program to create Fibonacci series upto n using Lambda. from functools import reduce def fib_series(n): return reduce( lambda x, _: x+[x[-1]+x[-2]], range(n-2), [0, 1]) print(fib_series(5)) # Reference # https://www.w3resource.com/python-exercises/lambda/python-lambda-exercise-10.php
# 23. Write a Python program to check a list is empty or not. l = [] print("List is not empty.") if l else print("List is empty")
# Write a Python script to merge two Python dictionaries. d1 = {'name': 'James', 'age': 20} d2 = {'gender': 'male', 'country': 'Nepal'} dict = {} for d in [d1, d2]: dict.update(d) print(dict)
# 22. Write a Python program to remove duplicates from a list. l = ['a', 'b', 'a', 'c', 'f', 'c', 'b', 'g', 't', 'c'] new_l = list(set(l)) print(new_l)
# 2. Write a Python function to sum all the numbers in a list. # Sample List : (8, 2, 3, 0, 7) # Expected Output : 20 def sum_of_list(lst): total_sum = sum(lst) return total_sum print(sum_of_list([8, 2, 3, 0, 7]))
# 30. Write a Python script to check whether a given key already exists in a # dictionary. dict = { 'name': 'James', 'age': 20, 'gender': 'male' } key_check = 'name' if key_check in dict.keys(): print("Key already exists.") else: print("Key does not exists.")
# 45. Write a Python program to find the index of an item of a tuple tup = ('Nepathya', '1974 AD', 'Albatross', 'The Edge Band') index_tup = tup.index('1974 AD') print(index_tup)
# 9. Write a Python function that takes a number as a parameter and check the # number is prime or not. # Note : A prime number (or a prime) is a natural number greater than 1 and that # has no positive divisors other than 1 and itself. def check_prime_number(num): if num == 1: print('It is not a prime nu...
import random counter=1 MAX_NO_OF_ATTEMPTS=6 print("\t*************Start the game*************") num = random.randrange(0,100) while counter<=MAX_NO_OF_ATTEMPTS: num1 = int(input("Please enter any number between 0-100: ")) if(num1==num): print("\t-----Congrats!!!You guessed it right in ",counter,"attem...
def largest_product(num_list): if len(num_list) < 3: raise IndexError('need at least three numbers') max_product_of_2 = num_list[0] * num_list[1] min_product_of_2 = max_product_of_2 max_num = max(num_list[0], num_list[1]) min_num = min(num_list[0], num_list[1]) max_product_of_3 = num_list[0] * num_list...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Kółko i krzyżyk Komputer gra w kółko i krzyżyk przeciwko człowiekowi """ # stałe globalne X = "X" O = "O" EMPTY = " " TIE = "TIE" NUM_SQUARES = 9 # wyświetla zasady gry i obsługi programu def display_instruct(): """Wyświetl instrukcję gry.""" print( """ ...
#day 8 #star 15 with open('day8.txt', 'r') as f: nums = [line.strip().split() for line in f.readlines()][0] nums = [int(x) for x in nums] hashes = [] #returns a tuple, the firs tbeing the trivial total (Part 1) the second being the carried value between nodes (Part 2), #and the shortening of the list as more an...
import os import multiprocessing from time import time def f(x): for i in range(10): x = x * x * x return x if __name__ == '__main__': numbers = 10000 # Using multiprocessing pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()) begin_time = time() pool.map(f, range(...
from flask import Flask from geo import distance_bp ''' Main Flask Server Program Will register Blueprint for MKAD distance ''' app = Flask(__name__) app.register_blueprint(distance_bp, url_prefix='/mkad') @app.route('/') def index(): return ''' <h3>Ths project is to calculate distance between MKAD to sp...
import math n = int(input()) even_num = 0 odd_num = 0 total_num = 0 even = "" odd = "" for i in range(n): if(i % 2 == 0): even += 'C' odd += '.' even_num += 1 else: even += '.' odd += 'C' odd_num += 1 if (n < 3): print(n) else: total_num += odd_num * (n ...
a=int(input("첫 번째 숫자를 입력하세요 : ")) b=int(input("두 번째 숫자를 입력하세요 : ")) print(a) print(b) print(100) print("a") print(a+b) print(a, "+", b, "=", a+b) result=a+b print(a, "+", b, "=", result) result=a-b print(a, "-", b, "=", result) result=a*b print(a, "*", b, "=", result) result=a/b print(a, "/", b, "=", result)
#!/usr/bin/env python3 import pandas as pd import os, re from functions import options, choose_separator, filter_value, choose_format pd.set_option('display.max_columns', None) os.system("clear") headings= {'head1':"open file", 'head2':"sort section", 'head3':"filter section", 'head4':"save file"} # Source Info while...