text
stringlengths
37
1.41M
''' def zero(list = None): if list == None: return 0 elif list[0] == 'a': return 0 + list[1] elif list[0] == 'b': return 0 - list[1] elif list[0] == 'c': return 0 * list[1] elif list[0] =='d': return int(0 / list[1]) def one(list = None): if list == None:...
""" Problem Solving and Algorithms Lean a basic process for developing a solution to a problem. Nothing in this chapter is unique to using a computer to solve a problem. This process can be used to solve a wide variety of leetcode, including ones that have nothing to do with computers. Problems, solutions, and Tools ...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None tree = TreeNode(1) class BSTIterator(object): def __init__(self, root): self.root = root self.data = [] self._inorder(root) self.current = 0 if root else -1 ...
""" Inorder tree traversal without recursion Using stack is the obvious way to traverse tree without recursion. Below is an algorithm for traversing binary tree using stack, see this for step wise step execution of the algorithm. 1. create an empty stack s. 2. initialize current node as root 3. push the current node ...
""" Solve tree problems recursively top down solution button up solution conclusion In previous sections, we have introduced how to solve tree traversal problem recursively. Recursion is one of the most powerful and frequent used methods for solving tree related problems. As we know, a tree can be define...
""" MERGE(A, p, q, r) n1 = q - p + 1 n2 = r - q Let L[1 .. n1 + 1] and R[1, n2 + 1] be new arrays for i = 1 to n1 L[i] = A[p + i - 1] for j = 1 to n2 R[j] = A[q + j] L[n1 + 1] = 'inf' R[n2 + 1] = 'inf' i = 1 j = 1 for k = p to r if L[i] <= R[j] ...
""" 686. Repeated String Match Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1. For example, with A = 'abcd' and B = 'cdabcdab'. Return 3, because by repeating A three times ("abcdabcdabcd"), B is a subsring of it; and ...
""" consistent hashing todo Distributed hash table (DHT) is one of fundamental component used in distributed scalable systems. Hash tables need key, value and hash function, where hash function maps the key to a location where the value is stored. index = hash_function(key) suppose we are designing a distributed...
""" Designing a url shortening service like TinyURL Let's design a url shortening service like TinyURL. This service will provide short aliases redirecting to long URLs. Similar services: bit.ly, goo.gl, 2020.fm etc. Difficulty Level: Easy 1. Why do we need url shortening? url shortening is used to create sho...
""" 683. K Empty Slots There is a garden with N slots. In each slot, there is a flower. The N flowers will boom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of booming since them. Given an array flowers consists of number from 1 to N. Each number in the arr...
import re phone_message = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # the mo is the generic name to use for Match Objects # search method with return Match object mo = phone_message.search('My number is 415-555-4242.') print('Phone number found: ' + mo.group()) """ review of regular expression matching While there ar...
""" Technical Questions There are logical ways to approach them: - How to prepare Need to try to solving problems, Memorizing solutions won't help you much. For the problem, do the following: 1. Try to solve the problem on your own. hints are provided at the backs of this book. after solve problem make sure think abo...
""" 816. Ambiguous Coordinates We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces, and ended up with the string S. Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representa...
import shutil import os shutil.move('data1', 'mydata') shutil.copy('mydata', 'databak') shutil.move('mydata', 'data1') """ - Call os.unlink(path) will delete the file at path - call os.rmdir(path) will delete the folder at path, the folder must be empty of any files or folders - call shutil.rmtree(path) will remove ...
buildings = 1 math = 1 science = 1 garedening = 1 biology = 1 nature = 1 planning = 1 culture = 1 politics = 1 social = 1 people = 1 speech = 1 language = 1 engineering = 1 computer = 1 graphics = 1 programming = 1 Systems = 1 development = 1 animation = 1 communication = 1 media = 1 design = 1 aesthetics = 1 art = 1 c...
def anagram(s1, s2): if(sorted(s1)== sorted(s2)): print("anagrams.") else: print("non anagrams.")
#section_035.py my_tuple = (1, 2, 3) your_tuple = (4, 5, 6) # 튜플 연산 our_tuple = my_tuple + your_tuple print(our_tuple) multiply_tuple = my_tuple * 3 print(multiply_tuple) #del our_tuple #print(our_tuple) # 튜플 멤버십 테스트 print(1 in my_tuple) print(4 in my_tuple) print(3 not in my_tuple) # 튜플 관련 메서드 print(multiply_tup...
#section_033.py # 인덱싱 myTuple = ('a', 'b', 'c') print(myTuple[0]) #print(myTuple[3]) # 오류 발생 #print(myTuple[2.0]) # 오류 발생 print() myTuple = ("tuple", (1, 2, 3), [4, 5, 6]) print(myTuple[0]) print(myTuple[0][1]) print(myTuple[2][0]) print(myTuple[-1]) print(myTuple[-1][0]) print() # 슬라이싱 myTuple = ('p', 'y', 't...
#section_070.py def select_even(*arg): result = [] for num in arg: if num%2 == 1: continue result.append(num) return result print(select_even(1,2,3,4)) print(select_even(-12, 2, 81, 99, 48, 20))
#section_062.py import turtle t = turtle.Pen() t.shape("turtle") for item in range(30): if item%2: t.penup() t.forward(10) t.pendown() continue t.forward(10)
""" ----- Day 14 Project: Higher or Lower ----- Using a list of personalities and their follower counts, Offer two random entries and ask user to choose the one that has more followers. If they get it right, then use the second person as the first person and compare to a new random person. If they get it wrong, then ga...
""" ----- Day 20 Project: Snake Game, pt 1 ----- Day 1: 1. Create snake body 2. Move the snake 3. Control the snake Day 2: 1. Detect collision with food 2. Create scoreboard 3. Detect collision with wall 4. Detect collision with self Classes: Snake, Food, Score (c)2021 John Mann <gitlab.fox-io@foxdata.io> """ from ...
#display all indexes in a list that have value n my_list = [int(i) for i in input().split()] n = int(input()) if n not in my_list: print(f'{n} is not in a list.') else: index = [i for i, val in enumerate(my_list) if val == n] for ind in index: print(ind, end = ' ')
# f string a= int(input("enter numbers :")) b= int(input("enter numbers :")) c= a+b print(f"the sum of {a} & {b} is {c} " )#simple code print("the sum of", a ,"&" ,b, "is", c) val = 'Metaeducators' print(f"{val} is a portal for learning coding in mother language .") print(val ,"is a portal for learning ...
# calculator print("for addition , sub, mul , div enter + , -, * , / respetively ") operation = input('enter your operation symbols : ') print(operation) a= int (input('enter first no : ')) b= int (input('enter secnod no : ')) exit() if operation == "+" : if a==5 and b== 4: print(14) ...
from random import randint print('Hello please enter the parameters for the game HIGHER LOWER to start') low = int(input("Lowest possible number: ")) high = int(input("Highest possible number: ")) print("\nOK now guess wich number between those above that i picked :)") answer = randint(low,high)# tar en slump värd...
förnamn = ["Maria","Erik", "Karl"] efternamn = ["Svensson", "Karlsson","Andersson"] for namn1 in förnamn: for namn2 in efternamn: print(namn1,namn2)#för varje förnamn så skrivs varje kombination av efternamn
import sys import pickle class Margaret: def __init__(self): self.empty_dict = dict() self.margaret_list = list() try: self.empty_dict = self.deserialize_dict() except FileNotFoundError: pass def serialize_dict(self): """ This method will serialize or convert the data into a format that is easi...
import random def rand_word_gen(lang): myline_1 = 0 myline_2 = 0 #myline_1 is the first word #myline_2 is the second word #we're adding the first word to myline_2 if lang=="1": file_1=open("wordsENG.txt","r") file_2=open("wordsENG2.txt","r") elif lang=="2": file_1=op...
import math import argparse def main(): my_parser = argparse.ArgumentParser() my_parser.add_argument("--type", type=str) my_parser.add_argument("--principal", type=int) my_parser.add_argument("--payment", type=float) my_parser.add_argument("--periods", type=int) my_parser.add_argument("--inter...
class ListNode: """ A node in a singly-linked list. """ def __init__(self, data=None, next=None): self.val = data self.next = next class SinglyLinkedList: def __init__(self): """ Create a new singly-linked list. Takes O(1) time. """ self.head ...
num = int(input('Digite um número: ')) print(f'O dobro de {num} é {num*2}') print(f'O triplo de {num} é {num*3}') print(f'A raiz quadrada de {num} é {num ** (1/2)}') print(f'A raiz cubida de {num} é {num ** (1/3)}')
#33 - Incremente o exercício anterior para receber 3 notas para cada aluno, onde deve ser possível efetuar as operações de adicionar, atualizar e deletar e mostre a média. (se possível você pode aproveitar exercícios anteriores) print('-='*20) print(f'Lançamento de notas') print('-='*20) turma = list() aluno = dict(...
#3 - Crie uma classe calculadora com as quatro operações básicas (soma, subtração, multiplicação e divisão). # O usuário deve informar dois números e o programa deve fazer as quatro operações. # # (modifique para calcular tudo no mesmo método, somando 1 ao resultado de cada operação) class Calculadora(): def toda...
#31 - Crie um dict com 5 nomes e profissões e remova o ultimo elemento pessoas = {} aux = {} for i in range(3): aux.clear() aux = {input('Digite o nome: '): input("Digite profissao: ")} pessoas.update(aux.copy()) print(f"Primeiro dicionário: {pessoas}") pessoas.popitem() print(f"Dicionário após exclusã...
dias = int(input('Quantos dias o carro foi alugado? ')) km = float(input('Quantos km rodados? ')) total = (dias * 60) + (km * 0.15) print(f'O total a pagar é R${total:.2f}')
from titulo import imprimirCabecalho from conversor import converte_data_nascimento #Estrutura de repetição de loop infinito. Sairá do loop comente quando chegar no Break while True: #Validação que verificará se a data está no formato correto [DD/MM/AAAA] try: # Entrada da data de nascimento pelo cons...
primeiro_termo = int(input('Digite o primeiro termo: ')) razao = int(input('Digite a razão: ')) print('=' * 15) print('10 TERMOS DE UMA PA') print('=' * 15) print(primeiro_termo, end='') for i in range(9): print('>', end='') print(primeiro_termo + razao, end='') primeiro_termo = primeiro_termo + razao
# Crie a classe Imóvel, que possui um endereço e um preço. # a. crie uma classe Novo, que herda Imóvel e possui um adicional no preço. Crie # métodos de acesso e impressão deste valor adicional. # b. crie uma classe Velho, que herda Imóvel e possui um desconto no preço. Crie # métodos de acesso e impressão para este de...
import random lista = [] for i in range(5): lista.append(input("Digite um nome: ")) print(f'O nome sorteado foi: {random.choice(lista)}')
#28 - Faça um programa que percorre uma lista e exiba na tela o valor mais próximo da média dos valores da lista. # Exemplo: lista = [2.5, 7.5, 10.0, 4.0] (média = 6.0). Valor mais próximo da média = 7.5 def media(lista): return float(sum(lista)) / max(len(lista), 1) lista = [2.5, 3, 10.0, 4.0] diff = [] for i ...
n1 = float(input("Digite primeiro nota do aluno: ")) n2 = float(input("Digite segunda nota do aluno: ")) media = (n1 + n2)/2 print(f'A média entre {n1} e {n2} é {media}')
#Multiples #Part I oddNumber = (i for i in range(1,1000) if i%2 !=0) for i in oddNumber: print i #Part II
# visit docs.python.org #1. Find and Replace built-in methods words = "It's thanksgiving day. It's my birthday, too!" #find string method #the position of the first instance of the word "day" is 18 print words.find("day")#day is a string object print words.replace("day", "month") #2. Min and Max x = [2,54,-2,7,12,98] ...
#!/usr/bin/env python import sqlite3 connection = sqlite3 connection = sqlite3.connect(':memory:') print "Content-Type: text/html\n" print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" cursor = connection.cursor() cursor.execute("CREATE TABLE books (name text, pub_date t...
#Author: CHINMAYA KAUNDANYA #This program is an example of insertion sort using Python # In Insertion sort elements get sorted in a same way playing # cards sort. Insertion sort is good for collections that are # very small or nearly sorted. Otherwise it's not a good sorting algorithm: # it moves data around too ...
def merge_sort(data): if len(data) > 1: middle = len(data) / 2 left_data = data[:middle] right_data = data[middle:] merge_sort(left_data) merge_sort(right_data) index, i, j =0, 0, 0 while i <len(left_data) and j < len(right_data): if left_data[i] ...
def is_prime(num: int) -> str: if num > 1: for i in range(2, num//2): if num % i == 0: return f'{num} is not prime!' return f'{num} is prime!' else: return f'{num} is not prime' while True: print("Check if a given number is prime (q) to quit") inp =...
name = input("what is your name? ") school = 'instincthub' print (f"my name is {name} and my school is {school}")
from Crypto.Cipher import AES def aes_ECB_Encrypt(pt,key): pt=padding(pt) ctext=AES.new(key,AES.MODE_ECB) ct=ctext.encrypt(pt) return ct def aes_ECB_Decrypt(ct,key): PT=AES.new(key,AES.MODE_ECB) ptext=PT.decrypt(ct) return ptext def padding(mesg): pad = 16-l...
def sigma(bot, top, inc=1): total = 0 while (bot <= top): total += bot bot += inc return total class Stock_Day(): """ """ def __init__(self, date, start, high, low, end, volume, adj_end): self.date = date self.start = start self.high = high self....
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.ace_spades = Card("spades", 1) self.ten_diamonds = Card("diamonds", 10) self.two_hearts = Card("hearts", 2) self.test_card_game = CardGame() ...
import numpy as np print( 11 // 2 == 5) print(11 // 2) print(11 % 2) def quickSort(a, l, r): if l < r: i = partition(a, l, r) quickSort(a, l, i-1) quickSort(a, i+1, r) def partition(a, l, r): key = a[l] i = l for j in range(l+1, r+1): if a[j] < key: i += 1 ...
# 最小生成树 # 并查集 import sys # 判断一个节点的root是谁 def find(x): t = x while pre[t] != t: t = pre[t] return t # 连通两个节点,并且是按大小顺序合并的(可以不做) def mix(a, b): fa = find(a) fb = find(b) if fa != fb: if fa < fb: pre[fb] = fa else: pre[fa] = fb # 判断两个节点是不是连通 def jud...
loc = locals() def gvn(variable): for key in loc: if loc[key] == variable: return key class ListNode: def __init__(self, value=None, next=None): self.value = value self.next = next def reverseList(head): if head is None or head.next is None: return head last...
import numpy as np def findMax(s1, s2): c = [ [ 0 for i in range(len(s2)+1)] for j in range(len(s1)+1)] m = 0 p = 0 for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: c[i+1][j+1] = c[i][j] + 1 if c[i+1][j+1] > m: ...
def func(num): x = num y = 0 while abs(x - y) > 0.00001: y = x x = (x + num / x) / 2 print(y) return x print(func(2)) print("1.4142135623731")
def main(): horas = int(input('Digite a quantidade de horas trabalhadas: ')) valor_hora = float(input('Digite o valor recebido por hora: ')) folha_pagamento(horas, valor_hora) def folha_pagamento(horas, valor_hora): salario_bruto = horas * valor_hora INSS = salario_bruto * 0.1 FGTS ...
def main(): numero = int(input('Digite um numero de dois digitos: ')) dezena = numero // 10 unidade = numero % 10 dezena_e_unidade(dezena, unidade) def dezena_e_unidade(dezena, unidade): if dezena == unidade: print('O numero da dezena é igual ao da unidade') else: print('O nu...
def main(): horas_de_aula1 = int(input('Digite a quantidade de horas que voce da aula:')) valor_hora1 = int(input('Digite quanto voce ganha por hora aula: ')) horas_de_aula2 = int(input('Digite a quantidade de horas que voce da aula:')) valor_hora2 = int(input('Digite quanto voce ganha por hora aula: ')...
def main(): num1 = int(input('Digite um numero: ')) num2 = int(input('Digite um numero: ')) num3 = int(input('Digite um numero: ')) num4 = int(input('Digite um numero: ')) num5 = int(input('Digite um numero: ')) media_total(num1, num2, num3, num4, num5) def media_total(num1, num2, num3, num4,...
def main(): n1 = int(input('Digite um numero: ')) n2 = int(input('Digite outro numero: ')) resto(n1, n2) def resto(n1, n2): if n1 % n2 == 0: pass elif n1 % n2 == 1: print(n1 + n2 + (n1 % n2)) elif n1 % n2 == 2: if n1 % 2 == 0: print(f'{n1} é par') e...
a = int(input("Digite os anos")) m = int(input("Digite os meses")) d = int(input("Digite os dias)")) r = a + m + d print("Você tem:", r "de vida.")
print("hello world") name = "Batman" print(name) x = 1 y = 2 z = x + y print(z) flag = False if flag: print("flag is true") else: print("flag is false")
import turtle import numpy as np turtle.shape('turtle') def strmm(n): i=0 n=200 for i in range(n): turtle.forward(2) turtle.right(360/n) for j in range(3): strmm(200) turtle.right(180) strmm(200) turtle.right(60)
import turtle import numpy as np turtle.shape('turtle') turtle.speed(0) def strmm(n, k): n = 200 for i in range(n): turtle.forward(k) turtle.right(360/n) def stlmm(n, k): n = 200 for i in range(n): turtle.forward(k) turtle.left(360/n) k = 2 turtle.right(90)...
""" This class consolidates functions related to the local datastore. """ import logging import sqlite3 import sys class DataStore: def __init__(self, config): """ Method to instantiate the class in an object for the datastore. :param config object, to get connection parameters. ...
#!/usr/bin/env python3 import unicodedata def name(ch): return unicodedata.name(ch) def unicode_code(ch): return 'U+{:04x}'.format(ord(ch)) def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper() if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Cha...
import string #пожключение библитоеки для операций со строками import random #подключение библиотеки для генерации случайных чисел my_number = 1000 while True: #проверка на условие задания №1 print("Введите число") user_number = int(input()) if user_number > my_number: break print("Ввод окон...
''' Created on Dec 14, 2015 @author: SRawoor ''' import re import operator def checkio(text): ''' You are given a text, which contains different english letters and punctuation symbols. You should find the most frequent letter in the text. The letter returned must be in lower case. While checking for t...
from sys import argv def format_price(price): if not isinstance(price, (int, float, str)): return None try: price_num = round(float(price), 2) except ValueError: return None if price_num.is_integer(): str_price = '{:,.0f}'.format(price_num).replace(',', ' ') else: ...
from collections import defaultdict import csv """ This function is used to parse the original data files and extract only the ratings that are higher than 3 and adding the movie id to the data for easier usage later on """ def transform_data(filename, output_filename): original_file = open(filename,...
earlycamp = {("earlycampAdmin") : "ec12!"} azizi = {("azizAdmin") : "9934"} twitter = {("twitterAdmin") : "t956"} def start() a = input("Hi. Are you an (a) employer or b(employee): ") if a == "a": b = input("Input your username here: ") c = input("Enter your password: ") if (b == earlycamp and c == earlycamp) ...
# Welcome the user print ("<<<<<WELCOME TO OPERATION: PRESIDENT DOWN!>>>>") # Initalize future variables total_score = 0 score_1 = 0 score_2 = 0 score_3 = 0 score_4 = 0 score_5 = 0 # Initalize while loop (boolean) variables guess_1 = False guess_2 = False # Asking user for their name so the game can adress the use...
# # # ##------------------------MAIN SELECTION INTRO------------------------------ from operator import itemgetter def main(): global storelist global incomelist storelist = ['store1', 'store2', 'store3', 'store4', 'store5'] incomelist = [0.0, 0.0, 0.0, 0.0, 0.0] usr_sel = 0 while (usr_sel != ...
# # # ##------------------------MAIN SELECTION INTRO------------------------------ def main(): global storelist global incomelist storelist = ['store1' 'store2', 'store3', 'store4', 'store5'] incomelist = float[0.0, 0.0, 0.0, 0.0, 0.0] while (usr_sel != 8): print("""\n\n Hello, this is a s...
def binarySearch(alist, item): first = 0 last = len(alist) - 1 found = False while first <= last and not found: midpoint = (first + last) //2 if alist[midpoint] == item: found = True else : if item < alist[midpoint]: last = midpoint - 1 else : first = midpoint + 1 return found testlist = [0, ...
l=[5, 3, 9, 10, 8, 2, 7] def find_min(l,current_minimum = None): if not l: return current_minimum candidate=l.pop() if current_minimum==None or candidate<current_minimum: return find_min(l,candidate) return find_min(l,current_minimum) print find_min(l)
# -*- coding: utf-8 -*- """ Created on Sun Feb 21 13:55:03 2021 @author: 6degt """ import math import numpy as np def calc_ypr(q): yaw = math.atan2(2.0 * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]) pitch = -math.sin(2.0 * (q[1] * q[3] - q[0] * q[2])) roll = math...
# Part 1 Find two numbers that sum up to one number #puzzle_input = {1721: "", 979: "", 366: "", 299: "", 675: "", 1456: ""} sum_number = 2020 with open("day1/input.txt") as input_file: puzzle_input = {int(line.rstrip("\n")): "" for line in input_file.readlines()} for first_num in puzzle_input: second_num = su...
# puzzle_input = """light red bags contain 1 bright white bag, 2 muted yellow bags. # dark orange bags contain 3 bright white bags, 4 muted yellow bags. # bright white bags contain 1 shiny gold bag. # muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. # shiny gold bags contain 1 dark olive bag, 2 vibrant p...
class student: def assign(self,rno,name): global math,science,eng self.rno=rno self.name=name math = int(input("math is=")) eng = int(input("english is =")) science = int(input("science is =")) def display(self): global total,percent total=math+...
person={"name":"sharad","gender":"male","age":"15","address":"siddanagoudar","phone":"12345678979"} key = input("what kind of info do you what to know?") result =person.get(key,"that info is not avalible") print(result)
n=int(input("enter the number:")) n1=1 n2=1 count=0 for i in range(0,n): print(n1) nth=n1+n2 n1=n2 n2=nth count+=1
''' This program reads integers from a user specified input file into two 2D arrays (matricies). The matricies are multipled together and the rows of the product matrix are sorted. All the matricies are written to an output.txt file in the same directory as matrix.py. @author Sean Brady @version 1.0 11/11/2017 ''' in...
from threading import Thread, Semaphore, Lock from random import randint from time import sleep """ majme vecerajucich filozofov spolu s manzelkami a detmi. o deti sa staraju sarmantne asistentky, vzdy musi byt k dispozicii 1 na 3 deti. manzelky rady chodia ku kadernikovi a filozofi pocas svojej rozpravy duchaju fa...
import unittest from Game import Game from Card import Card class GameTests(unittest.TestCase): def test_shuffle_deck_length(self): game = Game() game.shuffle_deck() self.assertEqual(game.deck.cards.__len__(), 52) def test_deal_player(self): game = Game() game.deal_player_a_card() self.assertTrue(game....
import os, random, hangman, time choice = 0 category = 0 hangman.start() time.sleep(1) os.system("CLS") while choice != "5": hangman.mainmenu() choice = input("\t"*3 + "Enter your choice: ") hangman.mainmenu_choice(choice) ...
# from pygame import * import pygame import sys # setting global variable XO = "X" winner = None draw = False board = [[None] * 3] * 3 pygame.init() width = 450 height = 450 fps = 30 CLOCK = pygame.time.Clock() WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) screen = pygame.display.set_mode((width, hei...
# coding:utf-8 import temperature as temper import operatePod as opPod import time as time import datetime as datetime import sys as sys #running_time :稼働時間(秒) #check_interva...
import random n = int(input("Вкажіть довжину списку \n ")) lst = random.sample(range(1, 100), n) print("Input list: {}".format(lst)) def split(l, start, end): """ Splits list into two parts. Splits list into two parts each element of first part are not bigger then every element of last part. """ i = start -...
import random def listback(l): """reverse list""" return l[::-1] n = int(input("Вкажіть довжину списку \n ")) lst = random.sample(range(1, 100), n) print("Input list: {}".format(lst)) print("Output list: {}".format(listback(lst)))
import re string = input("Hello! What is your name?\n > ") sample_name = re.compile(r'\b[A-Z][a-z]{2,}\b') name = sample_name.search(string) print("Hello, {}!".format(name.group(0)))
name = input("Привіт! Як тебе звати?\n > ") print("Привіт, {}!".format(name)) age = int(input("Скільки тобі років?\n > ")) yearleft = 2018 - age years100 = yearleft + 100 print("Вам виповниться 100 років у {} році.".format(years100)) print("Щасти вам!!!!")
def factorial(x): """x!""" if x <= 0: return 1 else: return x * factorial(x - 1) n = int(input("Вкажіть факторіал якого числа шукати \n ")) print(factorial(n))
a = int(input("Вкажіть число a \n ")) b = int(input("Вкажіть число b \n ")) if a == b: print('Числа не можуть бути однаковими') elif a > b: while a > b: a = a - b print('Найбільший спільний дільник = {}'.format(a)) else: while b > a: b = b - a print('Найбільший спільний дільник = {}'.format(b))
#The Camel game by Pvrpl import random print("You just stole a camel! You have a few options.") print("A. Drink from your Canteen") print("B. Ahead moderate speed") print("C. Ahead full speed.") print("D. Stop for the night") print("E. Status Check") print("Q. Quit") done = False miles = 0 #Distance trave...
import csv input_file = "budget_data.csv" output_file = "analysis.txt" #create variables for calculations and code total_months = 0 previous_revenue = 0 total_revenue = 0 month_of_change = [] revenue_list = [] greatest_increase = ["",0] greatest_decrease = ["",9999999] #create a FOR loop with open(input_file) as r...
# -*- coding:utf-8 -*- ''' Python调试及单元测试 http://www.fuzhijie.me/?p=310 ''' def add(op1, op2): return op1+op2 def sub(op1, op2): return op1-op2 import unittest class MathTestCase(unittest.TestCase): '''math test case''' def setUp(self): pass def tearDown(self): pass def testA...
reg_num = input("주민등록번호:") sum = int(reg_num[0])*2 + int(reg_num[1])*3 + int(reg_num[2])*4 + int(reg_num[3])*5 + int(reg_num[4])*6+ int(reg_num[5])*7 + int(reg_num[7])*8 + int(reg_num[8])*9 + int(reg_num[9])*2 + int(reg_num[10])*3 + int(reg_num[11])*4+ int(reg_num[12])*5 # 1차 계산 rem = sum % 11 # 2차 계산 valid_num...