text
stringlengths
37
1.41M
''' Al igual que las condiciones se pueden anidar, los ciclos tambien, ejemplos clasicos son el trabajo con matrices datos en formato tabla, series de tiempo doble, dobles sumatorias, expresiones matematicas, etc. En este script se mostraran algunos ejemplos clasicos ''' #Imprimiendo un cuadrado de * filas = int(inpu...
#!/usr/bin/env python # -*- coding: utf-8 -*- #This program will evaluate the accuracy of the reorder code based on 2 criteria: #1 the sentence should have the same word order as the english sentence #2 the words in the sentence should be aligned as it would be in an english sentence import argparse from iterto...
def countCase(str1): countUp=0 countLw=0 for i in str1: if(i.isupper()): countUp=countUp+1 if(i.islower()): countLw= countLw+1 print("No of uperCase letter is: ",countUp) print("No of lowerCase letter is: ",countLw) str = input("Enter strin...
import logging logging.basicConfig(level=logging.DEBUG, format="%(asctime)s-->>%(levelname)s==>%(message)s", filename="log.txt") logging.info("program started") a=raw_input("Enter a value:") logging.info("Got the a value from the user") b=raw_input("Enter b value:") logging.info("Got the b value from the user")...
pi = 3.142 radius = float(input('what is the radius of your circle? ')) area = pi * ((radius) **2) print (area)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Michael Lockwood' __github__ = 'mlockwood' __email__ = 'lockwm@uw.edu' def levenshtein(a, b): """This function applies the levenshtein algorithm between an the object's gloss and a leipzig or gold tag. """ # Reset to calculate whereas b has...
N = int(input("berapa angka = ")) ruang = [] for i in range(N): ruang.append(int(input("masukkan angka ke {} = ".format(i)))) print("Nilai Maksimal = {}".format(max(ruang))) print("Nilai Minimum = {}".format(min(ruang)))
n = int(input()) if n == 1 or n == 2: print(1) else: a, b, ans = 1, 1, 0 for i in range(2, n): ans = (a + b) % 10007 a, b = b, ans print(ans)
for num in range(1000, 10000): string = str(num) if string[0] == string[3] and string[1] == string[2]: print(num)
import os import string def get_valid_drives(): print("Getting valid drives...") valid_drives = [] for elem in string.ascii_lowercase: path = elem + ":\\" #if os.path.isdir(path): # print(path) if os.path.exists(path): valid_drives.append(path) #pr...
def read_a_number(): nb = input('Choose a number: ') try: mode = int(nb) except ValueError: print("Not a number") mode = read_a_number() return mode def pag12_prog(): n = read_a_number() x = [] for a in range(n): x.append(read_a_number()) print(x) s=0 ...
part_number = "42560353245833ab" def cardLuhnChecksumIsValid(card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(0, num_digits): digit = int(card_number[count]) if...
__author__ = 'darakna' # python 2 # # Homework 3, Problem 3 # List comprehensions! # # Name: # # this gives us functions like sin and cos from math import * # two more functions (not in the math library above) def dbl(x): """ doubler! input: x, a number """ return 2*x def sq(x): """ squarer! input: x, ...
import binascii import base64 req_n = "5203054907932715072219463010433671501242324999101031961778551414523203642794654633954122128718395475257091609045094294305282429283375416003959025668410070733743" resp_n = "131618988864947543213776229531634193412737234854212651796818129365118569829291789642298561838219946234914193...
"""The module encrypts a message using one key that is entered as an interger and it shifts the message letter by letter according to the key. This kind of encryption is called Substitution Encryption. - The module also decrypts the message given that we know the key value of the encryption.""" try: import rand...
#!usr/bin/env python #list name = ['macel','zhangkai','zkorangesun'] #dist d = {"macel":95,"zhangkai":84,"zkorangesun":93} print d['macel'] print name[0] print d.get('zk') if 'zk' in d: print 'y' else: print 'n' print abs(-100) def my_abs(arg): return abs(arg) print my_abs(-101) print "hello"
# Project : Persistent Dictionary For Alien Civilization # Author : Syed Azam Hassan import json # Alien Language JSON Datafile def box(s): l = len(s) print("┌"+"─"*l+"┐") print("│"+s+"│") print("└"+"─"*l+"┘") print("\a") print(" ▄▄▄· ▄▄▌ ▪ ▄▄▄ . ▐ ▄ ·▄▄▄▄ ▪ ▄▄· ▄▄▄▄▄▪ ▐ ▄ ▄▄▄· ▄▄▄ ...
# https://towardsdatascience.com/common-loss-functions-in-machine-learning-46af0ffc4d23 import numpy as np y_hat = np.array([0.000, 0.166, 0.333]) #Prediction for training example y_true = np.array([0.000, 0.254, 0.998]) #actual result #Regression Losses #mean square error def rmse(predictions, targets): diffe...
class nguoi: def __init__(self,ten=None): self.ten=ten def nhap(self): self.ten=input("Ten: ") def xuat(self): print(self.ten,"la nguoi") class hocsinh(nguoi): def __init__(self,masv=None,ten=None,lop=None): super().__init__(ten) self.masv=masv self.lop=l...
# def tieneRepetidos(arr): # repetido = False # for i in arr: # if arr.count(i) > 1: repetido = True # print(repetido) # x = list(input('Ingrese una lista: ').split(', ')) # tieneRepetidos(x) # def esPalidrome(arr): # if arr[::-1] == arr: print('Es palídrome') # else: print('No es palídrom...
# map(int, input().split(' ')) def promedio_arreglo(arr): mappedList = list(map(int, arr)) sum = 0 for i in mappedList: sum += i return sum / len(mappedList) x = list(input('Ingrese el arreglo: ').split(', ')) print(promedio_arreglo(x))
# lista1 = [0, 1, 2, 3] # lista2 = ['A', 'B', 'C'] # lista3 = [lista1, lista2] # print(lista3) # print(lista3[0]) # print(lista3[1]) # print(lista3[1][0]) # lista1 = ["A", "B", "C", "E"] # lista2 = [1, 2, 3, 4, 5] # lista3 = lista1 + lista2 # aqui se presenta un pequeño error # print(lista3) # nombres = ['Antonio', '...
# Examples of Python lists # A list is defined using the [] (Square) brackets. # Individual items are seperated by commas. my_shopping_list = ["Apples","Oranges","Milk", "Bread"] print("="*20) print("The list: ") print("="*20) print(my_shopping_list) raw_input("\nPress Enter to advance...") # We can add items to t...
# -*- coding: UTF-8 -*- #지하철 카드는 어떻게 돌아갈까? #구성 : 사람, 리더기, 기계, 문 #고려사항 : 나이, 환승횟수 #card 세팅 : 연령, 가진 돈, 환승횟수, 거리 usercard_age = 0 #(청소년 = 0, 일반인 = 1) usercard_money = 0 usercard_transfer = 0 transfer = 1 #카드 충전 및 카드 상태설정 usercard_money = input("얼마를 충전하시겠습니까? : ") usercard_age = input("당신의 연령은 ?(청소년 = 0, 어른 =1) : ") ...
from tkinter import * # For some reason, importing tkinter doesn't import messagebox in Python 3.6+ from tkinter import messagebox from tkinter import simpledialog guessList = [] class GuessNumber(Frame): '''represents a board of guess your number''' def __init__(self,master,lowerRange,upperRange): '''...
#!/usr/bin/env python # coding: utf-8 # In[1]: class NumberPattern(object): def __init__(self,start,end = 0,step = -1): self.start = start self.end = end self.step = step def pattern(self): numbers = [i for i in range(self.start,self.end,self.step)] ...
def inches_to_cm(inches): return inches * 2.54 def lbs_to_Kg(lbs): return lbs * 0.453592 name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' height_in_cm = inches_to_cm(height) #cm weight_in_kg = lbs_to_Kg(weight) # Kg print(f"L...
import argparse import json import sys class PasswdFieldEnum(object): USERNAME = 0 UID = 2 GECOS = 4 TOTAL_FIELDS = 7 class GroupFieldEnum(object): GROUPNAME = 0 USERS = 3 TOTAL_FIELDS = 4 class FileFormatError(Exception): pass def validate_passwd_format(user_data, line_num, user...
#!/usr/bin/env python3.8 # -*- coding: utf-8 -*- #数据类型 #1.整数 -精确运算 print("整数:") print(1,-1,0) #十进制 print(0xff,0x00) #十六进制 0x开头 print("\n") #2.浮点数 -四舍五入存储 print("浮点数:") print(1.23e10) #科学计数法:1.11 -> 0.111e1 print(1.11e-3) print("\n") #3.字符串 -’.‘或者“.”或者’‘’.''' print("字符串:") print('I\'m OK!') # 转义 \' pri...
#!/usr/bin/env python3.8 # -*- coding: utf-8 -*- #高阶函数,返回函数,匿名函数,装饰器,偏函数 #1.高阶函数 Higher-order function #函数名也是变量,指向函数代码 fabs=abs print("1.",fabs(-12),type(fabs),fabs.__name__) #函数作为变量,传入某个函数当做参数,即是高阶函数 #函数的参数,是变量,这个变量是另一个函数 def abs_add(x,y,f=abs): return f(x)+f(y) print("2.",abs_add(-10,-28,abs),abs_add(19,-11)...
sum_num = 1 for i in range(1, int(input()) + 1): sum_num = (sum_num * i) % (10**9 + 7) print(sum_num)
a, b = map(int, input().split()) if a == 1: a = 14 if b == 1: b = 14 def calc(a, b): if a > b: return 'Alice' elif a < b: return 'Bob' else: return 'Draw' print(calc(a, b))
# 'a' + str + 'b' # 'c' + str + 'a' # 'b' + str + 'b' n = int(input()) ans = input() count = 0 turn = 0 s = 'b' while True: if len(s) > n: print(-1) break elif ans == 'b': print(0) break else: if turn == 0: s = 'a' + s + 'c' turn += 1 ...
x = float (input ("введите число: ")) if -2.4 <= x <= 5.7: print (x ** 2) else: print(4) else: ("введите число!:")
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self, root): self.root = Node(root) self._print_tree_selector = { 'preorder': self._preorder_print, 'inorder': sel...
import numpy as np import random def swap_mutate(chromosome,mutate_percent): ## flip coin to see if chromosome gets mutated if random.uniform(0,1) < mutate_percent: ## select 2 random genes of the chromosome gene1 = random.randint(0, len(chromosome)-1) gene2 = random.randint(0, ...
# This function is an implementation of the autokey Vigenere cipher algorithm. def decryptVigenere(ciphertext, key): ciphertextbreak = [] ciphertextbreakextra = [] Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' smallLetters = 'abcdefghijklmnopqrstuvwxyz' keylength = len(key) ciphertextlength = len(cip...
#!/usr/bin/python3 print("Stoisz przed kamienną bramą podczas pełni księżyca. ") password = input("Podaj hasło: ") if password.lower() == "melon": print("Możesz wejść, brama została otwarta!") else: print("Hasło nie zadziałało")
# STEP 4 # Create a checking account class that is a subclass of the abstract account class. It should have the # following member methods: # makeWithdraw: Before the super class method is called, this method will determine if a # withdrawal (a check written) will cause the balance to go below $0. If the # balance goe...
#practice working with dates and time from datetime import date from datetime import time from datetime import datetime def main(): print("Today's date = ", date.today()) print("Current time = ", datetime.now()) print("The current year =", date.today().year) print("The current month =", date.today().month) if __n...
#task1 def binarysearch(arr, l, r, x): if r >= l: mid = l + (r - l) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binarysearch(arr, l, mid - 1, x) else: return binarysearch(arr, mid + 1, r, x) else: return -1 ...
#Questao 1 # 1. Escreva um programa em Python que leia uma tupla contendo 3 números inteiros, (n1, n2, n3) e os imprima em ordem crescente. print("Digite 3 números conforme exemplo: (n1, n2, n3)") numeros = tuple(str(input("Informe os 3 numeros ")).split(",")) numeros = [int(i) for i in numeros] numeros.sort(reverse=...
# Questao 9 # 9. Usando o código anterior, escreva um novo programa que, quando as teclas ‘w’, ‘a’, ‘s’ e ‘d’ forem pressionadas, # ele movimente o círculo com o texto “clique” nas direções corretas. # Caso colida com algum retângulo, o retângulo que participou da colisão deve desaparecer. import pygame from pygame.l...
a = 10 b = 5 print('a =', a, '\tb = ', b) a = a ^ b b = a ^ b a = a ^ b print('a =', a, '\tb =', b)
a = 8 b = 2 print('Addition:\t' , a, '+', b, '=', a+b) print('Subtraction:\t' , a, '-', b, '=', a-b) print('Multiplication:\t' , a, '*', b, '=', a*b) print('Floor Division:\t' , a, '/', b, '=', a//b) print('Modulo:\t\t' , a, '%', b, '=', a%b) print('Exponent:\t' , a, '^2=', b, '=', a**b)
#queremos usar multiprocessamento sempre que for para acelerar significativamente nosso programa, #agora a aceleração vem de diferentes tarefas executadas em paralelo import concurrent.futures import time #inicio marcador do tempo start = time.perf_counter() #função responsável pelo delay def do_something(seconds): ...
#dicionarios student = {'name': 'Guilherme', 'age': 21, 'courses': ['Math', 'CompSci']} print(student['name']) student['phone'] = '111-111' print(student.get('phone','not found')) print(student.items()) print('\n') for key, value in student.items(): print(key, value)
""" Contains exceptions that can be thrown during the course of executing this client """ class NetworkError(IOError, RuntimeError): """ Thrown if the client is unable to connect to the server, or recieves an unexpected response from the server. """ pass class ValidationError(ValueError): ""...
import unittest from populace import find_users class TestFindUsers(unittest.TestCase): def test_valid_city_with_results(self): """ Test method returns correct number of users for a valid city """ users = find_users("London") self.assertEqual(len(users), 9) def test_v...
from Student import Student from Dorm import Dorm from matrix import Matrix import random dorms = [] students = [] NUMDORMS = 2 NUMSINGLES = 3 NUMDOUBLES = 3 ROOMSPERDORM = NUMSINGLES + NUMDOUBLES NUMSTUDENTS = NUMDORMS * (NUMSINGLES + NUMDOUBLES * 2) def initDorms(): for dorm in range(NUMDORMS): ...
A = float(input()) B = float(input()) C = float(input()) PESO_A = 2 PESO_B = 3 PESO_C = 5 A_POND = PESO_A * A B_POND = PESO_B * B C_POND = PESO_C * C MEDIA = (A_POND + B_POND + C_POND) / (PESO_A + PESO_B + PESO_C) print("MEDIA = %.1f" % MEDIA)
number_1 = input('enter 1-st number: ') number_2 = input('enter 2-nd number: ') if number_1.isdigit(): if number_2.isdigit(): sum = int(number_2) + int(number_1) print(number_1,"+",number_2,"=",sum) else: print(number_2," is'nt a digit") else: print(number_1," is'nt a digit") print("Good...
#!usr/bin/env python def hora_minuto(horas=0): if horas < 1 or horas > 100: print("Error no puede ingresar numeros menores a 0 o mayores a 100") else: print("Existen {result} minutos en {hora} hora(s).".format( result=horas * 60, hora=horas)) def main(): try: horas = i...
def fibonacci(n): """ Metodo recursivo # para 34 toma 5 seg """ if n == 1 or n == 2 or n < 1: return 1 else: result = fibonacci(n - 1) + fibonacci(n - 2) return result def fibonacci_2(n): """ Funcion fibonacci usando el metodo de menor a mayor ...
from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize ps=PorterStemmer() example_words=['python','pythoner','pythoning','pythoned','pythonly'] for w in example_words: print(ps.stem(w)) new_text='it is very important to be pythonly while you are pythoning with python. All pythoners h...
#calculate the number of students in this classroom total = 0 student = int( input("Enter value: ") ) while student != -1: total += student student = int( input("Enter value: ") ) print( "total=" , total )
#1. Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big".Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5] arr = [-1, 34, -3, 37, 16, -25, -5, 87] def newArr(arr): for i in range(0, len(arr), 1): i...
#import modules/requests import requests import bokeh import pandas as pd import csv import numpy as np import json api1="https://maps.googleapis.com/maps/api/geocode/json" csvfile=open('data.csv','w') csvwriter=csv.writer(csvfile, delimiter=',') #the while loop allows the user to enter the desired amount of inputs n...
class Casting: def to_int(s): if type(s) == str: return int(s.strip()) else: return s class 사각형: name = "사각형" def __init__(self): print("사각형 created") def input_data(self): datum = input(self.msg) # 5, 3 data = datum.split(',') # [...
import math A=float(input("Digite o valor do coeficiente A: ")) B=float(input("Digite o valor do coeficiente B: ")) C=float(input("Digite o valor do coeficiente C: ")) Delta=B**2-4*A*C if Delta<0: print(f"Seu delta vale {Delta} , portanto a equação não possui raízes reais.") if (Delta >=0): x1=(-B+math.sqrt(Del...
c=0 s=0 maiors=0 menors=float(input("Digite o valor do salário: ")) while(c<4): s=float(input("Digite o valor do salário: ")) c+=1 if maiors<s: maiors=s if menors>s: menors=s print(f"O maior salário foi de R${maiors:.2f} e o menor foi de R${menors:.2f}")
import os import pygame from random import choice chanse = [0] * 8 + [1] * 2 # вероятность появления (2/10) class Board: # класс поля def __init__(self, board_size): self.board_size = list(board_size) self.board = [[0] * board_size[0] for _ in range(board_size[1])] # сам...
def AnoPangalanMo(): PangalanMoPo = input("What's your name?: ") return PangalanMoPo def AnongEdadMoNa(): WhatsYourAge = input("What is your Age?: ") return WhatsYourAge def SaanKaPoNakatira(): WhereDoYouLive = input("What's your Address?: ") return WhereDoYouLive def GaanoKaKatangkad(): ...
#https://adventofcode.com/2016/day/6 from collections import defaultdict def part1(input_file): with open(input_file, "r") as f: lines = f.read().strip().split("\n") letter_counts = [defaultdict(int) for i in range(len(lines[0]))] for line in lines: for i in range(len(line)): letter_co...
#https://adventofcode.com/2016/day/7 def is_abba(string): return ((string[0] != string[1]) and (string[2] == string[1]) and (string[3] == string[0])) def part1(input_file): with open(input_file, "r") as f: ips = f.read().strip().split("\n") valid_count = 0 for ip in ips: ...
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ zero_index = 0 curr_index = 0 two_index = len(input_list)-1 while curr_index <= two_index: curr_val = inp...
class PizzaStorage: def __init__(self): self.count = 10 def minus(self, count): self.count = self.count - count class Customer: def __init__(self, name, storage): self.name = name self.storage = storage def eat(self): self.storage.minus(1) class FatCustomer(...
import random def gen_func(): while True: yield random.random() generator = gen_func() print('generator function', gen_func) # генераторная функция print('generator', generator) # генератор print('value: ', generator.__next__()) print('value: ', generator.__next__()) print('value: ', generator.__next__()) # O...
#!/usr/bin/env python3 class A(object): def foo1(self,x): print("executing foo1(%s,%s)" % (self,x) ) self.foo2() def foo2(self): print('method foo2 ' + str(self.__class__)) @classmethod def class_foo(cls,x): print("executing class_foo(%s,%s)" % (cls,x) ) cls.class_foo2() @clas...
# oprator haye condition < > >= <= == != # int * int = int # str * int = str # int * float = float num_2 = 20 num_1 = 10 result = num_1 > num_2 print(result) num = 50 start = 0 stop = 100 res_1 = num > start res_2 = num < stop print (res_1,"\n", res_2) # "\n" baraye new line # mitavan shart haro to ye khat tarkib ka...
import pandas import turtle screen = turtle.Screen() screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) # A writing "turtle" that will write in the names of correctly guessed states: writer = turtle.Turtle() writer.hideturtle() writer.penup() # Co...
def main(): baseWord = getMainWord() baseWordSplat = list(baseWord) wordList = [] getWords(wordList) compTotalResultList = engine(wordList, baseWordSplat) print('\nDifferences from', baseWord, 'based on ASCII values per character (somewhat pointless): \n') for each in range (0, len(compTo...
import streamlit as st import numpy as np import pandas as pd # Add a title st.title('My first app_') # Add some text st.text('Streamlit is great') st.dataframe(pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] })) # lineplot chart_data = pd.DataFrame( np.rand...
number=int(input()) sum_int=0 while number>0 : sum_int += number%10 number //= 10 print(sum_int)
hours = [False] * 4 minutes = [False] * 6 def clock(n, hours, minutes, h, m, posh, posm): if(posm > 5 or posh > 3): return if(n == 0): if(h < 12 and m < 60): print(str(h) + ":" +str(m)) return for pos in range(posh, len(hours)): if not hours[pos]: ...
import numpy as np from PIL import ImageFont, Image, ImageDraw, ImageEnhance from colour import Color from math import floor SAMPLE_LETTER = "x" # Used to determine the typical width and height of an ASCII character BRIGHTNESS_FACTOR = 1.5 # How much to brighten image by GRAYSCALE_LVLS = "#&B9@?sri:,. " # GR...
def restaurant(cruzer1): menu = [] foods = cruzer1["sells"] cocacola = foods[0]["name"] cocacola_price = foods[0]["price"] pizza = foods[1]["name"] pizza_price = foods[1]["price"] hamburguesa = foods[2]["name"] hamburguesa_price = foods[2]["price"] hamburguesa_refresco = foods[3]["name"] hamburgue...
def fibo(n): a = 0 b = 1 sum = 0 series =[] series.append(a) series.append(b) while(sum < n): sum = a + b series.append(sum) a = b b = sum print(series) limit = int(input("enter the number till where u want your fib series : ")) fibo(limit)
from cs50 import SQL import csv from sys import argv # Open Db db = SQL("sqlite:///students.db") # Read parameters if len(argv) != 2: print("Usage : python roster.py <house name>") exit(1) query = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first", argv[1]) lis...
year = int(input()) while True: year += 1 string = str(year) if len(set(string)) == len(string): print(string) break
from re import findall pattern = r"([@|#])([A-Za-z]{3,})\1\1([A-Za-z]{3,})\1" data = input() matches = findall(pattern, data) mirror_words = [] for match in matches: if match[1] == match[2][::-1]: mirror_words.append(match[1] + " <=> " + match[2]) if not matches: print("No word pairs found!") else: print(f"{len...
start_index = int(input()) stop_index = int(input()) for index in range(start_index, stop_index + 1): print(chr(index), end=' ')
goal_height = int(input()) current_height = goal_height - 30 total_attempts = 0 success = False while not success: for _ in range(3): attempt_height = int(input()) total_attempts += 1 if goal_height <= current_height < attempt_height: success = True break if a...
guests_count = int(input()) price_per_guest = float(input()) budget = float(input()) discount = {10 <= guests_count <= 15: 0.15 * price_per_guest * guests_count, 15 < guests_count <= 20: 0.2 * price_per_guest * guests_count, guests_count > 20: 0.25 * price_per_guest * guests_count, ...
tournaments_count = int(input()) starting_points = int(input()) points = {"W": 2000, "F": 1200, "SF": 720} final_points = 0 won_tournaments = 0 for _ in range(tournaments_count): stage_reached = input() final_points += points[stage_reached] if stage_reached == "W": won_tournaments += 1 avrg_poin...
from re import compile pattern = compile(r"(w{3}.[A-Za-z0-9-]+(\.[a-z]+)+)") data = input() while data: match = pattern.findall(data) if match: print(match[0][0]) data = input()
import string READ_PATH = 'text.txt' WRITE_PATH = 'output.txt' def count_symbols(line, validation): return len([ch for ch in line if ch in validation]) with open(READ_PATH, 'r') as r_file: with open(WRITE_PATH, 'w') as w_file: reader = r_file.readlines() for index, line in enumerate(reader)...
sweets_prices = {"cookies": 1.50, "cakes": 7.80, "waffles": 2.30} sweets_count_total = {"cookies": 0, "cakes": 0, "waffles": 0} bakers_count = int(input()) for _ in range(bakers_count): baker_name = input() sweets_type = input() sweets_per_baker = {"cookies": 0, "cakes": 0, "waffles": 0} while sweets_...
"""Search for element's COORDINATES until element is found from given POSITION in SQUARE matrix""" QUEEN = 'Q' KING = 'K' SIZE_OF_MATRIX = 8 DELTAS = [ (0, -1), # left (-1, -1), # up left (1, 0), # up (-1, 1), # up right (0, 1), # right (1, 1), # down right (-1, 0), # down (1, -1...
width = int(input()) height = int(input()) depth = int(input()) priority = input() volume = width * height * depth taxes = {"true": {50 < volume <= 100: 0, 100 < volume <= 200: 10, 200 < volume <= 300: 20}, "false": {50 < volume <= 100: 25, 100 < volume <...
sold_count = int(input()) hearthstone_count = 0 fornite_count = 0 overwatch_count = 0 others_count = 0 for s in range(sold_count): game_name = input() if game_name == "Hearthstone": hearthstone_count += 1 elif game_name == "Fornite": fornite_count += 1 elif game_name == "Overwatch": ...
x = int(input()) y = int(input()) for number in range(x, y + 1): even_sum = 0 odd_sum = 0 counter = 1 num = number while num > 0: last = num % 10 if counter % 2 == 0: even_sum += last else: odd_sum += last num = num // 10 counter += 1...
#!/usr/bin/env python3 def print_line(n): ll = [] for i in range(1, n+1): ll.append(i) print(' '.join(map(str, ll))) def print_triangle(size): for row in range(1, size + 2): print_line(row) for row in range(size, 0, -1): print_line(row)
n = int(input()) even_sum = 0 odd_sum = 0 for index, _ in enumerate(range(n), 1): number = int(input()) if index % 2 == 0: even_sum += number else: odd_sum += number difference = abs(even_sum - odd_sum) if difference == 0: print(f"Yes\nSum = {even_sum}") else: print(f"No\nDiff = {...
def draw_battle_field(n_raws): """You will be given a number n representing the number of rows of the field. On the next n lines you will receive each row of the field as a string with numbers separated by a space. Each number greater than zero represents a ship with a health equal to the number value.""" field = ...
budget = float(input()) category = input() people_count = int(input()) prices = {"VIP": 499.99, "Normal": 249.99} transport_price = {1 <= people_count <= 4: 0.75 * budget, 5 <= people_count <= 9: 0.6 * budget, 10 <= people_count <= 24: 0.5 * budget, 25 <= peopl...
city = input() sales = float(input()) commission = 'error' commissions = {'Sofia': {0 <= sales <= 500: 0.05, 500 < sales <= 1000: 0.07, 1000 < sales <= 10000: 0.08, sales > 10000: 0.12}, 'Varna': {0 <= sales <= 500: 0.045, ...
data = input() resources = {} all_input_list = [] while not data == "stop": all_input_list.append(data) data = input() for index in range(0, len(all_input_list), 2): key = all_input_list[index] value = all_input_list[index + 1] if key not in resources.keys(): resources[key] = int(value) else: resources[key] ...
class Customer: __id = 0 def __init__(self, name: str, address: str, email: str): self.name = name self.address = address self.email = email self.id = self.set_id() def __repr__(self): return f"Customer <{self.id}> {self.name}; Address: {self.address}; Email: {self....
money_vacation = float(input()) money_available = float(input()) total_days = 0 spend_days = 0 while money_available < money_vacation: total_days += 1 action = input() action_money = float(input()) if action == 'save': money_available += action_money spend_days = 0 elif action == ...