text
stringlengths
5
121k
def SquareRootAlgorithm(VARIABLE): for i in range(0, VARIABLE+1): if( pow(i,2) >= VARIABLE): MULTIPLE = i-1 PROBLEM = VARIABLE-pow(i-1,2) FINAL_ANSWER = MULTIPLE break for i in range(1, 100): PROBLEM = PROBLEM*100 MULTIPLE = (MULTIPLE+(...
print('Please enter a number from the hex number system: ') user = input() output_sentence = 'The decimal number for ' + str(int(user, 16)) print(output_sentence)
numbs=[1,2,3,4,5,6,7,8,9,10] square=numbs.copy() for i in numbs: print(numbs[i]) square[i] = numbs[i]**2 print(square[i]) print("s",square)
class Horse(): """Class for Horse.""" def __init__(self, position, speed, destination): self.position = position self.speed = speed self.time_to_destination = (destination - self.position) / self.speed def find_max_speed(horses): """Finds max speed to reach destination.""" ma...
def information(): print("Please enter the currency you have out of: GBP, USD or EURO: ") currency = input("Please enter the currency you have that you wish to convert: ") amount = int(input("how much do you have?")) return currency, amount def choice(currency, amount): if currency == "GBP": ...
""" Importing Tkinter """ import tkinter as tk from tkinter import Button, Label from wiki_app import * root = tk.Tk() root.title("Randow Wikipedia Article") button_label = Label(root, text="Press the button to generate a Wikipedia page") gen_button = Button(root, text="Generate", command=gen_rand, bg="#F9E178") ...
with open('input') as f: _in = f.read().strip() score = 0 level = 0 ignorenext = False ingarbage = False garbage = 0 for c in _in: if not ingarbage: if c == '{': level += 1 elif c == '}': score += level level -= 1 elif c == '<': ingarbage...
from tkinter import * root = Tk() root.title('Login Center') root.geometry("600x600") root.config(bg="OrangeRed2") l1 = Label(root, text='Login Details:', bg='OrangeRed2', fg='honeydew', font=('Arial', 20, 'bold')) l1.place(x=120, y=10) l2 = Label(root, text='Enter Username : ', bg='OrangeRed2', fg='honeydew', font...
year = int(input("Give the year to be checked for leap year")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print(f"The year {year} is a leap year") else: print(f"The year {year} is not a leap year") else: print(f"The year {year} is a ...
string=input() maximum=0 count=1 for i in range(len(string)-1): if string[i]==string[i+1]: count+=1 else: maximum=max(count,maximum) count=1 print(max(maximum,count))
def count_changes(string,n): count=0 sum_s=0 x=int(string,2) sum_s=int(bin(x).count('1')) if(sum_s==0): count=(len(string)/n) elif(sum_s!=len(string)): p=string[0:n] x=int(p,2) sum_s=int(bin(x).count('1')) if(sum_s==0): count+=1 sum_s=1 string=string[:n-1] + '1' +string[n:] for i in ra...
import threading class Singleton(object): _instance = None def __new__(self): self.lock.acquire() if not self._instance: self._instance = super(Singleton, self).__new__(self) return self._instance self.lock.release() def Accion(accion): for vuelta in ...
n = 100 prime_list = [] for i in range(1, n + 1): count = 0 for j in range(1, i + 1): if i % j == 0: count += 1 if (count < 3) and (i != 1): prime_list.append(i) print(prime_list)
from Vector import * from Curve import Curve class Circle(Curve): C=Vector([0.0,0.0]) r=0.0 def __init__(self,r=1.0,C=None,NP=0): if (C): self.C=C if (NP): self.NP=NP self.r=r self.Closed=True return def R(self,t): ret...
""" Ejemplo17 """ nombre = str(input("Ingrese el nombre de la persona: ")) print("El nombre ingresado es %s\n" % nombre)
""" Ejemplo14 """ bandera = True salir = "" while(bandera): salir = str(input("Desea salir del ciclo; digite: si: ")) salir = salir.lower() if(salir == "si"): bandera = False
""" Ejercicio10 Salida de datos """ import math print((math.sqrt(25)*10)>=100 and (True) or (False) or (10/5 >=2))
def func_multiples(begin,end): output_values=[] for j in range(begin,end+1): if j%7 == 0 and j%5 != 0: output_values.append(str(j)) return ','.join(output_values) print(func_multiples(3000,5300))
def leapCheck(int): if int % 4 != 0: int = str(int) print(int + " is not a leap year") return False else: if int % 100 != 0: int = str(int) print(int + " is a leap year") return True else: if int % 400 != 0: ...
def calculator(x, y, z): if x == ("+"): return y + z elif x == ("-"): return y - z elif x == ("*"): return y * z else: return y / z x = input("Welcome! What opperation would you like to preform (+, -, *, /)? ") y = input("What is the first number? ") y = float(y) z = in...
import random def pick6(): randCount = 0 lotto = [] while randCount < 6: lotto.append(random.randint(1,99)) randCount += 1 return lotto def num_matches(lotto, ticket): winnings = 0 for i in range(len(lotto)): if lotto[i] == ticket[i]: winnings += 1 return winnings balance = 0 winBalance = 0 tryCount ...
madlib = "" a = input("Verb ending in 'ing': ") madlib += f"Espionage is the formal word for {a}. " b = input("Adjective: ") madlib += f"In the shadowy world of spies, a/an {b} organization like the US government " c = input("Adjective: ") madlib += f"uses spies to infiltrate {c} groups " d = input("Plural Noun: ") mad...
ones = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"} tens = {2: "twenty", 3: "thirty", 4: "fourty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety"} def intToEng(x): word = "" if x == "10": return("ten") elif x == "11": return("eleven") elif ...
file = open('words.txt', 'r') f = file.readlines() newList = [] for line in f: if line[-1] == '\n': newList.append(line[:-1]) else: newList.append(line) longWords = [] for word in newList: if len(word) >= 20: longWords.appe...
def has_no_e(word): for letter in word: if letter == 'e': return False return True has_no_e('star') has_no_e('hello') file = open('testWords.txt', 'r') f = file.readlines() wordList = [] for line in f: if l...
import os from itertools import combinations expenses = [] with open(os.path.join('.', 'input.txt')) as f: for line in f.readlines(): expenses.append(int(line)) for a, b in combinations(expenses, 2): if a + b == 2020: print('Found two numbers ({a}, {b}) that sum 2020'.format(**locals())) ...
''' Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "abab" Output: ...
import operator import re ops = { '+': operator.add, '-': operator.sub } pattern = re.compile(r'([0-9]+)([+-]*)') expression = str(input('Enter mathematical expression containing plueses and minues :: ')) stack = 0 operation = None for number, operator in re.findall(pattern, expression): if operation: ...
''' https://leetcode.com/problems/roman-to-integer/ Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Given a roman numeral, convert it to an integer. Input is guaranteed to be within the...
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? Algorithm is based on idea that prime numbers are always of the form 6*k + 1 So we would only check those numbers which can be expressed in 6*k + 1 form ''' from timeit import ...
from timeit import default_timer as timer import math def rwh_prime(upper_bound, number): primes = [True] * upper_bound primes[0] = False primes[1] = False i = 3 limit = int(upper_bound ** 0.5) + 1 while i <= limit: if primes[i]: primes[i*i::2*i] = [False] * ((upper_bound-...
from timeit import default_timer as timer if __name__ == '__main__': test_cases = int(input('Enter test cases :: ')) for t in range(test_cases): number = int(input('Enter number :: ')) start = timer() number -= 1 mux3 = number // 3 mux5 = number // 5 mux...
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? ''' from timeit import default_timer as timer import math def prime_rwh(upper_limit, number): primes = [True]* upper_limit primes[0] = False primes[1] = False...
''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes not greater than given N. Input Format The first line contains an integer T i.e. number of the test cases. The next T lines will contains an integer N. Constraints 1 <= T <= 10^4 1 <= N <= 10^6...
import operator import re ops = { '+': operator.add, '-': operator.sub } expression = str(input('Enter mathematical expression(containing pluses and minues) :: ')) pattern = re.compile(r'([0-9])+([+-])*') operation = None stack = 1 for number, op in re.findall(pattern, expression): if operation: ...
''' n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! Algorithm 4:: Use prime decompositions ''' from timeit import default_timer ...
from timeit import default_timer as timer if __name__ == '__main__': start = timer() number = 1000 number -= 1 upper3 = number // 3 sum3 = 3 * upper3 * (upper3 + 1) // 2 upper5 = number // 5 sum5 = 5* upper5 * (upper5 + 1) // 2 upper15 = number // 15 sum...
from timeit import default_timer as timer import math def isPrime(number): if number % 2 == 0 and number != 2: return False for x in range(3, int(math.sqrt(number)) + 1, 2): if number % x == 0: return False return True if __name__ == '__main__': start = timer() numbe...
''' 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ''' from timeit import default_timer as timer power = int(input('Enter the power that needs to be raised to base 2 :: ')) start = timer() sum_of_digits = 0 number = 2 << (power - 1) numb...
from timeit import default_timer as timer if __name__ == '__main__': number = int(input("Enter the upper limit of number :: ")) start = timer() addition = 0 sequence = [1, 2] term = 0 if number <= 1: sequence = [] addition = addition + 2 while term <= number and len(sequ...
from timeit import default_timer as timer def additionFabonacii(limit): sequence = [1, 2] term = 0 addition = 0 if limit > 0: addition = addition + 2 while term < limit: length = len(sequence) term = sequence[length - 1] + sequence[length - 2] if term < limit: ...
''' https://leetcode.com/problems/unique-email-addresses/ Every email consists of a local name and a domain name, separated by the @ sign. For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. Besides lowercase letters, these emails may contain '.'s or '+'s....
''' 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ''' from timeit import default_timer as timer number = int(input('Enter power :: ')) start = timer() exp = 2 << (number - 1) sum = 0 while exp != 0: sum += (exp % 10) exp //= 10...
class ArraySetOps: def mean(self, items): length = len(items) sum_of_items = 0 for item in items: sum_of_items += item return (sum_of_items / length) if __name__ == '__main__': arraySetOps = ArraySetOps() numbers = str(input('Enter list of numbers(separa...
class Node: def __init__(self, data = None): self.data = data self.next = None class LinkedList: def __init__(self): self.start_node = Node() def add_to_start(self, data): node = Node(data) node.next = self.start_node.next self.start_node.next = node ...
from timeit import default_timer as timer def sumOfPrimes(number): number += 1 primes = [True] * number sum = [0] * number i = 3 limit = int(number ** 0.5) + 1 while i <= limit: if primes[i]: primes[i*i::2*i] = [False] * (((number - i*i - 1)//(2*i)) + 1) i += 2 ...
from timeit import default_timer as timer def partition(input, low, high): i = low - 1 pivot = input[high] j = low while j < high: elem = input[j] if elem <= pivot: i += 1 temp = input[j] input[j] = input[i] input[i] =...
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is...
def _get_input(): words = [] while len(words) == 0: x = input("Imprime una lista de palabras separadas por espacios: ") y = [x.strip() for x in x.split(' ')] if len(y) == 1 and y[0] == '': print("Entrada inválida.") continue words = y return word...
def main(): x = input("Introduce texto:") if x.lower() == "yes": print("Yes") else: print("No") if __name__ == "__main__": main()
"""YAML utilities """ import requests import urllib import yaml def load_file(path): """Load a YAML file. Args: path: Path to the YAML file; can be a local path or http URL Returs: data: The parsed YAML. """ url_for_spec = urllib.parse.urlparse(path) if url_for_spec.scheme in ["http", "https"]: ...
G = {} for i in range(1,1003): G[i] = set() visited = [False for i in range(1003)] def dfs(graph, node): if visited[node]==True: return visited[node] = True for v in G[node]: dfs(graph, v) N = int(input()) for i in range(N): a, b = map(int, input().split()) G[a].add(b) X, Y = m...
a = int(input()) b = int(input()) c = int(input()) x = [] x.append(a) x.append(b) x.append(c) x.sort() if x[0] + x[1] > x[2]: print("Huh? A triangle?") elif x[0] + x[1] <= x[2]: print("Maybe I should go out to sea...")
n = int(input()) for i in range(0,n): count = 0 each = int(input()) for j in range(1, each + 1): if each%j == 0 and each != j: count +=j if count == each: print(str(each) + " is a perfect number.") elif count > each: print(str(each) + " is an abundant number.") elif count < each: prin...
for i in range(10): n = input() if n=="encode": p = input().split(" ") print(p) elif n=="decode": p = input().split(" ") print(p)
""" Game_dev_oop_ex1 Attributes: Each class below, has at least one attribute defined. They hold data for each object created from the class. The self keyword: The first parameter of each method created in a Python program must be "self". Self...
from typing import List class Solution: def validUtf8(self, data: List[int]) -> bool: def check(bytes: int, start: int) -> bool: for i in range(start + 1, start + bytes): if i >= len(data) or (data[i] >> 6) != 0b10: return False ...
from typing import List import sys class Solution: def maxSubArray(self, nums: List[int]) -> int: best_sum = -sys.maxsize current_sum = 0 for num in nums: current_sum = max(num, current_sum + num) best_sum = max(best_sum, current_sum) return b...
import collections class Solution: dp = collections.defaultdict(int) def fib(self, n: int) -> int: if n <= 1: return n if self.dp[n]: return self.dp[n] self.dp[n] = self.fib(n - 1) + self.fib(n - 2) return self.dp[n] class Solution: ...
from typing import List class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() greed_idx = size_idx = 0 while greed_idx < len(g) and size_idx < len(s): if g[greed_idx] <= s[size_idx]: greed...
import collections class Solution: def characterReplacement(self, s: str, k: int) -> int: left = 0 count = collections.defaultdict(int) max_freq = 0 for right in range(len(s)): count[s[right]] += 1 max_freq = max(max_freq, count[s[right]]) ...
from typing import List class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(gas) < sum(cost): return -1 start, fuel = 0, 0 for i in range(len(gas)): if gas[i] + fuel < cost[i]: start = i...
import collections class Solution: def minWindow(self, s: str, t: str) -> str: need = collections.Counter(t) missing = len(t) left = start = end = 0 for right, char in enumerate(s, 1): missing -= need[char] > 0 need[char] -= 1 ...
from typing import List class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: for idx1, num1 in enumerate(numbers): left, right = idx1 + 1, len(numbers) - 1 expected = target - num1 while left <= right: mid = left +...
from typing import List class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: max_sum = 0 current_sum = 0 left = right = 0 subarray = {} while right < len(nums): if nums[right] not in subarray: subarray[nums[right]]...
class Color: def __init__(self, name, r, g, b): """ :param str name: color name :param float r: :param float g: :param float b: """ self.name = name self.r = r self.g = g self.b = b RED = Color(name='red', r=1, g=0, b=0) BLUE...
import string def ispangram(str): alphabet = "abcdefghijklmnopqrstuvwxyz" for char in alphabet: if char not in str.lower(): return False return True string = 'the five boxing wizards jump quickly.' if (ispangram(string) == True): print ("yes") else: print ("no")...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.c...
import random from Character import Character class CharacterCreator : def createCharacter() : print('Please enter the following information to setup your character...\n') firstName = input('What is your first name? ') heightInFeet = float(input('What is your height in feet approx? ')) ...
import random def low_level() : number = random.randint(1,10) chances = 3 while (chances > 0) : guess = int(input('Your guess : ')) if (guess == number) : print ('Congratss you win the game!!') break elif (guess > number) : print ('your guess is...
materi_bio = [] def list_materi() : if (len(materi_bio) <= 0) : print ('MATERI KOSONG') else : for i in range(len(materi_bio)) : print (i,'.', materi_bio[i]) def input_materi() : materi = str(input('Materi Bio : ')) materi_bio.append(materi) def ralat_materi() : lis...
angka = [1, 2, 4, 5, 34, 45, 23, 31] tertinggi = max(angka) terendah = min(angka) print (tertinggi) print (terendah) bulan = { 'januari' : 0, 'februari' : 0, 'maret' : 0, 'april' : 0, 'mei' : 0, 'juni' : 0 } for i in bulan : bulan[i] = int(input(f'penghasilan pada bulan {i} : Rp. ...
print("Hello VSCode") a=1 b=2 c=a+b print(c) t=[1,2,3] a,b,c=t print(t,a,b,c) score = 92 if score >=90 : print('합격') else : print('불합격') for i in[0,1,2,3,4,5,6,7,8,9,10] : print(i) for i in range(0,11): print(i) favorite_hobby = ['reading','fishing','shopping'] for hobby in favorite_hobby : ...
import pandas as pd import math import scipy.stats as st pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) pd.set_option('display.width', 500) pd.set_option('display.expand_frame_repr', False) pd.set_option('display.float_format', lambda x: '%.5f' % x) df = pd.read_csv("datase...
import numpy as np ''' mat1 = np.zeros((3,4)) #3*4的矩陣 print(mat1) print(mat1.ndim) print(mat1.shape) mat2 = np.ones((2,3)) * 2 mat2_2 = mat2 * 2 mat2_3 = mat2 * mat2_2 print(mat2) print(mat2_2) print(mat2_3) #對角矩陣 mat3 = np.eye(3,4) print(mat3) #真的矩陣運算 #print(np.matmul(mat2, mat3)) ''' import matplotlib.pyplot a...
import math m1=int(input("Pendiente de la recta 1: ")) b1=int(input("Ordenada al origen de la recta 1: ")) m2=int(input("Pendiente de la recta 2: ")) b2=int(input("Ordenada al origen de la recta 2: ")) if m1!=m2: x=(b2-b1)/(m1-m2) print(f"El punto de interseccion es {x}") if m1==m2: print(f"L...
x1=int(input("Elemento x del primer vector: ")) y1=int(input("Elemento y del primer vector: ")) x2=int(input("Elemento x del segundo vector: ")) y2=int(input("Elemento y del segundo vector: ")) def resta1 (x1,x2): return x2-x1 def resta2 (y1,y2): return y2-y1 x=x2-x1 y=y2-y1 def modulo(x,y): ret...
"""imported the requests library""" import requests DATA_URL = "https://simple.wikipedia.org/wiki/Rose" OBJECT= requests.get(DATA_URL) with open("webcontent.txt", 'wb') as f: f.write(OBJECT.content)
"""importing webbrowswer module""" import sys import webbrowser def opensetup(): """function for open user specified website""" var = input("Enter g-google, 'd'-darwin, o-office: ").strip() if var == 'g': webbrowser.open("www.google.com") elif var == 'd': webbrowser.open("https://ojas...
import tkinter as tk import requests import time def getWeatherInfo(window): city = textField.get() API = "" jsonData = requests.get(API).json() weatherCondition = jsonData["weather"][0]["main"] temperature = int(jsonData["main"]["temp"] - 273.15) minTemperature = int(jsonData["main"...
class Destino(object): """ Destino posible al que se puede ir. Attributes: nombre (String): nombre del destino. ubicacion (String): ubicacion deonde se encuentra. tags (list): categorias a las cuales puede ser asignado el destino. clima (String): clima del destino. """ def __init__(self, nombre, ubicaci...
def DFS(num): visited[num] = 1 for i in range(N): if visited[i] == 0 and connectList[num][i] == 1: DFS(i) import sys N, M = map(int, sys.stdin.readline().split()) connectList = [[0] * (N) for _ in range(N)] visited = [0 for _ in range(N)] notVisitede = [0 for _ in ran...
def checkio(data: str) -> bool: upper = False lower = False digit = False if not len(data) >= 10: return False for i in data: if i.isdigit(): digit = True if i.isupper(): upper = True if i.islower(): lower...
from typing import Union class Node: def __init__(self, data=None): self.data = data self.next: Union[Node, ()] = None def has_next(self) -> bool: return self.next is not None class LinkedList: def __init__(self): self.head: Union[Node, ()] = None self.length = 0...
from tkinter import * def tick(): import time time1 = '' time2 = time.strftime('%a, %d %b %y %H:%M:%S') if time2 != time1: time1 = time2 clock.config(text=time2) clock.after(200, tick) def StallList(index): import csv listof = set() with open("Menu.c...
x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) print(x) print(y) print("I said: %r." % x) print("I also said: '%s'." % y) hilarious = True joke_evaluation = "Isn't that joke so funny?! %r" print(joke_evaluatio...
import turtle import pandas as pd screen = turtle.Screen() screen.title('U.S. States Game') image = "blank_states_img.gif" turtle.addshape(image) turtle.shape(image) guessed_state = [] data = pd.read_csv("50_states.csv") states = data.state.to_list() while len(guessed_state) < 50: answer = turtle.textinput(title...
import re from math import ceil from decimal import Decimal import unittest string_example="all I did today; i 20m, 35m, 2.5h, 2h40m v 40m 35m 1.2h e 30, 60m " class MinutesTest(unittest.TestCase): def test_calculate_total_minutes_in(self): self.assertEqual(calculate_total_minutes_in(), 602) ...
class Employee: emp_count = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.emp_count += 1 """def display_count(self): print(f"Total number of employees: {Employee.emp_count}")""" def display_employee(self): print("Name: ", ...
import math number=(input("input a number:")) number_new=number[::-1] number_result=int(number_new.lstrip("0")) print(number_result)
from myOwnfunc import Reverse def isPalindrom(number): if number==Reverse.reverse(number): return 1 else: return 0
def IsLeapYear(year): if year%4==0 and year%100!=0: return 1 elif year%400==0: return 1 else: return 0 monthLeap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def NumberOfDaysOftheMonth(year,month): if IsLeap...
''' import os.path if os.path.isfile('President.txt'): print("President.txt exists") ''' outfile = open("President.txt","w") outfile.write('Bill Clinton\n') outfile.write("George Bush\n") outfile.write('Barack Obama\n') outfile.write('Donlord Trump') outfile.close() ''' infile = open("President.txt", "r") #...
print(chr(1)) ''' def containsDuplicate(lst): s = set(lst) # without set if len(s)==len(lst): print('NO') return 0 else: print('YES') return 1 n = int(input()) lst = input().split() lst = [ int(x) for x in lst] containsDuplicate(lst) ''' ''' n = int(input()) lst = inpu...
def reverse(number): rnumber=0 if number<0: number=-1*number while number != 0: rnumber = 10 * rnumber + number % 10 number = (number - number % 10) / 10 rnumber=-1*rnumber else: while number != 0: rnumber = 10 * rnumber + number % 10 ...
def f(n): sum = 1 if n == 0: return 1 elif n ==1: return 1 else: for i in range(1,n+1): sum *= i return sum n = int(input()) lst = [ f(i) for i in range(1,n+1,2)] s = sum(lst) print('n='+str(n)+',s='+str(s))
def f(n): sum = 1 if n == 0: return 1 elif n ==1: return 1 else: for i in range(1,n+1): sum *= i return sum n = int(input()) lst = [1/f(i) for i in range(0,n+1)] result = sum(lst) print("{:.8f}".format(result) )
import math class Circle: def __init__(self,radius=1): self.radius=radius def getPerimeter(self): return self.radius*2*math.pi def getArea(self): return self.radius*self.radius*math.pi def setRadius(self,radius): self.radius=radius class Rectangular: def __init__(se...
num = eval(input(" enter a number, except 0:")) sum=num count=0 while num!=0: num = eval(input(" enter a number, except 0:")) sum+=num count+=1 print("sum={}".format(sum/count,"5.2f")) print(format(sum/count,"5.2f"))
ch=input("enter a letter:") print(ord(ch)) nu=eval(input("enter an ascii code:")) print( chr(nu))