text
stringlengths
37
1.41M
import threading import time # fasdasdasd def t(): """Prosta funkcja podająca nazwę aktualnego wątku; skraca zapis poniżej... :returns nazwa wątku """ return threading.current_thread().name class MyJob(threading.Thread): def __init__(self, title: str): threading.Thread.__init__(self...
from Node import Node class Tree(object): def __init__(self): self.root = None def insert(self, key, value): if self.root is None: self.root = Node(key, value) return self.root node = self.root while True: if key < node.get_key(): if node.left: node = node.left else: leaf = Node...
from typing import List def read_file(input) : data = open(input,"r") res = data.readlines() res = list(map(lambda x: x[:-1].split(')'),res)) data.close() return res dictNodes = {} class Node: def __init__(self, name: str, parent) : self.name = name self.parent = parent ...
import turtle def draw_square(some_turtle): for i in range(0,4): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window = turtle.Screen() window.bgcolor("blue") #brad draws a bunch of squares brad = turtle.Turtle() brad.shape("square") brad.color("b...
import logging import time logging.basicConfig( # filename='algorithm-output.log', level=logging.INFO, format='[%(asctime)s] {%(filename)s:%(funcName)s:%(lineno)d} %(levelname)s - %(message)s', datefmt='%H:%M:%S' ) logger = logging.getLogger(__name__) def knapsack_repeat(weight_list: list,value_list...
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 10:58:12 2020 @author: dalan """ # Sequential is the neural-network class, Dense is # the standard network layer from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras import optimizers # to choose more advanced optim...
import time # My way # Use oof as an argument in foo - i.e. sum(foo(oof)) # Or foo as an argument of even_nos - i.e. sum(even_nos(foo)) def oof(): seq = [1,1] for i in seq: if seq[-1] + seq[-2] < 4000000: seq.append(seq[-2] + seq[-1]) # if seq[-1] % 2 != 0: # se...
from shared import * import re input_ary = read_input('input.txt') count = 0 def is_triangle(arr): largest = max(numbers) numbers.pop(numbers.index(largest)) return largest < (numbers[0] + numbers[1]) for line in input_ary: matches = re.findall('(\d{1,3})', line) numbers = [int(x) for x in mat...
flag = True fibval = 0 counter = 0 sum = 0 def fib(n): if n == 0 : return 0 elif n == 1: return 1 else: temp = fib(n - 1) + fib(n - 2) return temp while flag: fibval = fib(counter) if fibval > 4000000: flag = False else: if fibval % 2 == 0: sum += fibval counter = counter + 1 print fibval #...
# Implement binary search """ What is it searching for? Ints, Strings, Objects? What do you want me to return if its not in the list? - Null, -1, exception? Should we assume the input is sorted? or do we sort it and then perform binary search? But that would take longer than the search Design Search for: 4.5 0 ...
""" Kitten is stuck on tree that is numbered First line is his branch """ from collections import defaultdict stuck_on = int(input()) next_line = input() graph = defaultdict(list) while next_line != "-1": parsed_line = next_line.split(" ") parsed_line = list(map(lambda x: int(x), parsed_line)) parent = p...
array = [-99, 4, 2, 1, -3, 4, 92, 11, -321, 66, 1, 0] expected = sorted(array) def insertion_sort(array): for i in range(1, len(array)): j = i while j - 1 >= 0 and array[j] < array[j - 1]: array[j - 1], array[j] = array[j], array[j - 1] j -= 1 return array print(expe...
num_cases = int(input()) for i in range(0, num_cases): number = input() reverse = number[::-1] final = "" found = False for num in reverse: num = int(num) if num - 1 >= 0 and found == False: final = str(num-1) + final found = True else: fi...
import string char_map = dict(zip(range(1, 27), string.ascii_lowercase)) first_line = input().split() length = int(first_line[0]) height = int(first_line[1]) k = int(first_line[2]) laptop_back = [["_" for j in range(length)] for i in range(height)] def is_oob(row, col): if not (0 <= row < height): retu...
''' Create a class to represent a patient of a doctor's office. The Patient class will accept the following information during initialization Social security number Date of birth Health insurance account number First name Last name Address The first three properties should be read-only. First name and last name shou...
import csv def timetable(x, y): x = int(input) y = int(input) for x in range(50): product = x * y result = product return result def timetable(x, y): if x < y: return x return y def love(name): first_name = input("Enter your first name: ") middle_name = input("...
# -*- coding: utf-8 -*- """ Created on Thu Nov 1 16:25:58 2018 @author: yangyang43 """ alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}] alist.sort(key=lambda x:x['age']) print(alist)
# -*- coding: utf-8 -*- """ Created on Tue Jan 22 22:11:27 2019 练习 杨辉三角定义如下: 1 / \ 1 1 / \ / \ 1 2 1 / \ / \ / \ 1 3 3 1 / \ / \ / \ / \ 1 4 6 4 1 / \ / \ / \ / \ / \ 1 5 10 10 5 1 把每一行看做一个list,试写一个generator,不断输出下一行的list: @author: yang...
# -*- coding: utf-8 -*- """ Created on Sun Sep 30 10:25:58 2018 @author: yangyang43 """ def is_amsteron(num): if type(num) != int: print ("Invalid input") return mystr = str(num) lenth = len(mystr) sum = 0 for x in mystr[:]: sum += int(x)**lenth if sum == num: ...
# -*- coding: utf-8 -*- """ Created on Mon Oct 22 16:12:12 2018 @author: yangyang43 """ def reverse_list(L): lenth = len(L) i = 0 while (i < lenth/2): L[lenth-1-i],L[i] = L[i],L[lenth-1-i] i += 1 myList = [1,2,3,4,5,6] reverse_list(myList) print (myList)
from sys import argv import csv import os.path from core import helpers from core import sudoku if len(argv) != 3: print("Two args are mandatory for sudoku command:") print("1) csv file path for reading input matrix") print("2) csv file path for writing resolved matrix") exit() sourcePath = argv[1] destPath = a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- r''' AddNum2Pic.py A python test project Add a number to a picture. ''' import os, sys from PIL import Image, ImageFont, ImageDraw def addNum2Pic( picPath, num): print( picPath ) print( num ) pic = Image.open( picPath ) w, h = pic.size fontsize = ...
import os import csv # path to collect data from the Resources folder csvpath = os.path.join('budget_data.csv') csv_output =os.path.join("results.txt") with open(csvpath) as csvfile: reader = csv.reader(csvfile) header =next(reader) total_months = 0 total_profit_loss = 0 tota...
import sys def print_puzzle(puzzle): for row in puzzle: print(" ".join([str(num) for num in row])) def find_empty_position(puzzle): for row in range(9): for col in range(9): if puzzle[row][col] == 0: return row, col return -1, -1 def can_place_number(number...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # Going through LinkedList and returning an Integer def linked_to_int(self, node: ListNode) -> int: data = '' current = node # if t...
class Solution: def romanToInt(self, s: str) -> int: doubles = { 'CM': 900, 'CD': 400, 'XC': 90, 'XL': 40 , 'IX': 9, 'IV': 4} singles = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I':1} integer = 0 i = 0 while i < len(s): if i < le...
a = int(input ("Digite um número inteiro: ")) if a % 3 == 0: print ("Fizz") else: print (a)
a = int(input ("Digite um número inteiro: ")) b = int(input ("Digite outro número inteiro: ")) c = int(input ("Digite outro número inteiro: ")) if a < b and a < c and b < c: print ("crescente") else: print ("não está em ordem crescente")
def compara_vogal(letra): if letra == "a" or letra == "e" or letra == "i" or letra == "o" or letra == "u": return True else: return False letra = input (str("Digite uma letra: ")) resposta = compara_vogal(letra) print (resposta)
from random import * def qSort(a): if len(a) <= 1: return a else: q = choice(a) return qSort([elem for elem in a if elem < q]) + [q] * a.count(q) + qSort([elem for elem in a if elem > q]) arr = [9, 1, 3, 5] print qSort(arr)
variavel=" " def parametroString(): variavel=input("Insira os caracteres {[()]}: ") if "{[()]}" in variavel: print("Parâmetro ok!",True) return True elif "{[()()]}" in variavel: print("Parâmetro ok!",True) return True else: print("Algo deu errado...",False) ...
import datetime class UserInput: def __init__(self): pass def addEmpSSN(self, emp_type): print() return input("\nEnter the new {}'s ssn: ".format(emp_type)).capitalize() def addEmpName(self, emp_type): return input("\nEnter {} first and last name (Non-Icelandic characters):...
class Nodes(object): def __init__(self, treeDict =None): if(treeDict is None): self.treeDict = {} else: self.treeDict = treeDict def showNodes(self): return list(self.treeDict.keys()) def findPath(self, limit, startNode, goalNode, s...
import pandas as pd import datetime import csv import matplotlib.pyplot as plt import matplotlib.dates as mdates plt.style.use('bmh') df = pd.read_csv("netflix_titles.csv") df.dataframeName = 'netflix_titles.csv' nRow, nCol = df.shape print(f'There are {nRow} rows and {nCol} columns') # How many movies and TV shows a...
from math import factorial as fact from constant import romans, romanLetters def factorial(numStr): try: n = int(numStr) r = str(fact(n)) except: r = 'Error!' return r def decToBin(numStr): try: n = int(numStr) r = bin(n)[2:] except: r = 'Error!' ...
import time # Example 1 # 下面这段代码,实际上是用deco函数在给run函数加一个计时器的功能,而任何包含了@deco的函数,都会有这样的功能 # 这样做的好处主要有: # 1)每个需要记时的函数,只需要@deco就可以了,这样可以节省很多代码量, # 2)在不改变run1,run2代码的基础上,就能实现给两个函数加功能 def deco(func): def wrapper(): start = time.time() func() end = time.time() print(f'{round(end - start, 4...
import unittest from my_bank.account import Account from my_bank.bank import Bank class BankTest(unittest.TestCase): def test_bank_is_initially_empty(self): bank = Bank() self.assertEqual({}, bank.accounts) self.assertEqual(len(bank.accounts),0) def test_add_account(self): ban...
''' 列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。 列表的数据项不需要具有相同的类型 创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可 ''' # list1=['Google','Runoob',1997,2000] # list2=[1,2,3,4,5,6,7] # list3=["a","b","c",'d'] ''' 访问列表中的值 使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符 ''' # print('list1[0]:',list1[0]) # print('list2[1:5]:',list2[1:5]) ''' 更新列表 你可以对列表的数据项进行修...
__author__ = 'Aman' name = "Lucy" if name is "Bucky": # this is how you say if name == bucky print("Hey there Bucky") elif name is "Lucy": print("What up Lucedawg") elif name is "Sammy" : print("What up Sammy") else : print( " Hi ")
__author__ = 'kaman' class Tuna : def __init__(self): #this is something similar to initialization, so when ever you make an object of class this will be executed #you can conclude that _init_ is a constructor print("Initialization function") def swim(self): print("Tuna Swiming") tuna1 ...
class Movie(object): """This is a movie object, containing information about a movie Attributes: movie_title (str): the title of the movie poster_image (str): a URL for the movie poster trailer_youtube (str): a youtube URL for the trailer genre (str): the movie's genre r...
#Enthalpy Changes #This program calculates the amount of energy and cost to melt some snow. #Water c 4.187 kJ/kgK, Ice C 2.108 kJ/kgK #Enthalpy of Vaporization 2.030 mJ/kg #Enthalpy of Fusion 334 kJ/kg print ("This program calculates the amount of energy and cost to melt some snow in a rectangular area."); print ("<En...
import unittest from chess.board import Board from chess.piece import Piece from chess.pawn import Pawn from chess.exceptions import InvalidInputException class TestBoard(unittest.TestCase): def setUp(self): self.board = Board() def test_init(self): self.assertEqual(self.board.__board__, [[Non...
# -*- coding: utf-8 -*- def add_1(xs): return [x + 1 for x in xs] def square(xs): return [x ** 2 for x in xs] def squared_mean(xs): return sum((x ** 2 for x in xs)) / len(xs)
class Solution(object): def isMatch(self, s, p): if p and s: if p[0] == s[0] or p[0] == ".": if len(p) > 1 and p[1] == '*': return self.isMatch(s[1:], p) return self.isMatch(s[1:], p[1:]) else: if len(p) > 1 and p[1] == '*': ...
# --- Day 1: The Tyranny of the Rocket Equation --- import math fuelTotal= 0 input_file = open('input', 'r') count_lines = 0 for line in input_file: #print (line, end = '') #count_lines += 1 mass = float(line) fuelNeeded = math.floor(mass / 3) - 2 fuelTotal = fuelTotal + fuelNeeded print (fue...
from abc import ABCMeta, abstractmethod class Iterator(metaclass=ABCMeta): """ Абстрактный итератор """ _error = None # класс ошибки, которая прокидывается в случае выхода за границы коллекции def __init__(self, collection, cursor) -> None: """ Constructor. :param coll...
def mySqrt(x: int) -> int: left = 0 right = x while left <= right: mid = (right+left)//2 if mid**2 == x: return mid elif mid**2 < x: left = mid + 1 ans = mid else: right = mi...
def returnOdd(array) : for i in range(0, len(array)) : if i % 2 != 0 : print(array[i]) arr = [None] enter = 0 while enter != "f" : enter = input("Enter values. Enter f when done. ") arr.append(enter) del arr[0] del arr[-1] returnOdd(arr)
n = int(input("This program prints out the first nth prime numbers. \nEnter n as an integer: ")) x = 1 #The xth number in the list of 1 to n. cand = 1 #The candidate number, check thi...
def readText(filename) : file = open(filename, "r") text = file.read().lower() textList = text.split() return textList def findWord(string, textList) : #generates a list that contains all the positions (elements of all matching words return [y for y in range(0, len(textList)) if textList[y] == stri...
print("This program tells you the size of a planet and its distance in kilometers from Earth.") print("Enter the name of a planet in the Solar System: ") input = input() if input == "Mercury" : print("Diameter: 4,878") print("Distance: 92,000,000") if input == "Venus" : print("Diameter: 12,104") print("Distance:...
import re def validateEmail(address): if re.search(pattern = '[a-zA-Z]+@[a-zA-Z]+\.[a-z]+', string = address) != None: return True else: return False def validateDate(date): if re.search(pattern = '[1-3]?[0-9]/1?[0-9]/[1-9]+', string = date) != None: return True else: r...
def pluralize(word, num): """ Returns a string that holds num in word form and the appropriate pluralization for "word." """ word = word.lower().lstrip() string = "" numList = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve...
from timeit import default_timer as timer import time import sys coffee = "" size = "" sugar = -1 wait = 0 price = 0 ans = "" skip = 0 resetting = 0 tinit = 0 tend = 0 def reset() : global coffee coffee = "" global size size = "" global sugar sugar = -1 global price price = 0 ...
from pandas import Series from pandas import DataFrame from pandas import concat series = Series.from_csv('daily-minimum-temperatures-in-me.csv', header=0) temps = DataFrame(series.values) width = 2 shifted = temps.shift(width - 1) print(shifted.head(12)) # 向上统计的步长 window = shifted.rolling(window=4) # 分别取过去四天的最小值,均值,最大...
from pandas import Series from pandas import DataFrame from pandas import concat from matplotlib import pyplot from sklearn.metrics import mean_squared_error series = Series.from_csv('daily-minimum-temperatures.csv', header=0) # create lagged dataset values = DataFrame(series.values) dataframe = concat([values.shift(1)...
class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) def earl...
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder, their colleagues and Huiruo Zou. """ ######################################################################## # DONE: 1. # On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name. ###...
import numpy as np def conv_single_step(image_slice, filt, bias): """ Apply one filter defined by parameters filt on a single slice (image_slice) of the output activation of the previous layer. Arguments: image_slice -- slice of input data of shape (f, f, n_C_prev) filt -- Weight pa...
# lower function changes letters in a string to lowercase: print("Angela".lower()) # "count" function will give you number of times a letter occurs in a string (case sensitive) print("Angela".count("a")) # example to count all letters (non case-sensitive) lower_case_name = "Angela".lower() print(lower_case_name.count...
# Program using math/fstrings that tells us how many days, weeks, months we have left if we live to 90 years # Example output: You have 12410 days, 1768 weeks and 408 months left. age = int(input("What is your current age? ")) years_left = 90 - age days = years_left * 365 weeks = years_left * 52 months = years_left * 1...
a=str(input("Cuvantul este ")) b=str(input("Litera este ")) for k in range(0, len(a)): print(f"{a[:k]}{b}{a[k+1:]}")
# Write a function for decompressing string “a4b3c2d” => "aaaabbbccd" string1 = input(f"Enter a string: ") def str_decompress(string): result = '' for i in range(0, len(string)): if string[i].isnumeric(): result += '' else: if i != len(string) - 1: if ...
# List Slices square = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(square[2:6]) print(square[3:8]) print(square[0:1]) print(square[:7]) print(square[7:]) print('\n') sq = (0, 1, 4, 9, 16, 25, 36, 49, 64, 81) print(sq[2:6]) print(sq[:7]) print(sq[7:]) print('\n') print(square[::2]) print(square[::3]) print(square[2:8:3...
# Data Hiding # Weakly private methods and attributes # Have a single underscore at the beginning. # It's mostly only a convention and does not stop external code from accessing them. # Actual effect: from module_name import * won't import variables that start with a single underscore. class Queue: def __init__(...
try: varible = 10 print (varible + "hello") print (varible / 2) except ZeroDivisionError: print("Divided by zero") except (ValueError, TypeError): print ("Error occurred") finally: print ("This code will run no matter what") # Raising Exceptions # num = input(":") # if float(num) < 0: # ra...
import numpy as np # map # Function map takes a function and an iterable as arguments, # and returns a new iterable with the function applied to each argument. def add_five(x): return x + 5 nums = [11, 22, 33, 44, 55] result = list(map(add_five, nums)) print(result) # use lambda print(list(map(lambda x: x + 5...
# encoding=utf-8 ######################################################################### #File Name: test.py #Author: Don Hu #Mail: hudeng@staff.sina.com.cn #Create Time: 2017-10-18 16:56:44 #Last modified: 2017-10-21 18:42:56 ######################################################################### #!/usr/bin/env py...
# encoding=utf-8 ######################################################################### #File Name: test.py #Author: Don Hu #Mail: hudeng@staff.sina.com.cn #Create Time: 2017-10-18 16:42:42 #Last modified: 2017-10-18 16:49:34 ######################################################################### #!/usr/bin/env py...
import random array = [] for i in range(0, 10): array.append(random.randrange(0,100)) print("Array to sort " + str(array)) def bubbleSort(): for i in range(0,len(array)): for j in range(0,len(array)-i-1): if array[j] > array[j+1]: temp = array[j+1] array[...
class matrix: def __init__(self,m=None,n=None,deflist=None,rowwise=None,displ=0,mode='n'): '''Constructor for matrix. (default values if not initialised are (self,1,1,[],[],0))''' self.defset=1 self.rwset=0 if m is None: self.row=1 else: self.row=m if n is None and mode=='n': self.col=1 elif n i...
import urllib2 import json from api_key import YOUTUBE_API_KEY def load_data(url): # Load json returned from a url try: data = json.load(urllib2.urlopen(url)) return data except urllib2.HTTPError: return None def get_movie(title, year): """Constructs a Movie object using tit...
class person: def __init__(self,name,age,sex):#this is constructor default method of the class self.Name = name#this is python properties self.Age = age self.Sex = sex def person_bio(self): information = "This is "+ self.Name +" bio data" name = self.Name age = self....
a=10 b=3 print(a+b) print(a-b) print(a*b) print(a/b) print(a**b) print(a//b)
class Binary_Search_Tree: class __BST_Node: def __init__(self, value): self.value = value self.right_child = None self.left_child = None self.height = 1 def __init__(self): self.__root = None def __return_height(self, root): if root.left_child is None and root.right_child i...
def extract(word, text): firstCharacter = word[0] firstIndex = text.index(firstCharacter) return text[firstIndex : firstIndex + len(word)] website = "http://www.batuhanduzgun.com" course = "Python Kursu: From Zero to Hero Course" courseLength = len(course) print(f"Course word length is {courseLength}")...
x = input('sayi1 giriniz:') y = input('sayi2 giriniz:') print(type(x)) print(type(y)) toplam = int(x) + int(y) print(type(int(x))) print(type(int(y))) print(toplam) a = 5 b = 2.5 name = 'Çınar' isOnline = True print(type(a)) print(type(b)) print(type(name)) print(type(isOnline)) aAsFloat = float(a) print(aAs...
x = y = [1, 4, 5, 11, 3, 9] z = [1, 4, 5, 11, 3, 9] # == operatorü bellek referanslarını değil, değerleri kıyaslar! print(x == y) print(z == x) # bellek referansını kıyaslamak istersek "is" operatorü kullanmalıyız! print(x is y) print(x is z) # membership operator is "in" fruits = ["Apple", "Banana", "Orange"] pri...
from typing import List delta = [-1, 0, 1, 0, -1] def search(board, r, c, word) -> bool: if len(word) == 0: return True for i in range(4): nr, nc = r + delta[i], c + delta[i + 1] if 0 <= nr < len(board) and 0 <= nc < len(board[0]) and board[nr][nc] == word[0]: temp = board...
# -*- coding: utf-8 -*- # author: sunmengxin # time: 18-12-12 # file: 函数闭包 # description: def adder(x): def wrapper(y): return x + y return wrapper adder5 = adder(5) adder6 = adder5(10) print(adder6) # ==> 15,因为函数最开始封装了x=5 # 输出 11 adder7 = adder5(6) print(adder7) # ==> 11,因为函数最开始封装了x=5
#Flips a coin 100 times and then reports back the number of heads and tails import random number_of_flips = 0 heads = 0 tails = 0 winner = "" input("We're going to flip a coin 100 times and see whether it's more 'heads' or 'tails', which one do you think it will be?") while number_of_flips < 100: if random.randint...
''' #Teste IF a = int (input("Digite o valor de a: ")) b = 150 c = 151 if (a == b): print("São Iguai!") else: print("São diferentes") if (a > b and a > c): print("a é maior que b e c") elif (b > c ): print("b é maior que a e c") else: print("c é maior que a e b") exercicio = int(input("Quantos...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 31 21:03:45 2019 @author: ece-student """ # Copyright 2019 Dingjun Bian braybian@bu.edu # Copyright 2019 Shiyang Hu shiyangh@bu.edu import sys import numpy as np import math class Circle(): def __init__(self, name, m, R, posit...
#! python3 """ Problem 1 Ask the user to enter a number. The number is considered "frue" if it is divisible by 6, but not divisible by 8. State whether the number is "frue" (2 marks) Inputs: a number Outputs: xx is frue xx is not frue example: Enter a number: 48 48 is not frue Enter a number: 36 36 is frue Ente...
# > width = 8 # > height = 4 # > number_of_mines = 8 # > generate_board(width, height, number_of_mines) # *112*100 # 123*3222 # 01**31** # 013*2122 # board = list # each row of the board = list - 4 with 8 items inside (start all items with 0) # randomizing the mines: random index for the row, random index for item ins...
import tkinter width = 500 height = 400 title = "bocharov" top = tkinter.Tk() top.minsize(width=width + 10, height=height + 10) if title: top.title(title) canvas = tkinter.Canvas(top, width=width + 2, height=height + 2) canvas.pack() canvas.xview_scroll(8, 'units') # hack so (0, 0) works correctly canvas.yview...
arr = [0, 3, 24, 2, 3, 7] for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): if int(arr[j]) < int(arr[minimum]): minimum = j arr[i], arr[minimum] = arr[minimum], arr[i] print(arr)
def compare (a, b, c): if a>=b and b>=c: print ("Samoe bolsho chislo " + str(a) + ", potom " + str(b) + ", potom " + str(c)) elif b>=a and a>=c: print ("Samoe bolsho chislo " + str(b) + ", potom " + str(a) + ", potom " + str(c)) elif c>=b and b>=a: print ("Samoe bolsho chislo " + str...
import tkinter width = 350 height = 250 title = "vasyaeva" top = tkinter.Tk() top.minsize(width=width + 10, height=height + 10) if title: top.title(title) canvas = tkinter.Canvas(top, width=width + 2, height=height + 2) canvas.pack() canvas.xview_scroll(8, 'units') # hack so (0, 0) works corr...
def compare(a, b): if a >= b: print(str(a) + ' Is bigger') else: print(str(b) + ' Is bigger') x = 34 y = 95 compare(x, y) def compare(d, f): if d >= f: return d else: return f x = 32 y = 99 compare(x, y)
mydict = {"comma":",","apostrophe": "'", "dot": ".", "space": " "} s = 'Sorry{comma}{space}I{space}didn{apostrophe}t{space}understand{space}this{space}task{dot}'.format(**mydict) print(s)
print("Переменные\n") k=input('Задача1. Перевод секунд в часы и минуты.\nВведите целое число секунд k = ') while k.isdigit()==False: k = input('Вы ввели ошибочные данные, введите целое число секунд k = ') else: h = int(k) // 3600 m = (int(k) % 3600) // 60 print("Ответ: " + str(k) + " секунд - это " + st...
import turtle import math turtle.title ("Run, turtle, run") width = 500 height = 400 x = -width/2 y = height/2 n = 100 turtle.setup = (width + 10, height + 10) turtle.speed (10) turtle.radians () turtle.penup () turtle.goto (x,y) turtle.pendown() # Рисуем красные линии turtle.color('red') for i in range(n): y_...
for a in range(1,101): # cоздаем список if (a%15)==0: #каждое кратное число переименоваем на FizzBuzz print("FizzBuzz") elif (a%3)==0: # кратное 3 меняем на Fizz print("Fizz") elif (a%5)==0: # кждае кратное 5 переменовать в Buzz print("Buzz") else: print(a) # Выв...
class Money(object): value = 0.0 USDexRate=65.31 Rubles=True def __str__(self): A = self.value//1 B = self.value%1*101 return (str(int(A))+","+str(int(B))) def __add__(self, other): self.value += other return self.value def __sub__(self, other): s...
class Money(): def __init__(self, wholes, cents): if type(wholes) != int: raise TypeError('Рубль должен быть целым числом') if cents not in range(0, 100): raise ValueError('Копейка должна быть числом от 0 до 99') self.wholes = int(wholes) self.cents = int(cent...
#1. Операции со строками s = "Дана строка." # Сначала выведите третий символ этой строки. print(s[2]) # Во второй строке выведите предпоследний символ этой строки. print(s[-2]) # В третьей строке выведите первые пять символов этой строки. print(s[0:5:1]) #начало строки 0, кол-во символов 5, шаг - каждый 1й # В четвер...
##### 1 def my_len(b): i = 0 for index in b: i += 1 print(i) b =[1, 3, 5, 6, 7] my_len(b) print() ##### 2 def my_reserve(a): rv_list=a[::-1] return rv_list print(my_reserve([5,6,5,9])) ###3 def Range(start, stop, step): a = start b = step c = stop while a <= c: yield...
d = input("Enter how many degrees the clock has shifted") # Ввод градусов d = int(d) if d >= 360: print("Enter the number of degrees no more than one turn of the arrow (360)") else: m = d * 2 #Преобразование градусов в минуты и часы h = int(m / 60) m = int(m - (h * 60)) print('It is ' + str(h) + '...