text
stringlengths
37
1.41M
print('-------爱你鱼C---------') temp = input('你输入的数字是啥呢:') guess = int(temp) while guess != 8: temp = input('猜错了,不妨在输入一次:') guess = int(temp) if guess == 8: print("一下子就猜中了") print("不玩了") else: if guess > 8: print("大了大了") else: print("小了小了") pri...
from tkinter import * root = Tk() def callback(): print("你好") menubar = Menu(root) filemenu=Menu(menubar,tearoff=True) filemenu.add_command(label="打开",command=callback) filemenu.add_command(label="保存",command=callback) filemenu.add_separator() filemenu.add_command(label="退出",command = root.quit) menubar.add_c...
""" Виселица. Програма выбирает слово из списка. Дается количество жизней по длине слова. Игрок должен называть букву. Если буква в списке есть, программа должна поставить ее на место и вывести в консоль. если нет -1 жизнь И так пока игрок не угадает слово или его не повесят. """ import random print("*" * 3, " Иг...
""" task_2.1 - сортировка списка из 6 чисел Создать лист из 6 любых чисел. Отсортировать его по возрастанию """ print(*sorted([10, 2, 35, 43, 5, 68, 19])) # 2 5 10 19 35 43 68 numbers = [10, 2, 35, 43, 5, 68, 19] numbers.sort() print(*numbers) # 2 5 10 19 35 43 68
""" Библиотека Pygame / Часть 2. Работа со спрайтами https://pythonru.com/uroki/biblioteka-pygame-chast-2-rabota-so-sprajtami """ """ Вторая часть серии руководств «Разработка игр с помощью Pygame». Она предназначена для программистов начального и среднего уровней, которые заинтересованы в создании игр и улучшении ...
""" task_2.7 - Создать матрицу Создать матрицу любых чисел 3 на 4, сначала вывести все строки, потом все столбцы https://silvertests.ru/GuideView.aspx?id=34372 """ m = [ [5, 6, 7, 8], [15, 13, 9, 4], [6, 18, 15, 28] ] x = [x[:] for x in m] print(x) # вывод в строку print() x = [x[0] for x in m], [x[1] ...
""" Виселица. Програма выбирает слово из списка. Дается количество жизней по длине слова. Игрок должен называть букву. Если буква в списке есть, программа должна поставить ее на место и вывести в консоль. если нет -1 жизнь И так пока игрок не угадает слово или его не повесят. """ import random count = 0 def att...
""" inheritance - наследование """ # class Parent(object): запись ниже идеинтична class Calc: def __init__(self, number): self.number = number def calc_and_print(self): value = self.calc_value() self.print_number(value) def calc_value(self): return self.number * 10 + 2 ...
import re import urllib.request str = ''' "we need to inform him with the latest information" ''' s1 = re.findall("inform", str) print(s1) str = "sat, mat, hat, pat" s1 = re.findall("[shmp]at",str) print(s1) s1 = re.findall("[h-m]at",str) print(s1) # Validate a phone number of pattern XXX-XXX-XXXX phnum = ...
def print_out_phrase(uni, phrase): i = 0 one_atatime = [] for e, letter in enumerate(uni): if i <= len(phrase) - 1: if phrase[i] == letter: i += 1 one_atatime.append(uni[:e] + letter.upper() + uni[e + 1:]) for one in one_atatime: ...
""" 斐波那契数列(Fibonacci sequence),又称黄金分割数列,是意大利数学家莱昂纳多·斐波那契(Leonardoda Fibonacci)在《计算之书》中 提出一个在理想假设条件下兔子成长率的问题而引入的数列,所以这个数列也被戏称为"兔子数列"。 斐波那契数列的特点是数列的前两个数都是1,从第三个数开始,每个数都是它前面两个数的和, 形如:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...。 斐波那契数列在现代物理、准晶体结构、化学等领域都有直接的应用。 """ num = 2 a = 1 b = 1 c = 0 print(a, ',', b, end='') while...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author: 了无此生 # DateTime: 2020/5/24 16:16 # File: 一元二次方程求根 import math def quadratic(a, b, c): d = b ** 2 - 4 * a * c if d < 0: return '方程无解' x1 = (- b + math.sqrt(d)) / (2 * a) x2 = (- b - math.sqrt(d)) / (2 * a) return x1, x2 if __name__ =...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: 了无此生 # DateTime: 2020/5/27 18:39 # File: 使用函数求特殊a串数列和 def fn(a, b): sum = res = 0 for i in range(b): sum += a #sum是a第i+1位数的值 a = a * 10 res += sum return res a, b = input().split() s = fn(int(a),int(b)) print(s)
# -*- coding:utf-8 -*- # Author: 了无此生 # DateTime: 2020/5/24 0:13 # File: 用函数实现52周存钱法 """ 52周存钱法,即52周阶梯式存钱法,是国际上非常流行的存钱方法。 按照52周存钱法,存钱的人必须在一年52周内,每周递存10元 例子: 第1周:10元,第2周:20元,第3周:30元·······一直到第52周:520元。 总计:10+20+30+······+520 = 13780元 """ def save_money(num): sum = 0 for n in range(1, 53): sum += num ...
message1 = '{0} is easier than {1}'.format('Python', 'Java') message2 = '{1} is easier than {0}'.format('Python', 'Java') message3 = '{:10.2f} and {:d}'.format(1.234234234, 12) message4 = '{}'.format(1.234234234) print (message1) print (message2) print (message3) print (message4) car = '{0} and {1} is a car'.format('...
message1 = "Global Variable (shares same name as a local variable)" def myFunction(): message1 = "Local Variable (shares same name as a global variable)" print("\nINSIDE THE FUNCTION") print (message1) #Calling the function myFunction() #Printing message1 OUTSIDE the function print ("\nOUTSIDE THE FUNCTI...
# raw_input() was renamed to input(). That is, the new input() function # reads a line from sys.stdin and returns it with the trailing newline stripped age = input("How old are you? ") height = input("How tall are you? ") print("So you're {0} old and {1} tall.".format(age, height)) print("Dat: {0!r}".format(input("...
def count(str): dict = {} for v in list(str): if v not in dict.keys(): dict[v] = str.count(v) # print(dict) return dict t = "x.nowcoder.com" s = "oooy" t_dict = count(t) s_dict = count(s) set_s = set(s_dict.keys()) set_t = set(t_dict.keys()) flag = True # print(set_s.intersection(s...
# a = "1 2 3 4" # b = a.split() # print(" ".join(b[::-1])) # a = "absba" # print(a[::-1]) # print(type(a[::-1])) # if a == a[::-1]: # print("true") # else: # print("false")
from animal_class import Animal class Dog(Animal): def __init__(self, name, fur, eye_colour, pet_id): self.name = name super().__init__(fur, eye_colour) self.__pet_id = pet_id def growl(self, animal): return f"BARK! I see {animal}" def get_pet_id(self): return se...
def printl(list): print "[" for elet in list: print "\t" + str(elet) print "]" row = [-2] * 10 board = [row] * 20 printl(board) pieces = [0,0,0] pieces[0] = [[0,0,0,0]] pieces[1] = [[1,1,1], [-2,-2,1]] pieces[2] = [[2,2], [2,2]] printl(pieces)
varone = int(input()) vartwo = int(input()) varthree = int(input()) if(varone>vartwo and varone>varthree): print('hey this is varone') elif(vartwo>varone and vartwo>varthree): print('vartwo is here') else print('i am varthree')
import multiprocessing class Node: parent = None horses = None priority = 1 def __init__(self, parent, horses, dept=0): self.parent = parent self.horses = horses self.dept = dept def __repr__(self): return str(self.horses) def __eq__(self, other): """th...
def read_text_file(file_path): with open(file_path, 'r', encoding='utf-8') as text_file: # can throw FileNotFoundError result = tuple(l.rstrip() for l in text_file.readlines()) return result example_string = 'ZUi there' #u'\u063a\u064a\u0646\u064a' # for c in example_string: # ...
croissantjes = input("hoeveel croissants :") prijsC = 0.39 stokbrood = input("hoveel stokbroden :") prijsS = 2.78 kortingsbonnen = input("hoveel kortngsbonnen :") korting = 0.50 #Prijs print(int(croissantjes) * prijsC + int(stokbrood) * prijsS - int(kortingsbonnen) * korting) prijs = (int(croissantjes) * pr...
def printGame(data): print(' A | B | C ') print(' ---|---|---') print("1|", data['a1'], "|", data['b1'], "|", data['c1'], "|") print(' ---|---|---') print("2|", data['a2'], "|", data['b2'], "|", data['c2'], "|") print(' ---|---|---') print("3|", data['a3'], "|", data['b3'], "|", data['...
from .direction import Direction class Bot(object): def __init__(self, board, loc, speed, id, team_id=None): """Initializes a basic bot.""" if board: (board.get(loc)).add_bot(self) else: self.loc = loc self.board = board self.progress = 0 sel...
import urllib.request import re def GetImage(url, img_path, img_name): ''' This function take url and image url as input. If the url is valid then it save the in local disk and generate true response if the url is invalid then it generate false response. Then return the response to ReadFile() fu...
# reference # https://scipython.com/blog/quadtrees-2-implementation-in-python/ import numpy as np import matplotlib.pyplot as plt # from matplotlib import gridspec class Point: """A point located at (x, y) in 2D space. Each Point object may be associated with a payload object. """ def __init__(sel...
def bubble_sort(list1): #""" sort list two-by-two until completely sorted """ #sorting pair n=len(list1)-1 p=0 r=0 while n>0: for i in range(1, len(list1)): if list1[p]>list1[i]: list1[p], list1[i]= list1[i], list1[p] p=p+1 ...
class ShoppingSurveyDiv2: def minValue(self, N, s): # infer total number of items in the store as sum(s) # return sum(s) s = ShoppingSurveyDiv2() # print s.minValue(5, (3, 3)) # 6 purchases, 2 items, 5 customers, 1 has bought both # print s.minValue(100,(97)) #97 # print s.minValue(10, (9,9,9,9,9)) #...
# SRM 636 DIV 2 250, 12.5 minutes coding, 185.15 pts class GameOfStones: def count(self, stones): if (len(stones) == 1): return 0 total = 0 for i in stones: total = total + i rem = total % len(stones) if (rem > 0): return -1 avg = total / len(stones) diffs = [...
# Exercício 2. Faça um programa que leia 4 valores, calcule a média e imprima positivo ou negativo (para ser positivo a média deve ser acima de 1). #Inicialização da variável soma soma = 0 for i in range(0,4): # loop para digitar 4 números numero = int(input("\nDigite um numero: ")) soma += numero # a cada lo...
#!/usr/bin/env python pi = [int(ch) for ch in '31415926535897932384626433833'] for _ in range(int(raw_input())): candidate = [len(word) for word in raw_input().split()] if candidate == pi[0:len(candidate)]: print "It's a pi song." else: print "It's not a pi song."
# -*- coding: utf-8 -*- """ Created on Tue Sep 11 18:39:27 2018 @author: hp """ import unittest #import unittest and below import all functions from our file, newCalculator. from newCalculator import * class CalculatorTest(unittest.TestCase): def testAdd(self):#Make sure all functions run normal...
a=10 b=20 print("Before swapping a is :",a," b is ",b) c=a a=b b=c print("After swapping a is :",a," b is ",b) print("****************************************") print("Before swapping a is :",a," b is ",b) a,b=b,a print("After swapping a is :",a," b is ",b) print("****************************************") print("Befo...
class Node: def __init__(self): self.data = data self.pointer = pointer def __str__(self): return str(self.data) class LinkedList(): def __init__(self, head=None): self.head = None def insert(self, data): new_node = Node(data) new_node.pointer = self.head self.head = new...
# -*-coding:Latin-1 -* def add(x,y): z=x+y print(z) def soust(x,y): z=x-y print(z) def mult(x,y): z=x*y print (z) def div(x,y): z=x/y print(z) import socket hote = '' port = 12800 connexion_principale = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connexion_...
#!/usr/bin/env python # coding: utf-8 # In[1]: a=10 #a is a varibale name which isalso called identifier # '=' is the assignment operator print(a) # In[2]: a=10.6#over riding of variables print(a) # In[8]: #to check the type of variable a=10.6 type(a) # In[9]: a='HUZAIFA' type(a) # In[10]: a=10 type(...
""" cakefinity.py ===== Do you want cake (again) __Repeatedy ask if user wants cake until user says yes or yeah: Do you want cake? > no Do you want cake? > No Do you want cake? > yeah Have some cake! """ usr = raw_input("Do you want cake?\n> ") while usr not in ["yes", "yeah"]: usr = raw_input("Do you want cake?\n...
""" FOLLOWED TUTORIAL:https://www.pyimagesearch.com/2020/03/02/anomaly-detection-with-keras-tensorflow-and-deep-learning/ Author: S.Hoogeveen Machine learning project for Special Topics in Computational Science & Engineering: Scientific Machine Learning, MSc Applied Mathematics, TU Delft """ # import the necessary pac...
import sys import json import os.path from collections import OrderedDict #TODO Text in alphabetical order // listOfStrings.sort() ? txtfile = sys.argv[1] def readTextFile(): try: f = open(txtfile) f.close() except FileNotFoundError: print('File does not exist') else: #pri...
#%% [markdown] # # Week 3: Exercise 3.2 # File: DSC540_Paulovici_Exercise_3_2.py (.ipynb)<br> # Name: Kevin Paulovici<br> # Date: 12/15/2019<br> # Course: DSC 540 Data Preparation (2203-1)<br> # Assignment: Exercise 3.2, csv, json, xml, excel #%% [markdown] # ## Data Files # Data files used for this exerci...
import datetime ''' Inspired by https://www.reddit.com/r/IsTodayFridayThe13th/ ''' print('Is Today Friday the 13th?') today = datetime.date.today() if today.weekday() == 5 and today.strftime('%d') == 13: print('Yes.') else: print('No.')
import random import time computer_antworten = ['Schere', 'Stein', 'Papier',] end_abfrage = "y" print("Willkommen zu Schere, Stein, Papier") time.sleep(1) eingabe_spieler = input("Wähle [1] Schere [2] Stein [3] Papier") if eingabe_spieler == "1": print("Du hast Schere ausgewählt!") time.sleep(1) print("...
alph="" Q="q" while(alph!=Q): alph=input("enter the alphabet") print(alph) if(alph==Q): print("exit")
x=int(input()) #ввод даных y=int(input()) i=0 while (x+x//10)<y: x+=x//10 i+=1 print(i)
h = int(input('часы - ')) #часы m = int(input('минуты - ')) #минуты s = int(input('секунды - ')) #секунды a = (h*30+m*0.5+s/120) #условие (подсказка 30-градусов 1 час,0,5 - градусов прибавляют минуты, и 1/120 секунды) print(a)
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] s = 0 for row in a: for elem in row: s += elem print(s)
def distance(x1,y1,x2,y2): return(((x1-x2)**2 + (y1-y2)**2)**0.5) x1 =float(input('Введите координаты центра окружности')) y2 =float(input('Введите координаты вне окружности')) x2 =float(input()) y1 =float(input()) r =float(input('Радиус окружности')) def IsPointInCircle(x,y,xc,yc,r): return distance(x,y,xc,...
i=0 n=1 print('Введите последовательность чисел, для окончания введите 0(ноль)') while n!=0: n=int(input('Введите число:')) if i<n: i=n print('Наибольшим числом последовательности является:',i)
a= int(input("Enter first number: ")) b= int(input("Enter second number:")) c= int(input("Enter third number:")) smallest=a if(b < smallest ): smallest = b if (c < smallest): smallest = c print(smallest, " is smallest") ## ##a= int(input("Enter first number: ")) ##b= i...
prices = [] tax = .065 while (True): p = float(input("Enter a price: ")) prices.append(p) for i in range(len(prices)): print(prices[i]) if(prices[i] == -1): break; print("Subtotal is ", sum(prices)) tax = sum(prices)*.065 print(" Your tax amount is ", tax) total = t...
from tkinter import * master = Tk() canvas_width = 800 canvas_height = 800 w = Canvas(master, width=canvas_width,height=canvas_height, bg="blue") w.pack() operand1 = int(input("Enter first operand: ")) operator = str(input("Enter operator: ")) operand2 = int(input("Enter second operand: ")) result = in...
##a = [0]*5 ## ##print(a) ## ##print(a[2]) ## ##a[0]= 5 ##print(a) ##a[2]=10 ##print(a) ## ##a[4]="hello" ##print(a) ## ##print(a[-5]) a1 = [2, 5, 6, 9, 6, 4, 3, 3, 5] print(a1) for i in range(4): a1[i]+=3 print(a1[3:7]) a2 = [3, 3, 3] a3 = a1 + a2 print(a3) if (3 in a1): ...
# cara input dan output file contoh .txt """ mode dalam membuat file w = write mode -> mode menulis dan menghapus file lama, jika file tidak ada, maka akan di buat file baru r = read mode only -> hanya bisa baca a = appending mode -> menambahkan data di akhir baris r+ = write dan read mode """ # MEMBUAT file file =...
def jumlah(a,b): c = a + b return c hasil = jumlah(4,5) print(hasil) # lambda function untuk mempermudah seperti fungsi di atas # misal, membuat anonymous function dengan lambda kali = lambda argumen: print(argumen) kali('test') kali = lambda x,y: x*y print(kali(3,4))
# list sebagai iterables gorengan = ["bakwan", "cireng", "bala-bala", "gehu", "combro", "pisang goreng", "pukis", "risoles", "tahu isi", "tempe goreng"] for g in gorengan: print(g) print(len(g)) # string sebagai iterable bakwan = 'bakwan' for i in bakwan: print(i) # for di dalam for buah = ['semangka', '...
import pprint # Setup, create menues main_menu = ''' Home Menu------ 1. Print Room Status 2. Check-In a customer 3. Check-Out a customer 4. Admin Features 5. Exit ''' check_in_menu = ''' Check In------ 1. Print Room Status 2. Add Customer Info 3. Request Room Specifics 4. Exit ''' check_out_menu = ''' Check Out------...
def min (a,b,c,d): if a<=b and a<=c and a<=d: return a elif b<=c and a<=d: return b elif c<=d: return c else: return d l=str.split(input()) a,b,c,d=int(l[0]),int(l[1]),int(l[2]),int(l[3]) print(min(a,b,c,d))
#!/usr/bin/python3 def complex_delete(my_dictionary, value): keys_to_del = [] for key in my_dictionary: if my_dictionary[key] == value: keys_to_del.append(key) for key in keys_to_del: del my_dictionary[key] return my_dictionary
class Queue: ''' Implementation of a queue using a fixed sized array (ring buffer). ''' def __init__(self, size): self.a = [None] * size self.read = 0 self.write = 0 def is_empty(self): return self.read == self.write def enqueue(self, val): ''' Adds the value to the back of the queue. The list p...
import heapq class Node: def __init__(self, val, weight): self.val = val self.weight = weight self.next = None class Alist: def __init__(self): self.list=[] def addNode(self, n): self.list.append(n) def addEdge(self, n1, n2): new2 = Node(n2.val) end = n1.next n1.next = new2 new2.next = end d...
# Game # Snake water gun import random choices=["Snake","Water","Gun"] player=input("Enter player name : ") play_again="Y" while(play_again.upper()=="Y"): games = 10 computer_points = 0 player_points = 0 draw = 0 while (games>0): print(f"------------- Game number : {11-games} -------------...
#dinamicamente tipado """ numero = 3 numero = "hola" print(numero) """ texto = "hola como estas" texto = texto.upper() print(texto) print(texto.isnumeric()) texto.isnumeric print(texto[0:3])
# https://leetcode.com/problems/invert-binary-tree/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def invertTree(self, root): """ ...
import numpy as np x = np.array([1,2,3]) y = np.array([1,0,2]) print("x ndim: ", x.ndim) print("x shape: ", x.shape) print("x size: ", x.size) print("x data type: ", x.dtype) print("-" * 20) print(x) print("-" * 20) print("y ndim: ", y.ndim) print("y shape: ", y.shape) print("y size: ", y.size) print("y data type: "...
vocal= input("Ingrese una vocal: ") while vocal not in ("a", "e", "i", "o", "u"): if vocal == "-": break vocal = input("Vocal:") print ("Su vocal o punto es:{}".format(vocal))
"""Funciones matematicas""" import math num1, num2, num, men = 12.572, 15.4, 4, '1234' print(math.ceil(num1), '\t',math.floor(num1)) print(round(num1,1),'\t',type(num),'\t',type(men)) # funciones de cadenas mensaje = "Hola" + "mundo " + "Python" men1=mensaje.split() men2=' '.join(men1) print(mensaje[0],...
x=int(input("Ingrese un numero entero: ")) if x<0: x = 0 ptint("Negativo cambiando a cero") elif x== 0: print ("Cero") elif x== 1: print ("Uno") else: print ("Ninguna opcion") print("Ok") if type(x) == int else print ("-")
# coding: utf-8 # ----- IMPORT ----- import csv, time import matplotlib.pyplot as plt # ----- /IMPORT ----- # ----- OPEN .CSV FILE ----- print("Reading the document...") with open("chicago.csv", "r") as file_read: reader = csv.reader(file_read) data_list = list(reader) # ----- /OPEN .CSV FILE ----- # -----...
# -*- coding: utf-8 -*- import re from functools import reduce import csv import json import _pickle as pickle def main(filename): # read file into lines f = open(filename) lines = f.readlines() # declare a word list all_words = [] pattern = re.compile(r'\w+\W*\w+|\w+') # extract all words...
number1 = int(input()) inheritance = {} # print(number) for x in range(number1): inputted = input().split(":") cn_left = inputted[0] if len(inputted) == 1: cn_right = [] inheritance[cn_left.strip()] = cn_right else: cn_right = inputted[1] inheritance[cn_left.strip()] =...
'''# формируем множество известных слов на основании построчного ввода dic = {input().lower() for _ in range(int(input()))} # заводим пустое множество для приема текста wrd = set() # т.к. текст построчно подается, а также в каждой строке несколько слов, # то каждую строку превращаем во множество и добавляем в единое ...
def my_min(fname): smallest_so_far= None for num in fname: if smallest_so_far is None: smallest_so_far = num continue elif smallest_so_far > num: smallest_so_far = num return smallest_so_far def my_max(fname): largest_so_far=None for a in fname: ...
A = raw_input("subject1: ") a = input("score: ") B = raw_input("subject2: ") b = input("score: ") C = raw_input("subject3: ") c = input("score: ") sum = a + b + c aver = round(float(sum) / 3, 3) print A + " " + str(a) print B + " " + str(b) print C + " " + str(c) print "sum: " + str(sum) print "average: " + str(aver)
print('Hello World!') va1= 'Sveika ' print(va1) va2 ='Pasaule' print(va1,va2) print(len(va1)) print("val[2:4]:", va1[::-1]) print(va1*2) va2 = 'Sashka' print(va1+va2) #pirma metode print("Mes te - %s - kaut ko ieleksim" %'kaut kas', end='\n\n') #otra metode print("Teksta ievetosana ar .format metodi: {}". format...
import unittest import re #Define exceptions class RomanError(Exception): pass class OutOfRangeError(RomanError): pass class NotIntegerError(RomanError): pass class InvalidRomanNumeralError(RomanError): pass romanNumeralMap = (('M', 1000), ('CM', 900), ('D', 500), ...
import unittest def searchinMatrixO_N(v, matrix): i = 0 j = len(matrix)-1 while i < v and j >= 0 : if matrix[i][j] == v: return (i,j) elif matrix[i][j] > v: j = j - 1 else: i = i + 1 return (-1, -1) def binSearchinList(v, l): low = 0 high = len(l) whi...
import calendar def search(year, month, day1): while year >= 2019 and 1 <= month <= 12 and day1 == 1: yield year, month, day1 month -= 1 if not month: year -= 1 latest_year, latest_month, day2 = 2019, 6, 1 your_day = input('Введите день: ') day = {'Monday': 0, 'Tuesday':...
def count(start, step): while True: print (start) start += step count(int(input('Введите start: ')), int(input('Введите step: ')))
import random def even(): positive_answer = 'yes' negative_answer = 'no' number = random.randint(1, 99) is_number_even = number % 2 == 0 correct_answer = positive_answer if is_number_even else negative_answer answer_type = str return number, correct_answer, answer_type
import prompt from brain_games.cli import welcome_user MAX_CORRECT_ANSWERS = 3 ANSWER_TYPE_MAP = { int: prompt.integer, str: prompt.string } def game(greeting, get_task_items): player_name = welcome_user() correct_answers_num = 0 print(greeting) while correct_answers_num < MAX_CORRECT_ANSWER...
m = list([]) n = int(input('Введите количество критериев: ')) for i in range(n): # Создаем двумерный массив m.append([]) for j in range(n): m[i].append(0) for i in range(len(m)): for j in range(len(m)): if i < j: m[i][j] = float( input(f'Введите важность критери...
''' Dynamic Programming Approach Accepted on leetcode(139) time - O(N^2) space - O(N) ''' class Solution: def wordBreak(self, s: str, wordDict) -> bool: # Edge case if len(s) == 0: return True HashSet = set(wordDict) # make a HashSet(O(1) search operation) ...
'''сумма чисел от числа_1 до числа_2''' from_num = int(input()) to_num = int(input()) summ = 0 i = from_num while i <= to_num: summ += i i += 1 print(summ)
from typing import List import requests, zipfile from io import BytesIO, StringIO import pandas as pd def get_epc_data(zip_file_url: str, local: bool) -> pd.DataFrame: """ Takes the local of the epc data and outputs a string :param zip_file_url: location of file :param local: Whether or no...
from json import load from random import shuffle from collections import Counter deck = [] hands = [] card = [] players = 0 ### Builds the deck using the data from the json ### def build(): ### Takes the data from the json and puts it into the data variable ### with open('Cards.json', 'r') as j: d...
num = int(input("Enter a number: ")) f = 1 while num>0: f = f * num num = num -1 print(f)
a = [1,2,3] n = int(input("Enter N:")) mul=1 for i in range(0,len(a)): mul =mul * a[i] print(mul%n)
# -*- coding: utf-8 -*- """ Created on Jan 2017 @author: relbaff """ import pandas import numpy # bug fix for display formats to avoid run time errors - put after code for loading data above pandas.set_option('display.float_format', lambda x:'%f'%x) # Load data from csv file original_data = pandas.read_csv('addhealt...
#Anton Danylenko #SoftDev1 pd8 #16 No Trouble #2018-10-05 import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O DB_FILE="discobandit.db" db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() #facilitate db ops #====================...
from random import randrange mystere3 = randrange(0, 1000) mystere2 = randrange(0, 100) mystere1 = randrange(0, 20) running = True print("niveau 1: 0 à 20") print("niveau 2: 0 à 100") print("niveau 3: 0 à 1000") saisie = int(input("Entrez le niveau de difficulté")) if saisie == 1: print("Le plus simple bien sû...
#!/usr/bin/env python3 """ Elliptic curve class, associated functions, and instances of SEC2 curves """ from math import sqrt from typing import Tuple, NewType, Union, Optional from btclib.numbertheory import mod_inv, mod_sqrt Point = Tuple[int, int] # infinity point being represented by None, # Optional[Point] do i...
import math import fractions class InvalidArgumentException(Exception): def __init__(self, exp_str): Exception.__init__(self) self.exp_str = exp_str class Fraction: def __init__(self, numerator=None, denominator=None): """ :type numerator: int float str """ s...
# 递归函数 def factorial(n): if n == 1: return 1 return n * factorial(n-1) print(factorial(10)) ## 使用尾递归 ## @尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式 def tail_factorial(n, result): if n == 1: return result # 这里是关键的一步 return tail_factorial(n-1, n*result) print(tail_factorial(10, 1)) print(f...
import copy num = [1, 2, 3] print(tuple(num)) test = (1, 2, 3) print(list(test)) test1 = (1) test2 = (1,) print(type(test1)) print(type(test2)) source = [1, 2, 3, 4] target1 = copy.copy(source) print(target1) target1[0] = -1 print(target1) print(source) source[0] = [4, 5, 6] target2 = copy.copy(source) print(source)...
class Animal(object): def __init__(self): pass def run(self): print('this animal is running!') class Dog(Animal): def run(self): print('this dog is running') class Cat(Animal): def run(self): print('this cat is running') animal1 = Animal() dog1 = Dog() cat1 = C...
i = 0 while i < 5: i += 1 # i = 4 终止循环 if i == 4: break # i= 2 跳过本次循环 if i == 2: continue print(i) for j in range(3): print(j) for k in range(10, 13): print(k) for l in range(0, 10, 3): print(l)
# 条件判断 a = 24 if a > 20: print('yeah, welcome!') elif a > 30: print('hello, welcome') else: print('nice, welcome') age = input('输入您的年龄:') age = int(age) # 将字符串转换整数 if age > 17: print('00前') elif age > 27: print('90前') else: print('00后') # 第二次学习条件判断 if None: print('None') else: print('...