text
stringlengths
37
1.41M
''' 位置参数 修改后的power(x, n)函数有两个参数:x和n, 这两个参数都是位置参数,调用函数时,传入的两个值按照位置顺序依次赋给参数x和n。 ''' def my_power(x, n): s = 1; while n > 0: n = n - 1 s *= x return s my_power(2, 3) ''' 默认参数 当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。 变化小的参数就可以作为默认参数。 定义默认参数要牢记一点:默认参数必须指向不变对象! ''' def my_power2(x, n=2): s = 1; ...
''' 在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。 举个例子,我们来计算阶乘n! = 1 x 2 x 3 x ... x n,用函数fact(n)表示,可以看出: ''' def fact(n): if n == 1: return 1 return n * fact(n - 1) print(fact(100)) ''' 汉诺塔问题 ''' m = 0 def move(n, x, y): global m m += 1 print("第%d步,将%d号盘子%s-->%s" % (m, n, x, y)) def ...
# -*- coding: utf-8 -*- """ Created on Fri May 10 11:35:37 2019 @author: hp """ """ Code Challenge Name: Zoo Management Filename: zoo.py Problem Statement: Create different functions to : read the zoo.csv file using readlines and print them Print in list of animals in groups (elephant / ti...
# -*- coding: utf-8 -*- """ Created on Mon May 20 12:22:11 2019 @author: hp """ """ Code Challenge Name: Random Data Filename: random_data.py Problem Statement: Create a random array of 40 integers from 5 - 15 using NumPy. Find the most frequent value with and without Numpy. Hint: Try...
# -*- coding: utf-8 -*- """ Created on Tue May 28 10:38:48 2019 @author: hp """ """ Q. (Create a program that fulfills the following specification.) bluegills.csv How is the length of a bluegill fish related to its age? In 1981, n = 78 bluegills were randomly sampled from Lake Mary in Minnesota. The researchers (Coo...
import pygame from GameParameter import display from GameEffects import drawing_text pygame.init() class Button: def __init__(self, x, y, width, height, text, image, func): self.x = x self.y = y self.width = width self.height = height self.text = text self.image_o...
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ min_buy_p = float("+inf") max_b = 0 for p in prices: max_b = max(max_b, p - min_buy_p) min_buy_p = min(min_buy_p, p) return max_b ...
raw = int(raw_input()) col = int(raw_input()) m = [] for i in range(raw): m.append([int(x) for x in raw_input().split(" ")]) print m def count(i, j, direction): if i >= raw or i < 0: return 0 if j >= col or j < 0: return 0 if m[i][j] == 0: return 0 else: if direct...
class Formater(object): def __init__(self): self.line_width = 0 self.ret = [] def parse_line(self, words): # print "-->",words line_str = "" one_line = [] free_space = self.line_width while len(words) > 0 and len(words[0]) <= free_space: next_...
''' The Dimension and DimensionVector classes are used to capture and allow the construction of a proper dimensional representation of compound units. ''' from re import search, IGNORECASE class Dimension: def __init__(self, symbol, uri, exponent: float): # L, Length, -1 self.symbol = symbol self...
nome = str(input('Digite o nome: ')).strip() print('Nome completo:',nome) nome = nome.split() print('Primeiro nome:',nome[0]) print('Último nome:',nome[-1])
from random import randint from time import sleep print('-=-'*18) print('Vou pensar em um número de 1 a 5. Tente adivinhar...') print('-=-'*18) n1 = int(input('Em qual número eu pensei? ')) print('PROCESSANDO...') sleep(2) n2 = (randint(0, 5)) if (n1 > 5): print('O número deve ser entre 0 e 5') else: if (n1 == ...
p = float(input('Digite o valor do produto: R$')) desc = p * 0.95 desc2 = p - desc print('O valor com 5% de desconto é: R${:.2f}. Um desconto de R${:.2f}'.format(desc,desc2))
numero = input('Digite um número inteiro de 0 a 9999: ') print('Unidade:',numero[-1]) print('Dezena:',numero[-2:-1]) print('Centeza:',numero[-3:-2]) print('Milhar:',numero[-4:-3])
num1 = int(input('Digite um número: ')) num2 = int(input('Digite outro número: ')) num3 = int(input('Digite um terceiro número: ')) if num1 > num2 > num3: print('O maior número é o {} e o menor número é o {}'.format(num1,num3)) else: if num1 > num3 > num2: print('O maior número é o {} e o menor número é...
tabela = ('Santos', 'Palmeiras', 'Flamengo', 'Atlético', 'São Paulo', 'Internacional', 'Corinthians', 'Atlético-PR', 'Botafogo', 'Bahia', 'Ceará SC', 'Goiás', 'Grêmio', 'Fortaleza', 'Vasco da Gama', 'Fluminense', 'Chapecoense', 'Cruzeiro','CSA', 'Avaí') primeiros = tabela[0:5] ultimos = tabela[-4:]...
from random import choice a1 = input('Escreva o nome do 1º aluno: ') a2 = input('Escreva o nome do 2º aluno: ') a3 = input('Escreva o nome do 3º aluno: ') a4 = input('Escreva o nome do 4º aluno: ') print('O aluno escolhido para apagar o quadro foi {}'.format(choice([a1,a2,a3,a4])))
from random import randint from time import sleep print('\033[33m-='*22) print('\033[36mVamos brincar de PEDRA, PAPEL E TESOURA? =D\033[m') print('\033[33m-='*22) print('\033[m') print('''\033[34mEscolha uma opção: [0] PEDRA [1] PAPEL [2] TESOURA\033[m\n''') opcao = int(input('\033[36mQual é sua jogada? : \033[m')) sl...
n = int(input('Digite um número: ')) print('A tabuada do número {} é:'.format(n)) for c in range(1, 11): print('{} x {:2} = {}'.format(n, c, (n*c)))
soma = cont = 0 lista1 = [] lista2 = [] while True: nome = str(input('Nome do Produto: ')) preco = float(input('Preço: R$')) print('-' * 20) soma += preco lista1.append(nome) lista2.append(preco) opcao = ' ' while opcao not in 'SN': opcao = str(input('Quer continuar [S/N]: ')).up...
grupo = list() pessoa = list() maiorpeso = menorpeso = 0 maispesado = list() maisleve = list() while True: nome = str(input('Nome: ')) pessoa.append(nome) peso = float(input('Peso: ')) pessoa.append(peso) if len(grupo) == 0: maiorpeso = pessoa[1] menorpeso = pessoa[1] else: ...
#Lamana Mulaffer - BOWLING GAME # 07/11/2018 import random import numpy NUM_FRAMES = 10 NUM_PINS = 10 NUM_ROLLS = 2 class bowlingGame(): def __init__(self): self.roll_seq = [] def roll(self, noOfPins): self.roll_seq.append(noOfPins) def roll_s(self, rolls): self.roll_seq = rolls #spare - both bowls ...
from os import listdir, chdir from os.path import isfile, isdir, join from src.ParseText import ParseText class ConvertDirectory: parse_text = ParseText() def read_file(self,path): try: with open(path, encoding="utf8") as file: text = file.read() except: ...
import sqlite3 def connect(): conn=sqlite3.connect("market.db") cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS market (name TEXT PRIMARY KEY,weight integer,price integer,quan integer)") conn.commit() conn.close() def insert(name, weight, price, quan): conn = sqlite3.connect(...
''' This code is about change the color of picture by using gaussian threshold. Step1. Get the grayscale of image. Step2. Adjust the histogram. (It in case the picture is to dark or to light) Step3. Using gaussian Threshold and rewrite the picture Step4. Set the white part of picture to color1 Set the b...
import sys import os import math import time import operator def makeGraph(): # make a list of the values as they are read in # since the number of the cities corresponds with its position in the list, that value is not saved coordList = list() filename = sys.argv[1] with open(filename) ...
# 画图,分case处理,记录prev_odd:最近发现的odd node; prev; curr # 每次找到odd node时,将其提出insert after previous odd node prev_odd, # 注意处理提出时的prev, next以及insert处的prev, next。 # update prev_odd, prev, curr (note that prev does not need update if we take out curr) # Input: 1->2->3->4->5->NULL # Output: 1->3->5->2->4->NULL # class ListNod...
import random class RandomizedSet: # we need a list and a dictionary # self.d = {} # value, index # self.vals = [] # vals def __init__(self): """ Initialize your data structure here. """ self.d = {} # value, index self.vals = [] # vals def insert(self, val: ...
# Example 1: # Input: # ["a","a","b","b","c","c","c"] # Output: # Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] # Explanation: # "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". # Example 2: # Input: # ["a"] # Output: # Return 1, and the...
# Given a 2D board and a word, find if the word exists in the grid. # The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. # For example, # Given board = # [ # ['A','B','...
# Given a 2D binary matrix filled with 0's and 1's, # find the largest square containing only 1's and return its area. # Example: # Input: # 1 0 1 0 0 # 1 0 1 1 1 # 1 1 1 1 1 # 1 0 0 1 0 # Output: 4 class Solution: # Brute force: O((mn)^2) # since we need to check for every cell = 1, # in worst case,...
class Solution: # Binary search # note that a rotatedly sortly array must have a half that is increasingly sorted # [1,2,3,4,5] -> [4,5,1,2,3], [5,1,2,3,4], [3,4,5,1,2] [1,2,3,4,5] # use this property to decide which part we want to search on # Use i to track index in recursion call, # for exam...
class Solution: # dynamic programming O(n) def climbStairs(self, n: int) -> int: if n == 1: return 1 if n == 2: return 2 a = [0 for i in range(n + 1)] a[1] = 1 a[2] = 2 for i in range(3, n+1): a[i] = a[i-1] + a[i-2] retu...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Input: # 5 # / \ # 4 5 # / \ \ # 1 1 5 # Output: 2 # Input: # 1 # ...
""" KMP (Knuth Morris Pratt) Pattern Searching - Worst case complexity is O(n) """ def KMPSearch(pattern, text): M = len(pattern) N = len(text) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pattern[] # Preprocess the patte...
""" Merge sort """ def merge(l, left, right, mid): i = left j = mid + 1 k = left while i <= mid and j <= right: if l[i] <= l[j]: temp[k] = l[i] i += 1 else: temp[k] = l[j] j += 1 k += 1 while i <= mid: temp[k] =...
n = int(input("Enter the positive number till where the sum is to be find out\n")) sum = (n * (n + 1))/2 print("sum of the given number is %d"%sum)
amt = float(input("Enter the deposited amount\n")) i = 0.04 * amt amt = amt + i print("After a year amount is :%.2f"%amt) i = 0.04 * amt amt = amt + i print("After 2 year amount is :%.2f"%amt) i = 0.04 * amt amt = amt + i print("After 3 year amount is :%.2f"%amt)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # BFS class Solution: def pathSum(self, root: TreeNode, Sum: int) -> List[List[int]]: if not root: return [] ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: dummy = p = ListNode(0) dummy.next = head for i in rang...
class Solution: def isRectangle(self, rectangles:List[List[int]]) -> bool: # ExpectedArea = Sum of all areas of rectangles # The areas of rectangles could not overlap. # initial status of corner positions [(Xm, Ym), (Xm, YM), (XM, Ym), (XM, YM)] and AreaSum Xm,Ym, XM, YM = r...
# 1~100까지 합 sum = 0 for num in range(1, 101): sum += num print("sum =", sum)
# 2~100까지 짝수의 합 sum = 0 for num in range(2, 101, 2): sum += num print("sum =", sum)
dic = {"boy":"소년", "school":"학교", "book":"책"} print(dic.keys()) print(dic.values()) print(dic.items())
dan = 2 while dan <= 9: hang = 1 print(dan, "단") while hang <= 9: print(dan, "*", hang, "=", dan * hang) hang += 1 dan += 1 print()
a = 3 if a > 1 and a < 10: print("ok") if 1 < a < 10: print("ok2")
class Date: def __init__(self, month): self.month = month def getmonth(self): return self.month def setmonth(self, month): if 1 <= month <= 12: self.month = month today = Date(8) today.setmonth(15) print(today.getmonth())
country = ["Korea", "japan", "CHINA", "america"] country.sort() print(country) country.sort(key = str.lower) print(country)
print("3 + 4 = ?") while True: a = int(input("정답을 입력하시오 : ")) if(a == 7): break print("정답입니다.")
class RangeOfThirdEdge: def findTheSide(self, side1, side2): highValue = 0 lowValue = 0 if side1 >= side2: highValue = side1 + side2 lowValue = side1 - side2 else: highValue = side2 + side1 lowValue = side2 - side1 ...
class UpperAndLowerCase: countUpper = 0 countLower = 0 def getInput(self): inputVal = input("Input String Containing Uppercase and Lower Case :") self.inputValue = inputVal self.Calculate(inputVal) def Calculate(self,inputVal): for element in range(0, len(inputVa...
''' Created on Jun 11, 2020 @author: Poshan ''' def checkKey(dict, key): if key in dict: print("Present, ", end =" ") print("value =", dict[key]) else: print("Not present") # Driver Code dict = {1: 10, 2:20, 3:30, 4:40, 5:50, 6:60} key = 1 checkKey(dict, k...
class DictionaryList: def myDictionary(self): dict = {"name" : {"Xavier", "Test1", "Test3", "Test2"}} list1 = list(dict.values()) print(sorted(list1, key=None, reverse=False)) obj1 = DictionaryList() obj1.myDictionary()
# Create a dictionary (in your file) of names and birthdays. # When you run your program it should ask the user to enter a name, # and return the birthday of that person back to them. # The interaction should look something like this: class DictionList: def myList(self, cName): birthDayList = {"John": ...
import unittest from immutability.cell import Cell from immutability.board import Board class CellShould(unittest.TestCase): """ - Acceptance tests: after an evolution phase - Any live cell with fewer than two live neighbours dies, as if by underpopulation. - Any live cell with two...
from builtins import print from dataclasses import dataclass from typing import TypeVar """ A utility company installs its services in sites. Most of the time, a site has a customer, but sometimes the customer is None. When this happens, the data record replace the customer field with the string "unknown". Clients o...
from builtins import print from dataclasses import dataclass from typing import TypeVar """ A utility company installs its services in sites. Most of the time, a site has a customer, but sometimes the customer is None. When this happens, the data record replace the customer field with the string "unknown". Clients o...
import time import pandas as pd CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analy...
from tkinter import * from tkinter import ttk import random board_list = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] move_count = 0 def winner_popup(winner): """ Creates a small popup window that prints the winner into a popup window :param winner: string of the winner of the game ("draw" if the game is ...
#!/usr/bin/env python # -*- coding=utf8 -*- """ # Author: HansHuang # Created Time : 2017年11月26日 星期日 12时20分09秒 # File Name: daily.py # Description: """ import logging logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s : %(levelname)s %(message)s',datefmt='%Y-%m-%d %A %H:%M:%S') class ListNode(obje...
#!/usr/bin/env python # -*- coding=utf8 -*- """ # Author: HansHuang # Created Time : 2017年11月14日 星期二 09时55分24秒 # File Name: daily.py # Description: 二分查找 给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1。 样例 在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2。 class Solution: def binarySearch...
#!/usr/bin/env python3 # -*- coding=utf8 -*- """ # Author: Hans # Created Time : 2017年10月27日 星期五 11时52分33秒 # File Name: twotree2.py # Description: 给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点 所在的层遍历,然后逐层从左往右遍历) 样例 给出一棵二叉树 {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 按照从下往上的层次遍历为: [ [15,7], [9,20], [3] ] ""...
''' given a product name, measure the similarity of its words against 'consumer' and 'product'. and select only those highly similar words ''' import sys,csv from util import nlp from sematch.semantic.similarity import WordNetSimilarity import operator import pandas as pd target_words=["product","consumer"] sim_ww_...
# Name :- Zeel Khatri ; Kishan Zalora ''' This is client, it will read HNS.txt and will store every DNS in the a List. -> Then it will send DNS one by one to RS(Root server). -> if root server has the IP address then it will send it with a Flag A. -> if RS dont have it then it will send a Flag NS with a TS(TOP...
# Lists:collection of itrms that are ORDERED,CHANGEABLE # DICTIONARY:collection of items that are UNORDERD,CHANGEABLE and INDEXED # TUPLE: collection of items that are ORDERED,UNCHANGEABLE # SET:collection of items that are Unordered,unchangeable list in Python #variablename-['item 1,', 'item 2','item 3'] shoppingList ...
""" Plot a spectrum =============== This is an example showing how to plot a spectrum with the :func:`mcalf.visualisation.plot_spectrum` function. """ #%% # First we shall create a list of wavelengths, with a variable # wavelength spacing. # Next, we shall use the Voigt profile to generate spectral # intensities at ea...
#Importing tkinter for our interface design import tkinter as tk #using the alias tk instead of the normal tkinter from tkinter import ttk #Create an instance of tk win = tk.Tk() #Giving window a title win.title( 'CUSTOMER SIGN-UP FORM' ) #Creating an empty space ttk.Label(win).grid(row = 0) #Setting our username...
#Health Management System import datetime def gettime(): return datetime.datetime.now() while(True): print("1.For write") print("2.For retrive") n = int(input()) if n==1: print("f For food") print("e For excise") n2=(input()) if n2=="f": pri...
""" --- Part Two --- For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words that are anagrams of each other - that is, a passphrase is invalid if any word's letters can be rearranged to form any other word in the passphrase. For example: ...
name = input("What is your name? ") age = int(input("What is your age? ")) if 18 <= age < 31: print("Welcome to the Holiday, {}".format(name)) else: print("I'm sorry, {}, but you must be between the ages of 18 and 30 to join the Holiday".format(name))
import numpy as np import pandas as pd from src.helper_function import calculate_enter_and_exit class Simplex(object): """ Simplex method class: Return the table of the solved simplex method and also saves the csv. # Input format: xi: encode the values in this format for the variables: yi: enc...
import re ips = open("input.txt").read().splitlines() def reverse(string): return ''.join(reversed(string)) def valid_part1(string): for i in range(len(string)-3): if string[i] != string[i+1] and string[i:i+2] == reverse(string[i+2:i+4]): return True return False count = 0 for ip in ips: ip_tokens ...
#!/usr/bin/python #coding:utf8 print '='*30 # 传递的实参和所定义的形参相同情况 def f(x,y): print '%s:%s' % (x,y) t=('name','age') f(*t) #把元组的值传过来 def fun(name='name',age='20'): print 'name:%s'% name print 'age:%s'% age fun('zhang',30) #用的是我们输入的参数 fun() #用的是默认参数 fun(40,'wang') #这只和顺序有关,前面第一对应第一个,第二个对应第二个 d={'name':'lily','age...
valid=False count=3 passwordlist=('123','234','456','567') while count>0: password=raw_input("Enter your the num's password:") for num in passwordlist: if password == num: valid=True print 'right' break if not valid: print "invalid password" ...
""" CodeNotes is an a Sublime-Text plugin that allows users to input snippets into a .json file and retrieve those snippets by activating the plugin. """ import json import os import sublime import sublime_plugin class AddCommand(sublime_plugin.TextCommand): """ This is the a child class of sublime_plugin to ...
class Node: def __init__(self, value, next_ = None): self.value = value self.next = next_ class LinkedList: def __init__(self, collection=None): self.head = None # reversed: O(n) # loop: O(n*1) if collection: for item in reversed(collection): # [a,b...
from collections import Counter # print(Counter([1,2,3,1,1,1])) ctr1 = Counter((3,1,2,3,1,1,1)) # print(ctr1) # print(ctr1.most_common(1)) # print(ctr1.most_common(2)) ctr2 = Counter({'a':3, 'b':7, 'c':6}) # print(ctr2.most_common(1)) # print(ctr2['a']) # print(dir(Counter)) # data = [3,2,6,4,1,5] # print(Counte...
''' Реализуйте при помощи pyTorch функцию, которая возвращает сумму (x.sum()) элементов тензора X, строго превышающих значение limit, которое является входным значением алгоритма. Входная матрица: X = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) ''' import torch X = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])...
# made by Josh def magic(): datainput = input() x,y = datainput.split() miles = float(y)/60 print(float(x)/miles) numtimes = int(input()) while numtimes > 0: magic() numtimes -= 1
import random from random import * #1 보다 작은 실수인 난수 # random.random() num = random() print("random.random() =>", num) # 인수로 주어진 a,b 사이의 난수 num = uniform(4, 6) print("uniform =>", num) # 0부터 인수로 주어진 범위 안에서 난수 발생 num = randrange(5) print("randrange => ", num) num = randrange(105, 110, 2) print("randrange => ", num) ...
class MyDict(dict) : def __init__(self): #상속 받은 클래스는 부모의 생성자 호출 반드시 필요 super().__init__() def setAttribute(self, key, value) : self[key] = value def getAttribute(self, key) : return self[key] def size(self) : return len(self) mydict = MyDict() mydict.setAttr...
import sys user_list = [] def mk_grade(avg) : grade = 'F' if avg >= 90 : grade = 'A' elif avg >= 80 : grade = 'B' elif avg >= 70 : grade = 'C' elif avg >= 60 : grade = 'D' return grade def input_data(user) : user.append(input('성명입력: ')) user.append(in...
user_list = ['이하은','김얄롱','김모세','몰라'] print(user_list) print(type(user_list)) # print(user_list[0]) for i, name in enumerate(user_list) : print(i, name) print() print("----------------------") cnt = 0 # lenght -> len while cnt < len(user_list) : # \t하면 한줄에 다나옴 # sep="" 안에 뭐 넣어주면 구분자를 바꿔줄 수 있음. pri...
import pickle from pprint import pprint person1 = { "name" : "이하은", "height" : 161, "weight" : 48 } person2 = { "name" : "이은", "height" : 163, "weight" : 48 } people = [person1, person2] # 객체니까 바이너리 코드로 with open("people.pickle", "wb") as f : pickle.dump(people, f) # 로드 with open("peopl...
T = int(input()) for _ in range(T): name, date1, date2, courses = input().split() year1, _, _ = map(int, date1.split('/')) year2, _, _ = map(int, date2.split('/')) if year1 >= 2010 or year2 >= 1991: print(name, "eligible") elif int(courses) > 40: print(name, "ineligible") e...
numbers = [] N = 10 MOD = 42 for _ in range(N): n = int(input()) mod = n % MOD if mod not in numbers: numbers.append(mod) print(len(numbers))
import math DIAMATER = 60 SPEED = 15 # ft/sec CIRCUM = math.pi * DIAMATER INDEX = {c: i for i, c in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ '")} def circular_distance(a, b): d = min(abs(INDEX[a] - INDEX[b]), len(INDEX) - abs(INDEX[a] - INDEX[b])) return CIRCUM * (d / len(INDEX)) n = int(input()) ...
while True: numer, denom = map(int, input().split()) if numer == 0 and denom == 0: break else: integer = numer // denom newNumer = numer % denom newDenom = denom print(integer, newNumer, '/', newDenom)
ABC = ' abcdefghijklmnopqrstuvwxyz' T = int(input()) for _ in range(T): string = input() purpose = string[0] actual = string[2:] if purpose == 'e': symbol = [] for char in actual: symbol.append(ABC.index(char)) for index in range(1, len(symbol)): symbol[in...
while True: x, y = map(int, input().split()) if x == 0 and y == 0: break if x + y == 13: print("Never speak again.") elif x == y: print("Undecided.") elif x > y: print("To the convention.") else: print("Left beehind.")
line = input() vowel = 'aeiou' decoded = '' i = 0 while i < len(line): decoded += line[i] if line[i] in vowel: i += 2 i += 1 print(decoded)
from math import degrees, atan while True: a, b, s, m, n = map(int, input().split()) if a == 0 and b == 0 and s == 0 and m == 0 and n == 0: break # tan = opposite / ajacent (hypotenuse) angle = degrees(atan((b * n) / (a * m))) # Magnitude or norm (treat as directional vectors) ...
T = int(input()) for _ in range(T): sound = input().split() while True: case = input() if case == 'what does the fox say?': break case = case.split() if case[2] in sound: while case[2] in sound: sound.remove(case[2]) print(*sound)
# import os # def find_popular(filename): # f = open(filename) # #print f.peek() # f.seek(0, os.SEEK_END) # size = f.tell() # print size # f.seek(0,0) # print f # wordList = [] # wordFrequency = {} # word = '' # currSpacePos = 0 # lastSpacePos = 0 # for line in f: # print line wordFrequency = {} wo...
import random choice = choice = int(input("Choose the door number(1,2 or 3):")) doors = [1, 2, 3] random.shuffle(doors) car = random.randint(1, 3) open_door = list(filter(lambda x: x != car and x != choice, doors))[0] close_door = list(filter(lambda x: x != choice and x != open_door, doors))[0] print ("Ok. But I want t...
import random import time import sys empty = " " x = "x" o = "o" print("welcome to tic tac toe!") time.sleep(0.6) for char in ("this will be the game board you can play on:"): sys.stdout.write(char) sys.stdout.flush() time.sleep(0.00000025) def movegrid(board): board = board[:] time.sleep(0.000002) ...
line = int(input()) for i in range(1, line): print("*" * i) for j in range(line, 0, -1): print("*" * j)
cnt_list = [0 for x in range(10)] mul = 1 for _ in range(3): num = int(input()) mul *= num for i in map(int, str(mul)): cnt = cnt_list[i] cnt_list[i] = cnt + 1 print('\n'.join(map(str, cnt_list)))
line = int(input()) width = (line*2) - 1 for i in range(width, 0, -2): print(" " * ((width - i) // 2), end='') print("*" * i) for j in range(3, width+1, 2): print(" " * ((width - j) // 2), end='') print("*" * j)
hour, minute = map(int, input().split()) if minute - 45 >= 0: print(hour, minute - 45) else: if hour - 1 >= 0: print(hour - 1, minute + 15) else: print(hour + 23, minute + 15)