text
stringlengths
37
1.41M
''' 假设函数f()等概率随机返回一个在[0,1)范围上的浮点数,那么我们知道,在[0,x)区间上的数出现的概率为x(0<x≤1)。 给定一个大于0的整数k,并且可以使用f()函数,请实现一个函数依然返回在[0,1)范围上的数, 但是在[0,x)区间上的数出现的概率为x的k次方。 ''' # -*- coding:utf-8 -*- import random class RandomSeg: def f(self): return random.random() # 请通过调用f()实现 def random(self, k, x): res = 0 ...
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Remove: def removeNode(self, pNode): # write code here self.pNode = pNode if self.pNode.next == None: return False else: self.pNode.val = sel...
import random class QuickSort: def quickSort(self,A,n): if A==[]: return [] x = A[0] left = self.quickSort([i for i in A[1:] if i<x],1) right = self.quickSort([j for j in A[1:] if j >= x ],1) res= left + [x] + right return res a = QuickSort() #out = a.qu...
''' Input: a List of integers where every int except one shows up twice Returns: an integer ''' import timeit def single_number(arr): start = timeit.default_timer() # Your code here # Store an array of double values seen in the loop. # Loop again and check if the value is in this list. # List com...
import random import math class Activation(object): #constructor method of Activation equation def __init__(self, input): #get the type self.get_type(input) #set dividor self.divide = 1 #set up random weight self.weight = random.uniform(-50, 50) ...
# For PiDay 2020 - Created by Brent Hartley using the Chudnovsky Algorithm # Program called Pi.py (pronounced pie (dot) pie), using a function called PiDay, and # Run on a raspberry pi, on 3-14-2020 # Variables spell p, i, d, a, y, because, why not? # This change to the digit limited program lets the program caculate p...
# Write your code here water = 200 milk = 50 beans = 15 cups = int(input("Write how many cups of coffee you will need:\n")) print(f'''For {cups} of coffee you will need: {water * cups} ml of water {milk * cups} ml of milk {beans * cups} g of coffee beans''')
def range_sum(numbers, start, end): valid_values = [num for num in numbers if start <= num <= end] return sum(valid_values) input_numbers = [int(num) for num in input().split()] a, b = [int(num) for num in input().split()] print(range_sum(input_numbers, a, b))
# Write your code here from random import randrange options = ["rock", "paper", "scissors"] usr_input = input() ai_input = options[randrange(3)] choices = {"player": usr_input, "AI": ai_input} if choices["player"] == "scissors": if choices["AI"] == "scissors": print(f"There is a draw ({choices['AI']})") ...
number_one = float(input()) number_two = float(input()) print(number_one + number_two)
def tallest_people(**people): sorted_people = sorted(people.items(), key=lambda k: (-k[1], k)) # for person in sorted_people: # print(person[0], ':', person[1]) for person in sorted_people: if person[1] == max(people.values()): print(person[0], ':', person[1])
# Don't forget to make use of lambda functions in your solution func = lambda x: "x ends with 0" if (x % 10 == 0) else "x doesn't end with 0"
# Write your code here tasks = ['Do yoga', 'Make breakfast', 'Learn basics of SQL', 'Learn what is ORM'] print('Today:') for i, task in enumerate(tasks): print(f'{i+1}) {task}')
# write your code here state = input("Enter cells: ") matrix = list(state) print("---------") print(f"| {matrix[0]} {matrix[1]} {matrix[2]} |") print(f"| {matrix[3]} {matrix[4]} {matrix[5]} |") print(f"| {matrix[6]} {matrix[7]} {matrix[8]} |") print("---------")
size = int(input()) message = "" if size < 1: message = "no army" elif size < 10: message = "few" elif size < 50: message = "pack" elif size < 500: message = "horde" elif size < 1000: message = "swarm" else: message = "legion" print(message)
class Painting: museum = "Louvre" def __init__(self, title, painter, year_of_creation): self.painter = painter self.title = title self.year_of_creation = year_of_creation painting = Painting(input(), input(), input()) print(f'"{painting.title}" by {painting.painter} ({painti...
class Student: courseMarks={} name="" family="" def __init__(self, name, family): self.name = name self.family = family def addCourseMark(self, course, mark): self.courseMarks[course] = mark def average(self): marks = self.courseMarks.values() average =...
#Sci 127 Teaching Staff #October 2017 #Count which cars got the most parking tickets #Import pandas for reading and analyzing CSV data: import pandas as pd csvFile = input('Enter CSV file name: ') #Name of the CSV file tickets = pd.read_csv(csvFile) #Read in the file to a dataframe print("The 10 worst off...
#Coin flip program #The Purpose of this program is to generate a random number from 1 to 6 and display it #As a dice face. I have then chnaged the program to continue until #it has rolled a 6 #<(^_^<) <(^_^)> (>^_^)> import random,time result = "" result2 = " " dice = ["- - - - -\n| |\n| O |\n| |\n- ...
"""Make a two-player Rock-Paper-Scissors game.""" import os ch='y' while ch=='y': player1=input("Player 1/enter value 1.rock 2.paper 3.siccor :") os.system('clear') player2=input("Player 2/enter value 1.rock 2.paper 3.siccor :") os.system('clear') if player1==player2: print("same") ch=input("\nclick y if you...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import requests,urllib import argparse import ast class UrlFit(): def __init__(self): self.URL = "https://api.url.fit/shorten" def Shorten(self,url): target = self.URL + "?long_url=" + urllib.quote_plus(url) resp = requests.get(target, headers={'User-Age...
# Check if an array is sorted # Given an array C[], write a program that prints 1 if array is sorted in non-decreasing order, else prints 0. ''' Example: Input 2 5 10 20 30 40 50 6 90 80 100 70 40 30 Output 1 0 ''' #-------------------------custom code---------------------------------------- t=int(inpu...
# Compete the skills ''' A and B are good friend and programmers. They are always in a healthy competition with each other. They decide to judge the best among them by competing. They do so by comparing their three skills as per their values. Please help them doing so as they are busy. Set for A are like [a1, a2, ...
a= [] #declaring list n=int(input("Enter number of leads you need to sort: "))#number of leads for i in range(n): #input the leads values using for loop a.append(input("Enter the leads ")) def list(lead_email): #recursive function to sort the list with respective company domain emails={ } ...
i = 0 while i <= 10: print(i) i += 2 for j in 'hello world': if j == 'w': continue print(j * 2, end='') for y in 'hello world': if y == 'w': break print(y * 3, end='') for t in 'hello world': if t == 'a': break else: print("Буквы нет") ...
print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") m_name=name1.lower() y_name=name2.lower() combine_name=m_name+y_name a=0 b=0 a+=combine_name.count("t") a+=combine_name.count("r") a+=combine_name.count("u") a+=combine_name.count("e") b+=combine_name...
print("Welcome to Python Pizza Deliveries! ") bill=0 size=input("What size pizza do you want? S,M or L ") if size=="Y": bill+=15 print("Small size pizza price is: $15") elif size=="M": bill += 20 print("Medium size pizza price is: $20") elif size=="L": bill += 25 print("Large size pizza price ...
row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") #1st Method # if position[0]=='1': # if position[1]=='1': # row1[0]='X' # elif position[1]=='2': # row2[0]...
def Create(i): print("1.Personal Acc") print("2.loan Acount") ch=int(input()) f=1 while(f): fnme=input("enter First name:") lnme=input("enter last name:") if fnme.isalpha() and lnme.isalpha(): name.append(fnme+" "+lnme) f=0 else: ...
if __name__ == '__main__': a=12+11 tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5) list1 = ["a", "b", "c", "d","e"] list2=['e','f'] set1={1,2,3} set2={1,3,2} list3=list1+list2 tup4=tup1+tup2 x='asdf' print(set2*2)
# coding: utf-8 # In[1]: ##playing with arrays in Numpy # In[3]: import numpy as np # In[7]: # passing lists mylist = [1,2,3] x = np.array(mylist) x # In[11]: y = np.array([4,5,6]) y # In[14]: # stacking lists vertically to build a (2,3) array z = np.vstack((x,y)) z # In[15]: np.shape(z) # In[...
# -*- coding: utf-8 -*- """ Created on Mon Nov 14 16:20:13 2016 @author: hg happy number takes a number and returns true if number is happy and false if number is unhappy """ def happy_number(n): ''' test conditions, if number is happy cycle ends in 1 by definition if the number is unhappy it enters a ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Chương trình chuyển đổi từ Tiếng Việt có dấu sang Tiếng Việt không dấu """ import re import unicodedata def no_accent_vietnamese(s): # s = s.decode('utf-8') s = re.sub(u'Đ', 'D', s) s = re.sub(u'đ', 'd', s) return unicodedata.normalize('NFKD', s).encod...
print('Enter the number, operation and the second number') n1=int(input()) op=str(input()) n2=int(input()) def calc(n1,op,n2): if op=='+': return int(n1)+int(n2) elif op=='-': return int(n1)-int(n2) elif op=='*': return int(n1)*int(n2) elif op=="/": return int...
import pandas as pd from pathlib import Path def merge_csv_to_excel(csv_files, sheet_names, sep=';', output='merged.xlsx'): """ Merge `csv_files` into a single excel file. Parameters: ----------- csv_files: List of Path Paths to the csv files to be merged. sheet_names...
import json filename = "understanding.json" while True: value = raw_input("Did you understand(Yes:1, No:0)") understandingObject = {"understanding":value} with open(filename, 'w') as understandingfile: json.dump(understandingObject, understandingfile)
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # # # Program: tictactoe.py # # Written by: Eric Cox ...
class Celsius: def __init__(self, temperature): self.__temperature = self.__to_fahrenheit(temperature) def __to_fahrenheit(self, valor): return (valor* 1.8) + 32 @property def temperature(self): print("Obteniendo valor") return self.__temperature @temperature.sette...
''' CREAR UNA CLASE GATO QUE LLEGUE A DORMIR COMER JUGAR gatito''' from random import randrange, choice class Gato(): conducta = 'bien' comida = True _raza = 'felino' def __init__(self,color='cafe',edad=2,genero='macho'): self.color = color self.edad = edad self.genero = gene...
# CON VARIABLES GLOBALES def suma(): global resultado def validar(): return numero_dos > 0 and numero_uno > 0 if validar(): resultado = numero_uno + numero_dos #solo se validaran si son mayores a cero numero_uno = 2 numero_dos = 2 sumando = suma() print('resultado-->{}'.format(resultado))
#DECORADOR VARIABLE GLOBAL # SOLO DEBO UAR VARIABLES GLOBALES # CUANDO SE DECLARE UNA CONSTANTE O ALGO SENCILLO def decorador(mi_funcion): def nueva_funcion(*args, **kwargs): resultado = mi_funcion(*args, **kwargs) return nueva_funcion @decorador def sumar(n_uno, n_dos): resultado = n_uno + n_dos ...
class Usuario: def __init__(self,usuario,contrasena,correo): self.usuario = usuario self.__contrasena = self.__encriptar(contrasena) self.correo = correo def __encriptar(self, contrasena): return contrasena.upper() # ME RETORNE ATRIBUTOS PRIVADOS def get_contrasena(self...
'''def halve_evens_only(nums): return [i/2 for i in nums if not i % 2] numeros = [1,2,3,4,5,6,7,8,9,0,67,34,234,34,2,2,2] resultado = halve_evens_only(numeros)''' def animal(nombre): if nombre == 'Rigoberto': print ('Se llama --> {}'.format(nombre)) mensaje = 'Tiene hambre' return mensaj...
class MiClase: def __init__(self,midato): self.set_dato(midato) def get_dato(self): return self.__dato def set_dato(self,midato): if isinstance(midato,(int,float)): if midato < 0: print('entro dato') self.__dato = 0 el...
# CLOUSER DE SUMA def clou_ser(): def validar(): return numero_uno > 0 and numero_dos > 0 return validar def sumar(mi_clouser): if mi_clouser(): resultado = numero_uno + numero_dos print('resultado-->{}'.format(resultado)) #solo se validaran si son mayores a cero numero_uno = 2 num...
Que es Python? python es un lenguaje de programacion interpretado, que a diferencia de otros lenguajes de programacion como java, go, sharp no necesita ser compilado, simplemente ejecutamos nuestro programa. python es multiparadigma ya que python podemos trabajar con programacion estructurada, orientada a objetos , fu...
# REALIZAR UNA LISTA QUE AGREGE INSERTE ETC. mi_lista = [0, True, 'Pajarito', 12.5] mis_enteros = [1,2,3,66,1,0,10,100,50] mi_lista.append('Agregando') mi_lista.insert(3,'Insertado') mi_lista.extend(mis_enteros) print('Lista-->{}'.format(mi_lista))
superhero = { "name": "Wonder Woman", "alias": "Diana Prince", "gear": [ "Lasso of Truth", "Bracelets of Submission" ], "vehicle": { "title": "Invisible Jet", "speed": "2000 mph", } } lasso = superhero["gear"][0] print(lasso) for item in superhero["gear"]: p...
user_input = int(input("Please enter a number under 50 for how many time you want it to loop. ")) n1, n2 = 0, 1 count = 0 if user_input <= 0: print("Please enter a positive number.") elif user_input == 1: for i in range(2, user_input): print(i, end=', ') print("Fibonacci sequence upto", range...
class Position: """Wannabe Immutable position/vector class that handels the needed add and multiply methods""" x: int y: int # The x and y values are not to be below 0 or above the below values. max_x: int = None max_y: int = None def __init__(self, x, y, max_x = None, max_y = None): ...
from collections import defaultdict m, n = (int(x) for x in input().split()) # find all haywords worth = defaultdict(int) for i in range(m): line = input().split() worth[line[0]] = int(line[1]) # job descriptions for i in range(n): job_desc = "" while True: line = input() job_desc +=...
order = [] order.extend(map(int, input().split())) order.extend(map(int, input().split())) order.extend(map(int, input().split())) def distance(a, b): import math diff_x = a[0] - b[0] diff_y = a[1] - b[1] return math.sqrt(diff_x ** 2 + diff_y ** 2) def index_to_pos(index): return (index % 3, index...
from collections import defaultdict def get_distance(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def get_grid(lowest_x, lowest_y, highest_x, highest_y, points): for i in range(lowest_x, highest_x + 1): for j in range(lowest_y, highest_y + 1): yield i, j def is_infinite(lowest_x, low...
def factorial(num): if (num == 1): return 1 elif(num == 0): return 1 else: return num*factorial(num-1) print(factorial(5))
class Empty(Exception): pass class ArrayQueue: def __init__(self): self._data= [] self._size = 0 self._front = 0 def __len__(self): #AQ_size 가 0이다 왜냐하면 위에 self._data = 빈 리스트기때문에 return self._size def is_empty(self): ...
def factorial(n): if n == 0: return 1 elif n == 1 : return 1 return n * factorial(n-1) def factor(n): u = 1 if n == 0 or n == 1: return 1 for i in range(2,n+1): u *= i return u print(factor(3)) def hanoi(n): if n == 1 : return 1 if n == 2: ...
def find(n): result = [] for char in n: list = ['h', 'e'] #print(char) if char in list: result.append(char) return result n = "heooooooooolllooohhhhhllooollololo" # result = [] # for c in find(n): # result.append(c) print(find(n))
class Empty(Exception): pass class ArrayQueues: def __init__(self): self.data = [] def __len__(self): return len(self.data) def enqueue(self, num): return self.data.append(num) def dequeue(self): how_long=len(self.data) if how_long==0: retu...
class Empty(Exception): pass class ArrayQueue: def __init__(self): self._data = [] def __len__(self): return len(self._data) def is_empty(self): if len(self._data): return False else: return True def first(self): if len(self._dat...
def hanoi_tower(num): if num is 1: return 1 else: return 2*hanoi_tower(num-1)+1 print(hanoi_tower(3)) print(hanoi_tower(2)) print(hanoi_tower(10)) def hanoi_instruction(num, startPeg=1, endPeg=3): if num: hanoi_instruction(num-1,startPeg,6-startPeg-endPeg) print("{}번 디스크를 {...
def hanoiTower(n): if (n == 1): return 1 else: return hanoiTower(n-1)*2 + 1 print(hanoiTower(10)) # def hanoi(n,start,end,mid): # # if(n == 1): # print("%d번 디스크를 %d에서 %d로 옮기시오" %(n,start,end)) # # else: # hanoi(n-1, start, mid, end) # hanoi(1, start, end, mid...
import tkinter as tk import os import sys import sqlite3 import argon2 ph = argon2.PasswordHasher() buttonValues = [] checkValues = [] #Connection to database connect = sqlite3.connect('users.db') cr = connect.cursor() command = """CREATE TABLE IF NOT EXISTS users(user_id INTEGER PRIMARY KEY, username TEXT, passw...
import numpy as np from keras.models import Sequential from keras.layers.core import Activation, Dense from keras.optimizers import SGD, Adam from util.callback import WeightLogger # We are going to train a model to perform either an and/or/xor based upon the first # value in a 3D input. Value 0 identifies the operati...
s = input("Please enter a string: ") lenOfString = len(s) #print(lenOfString) maxLen = lenOfString // 2 #print(maxLen) numRepeat=0 for length in range(1, maxLen): subString = s[:length] #print(subString) for index in range[0,len(s), length]: segment = s[index: index + length] if subString...
n = int(input("Input a dimension: ")) for i in range (1, (n//2) + 1): for j in range(1, n+1): print(j**i, end="\t") print()
#Problem 4 lst = ['2','4','6','8','10'] def create_prefix_lists(lst): outlst = [[]] inlst = [] for i in range(len(lst)): inlst.append(lst[i]) outlst.append(inlst[:]) #inlst[:] is a copy of inlst and thus removes the issue of the changing inlst #print(inlst,'in') #print(outl...
def sum_of_squares(lst): sum = 0 for element in lst: sum += element**2 print(sum) sum_of_squares([1,2,3,4,5])
#Problem 1 print("Kevin") #Problem 2 int1 = input("Please enter the first integer: ") int2 = input("Please enter the second integer: ") sum = int(int1) + int(int2) diff = int(int1) - int(int2) prod = int(int1)* int(int2) print("Their sum is: " , str(sum) + "," , "their difference is: " , str(diff) +"," , "their produc...
def find_max_even_index(lst): max = 0 index = -1 for i in range(len(lst)): if lst[i] % 2 == 0: if lst[i] > max: max = lst[i] index = i print(index) find_max_even_index([56, 24, 58, 10, 33, 95]) find_max_even_index([3,5])
#Problem 3: Write a program that asks for the user’s name and prints a personalized welcome message for him. name = input("Please enter your name: ") print("Hi "+ name + ", Welcome to CS-UY 1114")
#Problem 2 n = int(input("Please enter an integer n: ")) times = 0 hold = n for i in range(n): times = (2*n) - 1 n = n - 1 print( (i * " ") + times * "*") while(n < hold): n = n + 1 times = (2*n) - 1 print((i * " ") + times * "*") i = i - 1
lst = [1,2,3,4,5,6,7,8] def circular_shift_list1(lst,k): newLst =[] newLst.extend(lst[-k:]) newLst.extend(lst[:-k]) print(newLst) circular_shift_list1(lst,3)
#Problem 3: Given sides and an angle in between calculate the third side and then make a turtle print the resulting triangle import math import turtle #inputs side1 = int(input("Please enter the length of side 1: ")) side2 = int(input("Please enter the length of side 2: ")) angle1 = int(input("Please enter the angle i...
#Problem 2 lst = ["a", "b", "10", "bab", "a"] val = "a" def find_all(lst,val): newlst = [] for i in range(len(lst)): if lst[i] == val: newlst.append(i) #newlst += [i] print(newlst) (find_all(lst,val))
#Problem 4: Write a program that takes years as input (as a integer) and prints out an estimated population (as an integer). year = int(input("Please enter the year: ")) currentYear = 2017 currentPop = 307357870 birth = int(31536000 / 7) death = int(31536000 / 13) immigrants = int(31536000 / 35) popChange = int( (year...
from datetime import timedelta TIME_ANGLE_RATIO = 0.25 # 90 degree for 360 minutes of time def sun_angle(time: str): sunrise = timedelta(hours=6, minutes=0) sunset = timedelta(hours=18, minutes=0) ar = time.split(":") now = timedelta(hours=int(ar[0]), minutes=int(ar[1])) angle = ((now - sunrise)...
# https://py.checkio.org/mission/army-battles/publications/Phil15/python-3/army-with-3-properties-is_alive-warrior-pop/ class Warrior: def __init__(self, health=50, attack=5): self.health = health self.attack = attack @property def is_alive(self) -> bool: return self.health > 0 ...
# https://py.checkio.org/mission/army-battles/publications/martin.pilka/python-3/army_1unitspop0/ class Warrior: """ Class Warrior, the instances of which will have 2 parameters - health (equal to 50 points) and attack (equal to 5 points), and 1 property - is_alive, which can be True (if warrior's health is...
# https://py.checkio.org/mission/double-substring/publications/StefanPochmann/python-3/4-problems-1-solution/share/af71a294ba1313bced37c36f80d834aa/ def longest_substring(string, predicate): n = len(string) for length in range(n, -1, -1): for start in range(n - length + 1): substring = stri...
def checkio(matrix): return matrix == [list(map((-1).__mul__, reversed(sub))) for sub in list(reversed(matrix))] if __name__ == '__main__': assert checkio([ [0, 1, 2, 3, 4], [-1, 0, 5, 6, 7], [-2, -5, 0, 8, 9], [-3, -6, -8, 0, 0], [-4, -7, -9, 0, 0]]) == True, "4th exam...
from typing import List def checkio(puzzle: List[List[int]]) -> str: """ Solve the puzzle U - up D - down L - left R - right """ return "ULDR" if __name__ == '__main__': print("Example:") print(checkio([[1, 2, 3], [4, 6, 8], [7, 5,...
def lesser(v1, v2): return v1 < v2 def greater(v1, v2): return v1 > v2 def find_min_max(comparator, *args, **kwargs): args = list(args[0]) if len(args) == 1 else args key = kwargs.get("key", lambda x: x) res = None for item in args: if res is None or comparator(key(item), key(res)): ...
# https://py.checkio.org/mission/army-battles/publications/JimmyCarlos/python-3/army-battles/ class Warrior(object): def __init__(self): self.health = 50 self.attack = 5 @property def is_alive(self): """Boolean property to test if health is above 0.""" return self.health > 0...
# https://py.checkio.org/mission/speechmodule/publications/veky/python-3/first/ # migrated from python 2.7 def checkio(number): l=["","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"] d=dic...
# Basim Siddiqui # PSID: 1517778 #class from lab 10.17 class ItemToPurchase: def __init__(self, item_name = 'none', item_price = 0, item_quantity = 0, item_description = 'none'): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity self.item_de...
# def lista(txt): # i=0 # l=len(txt) # lisdev=[] # while i<l: # if len(txt[i:i+2])<2: # lisdev.append(txt[i:i+2]+"_") # else: # lisdev.append(txt[i:i+2]) # i=i+2 # return lisdev # a="algun perr" # print(lista(a)) # def dividirdeados(cadena): ...
print("What do you like to purchase: ") search = input() itemList=["Dalmot", "Chauchau", "Chips","Juice"] itemPrice = {'Dalmot' :100, 'Chauchau' :20, 'Chips':50, 'Juice':100 } if search in itemList: print("Available") print("Price of: " + search + " is " + str(itemPrice[search])) else: print("Sorry! Not A...
from typing import List, Dict class Solution: # O(log(n)) - time, O(1) - space def binarySearchIterate(self, nums: List[int], target: int): left=0 right=len(nums) - 1 if left > right: return -1 while left <= right: middle = (left + right) // 2 ...
import numpy as np import random def print_header(): print("\t What is the number you want the computer to guess?!") print("\t Your number must be between 1 and 100") print("\t If your number is higher type h, if your number is lower type l.") def main(): # prints the greeting banner ...
import random import sys #print(sys.getrecursionlimit()) sys.setrecursionlimit(11000000) #print(sys.getrecursionlimit()) def ordenamiento_de_burbuja(lista): n = len(lista) for i in range(n): for j in range(0, n-i-1): # O(n) * O(n) = O(n*n) =O(n)**2 if lista[j] > lista[j + 1]: ...
##balance = 4213 ##annualInterestRate = .2 ##monthlyPaymentRate = .04 ##numberMonths = 12 ##i = 0 ##totalPaid = 0 ## ##while i < numberMonths: ## minMonthPay = balance*monthlyPaymentRate ## balance = (balance - minMonthPay)* (1 + annualInterestRate/12) ## i += 1 ## totalPaid = totalPaid + minMonthPay ## ...
#2794 arr=[] for i in range(3): line=input('').split(' ') arr.append(int(line[0])) arr.append(int(line[1])) for elem in arr: if arr.count(elem)==1: if arr.index(elem)%2==0: x=elem else: y=elem print(x,y)
s1=input('') s2=input('') if s1[0]==s2[-1]: print('YES') else: print('NO')
word1 = input('') sentence1 = input('') if word1 in sentence1: print(1) else: print(0)
def compare(string1, string2): i=0 while len(string1)>0 and len(string2)>0: if string1[i]>string2[i]: string2=string2[i+1:] elif string1[i]<string2[i]: string1=string1[i+1:] else: string1=string1[i+1:] string2=string2[i+1:] s...
a = str(input('')) b = str(input('')) # if a==b: # print("{} = {}".format(a,b)) # else: # print("{} {} {}".format(max(a,b),'<',min(a,b))) a1=list(a) a1.reverse() b1=list(b) b1.reverse() a2=int(''.join(a1)) b2=int(''.join(b1)) # print(a2,b2) if a2<b2: print("{} < {}".format(a,b)) if b2<a2: pr...
s=list(input('')) count=0 for i in s: if i=='a' or i=='e' or i=='i' or i=='o' or i=='u': count=count+1 print(2**count)
n = int(input('')) mainStr = input('') artStudentStr = input('') numberOfFailure = 0 for index in range(len(mainStr)): if mainStr[index]!=artStudentStr[index]: numberOfFailure = numberOfFailure+1 print(numberOfFailure)
n = int(input('')) arr = [] for i in range(n): arr.append(int(input(''))) average = sum(arr)//n times =0 for val in arr: times = times + ((val-average) if (val-average)>0 else 0) print(times)
## https://leetcode.com/problems/reverse-bits/ class Solution: def reverseBits(self, n: int) -> int: reverse = bin(n)[::-1][:-2] reverse += "0"*(32-len(reverse)) return int(reverse,2) ####### Another approach ###### ## https://leetcode.com/problems/reverse-bits/ class Solution: ...