content
stringlengths
7
1.05M
# Eingabe print("Geben Sie Ihr Bruttogehalt in Euro ein:") brutto = float(input()) # Berechnung if brutto > 2500: steuer = brutto * 0.22 else: steuer = brutto * 0.18 # Ausgabe print("Es ergibt sich ein Steuerbetrag von", steuer, "Euro")
#!/usr/bin/python # -*- coding: utf-8 -*- print('開檔,並覆寫') f = open('output.txt', 'w') f.write('123') f.write('456\n') f.close print('開檔,並新增內容') f = open('output.txt', 'a+') f.write('123') f.write('456\n') print('移動指針, 讀出數值') f.seek(5) print(f.read(1)) f.close
# keywords MEMORY = 'memory' SOURCE = 'source' FILE_TYPE = 'file_type' FILE_NAME = 'file_name' FILE_STREAM = 'file_stream' SESSION = 'session' TABLE = 'table' MODEL = 'model' TABLES = 'tables' MODELS = 'models' DEPRECATED_CONTENT = 'content' FILE_CONTENT = 'file_content' ADICT = 'adict' RECORDS = 'records...
##To print the below pattern ## * ## # # ## * # * ## # * * * def pattern_generator(end_point): #counter = 1 for i in range(1, end_point+1): symbol = '#' if (i == 2 or i == 3 or i == 5 or i == 7) else '*' print(symbol, end='') if (i == 1 or i == 3 or i == 6): print('\r') if ...
# ░░░░░░░░░░░░░░░░░░░░░░░ # ░░░░░▄▀▀▀▄░░░░░░░░░░░░░ # ▄███▀░◐░░░▌░░░░░░░░░░░ # ░░░░▌░░░░░▐░░░░░░░░░░░░ # ░░░░▐░░░░░▐░░░░░░░░░░░░ # ░░░░▌░░░░░▐▄▄░░░░░░░░░░ # ░░░░▌░░░░▄▀▒▒▀▀▀▀▄░░░░░ # ░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄░░░ # ░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄░ # ░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄ # ░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄ # ░░░░░░░░░░░▌▌░▌▌░░░░░░░ # ░░░...
""" Linear Probing is a technique for resolving hash collisions of calues of hash function.It is a form of open addressing. In this scheme, each cell of a hash table stores a single key–value pair. When the hash function causes a collision by mapping a new key to a cell of the hash table that is already occupied by an...
# For this fantasy planet, the following is "hard canon". # * Orbital period = exactly 365 days # * The planet reaches periapsis at 00:00am Jan 1 each year # (which I *think automatically means...) # --> Argument of Periapsis = 270 degrees (it reaches periapsis at the southernmost point from the plane o...
# Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator(object): def appendToCache(self, cache, branches, curr): while curr: cache.append(curr.val) if ...
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2018-11-13 20:51:10 # @Last Modified by: 何睿 # @Last Modified time: 2018-11-13 20:51:10 class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ ...
""" Multiply any two numbers by: 1. taking the individual digits out using division and mod 2. performing partial multiplication and multiplying by 10**n-1 where n is the total length of the number string; 3. adding all product outputs. """ def partial_shift_multiply(target, num): """ A typical...
t = int(input()) for i in range(t): base=int(input()) n = base//2 n = n-1 sq=(n*(n+1))//2 print(sq)
__author__ = 'Vladimir Ivanov' __copyright__ = 'Copyright 2020, Raw-packet Project' __credits__ = [''] __license__ = 'MIT' __version__ = '0.2.1' __maintainer__ = 'Vladimir Ivanov' __email__ = 'ivanov.vladimir.mail@gmail.com' __status__ = 'Development'
# Default production config DEBUG = True TEAM_COUNT = 20 # MongoDB MONGODB_SETTINGS = { 'db': "fpc2017", # "project" 'host': "localhost", # "127.0.0.1" 'port': 27017, # 27017 # 'username': "None", # 'username' # 'password': None, # 'passwd' } # ReCaptcha RECAPTCHA_ENABLED = False RECAPTCHA_SITE_KEY = '6Leyx...
#!/usr/bin/env python3 """ A popular word game in which without reading the story you have to substitute some words. The program reads in a text file and lets the user replace word ADJECTIVE, NOUN, ADVERB or VERB with their own text. """ def mad_libs(filename): with open(filename, 'r') as file: filedata = file.rea...
# -*- coding: utf-8 -*- t = int(input()) for _ in range(t): d = {} m, n = map(int, input().split()) for _ in range(m): w = input() d[w] = input() for _ in range(n): ly = input().split() ln = '' for i in range(len(ly)): if ly[i] in d.keys(...
# Problem: Find Median from Data Stream def findMedian(stream): # print(stream) streamSize = len(stream) if streamSize == 1: return stream[0] else: stream = sorted(stream) midPt = streamSize // 2 if streamSize % 2 == 1: return stream[midPt] else: return (stream[midPt] + stream...
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: query.py Description : Author : charl date: 2018/11/6 ------------------------------------------------- Change Activity: 2018/11/6: ------------------------------------------------- """
class LearnerParams: """ Defines the fields used to set halton space that is used for generating halton samples """ def __init__( self, eps=0.1, lr=0.8, y=0.9, num_episodes=200, num_steps=100, observation_space=1000, columns=["UserId",...
for _t in range(int(input())): N, S = map(int,input().split()) steps = input() #print(N,S,steps) pos = [S] cnt = 1 for x in steps: if(x == 'R'): step = 1 else: step = -1 S += step if S not in pos: pos.ap...
j = 7 for a in range(1, 10, 2): print("I={} J={}".format(a, j)) print("I={} J={}".format(a, j-1)) print("I={} J={}".format(a, j-2)) j += 2
""" Given a sorted linked list, delete all duplicates such that each element appear only once. Example: Input: 1->1->2->3->3 Output: 1->2->3 """ #Difficulty: Easy #165 / 165 test cases passed. #Runtime: 40 ms #Memory Usage: 13.9 MB #Runtime: 40 ms, faster than 87.68% of Python3 online submissions...
class UI: def __init__(self, screen): self._screen = screen self._screen.setup(600, 600) self._screen.title("Turtle Crossing") self._screen.tracer(0) # PUBLIC METHODS def update(self): self._screen.update() def listen(self): self._screen.listen() d...
# Time: O(nlogn) # Space: O(1) class Solution(object): def reductionOperations(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() result = curr = 0 for i in xrange(1, len(nums)): if nums[i-1] < nums[i]: curr += 1 ...
"""Dummy helper methods invoked in other constructors.""" def GenerateMachineName(prefix, suffix): """Generates name of a VM.""" return prefix + "-" + suffix
# The sum of all numbers from 1 upto # that input natural number n def sum_N_Numbers (n): if n == 1: return 1 # Write code here return n + sum_N_Numbers(n-1)
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- ''' @File : types.py @Author : alexander.here@gmail.com @Date : 2020-01-13 18:36 @Brief : ''' # type() function: print( type( 1), type( 1.2), type( 'hello'), type( ( 1, 2, 3)), type( [ 1, 2, 3]), type( { 1, 2, 3}), type( { 1:2, 3:4})) # ...
class DfuStatus: OK = 0x00 ERROR_TARGET = 0x01 ERROR_FILE = 0x02 ERROR_WRITE = 0x03 ERROR_ERASE = 0x04 ERROR_CHECK_ERASED = 0x05 ERROR_PROG = 0x06 ERROR_VERIFY = 0x07 ERROR_ADDRESS = 0x08 ERROR_NOTDONE = 0x09 ...
list_of_items = input().split("|") budget = float(input()) initial_money = budget profit = 0 for i in range(len(list_of_items)): product_characteristics = list_of_items[i].split("->") type1 = product_characteristics[0] value = float(product_characteristics[1]) new_price = 0 if value > bud...
def init_n(d): n = 1 while True: if n * n > d: return n - 1 n += 1 def main(x, y): d = y - x if d <= 2: return d n = init_n(d) remain_d = d - (n * n) if remain_d == 0: return n + (n - 1) if remain_d % n == 0: return n + (n - 1)...
if __name__ == '__main__': i=input("your age:") age=int(i) if age<3: print('child') elif age>3 and age<30: print('adult') else: print('man')
# -*- coding: utf-8 -*- """Job Args""" class Args: """Job Args""" def __init__(self, parser): """Initialize class properties.""" parser.add_argument('--tc_owner', required=True) parser.add_argument('--rating', required=True, default=3) parser.add_argument('--confidence', requi...
result = ('tuple',) + 'string' ''' Traceback (most recent call last): File "exceptions_TypeError.py", line 12, in <module> result = ('tuple',) + 'string' TypeError: can only concatenate tuple (not "str") to tuple '''
hrs = input("Enter Hours:") rate = input("Enter Rate:") try: h = float(hrs) r = float(rate) except: print("Error, please enter numeric input") quit() if h>40: pay = 40 * r + (h - 40) * 1.5 * r else: pay = h * r print(pay)
class Solution: def numPairsDivisibleBy60(self, time: List[int]) -> int: remainders = collections.defaultdict(int) count = 0 for t in time: if t % 60 == 0: # check if a%60==0 && b%60==0 count += remainders[0] else: # che...
__AUTHOR__ = "Dipankar Pal" __EMAIL__ = "dipankarpal5050@gmail.com" __WEBSITE__ = "deep5050.github.io" # def get_version(): # return __VERSION__ # if __name__ == "__main__": # get_version()
#!/usr/bin/env python # -*- coding: utf-8 -*- def windplot(t, windv, pos=5, angle=0.0, color='k'): """Computes angle of arrows based on wind direction. t : arr time position (inform as integers values. Datatime will be processed in the near future) windv : arr Wind Velocity. ang...
class Fortnite: CHARACTERS = {"Raven" :"https://lh5.googleusercontent.com/89tmMS73f0Xa6ki9DPQ1ww1foWMAztEFrTw_cNKiB6ttdbYTfySZwLoUJKMluR5vVW_Z3HvTdrkmP4Jv9Q82nCUg-0cFk1ydPHXGMIt1OQwEJ8KnCFt7DO1fwWioSKuuudPLe5_x", "Dark Hound" :"https://brokenpanda.net/wp-content/uploads/Molten-Battle-Hound-Fortnite-Wal...
""" _______ __ _______ __ __ __ | _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----. |. 1___| _| _ | | | | _ | 1___| _| _| | <| -__| |. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____| |: 1 | |: 1 | |::.. ...
def col_groupby_pdf(data, col, metric_col, ascending=False): '''Cumulative Distribution Function Takes in a dataframe with at least 2 columns, and returns a groupby table with PDF. data | DataFrame | a pandas dataframe with the data col | str | name of the column to be grouped by metric_col |...
''' Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [...
# Python - 3.4.3 test.describe('Example Test Cases') test.assert_equals(dating_range(17), '15-20') test.assert_equals(dating_range(40), '27-66') test.assert_equals(dating_range(15), '14-16') test.assert_equals(dating_range(35), '24-56') test.assert_equals(dating_range(10), '9-11')
color_pink = '#fff5f6' color_white = '#ffffff' color_gray = '#f0f0f0' color_bright = '#E8E9EB' button_color = color_white button_style_classic = "background-color: " + button_color + "; border-style: outset; border-width: 2px; " \ "border-radius: 10px; " \ ...
IS_WINDOWS = True def lineJuggle_logic(n1, n2, operation, linePrefix): delete_to_mark=min(n1,n2) delete_from_mark=max(n1,n2) if linePrefix == "+": delete_to_mark, delete_from_mark = delete_from_mark, delete_to_mark delete_to_mark=delete_to_mark-delete_from_mark # lower_line is now offset r...
VERSION = (0, 3, 5) __version__ = '.'.join(map(str, VERSION)) class PaymentProviderException(Exception): def __init__(self, message, *args, **kwargs): super(PaymentProviderException, self).__init__(message, *args, **kwargs) payment_providers = {} def register_provider(name, provider): payment_prov...
#!/usr/bin/env python3 class Util(object): @classmethod def has_key_recursion(cls, obj: dict, key: str) -> any: """Returns the value of the first key found in the dictionary. (No recursive search is performed.) Args: obj (dict): target key (str): key Returns: ...
def years(start, end): """ Build a list of years in the recent past/future as strings.""" try: too_far_in_past = start <= 1999 too_far_in_future = end >= 2020 if too_far_in_future or too_far_in_past: raise ValueError except ValueError: raise else: en...
k = 0 prevAvg = 0 firstRun = 0 def AvgFilter(x): global k, prevAvg, firstRun if firstRun == 0: k = 1 prevAvg = 0 firstRun = 1 alpha = (k - 1) / k avg = alpha + (1 - alpha) prevAvg = avg k = k + 1
# The name of the transpiler. This line is required. Do not change it. transpiler_name = "adam" """ The following code is the translation of the code. You can write your code here and modify the content of the variables. Do not change the name of the variables. """ # All the symbols that the transpiler uses. mayusc =...
# # PySNMP MIB module BENU-TWAG-STATS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BENU-TWAG-STATS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:20:36 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
# abc acb bac bca cab cba inputs = [["abc","acb"],["abc","bac"],["abc","bca"],["abc","cab"],["abc","cba"],["abcd","abc"],["tacocat","catastrophy"]] def checkPerm(inp): cache = {} for char in inp[0]: if char in cache: cache[char] += 1 else: cache[char] = 1 for char in...
notebook.width = 10 plt.rcParams['figure.figsize'] = (notebook.width, 2) # only display [0, 20] timerange notebook.crop = Segment(0, 20) # plot annotation annotation = Annotation() annotation[Segment(1, 5)] = 'Carol' annotation[Segment(6, 8)] = 'Bob' annotation[Segment(12, 18)] = 'Carol' annotation[Segment(7, 20)] =...
# # PySNMP MIB module CISCO-802-TAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-802-TAP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:32:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
# Code Demo for 06 Lecture # Working with Repetition as Loops in Python # CIS 135 - Code Demo File # Sample Variable Declaration userReply = "YES" inputData = -99 counter = 10 # Sample Comparisons print('True/False userReply == "YES")', userReply == "YES") print('True/False inputData != -99)', inputData != -...
# basicTag 基本分類辞書 Tag = { 1: "Coming_out", 2: "Divined_inquested", 3: "Guard", 4: "Vote", 5: "Estimate", 6: "Agree", 7: "Disagree", 8: "Opinion", 9: "Information", 10: "Question", 11: "Ans", 12: "Request" } # swapedTag 辞書のキーと値を入れ替えたもの swapedTag = {val: key for key, val i...
# Version 1: space: O(N * M) class Solution: """ @param m: An integer m denotes the size of a backpack @param A: Given n items with size A[i] @param V: Given n items with value V[i] @return: The maximum value """ def backPackII(self, m, A, V): n = len(A) dp = [[0 for _ in ran...
# Link to problem: https://leetcode.com/problems/n-queens/ # Problem :The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. #Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. #Each solu...
input1 = """2 book at 12.49 1 music CD at 14.99 1 chocolate bar at 0.85""" input2 = """1 imported box of chocolates at 10.00 1 imported bottle of perfume at 47.50""" input3 = """1 imported bottle of perfume at 27.99 1 bottle of perfume at 18.99 1 packet of headache pills at 9.75 3 box of imported chocolates at 11.25"...
def kill_kth_bit(n, k): """ use bitwise AND 0 & 0 = 0 1 & 0 = 0 to clear the bit: perform a bitwise AND of the number with a reset bit n = n & ~(1 << k) OR n &= ~(1 << k) """ return n & ~(1 << k - 1) if __name__ == '__main__': n = 37 k = 3 print(kill_kth_...
class Queue: def __init__(self): self._head = None # first order in the list self._tail = None # last order in the list self.length = 0 # number of Orders in the list self.volume = 0 # sum of Order quantity in the list AKA share volume self.last = None # helper for iter...
""" Poetry Environment Repository Designed to manage the virtual environment using Poetry and export a further repository to interact with it. """ def _symlink_venv(repository_ctx): project_dir = repository_ctx.path(repository_ctx.attr.project).dirname repository_ctx.symlink(repository_ctx.path(str(project_di...
class MaskSensitiveDataException(Exception): pass class RequestException(Exception): pass class ResponseParsingException(Exception): pass
def findRoots(A, B, C): D = B**2 - 4*A*C if D >= 0: r1 = (-B-D**(0.5))/(2*A) if D == 0: R = [r1] else: r2 = (-B+D**(0.5))/(2*A) if A > 0: R = [r1, r2] else: R = [r2, r1] else: R = [-1] return ...
def rc(num, low, high): if num >= low and num <= high: print(f'num = {num} is between {low} and {high}') rc(5,2,7)
class Solution(object): def validWordSquare(self, words): """ :type words: List[str] :rtype: bool """ n = len(words) for i in range(n): for j, ch in enumerate(words[i]): # compare with ith col if j >= n or i >= len(words[j])...
""" Configuration for docs """ # source_link = "https://github.com/[org_name]/hoa_alliance" # docs_base_url = "https://[org_name].github.io/hoa_alliance" # headline = "App that does everything" # sub_heading = "Yes, you got that right the first time, everything" def get_context(context): context.brand_html = "Hoa Al...
# Fill fields with your data login = '' passwd = '' host = ''
PUZZLE_INPUT = input("> ") # PART 1 def phase(input_signal, base_pat=(0,1,0,-1)): if isinstance(input_signal, int): input_signal = str(input_signal) numbers = [int(x) for x in input_signal] # 12345 -> 1, 2, 3, 4, 5 new_numbers = [] for n in range(1, len(input_signal)+1): number_total = 0 ...
__author__ = 'schlitzer' __all__ = [ 'Connection', 'Hash', 'HyperLogLog', 'Key', 'List', 'Publish', 'Scripting', 'Set', 'SSet', 'String', 'Subscribe', 'Transaction' ] class BaseCommand(object): def __init__(self): self._cluster = False def execute(self...
#tablas de 1 al 10 print ("numero de tabla de a l 10") n= int(input("ingresa tu numero de tabla")) print (n,(" * 1 es ="),(n*1)) print (n,(" * 2 es ="),(n*2)) print (n,(" * 3 es ="),(n*3)) print (n,(" * 4 es ="),(n*4)) print (n,(" * 5 es ="),(n*5)) print (n,(" * 6 es ="),(n*6)) print (n,(" * 7 es ="),(n*7)) print (n...
# # MIT License # # Copyright (c) 2021 David Walters # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, mer...
''' For Dataset1: This is list of models and parameters where model with parameter 0.p is represented by 'modelp' ''' dataset = 'Dataset' metrics_dict = ['PD', 'TEuc', 'TEMD','param', 'random'] feat_dict = ['top_log_Betti','top_log_simplex'] model_dict = ['ER03', 'ER06', 'ER1', 'ER15', 'ER2', 'ER25', 'GR1', 'GR175', ...
# # @lc app=leetcode id=40 lang=python3 # # [40] Combination Sum II # # @lc code=start class Solution: def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]: dp = [set({()})] + [set() for _ in range(target)] for c in sorted(candidates): for i in range(target,...
""" 66 / 66 test cases passed. Runtime: 140 ms Memory Usage: 36 MB """ class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: indegree = [0] * n for edge in edges: indegree[edge[1]] = True ans = [] for i, d in enumerate(indegree)...
techTreeDict = { "Elite Genitour": ["Berbers"], "Supremacy": ["Spanish"], "Battle Elephant": ["Vietnamese", "Burmese", "Khmer", "Malay"], "Perfusion": ["Goths"], "Thalassocracy": ["Malay"], "Supplies": [ "Turks", "Vietnamese", "Burmese", "Incas", "Indians"...
produtos = ('Lapis', 1.75, 'Caderno', 5.50, 'Borracha', 1.10, 'Estojo', 7.50, 'Transferidor', 3.60, 'Compasso', 9.99, 'Mochila', 120.99, 'Canetas', 22.30, 'Livro', 34.90) print(40*'=') print(f'{"LISTAGEM DE PRECOS":^40}') print(40*'=') for c in produtos: index = produtos.index(c) if index % 2 == 0: pr...
num=[[], []] valor=0 for c in range (1,8): valor=int(input(f'Digite o {c}o. valor: ')) if valor % 2 == 0 : num[0].append(valor) else: num[1].append(valor) print('-=' *30) num[0].sort() num[1].sort() print(f'Os valores pares foram {num[0]}') print(f'Os valores ímpares foram {num[1]}') print('...
def sublister(q,modulo=1): i=0 j=0 while True: yield j % q i+=1 if i % modulo==0:j+=1 # def lister(q): # lea=q # border=lea # gen=[sublister(q)] # i=0 # while True: # ac=[zw.__next__() for zw in gen] # yield ac # i+=1 # if i==border: # q-=1 # if q<=0:brea...
#!/usr/bin/env python """ -------------------------------- project: code created: 02/07/2018 14:00 --------------------------------- """
# One Iteration, Linear Space (Stack) Sol. # IB : Rain Water Trapped # Author : @amitrajitbose # # class Solution: # @param A : tuple of integers # @return an integer def trap(self, A): st = [] i = 0 ans = 0 while i<len(A): while st and A[i]>A[st[-1]]: top = st.pop(-1) ...
def vogal(x): if x in "aAeEiIoOuU": return True else: return False
class Vehicle: def __init__(self, id = None, license_plate = None, brand = None, model = None, id_user = None, id_vehicle_type = None): self._id = id self._license_plate = license_plate self._brand = brand self._model = model self._id_user = id_user self._id_vehicle_t...
''' 2) Faça um programa em Python que conte de 1 a 100 e a cada múltiplo de 10 emita uma mensagem: “Múltiplo de 10”. ''' for num in range (1,101,1): if (num % 10 == 0): print("O número", num, "é múltiplo de 10")
""" In mathematics, the greatest common divisor (gcd) of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. For example, the gcd of 8 and 12 is 4. » https://en.wikipedia.org/wiki/Greatest_common_divisor Due to limited recursion depth this algorithm is not...
time_pitch=1.0 sim_len_sec=10.0 NE=300 Nsominh=200 Ndndinh=200 Ninput=300 Ndistractor=0
x = 0 while x < 10: print(x) x = x + 1 x = "horse" print(x) print(5 + "horse")
# # PySNMP MIB module IBM-ELAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IBM-ELAN-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:50:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
class Person: def __init__(self, name, age, height_in_cm): self.name = name self.age = age self.height_in_cm = height_in_cm def speak(self): print(f'Hello! My name is {self.name}. I am {self.age} years old.') def greet(self, person): if person.name == 'Rogers': ...
''' William, John é um aluno vidrado por matemática, mas poucas pessoas sabem disso. Certo dia, um de seus colegas de classe achando que John não sabia conceitos básicos da matemática o desafiou a realizar um simples cálculo que era: Calcular o resto da divisão de A ÷ B Como John é muito tímido e vocês são melhores am...
numbers_count = int(input()) p1 = 0 p2 = 0 p3 = 0 p4 = 0 p5 = 0 for i in range(numbers_count): current_number = int(input()) if current_number < 200: p1 += 1 elif 200 <= current_number <= 399: p2 += 1 elif 400 <= current_number <= 599: p3 += 1 elif 600 <= current_number <= ...
""" Assignment 3""" customer_id = 101 type(customer_id) #int customer_name = 'John' type(customer_name) #str bill_amount = 675.45 type(bill_amount) #float x = 5.3 + 0.9j type(x) #complex print(customer_id,customer_name,bill_amount) print(x.real) print(x.imag+3) Flag = True type(Flag)
def fib(): x = y = 1 c=2 while len(str(y)) < 1000: x , y = y , y+x c += 1 return c print(fib())
def rotate_left(point_a, point_b, sin, cos): x1, y1 = point_a x2, y2 = point_b x_rot = (x2 * cos) - (y2 * sin) + (x1 * (1 - cos)) + (y1 * sin) y_rot = (x2 * sin) + (y2 * cos) + (y1 * (1 - cos)) - (x1 * sin) return x_rot, y_rot def rotate_right(point_a, point_b, sin, cos): x1, y1 = point_a ...
def square(x): return x*x def minus_one(x): return x - 1
temperatures_arr = [21, 23, 26, 22, 25, 20, 19, 23] i = 0 max = 0 while i < 8: temp = temperatures_arr[i] i = i + 1 if temp > max: max = temp print(max)
def probarFigura(s, delta): assert s.centroX == 200, s.centroX assert s.centroY == 200, s.centroY assert s.izquierda < s.centroX, s.izquierda assert s.centroX < s.derecha, s.derecha original_izquierda = s.izquierda s.derecha += delta assert rounded(s.izquierda - original_izquierda) == delta...
''' A number where one digit is the sum of the other digits is called a digit sum number or DS-number for short. For example, 352, 3003 and 32812 are DS-numbers. We define to be the sum of all DS-numbers of digits or less. You are given and . Find . Give your answer modulo . ''' n=1 s=0 while(n<50): cn=n ...
# code def solve(num): count = 0 num = str(num) revNum = int(num[::-1]) nextNum = int(num) + revNum count += 1 if (count > 5): return -1 if poli: return nextNum else: return solve(nextNum) def poli(nextNum): if nextNum == int(str(nextNum)[::-1]): re...
""" HTTPies: Api-testing made portable from the terminal. """ __version__ = '1.0' __author__ = 'Flip Vernooij' __licence__ = 'BSD'
''' Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table: Score Grade >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F If the user enters a value out of range, print a suitable error message a...
indices = [] a = 2 for i, c in enumerate(format(a, '02b')): if c == "1": indices.append(i) print(indices)