text
stringlengths
37
1.41M
import urllib2 """ In this implementation, if the first 3 lines of a file are 'un:' or 'pw:', then retreive whatever is located at index 5 to the second last character and assign it to a variable. """ page = urllib2.urlopen('http://www.pythonchallenge.com/pc/def/integrity.html') for line in page: if line[:3] == '...
import urllib2 """This solution assumes rare to be the least occuring. It maps out the occurence of the characters and then finds the characters that occur the least number of times and uses that. By splitting the raw_data using "<!--" we get three separate lists. We're only interested in the third list hence "[2]" ...
""" The image at the bottom of the page is actually 10000 x 1 pixels Above it is an image of a spiralled bun. This is a hint that you need to create a spiral of the image at the bottom. In the source you'll find <!-- remember: 100*100 = (100+99+99+98) + (... --> These are the dimensions you're supposed to use to spir...
while True: try: cantidad_amigos = int(input("Cuantos amigos tienes: ")) break except ValueError: print("No has introducido un numero!") for cantidad in range(cantidad_amigos): print("Hola", input("Nombre amigo:"))
#! /usr/bin/python3 def main(): import random dice_rolls = int(input('How many dice would you like to roll?\n')) dice_sides = int(input('How many sided die?\n')) dice_sum = 0 for i in range(0,dice_rolls): roll = random.randint(1,dice_sides) dice_sum = dice_sum + roll if roll == 1: print(f'...
def iszhishu(tmpint): if tmpint < 2: return False elif tmpint == 2: return True else: x = int(tmpint ** 0.5) for tmp in range(2, x + 1): if tmpint % tmp == 0: return False return True def get_zhishu_list(num): tmplist = [] for i i...
#Slots #5/6/2013 @ 00:05 from tkinter import * from random import * class Player: def __init__(self): self.cash = 1500 self.loss = 0 self.win = 0 self.lossStreak = 0 self.bet = 1 def getCash(self): return self.cash def addCash(self, money): sel...
import unittest # accepts a string of the form 1-2,4,5-9 and returns a list of numbers # or the lengths of each segment # asserts if ranges are out of order or duplicated def Parse(input, lengths=False): result = [] rangeLength = [] terms = input.split(',') assert (len(terms) >= 1) for term in terms: su...
Other_name = input("Tell your name: ") My_name_Correct = Other_name.lower() My_name = "yevhen" My_name == My_name_Correct if My_name == My_name_Correct: print("Good Boy, Yevhen") else: print(Other_name + ",your not Ivzhen")
# AOC 2019 - DAY 1 # Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, # safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars. # Collect sta...
def ftp_calc(twenty_min_power, weight_in_lbs): ftp = round(twenty_min_power * .95) weight_in_kg = round(weight_in_lbs / 2.2, 2) w_per_kg = round(ftp / weight_in_kg, 2) print(f"Your FTP in watts per kilo is {w_per_kg}.") ftp_calc(282, 165) twenty_power = 282 pounds = 165 ftp_calc(twenty_power, pounds)...
#Lists #List is mutable data structure #Empty list creation my_list = [] my_list = list() #Lists examples my_list = [1, 2, 3] my_list2 = ["a", "b", "c"] my_list3 = ["a", 1, "Python", 5] my_nested_list = [my_list, my_list2] my_nested_list # return [[1, 2, 3], ['a', 'b', 'c']] #Combine two lists together #First way...
# sys module sys.argv # list of command line arguments that were passed to the Python script argv[0] # return python script name. Depending on the platform that you are running on, the first argument may contain the full path to the script or just the file name sys.executable # will return absolute path to python inte...
import os import json from flask import Flask, render_template, request, flash if os.path.exists("env.py"): import env # we import the flask class from Flask dependency app = Flask(__name__) """ We create an instance of the flask class and save it as a variable called app. The first arguement of the Flask class, ...
def get_api_url(method): """ Returns API URL for the given method. :param method: Method name :type method: str :returns: API URL for the given method :rtype: str """ return 'https://slack.com/api/{}'.format(method) def get_item_id_by_name(list_dict, key_name): for d in list_dict...
import random from dict_names import first_name, middle_name, last_name def name_gen(): num_of_name = random.randint(1, 3) if num_of_name == 1: return random.choice(first_name) elif num_of_name == 2: return random.choice(first_name) + random.choice(last_name) elif num_of_name...
class ListNode: def __init__(self, value, next_node=None): self.value = value self.next = next_node class LinkedList: def __init__(self): self.head = None def add(self, value): # If head is empty, set head if self.head is None: self.head = ListNode(valu...
# 9.4 Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a co...
import math from tensorboardX import SummaryWriter if __name__ == "__main__": writer = SummaryWriter() funcs = {"sin": math.sin, "cos": math.cos, "tan": math.tan} for angle in range(-360, 360): angle_rad = angle * math.pi / 180 for name, fun in funcs.items(): val = fun(angle_rad) writer.add_scalar(name,...
import math def main(): #escribe tu código abajo de esta línea largo = float(input("(largo)>>>")) ancho = float(input("(ancho)>>>")) diagonal = math.sqrt(largo ** 2 + ancho ** 2) print(diagonal) if __name__=='__main__': main()
import sqlite3 from creds import database,table conn=sqlite3.connect(database)# your database name cur=conn.cursor() def confirm_exists(name): cur.execute('SELECT Name FROM '+table+' WHERE Name like \'%'+name+'%\'')# MySQL query to search databse # PS:If you want,you can search multiple table simultaneously. j...
import math numbers=range(5) print(numbers) factorials = [math.factorial(num) for num in range(5)] print(factorials)
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html ha...
def fatorial(num): if num ==1: return 1 return num * fatorial(num-1)
import pygame class SnakeBody(object): def __init__(self, xPos, yPos, color, window): '''initiate and draw a snake part''' self.xPos = xPos self.yPos = yPos self.color = color self.drawBody(window) #when created, draw the box def drawBody(self, window): '''draw ...
string1 = "he's " string2 = "probably " string3 = "pining " string4 = "for the " string5 = "fjords" print(string1 + string2 + string3 + string4 + string5) print("he's " "probably " "pining " "for the " "fjords") # don't need the + sign to concatenate print("Hello " * 5) # Hello Hello Hello Hello Hello # print("Hello ...
def consistency_test(val1, val2, sigma1, sigma2) : t = abs((val1 - val2))/(sigma1 + sigma2) if t > 2 : print("Inconsistent, t = ", t) else : print("Consistent, t = ", t)
import sys import json def bubbleSort(tableToSort): result = tableToSort for index in range(len(result) - 1, 0, -1): for i in range(index): if result[i] > result[i + 1]: tmp = result[i] result[i] = result[i + 1] result[i + 1] = tmp return...
def get_numbers_from_file() -> None: with open('numbers.txt') as my_file: numbers = ''.join(my_file.readlines()).split(',') for i in numbers: print(i) if __name__ == '__main__': get_numbers_from_file()
# создание цикла по списку #sps=[2,3,4,12,17345,-1,-15] #for nbr in sps: # a=nbr+1 # print(a) # цикл на введенную с клавиатуры строку #a=input("Введите строку :") #print(a) #for letter in a: # print(letter) #Цикл по оценкам #maz = [ # {"kls":"2a", "marks":[4,4,5,4,5]}, # {"kls":"3б", "marks":[3,...
import os import json import torch import numpy as np def mean_std(dataloader_object, axis=None): """ Compute the mean and standard deviation of a dataset. Useful for test data normalization, when the mean and std are unknown. Argument: dataloader_object (torch.utils.data.DataLoader) - your da...
import numpy as np def softmax(a): exp_a = np.exp(a) sum_exp_a = np.sum(exp_a) y = exp_a / sum_exp_a return y def softmax_solution(a): c = np.max(a) exp_a = np.exp(a - c) sum_exp_a = np.sum(exp_a) y = exp_a / sum_exp_a return y if __name__ == '__main__': a = np.array([1010, ...
l1 = [('a', 1), ('b', 2), ('c', 3)] print(l1) d1 = dict(l1) print(d1) st1 = "dfsdf" l2 = list(st1) d1 = {'x':1, 'y':2} m1,m2 = d1 print(d1.it) #i1, i2 = d1.items print(m1, " ", m2, " ")
#Sevren Gail #Christopher Rendall #Team 3 - Lab 14 import re #For regular expressions, to replace an undetermined number of spaces in eggs.txt. #wordCount counts the number of total words in wordDict and returns the result. def wordCount(wordDict): count = 0 for key in wordDict: count += wordDict[key] return...
#################### # CST-205 # # Module 5 Lab 12 # # Sevren Gail # # Chris Rendall # #################### from random import randint class Object: #These are objects found around the mansion. def __init__(self, name, description, permanence): #This constructor estabishes the name, description an...
class Animal(object): def __init__(self): self.type="animal" def breed(self): return Animal() def makeNoise(self): print "I am %s, I am an animal" % self.type class Dog(Animal): def __init__(self,numlegs): self.type="dog" self.eager=False self.numlegs=num...
import math def magnitude_3d_euclid(v): '''Calculate 3d euclidian magnitude of the vector v arg v: indexable of length 3 ''' return math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) def distance_3d_euclid(v1, v2): '''Calculate 3d euclidian distance between vectors v1 and v2''' return magnitu...
def print_menu(): print("1. Print all the Contacts") print("2. Add a Contact") print("3. Remove a Contact") print("4. Lookup a Contact") print("5. Quit the program") print() emailid = {} numbers = {} birthday = {} menu_choice = 0 print_menu() while menu_choice != 5: menu_choice = int(input(...
#7. Write a Python Program to read a input from the user and then check whether the given character is an alphabet, number or a special character. If it is an alphabet, convert in to UPPERCASE and vice-versa. import string a = input("Enter the String: ") def is_number(s): try: float(s) return True ...
#2. Write a Python Program to implement swapping or exchanging two numbers. first = int(input("Enter the First Number: ")) second = int(input("Enter the Second Number")) print("Before Swap") print ("The First Number is ",first," and the Second Number is ",second) first = first + second second = first - second first = ...
#10. Check whether a given Number is Armstrong or not n = int(input("Enter the Number: ")) m = n s = 0 while (n>0): r = n%10 n = n//10 s = (s+(r*r*r)) if(s==m): print("The Number ",m," is Armstrong Number!") else: print("The Number is not a Armstrong Number!") """ num = int(input("enter a number: ...
import math import random def halfthenumber(n): n=n/2 return n humannum=float(raw_input("Please Enter a number between 0 and 100 ")) compguess = random.randrange(0,100) guesscount=1 #print "The Entered number between (0 and 1000) is : " + str(humannum) #print "The Current Guess is : " + str(com...
##### To Import Packages######## import math import os import random ##### End of Packages######### ##### Welcom Message######### print "Welcome to Ravi's Math programs" ##### End of Welcome Messages ######### frect_area = 0 frect_perimeter=0 def conv_milestofeet(x): feet=5280*float(x) ...
########################### # 6.0002 Problem Set 1b: Space Change # Name: # Collaborators: # Time: # Author: charz, cdenise #================================ # Part B: Golden Eggs #================================ # Problem 1 def recursion(egg_weights, target_weight, choice, memo={}): # I think we can remove this...
class People: def __init__(self , age=0, name=None): self.__age = age self.__name = name def introMe(self): print("Name: ",self.__name,"age: ", str(self.__age)) class Teacher(People): def __init__(self , age=0, name=None, school=None): super().__init__(age, name) #...
ages = [10,30,45,18,21,8,19,20,28,33] print('청소년:') for a in filter(lambda x:x<20, ages): print(a , end=" "); print(); print(list(filter(lambda x:x%2!=1 , range(11))))
#str = input("문자를입력하세요") str = 'I love Python' word = "love" print(len(str)) ''' for i in range(0,10,1): print(word, end="") print(""); ''' print(word * 10) #2 print(str[0]) print(str[:3]) print(str[len(str)-3:]) for j in range(-1, -len(str)-1, -1): print(str[j], end="") print("") if(str[6].isalpha()): #7 p...
days = {'January':31, 'February':28, 'March':31, 'April':30, 'May':31, 'June':30, 'July':31, 'August':31, 'September':30, 'October':31, 'November':30, 'December':31} #1. 월 입력 일수 출력 ''' mon = input("월 입력") print(days.get(mon)) ''' #...
#튜플 t1 = (1,2,3,4,5) #소괄호 사용 print(t1) t1 = 1,2,3 #소괄호 생략 가능 print(t1) t1 = 1 print(type(t1)) t1 =1, #요소가 1개일 때는 ,을 붙인다. print(type(t1)) t1 = tuple() # 빈튜플 생성 print(t1)
a=[] #빈리스트 for i in range(0,50): #0~49 a.append(i) print(a) #아래도 과제 # 1~50 가지 수의 제곱으로 구성되는 리스트 a=[] for i in range(1, 51): a.append(i**2) print(a) #L=[1,2,3] M=[4,5,6] LM=[5,7,9]인 리스트 만들기 L=[1,2,3] M=[4,5,6] LM=[] for i in range(0,3): LM.append(L[i] + M[i]) print(LM) #과제는 날짜별로 출력해서 제출
def viewvoterlist(): b=int(input("candidate number political party\n1) BJP\n2) BSP\n3) Congress\n4) other")) if(b==1): f=open("bjp","r") data=f.read() ...
number = int(input("enter a number.")) print("Then number is {}".format(number))
# Corey Schultz # 4/3/2016 import time time.sleep(2) print "Welcome to Prison Break!" time.sleep(2) print "The Interactive Prison Escape Game" time.sleep(3) print "Created by Corey Schultz" time.sleep(3) print "Let's Begin" time.sleep(2) import os os.system("cls") time.sleep(3) # end of intro / start of ...
from LanguageAbstract import * """ This module defines the concrete subclass, i.e. the ConcreteProduct class in the Factory pattern. The language defined here is English. """ class LanguageEnglish(Language): def addSounds(self, sounds): """ :param sounds: string :return: """...
from abc import ABC, abstractmethod """ This module defines the abstarct superclass LanguageCreator, i.e. the Creator in the Factory pattern """ class LanguageCreator(ABC): # def __init__(self): # self.data = {} @abstractmethod def createData(self, sounds, rules): """ :type soun...
from abc import abstractmethod, ABC class RuleComparator(ABC): @abstractmethod def greater_than(self, rule1, rule2): pass @abstractmethod def lesser_than(self, rule1, rule2): pass class RuleComparatorF1(ABC): @abstractmethod def greater_than(self, rule1, rule2): """...
# -*- coding: utf-8 -*- import sys import re import math from urllib.request import urlopen """ Реализовать функцию-генератор строки с таблицей умножения на число Х. """ def multiplication_table(x): res = [str(x) +"x" + str(a) + "=" + str(a*x) for a in range(10)] print ('\n'.join(res)) """ Есть лог-файл како...
def beber(idade): if idade>=18: print("Pode beber! ") elif idade<18 and idade>0: acomp = str(input("Você está acompanhado de algum responsável? ")) if acomp == "sim": print("Pode beber se seu responsável deixar, mas faz isso escondido tá?") else: ...
def printList(val): for k in range(len(val)): if k != len(val)-1 and k != len(val)-2: print(val[k], end=', ') elif k == len(val)-2: print(val[k], end=' and ') else: print(val[k]) spam = ['app', 'ban', 'tof', 'cat'] printList(spam) vl = str(inpu...
#! python # strongPass.py - функция проверки пароля. import re def checkPass(prompt): # Сильным будет пароль не меньше 8 символов, в вернем и нихнем регистре и 1 цифра # passRe = re.compile(r'(([0-9a-zA-Z]){8,})') passRe = re.compile(r'([0-9a-zA-Z]){8,}') passReDit = re.compile(r'.*(\d)+.*') ...
import sys import math import random def main(): # ./RSA.py init {size} if(len(sys.argv) == 3): if(sys.argv[1] == 'init'): generate_key(int(sys.argv[2])) elif(len(sys.argv) == 5): # .RSA.py -e {plaintext} {n} {e} if(sys.argv[1] == '-e'): print(encrypt(sys.ar...
#Outline: #1. File unshaad List butsaadag class #2. List ~ QuestionAnswer/Class/ #3. Play class ReadFile(): def __init__(self, fileName): self.fileName = fileName def getList(self): myFile = open(self.fileName, 'r') fullText = myFile.read() fullText = fullText[:-1] allDa...
#limited scope experiment with grid and tiles class TinyTile: def __init__(self, name): self.name = name class TinyGrid: def __init__(self,x,y=None): # Assume square unless otherwise said if (y is None): y = x tiny_array = [] for column in range (0,x): ...
from RobotArm import RobotArm robotArm = RobotArm('exercise 13') robotArm.randomLevel(1,7) move = 1 # Jouw python instructies zet je vanaf hier: robotArm.grab() while robotArm.scan() != "": for x in range(move): robotArm.moveRight() robotArm.drop() move = move + 1 for x in range(move): ...
def calculator(num1, operator, num2): return { "+" : num1 + num2, "-" : num1 - num2, "*" : num1 * num2, "/" : num1 // num2 if num2 else "Can't divide by 0!" }[operator]
def correct_title(txt): def func(x): if x in "and the of in": return x else: if "-" in x: return "-".join(map(func,x.split("-"))) else: return x[0].upper() + x[1:] return " ".join(map(func,txt.lower().split(" ")))
#!/bin/env/python # Solution for : https://leetcode.com/problems/array-partition-i/description/ # # To get the maximum sum, we need to include as many large numbers as possible # Largest numbers at even positions would never win in min(ai,bi) selection so # we have pick the numbers at odd position. # # It is an intere...
#!/usr/bin/env python ''' Multiply two integers without using "*" operator. ''' def mult(a, b): """ Multiplies two integers """ try: a = int(a) b = int(b) # TODO # 1) -ve numbers # 2) If one number is 1 only or zero if a == 0 or b == 0: retu...
from multiprocessing import Pool, cpu_count from joblib import Parallel, delayed def parfor(task, processes, args): """Parallel For. Applies a function *task* to each argument in *args*, using a pool of concurrent processes. Parameters ---------- task : function Function object t...
import numpy as np import matplotlib.pyplot as plt from secml.figure import CFigure fig = CFigure(fontsize=16) # create a new subplot fig.subplot(2, 2, 1) x = np.linspace(-np.pi, np.pi, 100) y = 2*np.sin(x) # function `plot` will be applied to the last subplot created fig.sp.plot(x, y) # subplot indices are are the ...
def slidingwindow(nums: list, k: int) -> list: if not nums: return [] window, res = [], [] for i, x in enumerate(nums): if i >= k and window[0] <= i - k: window.pop(0) while window and nums[window[-1]] <= x: window.pop() window.append(i) if i >= k - 1:...
import sys class Employee: def __init__(self): self.num = 0 self.salary = 0 self.name = '' self.next = None findword = 0 namedata = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] data = [[1001, 22222], [1002, 23451], [1003, 32456], [1004, 45678], [1005, 43214], [1006, 23332], [1007, 25552...
"""Calculate possibilities of flipping a coin.""" def full_probability(coin_probabilities: list[float], event_probabilities: list[float]) -> float: """Calculate full probability of flipping a coin and getting desired side. Parameters ---------- coin_probabilities : list of float Probabilities...
class Solution(object): def shortestDistance(self, words, word1, word2): """ :type words: List[str] :type word1: str :type word2: str :rtype: int """ j, k = float('inf'), float('inf') d = float('inf') for i in range(len(words)): if ...
''' Write a program to compute: f(n)=f(n-1)+100 when n>0 and f(0)=1 with a given n input by console (n>0). ''' def f(n): if n == 0: return 0 else: return f(n-1)+100 num1 = int(input("请输入一个正整数:")) print(f(num1)) ''' 递归的使用 '''
''' 定义一个方法,接受一个整数,判断这个数为基数或者偶数,打印输出结果 ''' def checkNum(n): try: if n%2 ==0: print("it is an odd number!") else: print("it is an even number!") except: print("{}不是一个整数!".format(n)) test = checkNum('s') ''' 利用偶数%2结果为0进行判断 '''
#计算一个数的阶乘 def test(l): if l == 1: return 1 else: return l*test(l-1) print('请输入一个数字:', end='') l = int(input()) print (test(l)) ''' 学习点:在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。 '''
''' 输入多个字符串,打印输出最长的那个 ''' def maxString(): str_input = input("请输入两个字符串:") str_list = str_input.split(' ') for s in str_list: len1 = len(s) len2 = 0 if len1>len2: len2 = len1 print(str_list[len2]) ''' 原题: 定义一个函数,接收两个字符串,打印输出最长的那个,如果相同长,那么全都输出打印出来 ''' de...
''' 字典的常用操作 ''' #get() 需要传一个key值 dict1 = {1:'abc','b':'weie','3':'abcid'} dict2 = {1:'sdf',3:'cdf',2:'iend'} result1 = dict1.get(1) print(result1) #dict.items() 输出字典内容以列表中的元组 #python3之后没有 iteritems result2 = dict2.items() print(result2) #dict_items([(1, 'abc'), ('b', 'weie'), ('3', 'abcid')]) #排序 dict3={} list1 =...
''' 定义一个函数,计算两个数的和 ''' def sum(num1,num2): return num1+num2 test = sum(2,3) print(test)
''' 网站要求用户输入用户名和密码进行注册。 编写程序以检查用户输入的密码的有效性。 以下是检查密码的标准: 1. [a-z]之间至少有1个字母 2. [0-9]之间至少有1个数字 1. [A-Z]之间至少有一个字母 3. [$#@]中至少有1个字符 4.最短交易密码长度:6 5.交易密码的最大长度:12 您的程序应接受一系列逗号分隔的密码,并将根据上述标准进行检查。 将打印符合条件的密码,每个密码用逗号分隔。 ''' import re values = [] list_password = [x for x in input().split(',')] for password in list_password: ...
#定义一个类,有两个方法,getString:从控制台获取字符串,printString:以大写的形式打印字符串 class InputOutputString(): def __init__(self): self.s = '' def getString(self): self.s = input() def printString(self): print(self.s.upper()) teststring = InputOutputString() teststring.getString() teststring.printString()...
# Import modules import os import csv # Paths to collect and write data input_path = os.path.join('resources', 'budget_data.csv') output_path = os.path.join('analysis', 'pnl_analysis.txt') # Create lists to store data revenue_changes = [] # Initialize variables total_months = 0 total_revenue = 0 prev_revenue = 0 rev...
import pygame import random as rand # Define ant class to make handling numerous ants easier class Ant(): # Initialize the ant with a direction and position def __init__(self,x,y,xVel,yVel): self.pos = (x,y) self.vel = (xVel,yVel) def getDirection(self): # Get the direction o...
import pandas as pd import os bank_csv = "Resources/budget_data.csv" bank_df = pd.read_csv(bank_csv) num_months = bank_df["Date"].count net_total = bank_df["Profit/Losses"].sum() difference_in_value = bank_df["Profit/Losses"].diff() bank_df["Difference"] = difference_in_value total_of_diff = bank_df["Difference"...
# Advent of Code 2017 - Problem 1, Day 3 ######################################## # You come across an experimental new kind of memory stored on an infinite two-dimensional grid. # They always take the shortest path: the Manhattan Distance between the location of the data and square 1. # How many steps are required to ...
# coding: utf-8 # In[24]: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt sess = tf.Session() # # Debugging # In normal code (in Python or otherwise), a pretty standard practice is to add conditionals in your code to look for certain behavior when something has gone awry. For example: #...
# Time Complexity :O(log n) # Space Complexity :O(1) # Did this code successfully run on Leetcode : yes # Any problem you faced while coding this : no class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode ...
""" Tournament class: storage of teams, schedules and output methods """ from collections import namedtuple TournamentDayTimings = namedtuple('TournamentDayTimings', 'date t_start t_end num_pitches') # Day-specific information DayTiming = TournamentDayTimings class Tournament(object): def __init__(self): ...
data = input() digits = "" letters = "" other = "" for chr in data: if chr.isdigit(): digits += chr elif chr.isalpha(): letters += chr else: other += chr print(digits) print(letters) print(other)
force_book = {} while True: user_in_force = False command = input() if command == 'Lumpawaroo': break if ' | ' in command: side, user = command.split(' | ') if side not in force_book: force_book[side] = [] for side, users in force_book.items(): ...
def cal_factorial(n): result = 1 for num in range(1, n + 1): result *= num return result number_1 = int(input()) number_2 = int(input()) factorial_n = cal_factorial(number_1) factorial_2 = cal_factorial(number_2) end_result = factorial_n / factorial_2 print(f'{end_result:.2f}')
command = input() company_users = {} while not command == 'End': company, id = command.split(" -> ") if company not in company_users: company_users[company] = [id] else: if id in company_users: command = input() company_users[company].append(id) command = input() s...
data = input().split() bakery = {} for word in range(0, len(data), 2): key = data[word] value = data[word + 1] bakery[key] = int(value) search_product = input().split() for product in search_product: if product in bakery: print(f'We have {bakery[product]} of {product} left') else: p...
import math n = int(input()) highest_snowball_value = 0 highest_snowball_snow = 0 highest_snowball_time = 0 highest_snowball_quality = 0 snowball_value = 0 for each in range(n): snowball_snow = int(input()) snowball_time = int(input()) snowball_quality = int(input()) snowball_value = math.ceil(snowbal...
array = [int(n) for n in input().split()] command = input() while not command == 'end': split_command = command.split() name = split_command[0] if name == 'swap': index_1 = int(split_command[1]) index_2 = int(split_command[2]) array[index_1], array[index_2] = array[index_2], array[in...
deck = input().split() number_of_shuffles = int(input()) left_half = [] right_half = [] for shuffels in range(number_of_shuffles): current_deck = [] half = int(len(deck)/2) left_half = deck[0:half] right_half = deck[half::] for index_of_cars in range(len(left_half)): current_deck.append(l...
from collections import defaultdict number_of_cars = int(input()) cars = defaultdict(dict) for n in range(number_of_cars): data = input() car, mileage, fuel = data.split("|") cars[car]['mileage'] = int(mileage) cars[car]['fuel'] = int(fuel) command = input() while not command == "Stop": name_comm...
import re data = input() pattern = r"(^|(?<=\s))-?\d+(\.\d+)?($|(?=\s))" dates = re.finditer(pattern, data) for d in dates: print(d.group(0), end=" ")
product = input() quantity = float(input()) def orders(current_product, current_quantity): result = None if current_product == 'coffee': result = current_quantity * 1.50 elif current_product == 'water': result = current_quantity * 1.00 elif current_product == 'coke': result = c...