text
stringlengths
37
1.41M
list_of_airlines=["AI","EM","BA"] print "Iterating the list using keyword in" for airlines in list_of_airlines: print airlines print "Iterating the list using range()" for index in range(len(list_of_airlines)): print list_of_airlines[index]
list2=[] i=0 while i<5: a=input("Enter the items of list2 %d"%i) list2.append(a) i+=1 print "List2 is ",list2
import sqlite3 con=sqlite3.Connection('hrdb') cur=con.cursor() from Tkinter import * root=Tk() Label(root,text='Employee Record Keeping System:',font="times 20 bold italic").grid(row=0,column=1) Label(root,text='Enter Emp Code:').grid(row=1,column=0) e1=Entry(root) e1.grid(row=1,column=1) Label(root,text='Ente...
def gcd(a,b): return a if b==0 else gcd(b,a%b) print(gcd(16,8))
def is_prime(num): if num<1:return False if num <=3: return True if num%2==0 or num%3==0: return False for i in range(5,num): if i*i>num: break if num%i ==0 or num%(i+2)==0: return False return True def are_sexy_primes(a, b): return is_prime(a) and is_prime(b) prin...
"""Example of an undirected graph.""" from queue import Queue class PersonNode(): """Node in a graph representing a person.""" def __init__(self, name, adjacent=None): """Create a person node with cohabitants adjacent""" if adjacent is None: adjacent = set() assert isin...
# -*- coding: utf-8 -*- """ Created on Tue Jul 26 15:55:34 2016 @author: pcarl_000 """ num = int(input("Please enter a number: ")) if num % 4 == 0: numtype = 'evenly divisible by four' elif num % 2 == 0: numtype = 'even' else: numtype = 'odd' print('Your number is ' + numtype + '.') ...
from sys import argv # this imports information from the command line script, filename = argv #this sets the information from the command line to the variables script and filename txt = open(filename) # this sets the variable txt to "open(filename)" which will open the file named the input from the command line ...
from sys import argv baller = argv filename = input("Want me to empty your file buddy? Go ahead and tell me the filename: ") print(f"Here, read your file one last time:") clearjob = open(filename) print(clearjob.read()) print(f"Now watch it disappear") clearjob = open(filename, 'w') clearjob.truncate(...
""" Another potential option is to create a class "Trivia" Objects could have attributes of category, question, answer, hint, etc. """ trivia_dictionary = { "What is the capital of California?": "Sacramento", "How many continents are there?": "7", "What is the smallest country?": "Vatican City", "What ...
# -*- coding: utf-8 -*- """ Created on Tue Nov 12 18:45:26 2019 @author: petru """ def anti_vowel(text): vowels = ('aeiouAEIOU') fl = [] for i in text: if i not in vowels: fl.append(i) return "" .join(fl) text = "GeeksforGeeks - A Computer Science Portal for Geeks" print(anti_vowel(text))
# -*- coding: utf-8 -*- """ Created on Fri Dec 6 20:52:04 2019 @author: petru """ from sys import argv script, filename = argv def print_all(f): print(f.read()) def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline()) current_file = open(filename) print("print first ...
# -*- coding: utf-8 -*- """ Created on Fri Nov 15 19:20:37 2019 @author: petru """ # censor letter from a text def censor(text, word): leeds = '*' * len(word) variabila = text.split() count = 0 for item in variabila: if item == word: variabila[count] = leeds count += 1 ...
cart={ '天谕':{'近战':["光刃","圣堂","业刹"], '远程':["炎天","玉虚","灵珑","流光"]}, '阴阳师':{'SSR':["一目连","荒","茨木童子"], 'SR':["姑获鸟","妖狐","夜叉"], 'R':["椒图","山兔","雨女"]}, '王者荣耀':{'法师':["诸葛亮","貂蝉","妲己"], '刺客':["兰陵王","荆轲","李白"], '射手':["李元芳","马可波罗","百里守约"]} } count...
class Node: def __init__(self, value, next_node = None): self.value = value self.next_node = next_node def get_node_value(self): return self.value def set_next_node(self, next_node): self.next_node = next_node def get_next_node(self): return self.next_node c...
#!/usr/bin/env python """Advent of Code 2020 - Day 08 - Solution by Julian Knorr (git@jknorr.eu)""" import re import sys from typing import List, Tuple OPERATION_REGEX = r"^([a-z]{3}) (\+|-)(\d+)$" def read_puzzle_file(filename: str) -> List[str]: file = open(filename, 'r') lines = file.readlines() retu...
#!/usr/bin/env python """Advent of Code 2020 - Day 09 - Solution by Julian Knorr (git@jknorr.eu)""" import sys from typing import List, Optional, Tuple def find_sum(puzzle: List[int], start: int, end: int, value: int) -> bool: for i in range(start, end): for j in range(start, end): if i == j: ...
__author__ = 'Lei Chen' ''' Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. ''' class Solution: # @param {integer[]} nums # @return {boolean} de...
__author__ = 'Lei Chen' ''' Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *. Example 1 Input: "2-1-1". ((2-1)-1) = 0 (2-(1-1)) = 2 Output: [0, 2] Example 2 Input: "2*3-4*5" (2*(3-(4*...
__author__ = 'Lei Chen' ''' Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. ''' import TreeNode class Solution: # @param {TreeNode} root # @re...
__author__ = 'Lei Chen' import TreeNode # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): ...
__author__ = 'Lei Chen' ''' Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. ''' class Solution(object): def removeZeros(self, nums): if not nums o...
__author__ = 'Lei Chen' ''' Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. ''' from ListNode import ListNode class Solution(object): def deleteDuplicates(self, head): cur = head ...
__author__ = 'Lei Chen' ''' Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1. For example, 123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Si...
__author__ = 'Lei Chen' class Stack: # initialize your data structure here. def __init__(self): self.q1 = [] self.q2 = [] # @param x, an integer # @return nothing def push(self, x): while len(self.q1)>0: self.q2.append(self.q1.pop(0)) self.q1.append(x)...
# 1. A recursive algorithm must have a base case. # 2. A recursive algorithm must change its state and move towards the base case. # 3. A recursive algorithm must call itself, recursively. # Print every number, starting at 'number', until you reach 0 def recurse(number): if number <= 0: return else: ...
import pandas # we need to import part of matplotlib # because we are no longer in a notebook import matplotlib.pyplot as plt import sys import glob # load data and transpose so that country names are # the columns and their gdp data becomes the rows # read data into a pandas dataframe and transpose #filename = "gapm...
from Strings import pad_string, unpad_string def conjugate(sentence: str): sentence = pad_string(sentence) # swap conjugations # This is mine and that is yours --> # This is yours and that is mine idx = 0 for key in conjugations.keys(): first_person = key second_person = con...
string=raw_input("Enter string:") char=0 word=1 for i in string: char=char+1 print("Number of characters in the string:") print(char)
""" Codefight Note: Your solution should have only one BST traversal and O(1) extra space complexity, since this is what you will be asked to accomplish in an interview. A tree is considered a binary search tree (BST) if for each of its nodes the following is true: The left subtree of a node contains only nodes ...
# Question - The variable nested contains a nested list. Assign ‘snake’ to the variable output using indexing. nested = [['dog', 'cat', 'horse'], ['frog', 'turtle', 'snake', 'gecko'], ['hamster', 'gerbil', 'rat', 'ferret']] output = nested[1][2] print(output) # Question 2 - Below, a list of lists is provided. Use in ...
# handling errors in python socket programs import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except Exception as err: code, msg = inst.args print('Failed to create socket. Error code: ' + str(code) + ', Error message ...
'''Create a class representing a concert ticket. Its constructor takes two values: a ticket price, and a section. >>> my_ticket = ConcertTicket(22.0, 'floor') >>> your_ticket = ConcertTicket(42.0, 'mezzanine') You can access these two values through the price and section attributes: >>> my_ticket.price 22.0 >>> your...
import re sub_name = 'REEILsEMKKV' sub_name=sub_name.strip() pattern = r'[a-z]' matches = re.findall(pattern,sub_name)[0] print(matches) print(filter(str.islower,sub_name))
ex=["left","right","up","down"] for i,j in enumerate(ex): print(i,j) new_dict = dict(enumerate(ex)) print(new_dict) [print(i,j) for i,j in enumerate(new_dict)]
from collections import defaultdict ''' This is my attempt at doing this from scratch. Helper file for encoding the Suduko Board. The display function is borrowed from a course. This question was inspired from a course on AI and deep-learning ''' # Variables to encode the board. Rows are horizont...
n=int(input("Enter the limit:")) a=0 b=1 c=0 print(a,b,end=" ") for i in range(0,n+1): c=a+b a=b b=c print(c,end=" ")
temperature = int(input("Enter the temperature (Celsius): ")) windspeed = int(input("Enter the wind speed (km/h): ")) print("The wind chill factor is:", end="") print(13.12 + (0.6215 * temperature) - (11.37 * windspeed ** 0.16) + (0.3965 * temperature * windspeed ** 0.16))
minutes = int(input("Enter number of minutes: ")) print("This is", minutes // 1440, "days,", minutes % 1440 // 60, "hours &,", minutes % 60, "minutes")
total = 0 number = int(input("Enter your number: ")) for i in range(number + 1): total = total + i print(total)
''' ------------------------------------------------------------------------------- Name: microbit_logical_demonstration_assignment.py Purpose: When button is pressed while potentiometer is turned down, displays an image on the screen while flashing the red led and playing a note on buzzer. When button is pressed an...
n = int(input("Enter your number: ")) i = n while i <=n: if 2 ** i < n: print("exponent:", i) print("2**n:", 2**i) break else: i -= 1
s1=input() l1=[0] if "ab1" not in s1: print("0") else: for i1 in range(len(s1)): c1=1 for j1 in range(i1,len(s1)-1): if s1[j1]=="a1" and s1[j1+1]=="b": c1=c1+1 elif s1[j1]=="b1" and s1[j1+1]=="a1": c1=c1+1 else: l1.append(c1) c1=1 break if s1[i1]=="a1": l1.append(c1) else: l...
import sys def read_file(file_location): """ Reads the file stored at :param file_location :param file_location: absolute path for the file to be read (string) :return: contents of file (string) """ try: with open(file_location, "r") as file: return file.read() ex...
>>> print ("hello world!") hello world! >>> print ('hello world!') hello world! >>> print ('hello William') hello William >>> #print ('hello world') >>> print ('Γειά σου Κόσμε') Γειά σου Κόσμε >>> print ('Olá Mundo') Olá Mundo >>> print ('안녕 세상') 안녕 세상 >>> ('你好,世界') '你好,世界' >>> print ('Salamu, Dunia') Salamu, Dunia >>>...
import argparse import re def string_type(string): """ @param string: Type of the string to be checked 0: both name and value 1: only the value 2: only the name """ if any(char.isdigit() for char in string): if re.search(r"\D{3,}\s", string): return 0 ...
''' Multiples of 3 and 5 ''' def multiples(num1, num2, maxNum): nums = [] for i in range(2, maxNum): if i % num1 == 0: nums.append(i) elif i % num2 == 0: nums.append(i) else: pass return nums def sum_multiples(num1, num2, maxNum): nums = m...
################################################### #################[ Module: Utils ]################# ################################################### """ Miscellaneous utilities for caspanda. """ def paste(x, sep=", "): """ Custom string formatting function to format (???) output. """ out = "" ...
print("1. Add Number") print("2. Search Number") print("3. Exit the program") dictContact = {} loop = True while loop: user_choice = input("Enter your choice:") if user_choice == '1': inp_name = input("Enter your name: ") inp_number = input("Enter your number: ") print() dictC...
list1 = ["Arteezy","Noone","Sumail","Crit"] for i in range (len(list1)): print(list1[i]) print("\n") list2 = ["A","N","S","C"] for z in range (len(list2)): print(list2[z]) print("\n") list3 = [1,3,2,4] for x in range(len(list3)): print(list3[x]) print("\n") list4 = ["EG","VP","TNC","MNSK"] for y in range(l...
string = "This is a string" string = string.split(" ") print(string) string = "hej".join(string) print(string)
foods = ["taco", "pizza", "Mom's spaghetti", "IKEA MEATBALLS DALAHORSE FTW", "taco"] not_foods = ["shoes", "fox", "mom", "warlock"] def has_equal_ends(list): x = len(list) if list[0] == list[x-1]: return True else: return False print(has_equal_ends(foods)) print(has_equal_ends(not_foods))
# print('안녕하세요') #프린트함수=> 화면출력 # print('이름이 무엇인가요?') # myName = input() #입력받기 # print('반갑습니다. ' + myName) # print('당신의 이름 길이는: ') # print(len('myName')) #len 문자열의 길이 # print('당신의 나이는?') # myAge = input() # print('당신은 내년에 ' + str(int(myAge)+1) + '살 입니다.') # print('안녕', 1, 2) # # print('안녕' + 1 + 2) #이 경우는 오류 # print...
TAX_RATE = 0.20 STANDARD_DEDUCTION = 10000.0 DEPENDENT_DEDUCTION = 3000.0 from breezypythongui import EasyFrame class TaxCalculator(EasyFrame): """Application window for the tax calculator.""" def __init__(self): """Sets up the window and the widgets.""" EasyFrame.__init__(self, title="T...
#Assignment 06 print("This is Program06 - Armando Castro") print("This program uses lists, strings, tuples, and dictionaries.") # Two Tuples weeks = ('Week One', 'Week Two') days = ('Thursday', 'Friday', 'Saturday') # Sales reps names and locations sales_rep_names = ['Frank Fleming', 'Domingo Depue', 'Ema Endicott...
from collections import Counter def uniqueOccurrences(arr): """ Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. >>> uniqueOccurrences([1,2,2,1,1,3]) True >>> uniqueOccurrences([-3,0,1,-3,1,1,1,-3,...
def reverseWords(s): """ Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. >>> reverseWords("Let's take LeetCode contest") "s'teL ekat edoCteeL tsetnoc" """ s = (s).split(' ') ret = '' ...
"""Return the number of students that were working during the queryTime. >>> busyStudent([9,8,7,6,5,4,3,2,1],[10,10,10,10,10,10,10,10,10],10) 9 >>> busyStudent([1,1,1,1], [1,3,2,4], 7) 0 >>> busyStudent([1,2,3], [3,2,7], 4) 1 """ def busyStudent(startTime, endTime, queryTime): ...
def lastStoneWeight(stones): """ We have a collection of stones, each stone has a positive integer weight. Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: If x == y, both stones are totally d...
def romanToInt(s): """ Given a roman numeral, convert it to an integer. >>> romanToInt("MCMXCIV") 1994 >>> romanToInt("LVIII") 58 """ roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100,'D': 500,'M':1000} num = 0 for idx, x in enumerate(s): value = roman_dict.g...
""" Write a function that prints a string, fitting its characters within char limit. It should take in a string and a character limit (as an integer). It should print the contents of the string without going over the character limit and without breaking words. For example: >>> fit_to_width('hi there', 50) hi there S...
def findOcurrences(text, first, second): """ Given words first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second. For each such occurrence, add "third" to the answer, and return the a...
def minSubsequence(nums): """ Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. >>> minSubsequence([4,3,10,9,8]) [10, 9] >>> minSubsequence([4,4,7,6,7]) [7, 7, 6] """ ...
#Escreva um programa que converta uma temperatura digitada em °C e converta para °F. c = float (input('Informe a temperatura em °C: ')) f = (9*c / 5) + 32 print('A temperatura em {} ° C corresponde a {}°F! '.format(c,f))
#Crie um algoritimo que leia um número e mostre o seu dobro, triplo e raiz quadrada n = int(input('Digite um numero: ')) print('O dobro do numero é: ',n*2) print('O triplo do numero é: ',n*3) print('A raiz do numero é: ',n**(1/2))
#Desenvolva um programa que leia as duas notas de um aluno, calculo e mostre sua media n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) media = (n1 + n2) / 2 print ('A media do aluno é: {}'.format(media))
# -*- coding: utf-8 -*- """ Rock, Paper, Scissors. Created on Sun Mar 8 10:48:11 2020 @author: Laura Rock Paper Scissors Game - Create a rock-paper-scissors game. - Ask the player to pick rock, paper or scissors. - Have the computer chose its move. - Compare the choices and decide who wins. - Pri...
import random numbers = [random.randint(0,1000000) for x in range(1000000)] def radix_sort(numbers): buckets = [[] for x in range(10)] for i in range(1, 7): digit = 10**i for x in numbers: d = (x%digit)//10**(i-1) buckets[d].append(x) numbers = [] for b i...
import unittest from ..foobar.classes.foobar import FooBar, Multiple class TestMultiple(unittest.TestCase): def test_multiple_10(self): """Testes if 100 is multiple of 10""" self.assertEqual(Multiple.is_multiple(100, 10), True, 'Should be True') def test_multiple_5(self): ""...
# KDR # Simulization & optimization problems: # The Whitt Window Company, a company with only three employees, makes two # different types of hand-crafted windowns: a wood-framed and an aluminum framed window. # The comapny earms $300 profit for each wood-framed window and $180 profit for each # aluminum-framed win...
from typing import List class Solution: # passed 34/66 test cases def checkStraightLine(self, coordinates: List[List[int]]) -> bool: if (len(coordinates) < 2): return False if len(coordinates) == 2: return True # got this without the hint for i in range(1, len(coordinates) - 1): ...
# # Ex. 1: Conta de energia # ======================= # # A função conta_de_energia(consumo, tipo) deve retornar o valor da conta de # energia em função da faixa de consumo e tipo de estabelecimento: # # Tipo | Faixa (kWh) | Valor por kWh # ================+=============+=============== # residencial ...
from board import TicTacToeBoard from move import BoardMove class Game: X = "X" O = "O" def __init__(self): self._board = TicTacToeBoard() self._player = self.X self._running = True self._has_winner = False self._moves = [] @property def running(self): ...
""" Les décorateurs singleton On peut créer des décorateurs dans des classes et dans ce cas on dit que la classe qui a un décorateur est une classe singleton, ce qui signifie qu'elle ne peut être instanciée qu'une seule fois. À titre d'exemple : la création d'une base de données... Éditeur : Laurent REYNAUD ...
# 1.去掉字符串中的所有空格 x = input('input something') print(x.split(' ')) # 2.根据完整的路径从路径中分离文件路径、文件名及扩展名 x = '‪D:\resource\py入门.pdf' print(x.split('.')) # 3.获取字符串中汉字的个数 x = 'Z:\share\Python人工智能1909\part_1第一阶段\随堂录屏\2019.9.26\2019.9.26_4循环控制.mp4' for i in x: if 0x4e00 <= ord(i) <= 0x9fa5: print(i, end='') # 4.对字符串进行加密...
import calendar import datetime # yy=2015 # mm=6 # print(calendar.month(yy, mm)) # with open('test.txt','wt')as out_file: # out_file.write('该文本会写入到文件中\n看到我了吧!') # # with open('test.txt','rt')as in_file: # text=in_file.read() # print(text) # mothrange=calendar.monthrange(2016,9) # print(mothrange) # today=d...
import random money = 0 print('欢迎来到皇家竞猜'.center(50, '*')) while True: while True: temp = int(input('请购买筹码')) if temp < 50: print('购买筹码50起') else: if money > 0: money += temp print('购买成功,余额:', money) break el...
#variable set to a string of formatters formatter = "%s %s %s %s" #print line- "format variable" % then references the (1,2,3,4) print formatter % (1, 2, 3, 4) #print line- quotes will be visible for %r but not for %s print formatter % ("one", "two", "three", "four") #print line- "format variable" % referencing...
#line 1-3: uses argv to get a filename. from sys import argv #line asking for argument variable. Script=__.py filename=whatever file you want #to open. MAKE SURE FILE IS IN SAME DIRECTORY AS SCRIPT. script, filename = argv #NEW COMMAND: JUST THE FILE attached to variable "txt" txt = open(filename) #Printin...
''' Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not already...
''' A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river. You are given a zero-indexed array A consisting of N integers representing the fal...
from __future__ import print_function from math import log from timeit import timeit from functools import reduce def prod_div(arr): # Make a copy of the input array to make this a functional solution. arr = list(arr) # If there is only one 0 in the array, the solution should have the product # of all...
from BinaryTree import BinaryTree, Node def num_unival_trees(node): count = [0] helper(node, count) return count[0] def helper(node, count): if node is None: return True left = helper(node.left, count) right = helper(node.right, count) if left == False or right == False: ...
def partition(arr, low, high): i = (low-1) pivot = arr[high] for j in range(low, high): if arr[j] <= pivot: i = i+1 arr[i], arr[j] = arr[j], arr[i] arr[i+1], arr[high] = arr[high], arr[i+1] return (i+1) def quickSort(arr, low, high): if len(arr) == 1: return arr if low < high: pi = partit...
import Encryption import os class Login: def __init__(self): self.encryption = Encryption.Encryption() # stores the current username and password self.__currentUsername = "" self.__currentPassword = "" # stores all the usernames and passwords self.__username = [] ...
""" Task that intakes and evaluates SA ID and outputs year born, month born, date of birth, gender, citizen/noncitizen. This SA ID program only works for years 1922 - 2021(a century) """ _id = 'global' year = 'global' # function asks user for ID and checks to see if ID given is valid. If not, it repeats itself until ...
import json a = {'name': 'she', 'age': 21} for i in a.keys(): print(i) data = json.dumps(a) print(data) print(a)
#!usr/bin/python3 # -*- coding: utf-8 -*- """ :authors: DELECLUSE MARILLESSE :date: 27/09/16 :object: TP2 Codage """ ##### Fonctions à réaliser pour le TP ##### # Question 5 def integer_to_digit(integer): """ Converts an integer into the corresponding hexadecimal digit. The integer given should be betwe...
def factorial (number): fact = 1 if number < 0: return 'negative' elif number <= 1: return fact else: for n in range(number): fact *= n+1 return fact def alt_factorial (number): #This finds factorial by recussion if number < 0: re...
import math from src.Utilities import PriorityQueue # AStarSearch is based on Amit Patel's tutorial: "Implementation of A*" at: # http://www.redblobgames.com/pathfinding/a-star/implementation.html def heuristic(point_a, point_b): """ Estimated cost of travelling between two points :param point_a: start ...
# * Map # - next_scene # - opening_scene # * Engine # - play # * Scene # - enter # * Death # * Central Corridor # * Laser Weapon Armory # * The Bridge # * Escape Pod from sys import exit from random import randint class Map(object): """The map of all the rooms.""" def __init__(self, start_...
""" As you can see, the code is broken. Create the missing functions, use default arguments. Sometimes you have to use 'return' and sometimes you dont. Start by creating the functions """ def is_on_list(): if day in days: print(True) else: print(False) def get_x(): pass def add_x(): pass def remove_x(): pa...
#!/usr/bin/env python3 """ From F(1) = 1, F(2) = 1, F(n) = F(n-1) + F(n-2), we see that F(3) is even, F(4), F(5) are odd, and F(6) is even, since even = odd + odd and odd = evev + odd. Thus the even Fibonacci numbers occur at F(n) where n % 3 == 0. We see if we can express an even F(n) in terms of earlier even Fibonac...
# cook your dish here def isprime(n): if n==1 or n==0: return False else: for i in range(2,int(n**0.5)+1): if(n%i==0): return False return True for _ in range(int(input())): x,y=map(int, input().split()) i=1 while(isprime(x+y+i)==False): i+...
for _ in range(int(input())): s=list(input()) if len(s)<=10: print(''.join(s)) else: print(s[0]+str(len(s)-2)+s[len(s)-1])
# cook your dish here for _ in range(int(input())): s=list(input()) n=len(s) pair=0 for i in range(n): if s[i]=='<': s[i]='>' elif s[i]=='>': s[i]='<' #print(s) for i in range(n-1): if s[i]=='>' and s[i+1]=='<': pair+=1 print(pair)
# cook your dish here for _ in range(int(input())): k=int(input()) a=[[],[],[],[],[],[],[],[]] for i in range(8): for j in range(8): a[i].append(0) a[0][0]='O' k-=1 for i in range(8): for j in range(8): if(j==0 and i==0): continue ...
####### ---- Import Modules Here ---- ####### import sys input = sys.stdin.readline pstr = sys.stdout.write ####### ---- Input Functions ---- ####### def intinp(): return(int(input())) def intlist(): return (list(map(int,input().split()))) def strlist(): s = input() return (list(s[:len(s) - 1])) def st...
a=list(map(float, input().split())) withdraw=a[0] balance=a[1] if(withdraw+0.5<=balance and withdraw<=2000 and withdraw%5==0): balance=balance-withdraw-0.5 print("%.2f"%balance)
n=int(input()) print("Bob" if n%2==0 else "Alice")