content
stringlengths
7
1.05M
def next_palindrome(digit_list): high_mid = len(digit_list) // 2 low_mid = (len(digit_list) - 1) // 2 while high_mid < len(digit_list) and low_mid >= 0: if digit_list[high_mid] == 9: digit_list[high_mid] = 0 digit_list[low_mid] = 0 high_mid += 1 low_mi...
print("Nome da Cidade\n") cid = str(input("Digite o nome da cidade que você nasceu: ")).strip() print(cid[0:5].upper() == "SANTO")
"""Definition of a pair.""" class Pair: """A pairing of people. Ordering doesn't matter in a pair. You can be paired with yourself. Treat as immutable. """ def __init__(self, name_a: str, name_b: str) -> None: """Make a new pair. >>> pair = Pair('A', 'B') >>> pair.n...
list = [123, "James", True] # Podemos criar listas mistas mas isso não é muito bom numbers = [78,900,1,4,5] names = ["Jhon", "Jack", "Jill"] print(list) # O python printa tudo como uma lista só sem precisarmos iterar sobre print(numbers[0]) # Naturalmente podemos printar apenas um elemento p...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 重连代理的重试次数 retry = 5 # 指定支持的代理类型,同时只能支持一种类型,可选值有:http、https、socks、http/https svr = { 'http': '0.0.0.0:1991', 'https': '0.0.0.0:1992', 'socks4': '0.0.0.0:1993', 'socks5': '0.0.0.0:1994', } plugins = [ "/home/father/projects/goudan_plugins/src/scanner...
''' Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. ''' class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place in...
''' As Jason discussed in the video, by using a where clause that selects more records, you can update multiple records at once. It's time now to practice this! For your convenience, the names of the tables and columns of interest in this exercise are: state_fact (Table), notes (Column), and census_region_name (Column...
""" Write a separate Privileges class. The class should have one attribute, privileges , that stores a list of strings as described in Exercise 9-7. Move the show_privileges() method to this class. Make a Privileges instance as an attribute in the Admin class. Create a new instance of Admin and use your method to s...
def sentence_analyzer(sentence): solution = {} for char in sentence: if char is not ' ': if char in solution: solution[char] += 1 else: solution[char] = 1 return solution
__version__ = "0.0.0" __title__ = "example" __description__ = "Example description" __uri__ = "https://github.com/Elemnir/example" __author__ = "Adam Howard" __email__ = "ahoward@utk.edu" __license__ = "BSD 3-clause" __copyright__ = "Copyright (c) Adam Howard"
"""Supervisr Core Errors""" class SupervisrException(Exception): """Base Exception class for all supervisr exceptions""" class SignalException(SupervisrException): """Exception which is used as a base for all Exceptions in Signals""" class UnauthorizedException(SupervisrException): """User is not auth...
# 002 找出檔案內6 & 11 的公倍數 f = open("input.txt", mode='r') for line in f.readlines(): num = int(line) if(num % 6 == 0 and num % 11 == 0): print(num) f.close()
class RecipeNotValidError(Exception): def __init__(self): self.message = 'RecipeNotValidError' try: recipe = 5656565 if type(recipe) != str: raise RecipeNotValidError except RecipeNotValidError as e: print(e.message) print('Yay the code got to the end')
# /* ****************************************************************************** # * # * # * This program and the accompanying materials are made available under the # * terms of the Apache License, Version 2.0 which is available at # * https://www.apache.org/licenses/LICENSE-2.0. # * # * See the NOT...
BOT_NAME = 'hit_dl' SPIDER_MODULES = ['hit_dl.spiders'] NEWSPIDER_MODULE = 'hit_dl.spiders' # downloads folder FILES_STORE = 'moodle_downloads' USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY =...
#Dog Years dog_years = int(input("What is the dog age? ")) human_years = (dog_years * 3) print("Human age: " + str(human_years))
class Solution(object): def countPrimes(self, n: int) -> int: # corner case if n <= 1: return 0 visited = [True for _ in range(n)] visited[0] = False visited[1] = False for x in range(2, n): if visited[x]: t = 2 ...
def main(): puzzleInput = open("python/day15.txt", "r").read() # Part 1 # assert(part1("") == 588) # print(part1(puzzleInput)) # Part 2 # assert(part2("") == 309) print(part2(puzzleInput)) def part1(puzzleInput): puzzleInput = puzzleInput.split("\n") a = int(puzzleInput[0].s...
class Solution: def isAnagram(self, s: str, t: str) -> bool: """ My idea is to use bucket -> Passed sList = list(s) tList = list(t) sCounter = len(sList) tCounter = len(tList) if sCounter != tCounter: return False sBucket ...
actual = 'day1-input.txt' sample = 'day1-sample.txt' file = actual try: fh = open(file) except: print(f'File {file} not found') depths = [int(x) for x in fh] inc = 0 for i in range(len(depths)): if i == 0: prevDepth = depths[i] continue if prevDepth < depths[i]: inc += 1 ...
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Yu Zhou # **************** # Descrption: # 20. Valid Parentheses # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. # The brackets must close in the correct order, "()" and "()[]{}" are all valid ...
def main(): A, B, C = map(int, input().split()) list = [A, B, C] list.sort() print(list[1]) if __name__ == "__main__": main()
# # PySNMP MIB module CISCO-TRUSTSEC-SXP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TRUSTSEC-SXP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:58:10 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
# import sys # from io import StringIO # # input_1 = """3 # 1, 2, 3 # 4, 5, 6 # 7, 8, 9 # """ # # sys.stdin = StringIO(input_1) matrix = [[int(x) for x in input().split(', ')] for x in range(int(input()))] primary_diagonal = [] secondary_diagonal = [] for row in range(len(matrix)): for col in rang...
""" You need to find the largest value in each row of a binary tree. Example: Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9] """ #Difficulty: Medium #78 / 78 test cases passed. #Runtime: 48 ms #Memory Usage: 16 MB #Runtime: 48 ms...
''' 说明: 所有对描述器属性(比如name, shares, price)的访问会被 __get__() 、__set__() 和 __delete__() 方法捕获到. 关键点: setattr(cls, name, Typed(name, expected_type)),将这个描述器(Typed)的实例作为类(Stock)属性放到一个类的定义中 详细: https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p09_create_new_kind_of_class_or_instance_attribute.html ''' # Descriptor for a ty...
txt = "hello, my name is Peter, I am 26 years old" minusculas = txt.lower() x = minusculas.split(", ") cont = 0 for palabla in x: for caracter in palabla: if caracter == 'a' or caracter == 'e' or caracter == 'i' or caracter == 'o' or caracter == 'u': cont += 1 #print(caracter,) ...
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt # partial branches and excluded lines a = 6 while True: break while 1: break while a: # pragma: no branch break if 0: never_happen() if...
mystock = ['kakao', 'naver'] print(mystock[0]) print(mystock[1]) for stock in mystock: print(stock)
# 1. Старата библиотека # • Ани отива до родния си град след много дълъг период извън страната. # Прибирайки се вкъщи, тя вижда старата библиотека на баба си и си спомня за любимата си книга. # Помогнете на Ани, като напишете програма, в която тя въвежда търсената от нея книга (текст). # Докато Ани не намери любимата с...
#%% """ - Logger Rate Limiter - https://leetcode.com/problems/logger-rate-limiter/ - Easy """ #%% """ Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds. Given a message and a timestamp (in seconds gr...
print(2 * 10 ** 200) def sqrt(my_number): a_index = 200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 the_index = int(a_index) the_index_plus_one = int...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeKLists(self, lists): amount = len(lists) interval = 1 while interval < amount: ...
## # @brief This is a class in BRIDGES a channel of audio data # # This class contains one channel of 8, 16, 24, or 32 bit audio samples. # # @author Luke Sloop # # @date 2020, 1/31/2020 # class AudioChannel(object): def __init__(self, sample_count: int=0, sample_bits: int=32) -> None: """ A...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 线性表: 下标 空表 表长度 下一个关系 顺序关系 线性关系 线性结构 唯一的首元素 唯一的尾元素 除首元素,每个元素都有一个前驱元素 除尾元素,每个元素都有一个后继元素 实现者: 如何表示 如何操作 使用者: 提供哪些操作 如何有效使用 使用者: 创建数据表,如何提供初始元素序列 检查表,获取如长度,特定数据,等信息 改变表:增删 -- 按条件对多个元素同时操作 多个表之间的操作 对表中的每个元素操作 - 表的遍历 变动型 -- 动原表 非变动型 -- 建新...
#!/usr/bin/python3 class standard: def __init__(self, name, message): self.app_name = name self.app_message = message def __del__(self): print("Python3 object finalized for: standard") def self_identify(self): print("Class name: standard") print("Application name: ...
phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } del phonebook["John"] print(phonebook)
#Evaluate two variables: x = "Hello" y = 15 print(bool(x)) print(bool(y))
# https://github.com/balloob/pychromecast # Follow their example to get your chromecastname # chromecastName = "RobsKamerMuziek" # pychromecast.get_chromecasts_as_dict().keys() server = 'http://192.168.1.147:8000/' # replace this with your local ip and your port port = 8000
class command_parser(object): argument_array=[] def __init__(self): pass def add_argument(self,arg): self.argument_array.append(arg) def get_shot_arg(self): shot_arg="" for arg in self.argument_array: shot_arg=shot_arg+arg.shot_text+':' return shot_arg def get_long_arg(self): ...
ENV = "dev" issuesPath = 'issues' SERVICE_ACCOUNT_FILE = 'config/credentials/firebase_key.json' AUTHORIZED_ORIGIN = '*' DEBUG = True
class Solution: def sortColors(self, nums: list[int]) -> None: """ Do not return anything, modify nums in-place instead. Dutch National Flag Problem (https://users.monash.edu/~lloyd/tildeAlgDS/Sort/Flag/) """ low = mid = 0 high = len(nums)-1 while mid <= high: ...
""" This is a comment written in more than just one line """ """ Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it: """ def add(x,y): """Add two nu,mers together""" return x + y
expected_output = { "interfaces": { "GigabitEthernet0/0/0": { "neighbors": { "172.18.197.242": { "address": "172.19.197.93", "dead_time": "00:00:32", "priority": 1, "state": "FULL/BDR", ...
# This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS). # Last modified by David J Turner (david.turner@sussex.ac.uk) 13/05/2021, 20:46. Copyright (c) David J Turner class HeasoftError(Exception): def __init__(self, *args): """ Exception rais...
# -*- coding: utf-8 -*- """Class for dependency error exception .. module:: lib.exceptions.dependencyerror :platform: Unix :synopsis: Class for dependency error exception .. moduleauthor:: Petr Czaderna <pc@hydratk.org> """ class DependencyError(Exception): """Class DependencyError """ def __init...
# https://www.codewars.com/kata/alphabetically-ordered/train/python # My solution def alphabetic(s): return sorted(s) == list(s) # def alphabetic(s): return all(a<=b for a,b in zip(s, s[1:]))
input = """29x13x26 11x11x14 27x2x5 6x10x13 15x19x10 26x29x15 8x23x6 17x8x26 20x28x3 23x12x24 11x17x3 19x23x28 25x2x25 1x15x3 25x14x4 23x10x23 29x19x7 17x10x13 26x30x4 16x7x16 7x5x27 8x23x6 2x20x2 18x4x24 30x2x26 6x14x23 10x23x9 29x29x22 1x21x14 22x10x13 10x12x10 20x13x11 12x2x14 2x16x29 27x18x26 6x12x20 18x17x8 14x25x...
class Statistic: def __init__(self): self.events = {} def add_event(self, event): try: self.events[event] += 1 except KeyError: self.events[event] = 1 def display_events(self): for event in sorted(self.events): print("Event <%s> occurre...
# time O(m*n*len(word)) class Solution: def exist(self, board: List[List[str]], word: str) -> bool: for i in range(len(board)): for j in range(len(board[0])): if self.dfs(board, i, j, set(), word, 0): return True return False def dfs(self, board, ...
# https://www.codechef.com/problems/COMM3 for T in range(int(input())): n,k,l=int(input()),0,[] for i in range(3): l.append(list(map(int,input().split()))) if(((l[0][0]-l[1][0])**2+(l[0][1]-l[1][1])**2)<=n*n):k+=1 if(((l[0][0]-l[2][0])**2+(l[0][1]-l[2][1])**2)<=n*n):k+=1 if(((l[1][0]-l[2][0...
def fibonacciModified(t1, t2, n): n-=2 t3=t2 while n!=0: t3=t1+t2*t2 t1,t2=t2,t3 n-=1; return t3 if __name__ == "__main__": t1, t2, n = input().strip().split(' ') t1, t2, n = [int(t1), int(t2), int(n)] result = fibonacciModified(t1, t2, n) print(result)
def swap(A, i, j): temp = A[i] A[i] = A[j] A[j] = temp def partition(a, start, end): pivot = a[end] pIndex = start for i in range(start, end): if a[i] <= pivot: swap(a, i, pIndex) pIndex = pIndex + 1 swap(a, end, pIndex) return pIndex def qui...
# # PySNMP MIB module DGS1100-26ME-MGMT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DGS1100-26ME-MGMT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:30:24 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
# Suppose we have a string with some alphabet and we want to # store all the letters from it in a tuple. Read the input string and # print this tuple. alphabet = input() print(tuple(alphabet))
# 3. Legendary Farming # You've done all the work and the last thing left to accomplish is to own a legendary item. # However, it's a tedious process and it requires quite a bit of farming. Anyway, you are not too pretentious – # any legendary item will do. The possible items are: # • Shadowmourne – requires 250 Shards...
# coding:950 __author__ = 'Liu' def letraParaNumero(list_numerais): resultado = '' letra_para_numero = { 'um':'1', 'dois':'2', 'tres':'3', 'quatro':'4', 'cinco':'5', 'seis':'6', 'sete':'7', 'oito':'8', 'nove':'9', 'zero':'0' } for numeral in list_numerais: resultado += letra_para_numer...
""" The schema package contains validation-related functionality, constants and the schemas Optimal BPM adds to the Optimal Framework namespaces Created on Jan 23, 2016 @author: Nicklas Boerjesson """ __author__ = 'nibo'
# -*- coding: utf-8 -*- _codes = { 1001:"参数token不能为空", 1002:"参数action不能为空", 1003:"参数action错误", 1004:"token失效", 1005:"用户名或密码错误", 1006:"用户名不能为空", 1007:"密码不能为空", 1008:"账户余额不足", 1009:"账户被禁用", 1010:"参数错误", 1011:"账户待审核", 1012:"登录数达到上限", 2001:"参数itemid不能为空", 2002:"项目不存在", 2003:"项目未启用", 2004:"暂时没有可用的号码", 2005:"获取号码数量已达到上限", 20...
N,K = map(int, input().split()) S = list(input()) target = S[K-1] if target == "A": S[K-1] = "a" elif target == "B": S[K-1] = "b" else: S[K-1] = "c" for str in S: print(str, end="")
def can_build(plat): return plat=="android" def configure(env): if (env['platform'] == 'android'): env.android_add_java_dir("android") env.disable_module()
class MyClass(object): pass def func(): # type: () -> MyClass pass
class Subsector: def __init__(self): self.systems = None self.name = None
info = { "name": "sw", "date_order": "DMY", "january": [ "januari", "jan" ], "february": [ "februari", "feb" ], "march": [ "machi", "mac" ], "april": [ "aprili", "apr" ], "may": [ "mei" ], "june":...
# Network parameters NUM_DIGITS = 10 TRAIN_BEGIN = 101 TRAIN_END = 1001 CATEGORIES = 4 NUM_HIDDEN_1 = 512 NUM_HIDDEN_2 = 512 # Parameters LEARNING_RATE = 0.005 TRAINING_EPOCHS = 50 BATCH_SIZE = 32 DECAY = 1e-6 MOMENTUM = 0.9
class PFFlaskSwaggerConfig(object): # General Config enable_pf_api_convention: bool = False default_tag_name: str = "Common" # Auth Config enable_jwt_auth_global: bool = False # UI Config enable_swagger_view_page: bool = True enable_swagger_page_auth: bool = False swagger_page_auth...
def remove_duplicates(arr): arr[:] = list({i:0 for i in arr}) # test remove_duplicates numbers = [1,66,32,34,2,33,11,32,87,3,4,16,55,23,66] arr = [i for i in numbers] remove_duplicates(arr) print("Numbers: ", numbers) print("Duplicates Removed: ", arr)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if not root: return [] res = [] def ...
a = int(input()) if ((a%4 == 0) and (a%100 != 0 or a%400 == 0)): print('1') else: print('0')
#!/usr/bin/env python # Programa 5.2 - Ultimo número informado pelo usuario print(' ') fim = int(input('Digite o último número a imprimir: ')) x = 1 while x <= fim: print(x) x = x + 1 print(' ') print('FIM ')
class Plot: def __init__(self, x=None, y=None, layers=None, fig=None, ax=None): self.x = x self.y = y self.layers = layers self.fig = fig self.ax = ax
#!/usr/bin/python """ Module by Butum Daniel - Group 911 """ def filter(iterable, filter_function): """ Filter an iterable object(e.g a list) by a user supplied function Example: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def filter_function(x): return x % 2 == 0 # all e...
__name__ = "jade" __version__ = "0.0.1" __author__ = "Aaron Halfaker" __author_email__ = "ahalfaker@wikimedia.org" __description__ = "Judgment and Dialog Engine" __url__ = "https://github.com/wiki-ai/jade" __license__ = "MIT"
# -*- coding: utf-8 -*- """ Created on Thu Jun 18 20:08:30 2020 @author: luol2 """ def combine_overlap(mention_list): entity_list=[] if len(mention_list)>2: first_entity=mention_list[0] nest_list=[first_entity] max_eid=int(first_entity[1]) for i in r...
#! /usr/bin/env python class arm_main: def __init__(self): list = [] self.planning_group = "arm_group" list.append(self.planning_group) object_f = arm_main() object_f.planning_group = "test" print(object_f.planning_group)
class Settings(): """ Uma Classe para armazenar todas as configurações da Invasão Alienigenas. """ def __init__(self): """ Inicializa as configurações do jogo """ # Configurações da tela self.screen_width = 800 self.screen_height = 600 s...
#Program to find perfect numbers within a given range l,m (inclusive) in python #This code is made for the issue #184(Print all the perfect numbers in a given range.) l = int(input()) m = int(input()) perfect_numbers = [] if l > m: l, m = m, l for j in range(l,m+1): divisor = [] for i in range(1,...
# Tuplas # sao imutaveis depois de iniciado o programa ( comando de atribuir (=) nao funcionara) print('-' * 30) print('Exemplo 1 print') mochila = ('Machado', 'Camisa', 'Bacon', 'Abacate') print(mochila) print('-' * 30) print('Exemplo 2 fatiando') # podemos manipular e fatir a tupla igual strings print(mochila[0]) #...
class Solution: def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ count = 0 circle = {} m = len(M) n = len(M[0]) for i in range(m): for j in range(n): if M[i][j] == 1 and (i, j) not in circ...
# Copyright 2015-2016 by Raytheon BBN Technologies Corp. All Rights Reserved. """ Old loop unroller Functionality is now done within eval """ class Unroller(ast.NodeTransformer): """ A more general form of the ConcurUnroller, which knows how to "unroll" FOR loops and IF statements in more general contex...
# pylint: disable=missing-docstring, line-too-long FINAL = b"""\ First line Line two. Line 3 Four? Five! 7 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et d...
#: Warn if a field that implements storage is missing it's reset value MISSING_RESET = 1<<0 #: Warn if a field's bit offset is not explicitly specified IMPLICIT_FIELD_POS = 1<<1 #: Warn if a component's address offset is not explicitly assigned IMPLICIT_ADDR = 1<<2 #: Warn if an instance array's address stride is n...
# 1470. Shuffle the Array # Author- @lashewi class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: out = [] for i in range(n): out.append(nums[i]) out.append(nums[i+n]) return out
line = input() result = "." for word in line: if word != result[-1]: result += word print(result.replace(".", ""))
def xor(a=False, b=False, c=False, d=False, e=False, f=False, g=False, h=False): """Checks if odd no. of values are True. `📘`_ - a: 1st boolean - b: 2nd boolean - ... Example: >>> xor(True, False) == True >>> xor(True, True) == False >>> xor(True, True, True, False) == ...
''' Система линейных уравнений - 1 ''' a = float(input()) b = float(input()) c = float(input()) d = float(input()) e = float(input()) f = float(input()) if (a != 0): y = (a * f - c * e) / (a * d - c * b) x = (e - b * y) / a else: y = e / b x = (f - d * y) / c print(x, y, sep=' ')
class Solution: def isPalindrome(self, s: str) -> bool: left=0 right=len(s)-1 while left<right: while left<right and not s[left].isalpha() and not s[left].isdigit(): left+=1 while left<right and not s[right].isalpha() and not s[right].isdigit(...
#!usr/bin/env python3 def main(): name = input("Enter ur Name to Start Quiz: ") ans = input("TRUE or FALSE: Python was released in 1991:\n") if ans == "TRUE": print('Correct') elif ans == "FALSE": print('Wrong') elif ans != ("TRUE" or "FALSE"): print('Please answer TRUE o...
n = list(input('Ingrese el número: ')) contador = 0 for i in n: if int(i)==4 or int(i)==7: contador+=1 if contador!=0 and (contador%4==0 or contador%7==0): print('YES') else: print('NO')
maior = '' while True: a = input() if a == '0': print('\nThe biggest word: {}'.format(maior)) break a = a.split() for y, x in enumerate(a): if len(x) >= len(maior): maior = x if y+1 == len(a): print(len(x)) else: print(len(x), e...
A, B, C, K = map(int, input().split()) ans = min(A, K) K -= min(A, K) K = max(0, K - B) ans += -1 * min(K, C) print(ans)
#18560 Mateusz Boczarski def testy(): #Zadanie 1 #Zdefiniuj klase Student(), ktora zawiera pola (niestatyczne): imie, nazwisko, nr_indeksu, #kierunek. Klasa ma posiadac __init__(), w ktorym podczas tworzenia instancji (obiektu) przypisywane #beda wartosci do wskazanych pol. Pole nr_indeksu powinno by...
def heapify(customList, n, i): smallest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and customList[l] < customList[smallest]: smallest = l if r < n and customList[r] < customList[smallest]: smallest = r if smallest != i: customList[i], customList[smallest] = customList[sma...
# This program creates a JPEG File Name from a Basic String word = "dog_image" print("Filename: " + word) word = word + ".jpeg" print("Image filename: " + word) # This section swaps the suffix '.jpeg' to '.jpg' i = len(word)-5 # Check if there's a suffix '.jpeg' if word[i:] == ".jpeg": #Remove the suffix ...
n= input() def ismagicnumber(number): if n[0] != '1': return False for i in range(len(n)): if n[i] != '1' and n[i] != '4': return False for i in range(1, len(n)-1): if n[i] == '4' and n[i-1] == '4' and n[i+1] == '4': return False return True flag =...
A = int(input()) B = int(input()) H = int(input()) A <= B if A <= H <= B: print("Это нормально") elif H < A and H < B: print("Недосып") elif H > A and H >= B: print("Пересып")
class TrackingSettings(object): """Settings to track how recipients interact with your email.""" def __init__(self): """Create an empty TrackingSettings.""" self._click_tracking = None self._open_tracking = None self._subscription_tracking = None self._ganalytics = None ...
n1=float(input('A primeira nota do aluno foi: ')) n2=float(input('A segunda nota do aluno foi: ')) s=n1+n2 m=s/2 print('A média do aluno é {:^20.2f}!'.format(m) ) #{:^20.2f} para ter 20 espaços, ser centralizado, e ter duas casas decimais
square = lambda x : x*x l = [1,2,3,4,5] #map return the finale value of the list. print("This is the map list.",list(map(square,l))) #filter return the original value of an list. print("This is the filter list.",list(filter(square,l)))
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...