text
stringlengths
37
1.41M
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root:return res = [] def helper(root, depth...
x = 1 while x==1: print("Triangle Program!") a = int(input("Enter value of a : ")) b = int(input("Enter value of a : ")) c = int(input("Enter value of a : ")) if(a<=0 or b<=0 or c<=0): print("Invalid dimensions!") elif(a>=b+c or b>=a+c or c>=a+b): print("Triangle cannot be formed...
# -*- coding: utf-8 -*- """ Created on Sat Dec 1 21:15:35 2018 @author: kaysm """ import itertools as it Input=open("Ordering Strings of Varying Length Lexicographically.txt", "r") Input=Input.read().strip().split("\n") Symbols="".join(Input[0].split(" ")) N=int(Input[1]) f = open('Ordering Strings ...
size=int(input()) for row in range(size): for space in range(size-(row+1)): print(" ",end=" ") for n1 in range(row+1): print("*",end=" ") print()
size=int(input()) for row in range(size): for space in range(row): print(" ",end="") for star in range(size-row): print("*",end=" ") print(6)
class CPF(object): INVALID_CPFS = ['00000000000', '11111111111', '22222222222', '33333333333', '44444444444', '55555555555', '66666666666', '77777777777', '88888888888', '99999999999'] def __init__(self, cpf): self.cpf = cpf def validate_size(self): cpf = self.cleaning...
def anonymous(x): return x**2 + 1 def integrate(fun, start, end): step = 0.1 intercept = start area = 0 while intercept < end: intercept += step high = fun(intercept) area = area + step*high ''' your work here ''' return area print(integrate(anonymous, 0, 10))
#try to plot bernoulli dsitribution import math import matplotlib.pyplot as plt def binom(n, p): list_x = [] list_y = [] for i in range(n+1): print(i) list_x.append(i) PX = ( math.factorial(n)/(math.factorial(i)*math.factorial(n-i)) ) * (p**i) * ((1-p)**(n-i)) list_y.append(PX) return list_x, list_y ...
largest = 0 smallest= 0 while True: num = input("Enter a number:") if num=="done": break try: n=int(num) except: print("Invalid input") continue if n>largest: largest=n else: smallest=n print("Maximum is",largest) print("Minimum is"...
names = [] for i in range(10): name = input("enter the name") if name not in names: names.append(name) else: print("please enter unique name") print(names)
a=[1,2,3,4,5,6,7] b=0 for number in a: b+=number print(b) # length=0 # for number in a: # length+=1 # print(length) # range(start, stop, step) tao ra cac so bang cach + step tu start den truoc stop # print(list(range(6))) # print(list(range(-3,8,1))) # print(list(range(3, -4.-1))) # for i in range(6): # pr...
''' Created on Apr 1, 2013 @author: redw0lf ''' import pygame from pygame.locals import MOUSEBUTTONDOWN, MOUSEMOTION from breakout.data.GameElement import GameElement class Ball(GameElement): """ This class describes the game ball, which moves around the screen with a given slope and a given speed ...
from tkinter import* from math import* def cal(): a=leng_e.get() b=wid_e.get() h=he_e.get() length=int(a) width=int(b) height=int(h) ans=2*height*(width+height) answer=Label(main,text="The abswer is: "+str(ans)) answer.grid(row=4,column=0) def cl(): main.destro...
from tkinter import* def triangle_w(): global triangle_main triangle_main=Tk() triangle_main.title("Triangle") pytago=Button(triangle_main,text="Square",command=pytago_w,fg="green") pytago.pack() Normal_area=Button(triangle_main,text="Normal area",fg="green",command=triangle_normal) Normal_area.pack() N...
total = 0 i = 8 while i > 0: total = total + i i=i-1 print(total)
class NombreCortoError(Exception): def __init__(self): self.mensaje="No cuela, tu nombre no puede tener solo dos letras..." super().__init__(self.mensaje) def solucionar(self): print("Solucionando...") class EdadInsuficienteError(Exception): def __init__(self): self.mensaje=...
import datetime as fechas anho_actual=int(fechas.date.today().year) Nombre_completo=input("Introduce tu nombre completo:") Anho_nacimiento=int(input("Introduce tu año de nacimiento:")) Direccion_email=input("Introduce un correo electrónico:") Telefono=input("Introduce un telefono:") nombre_correcto=len(Nombre_completo)...
INTENTOS=3 SWITCHOFF="0" ip="-1" listaip=[] blacklist=[] while ip!=SWITCHOFF: ip=input("Introcude una dirección IP:") #if (listaip.count(ip)<2) or (ip not in blacklist): if ip not in blacklist: listaip.append(ip) if listaip.count(ip)==INTENTOS: blacklist.append(ip) else: ...
''' Two words are blanagrams if they are anagrams but exactly one letter has been substituted for another. Given two words, check if they are blanagrams of each other. Example For word1 = "tangram" and word2 = "anagram", the output should be checkBlanagrams(word1, word2) = true; After changing the first letter 't' ...
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): if not matrix: return None res = [] while matrix: res += matrix.pop(0) # 取出矩阵的第一行 if not matrix or not matrix[0]: break matrix = s...
# -*- coding:utf-8 -*- def swap(_ls, _a, _b): tmp = _ls[_a] _ls[_a] = _ls[_b] _ls[_b] = tmp return _ls class Solution: def __init__(self): self.res = [] def Permutation(self, ss): if ss != None and len(ss) > 0: self.PermutationHelp(list(ss), 0) self.res...
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here if not pHead1: return pHead2 if not pHead2: return pHead1 i...
# -*- coding:utf-8 -*- class Solution: def reOrderArray(self, array): if len(array) == 0: return array # 偶数指针和奇数指针 ptr_o = ptr_j = 0 while ptr_o < len(array) and ptr_j < len(array): if (array[ptr_o] % 2 == 1): # 如果是奇数则指针后移 ptr_o...
#!/usr/bin/env python3 import sys import random #argument checks if len(sys.argv) <=1: print("Monty Hall Problem Simulator") print("Usage: monty num_tests") sys.exit(1) if len(sys.argv) >=3: print("Too many arguments.") print("Usage: monty num_tests") sys.exit(1) #test if argument is int num...
"""An exercise in remainders and boolean logic.""" __author__ = "730529273" choice: int = int(input("Enter ana int: ")) leftover_one: int = choice % 2 leftover_two: int = choice % 7 leftover_three: int = choice % 14 if leftover_three == 0: print("TAR HEELS") else: if leftover_one == 0: print("TAR") ...
"""List utility functions.""" __author__ = "730529273" def all(numbers: list[int], b: int) -> bool: """Iff b is found in the numbers, return true.""" # Move through each int within the list. i: int = 0 if len(numbers) == 0: return False while i < len(numbers): item: int = numbers[i...
# integer x = 100 print type(x) if x >= 100: print "That's a big number!" else: print "That's a small number" # string y = 'hello world' print type(y) if y >= 50: print 'Long sentence' else: print 'Short setence' z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] print type(z) if len(z) >= 10: print 'Big L...
class Store(object): def __init__(self, product, location, owner): self.product = product self.location = location self.owner = owner def add_product(self, product): self.product.append(product) def remove_product(self, product): self.product.remove(product) ...
black = ['* * * *'] red = [' * * * *'] # print black # print red for new in range(1, 9): if new % 2 == 1: print black else: print ' ', black star1 = '* * * *' star2 = ' * * * *' for new in range(0, 8): if new % 2 == 1: print star1 else: print star2
grad = float(input("점수 : ")) toelc = int(input("토익 : ")) if toelc >= 700 and grad >= 4.0: print('면접대상자') elif toelc >= 700 and grad >= 3.5: print('서류전형대상자') elif toelc >= 700 and grad >= 3.0: print('필기시험대상자') else: print('지원불가')
h = int(input('근무시간')) p = int(input('시간당 임금')) if h > 40: over = h - 40 total = p * 40 + over * p * 1.5 else: total = h * p print(f'total{total}')
""" В некоторой школе занятия начинаются в 9:00. Продолжительность урока — 45 минут, после 1-го, 3-го, 5-го и т.д. уроков перемена 5 минут, а после 2-го, 4-го, 6-го и т.д. — 15 минут. Дан номер урока (число от 1 до 10). Определите, когда заканчивается указанный урок. Выведите два целых числа: время окончания урока в ч...
import Card import random import Player suits = ["Clubs", "Diamonds", "Hearts", "Spades"] class Game: def __init__(self, startingBalance): self.startingBalance = startingBalance self.deck = list() self.players = list() self.button = 0; self.board = list() Game.addC...
''' 产生一个0~500的一个随机数,给5000金币 -- 输入的数字大于随机数输出大了-500 -- 输入的数字小于随机数输出小了-500 -- 输入的数字正确输出“恭喜您猜对了”+3000金币 系统在输入15锁定。系统没有金币系统锁定 ''' #产生一个随机数 import random num = random.randint(0,500) kj = 5000 #开始金币 # i = 0 print(num) while i < 15: #判断次数 number = input("请输入一个数字") #键盘输入 number = int(number) #将...
import unittest import random class TestMethods(unittest.TestCase): def test_No_Players(self): TeamOne = [] ChoicesOne = [] TeamTwo = [] ChoicesTwo = [] Team_One_Index = 0 Team_Two_Index = 0 game_over = True if game_over == True: compute...
import random Rock = '1' Paper = '2' Scissors = '3' Gun = '4' TeamOne = [] ChoicesOne = [] TeamTwo = [] ChoicesTwo = [] Team_One_Index = 0 Team_Two_Index = 0 game_over = False def do_stuff(): print('Welcome to Rock, Paper, Scissors! The game of all kids to decide on something. \n(Psst if it\'s a draw the start th...
import cv2 import numpy as np puppy_img = cv2.imread("Computer-Vision-with-Python//DATA//dog_backpack.jpg", cv2.COLOR_BGR2RGB) copyright_img = cv2.imread("Computer-Vision-with-Python//DATA//watermark_no_copy.png", cv2.COLOR_BGR2RGB) print("Puppy image size = ",puppy_img.shape) print("Copyright image size = ",copyrigh...
import random from articles import articles # Add a key-value pair to each article. for article in articles['response']['results']: article['view'] = 0 # print(article) def read_article(): # Randomly selects an article and increases the articles "views" by one each time it's selected. num_of_articles = l...
#!/usr/local/bin/python # -*- coding: utf-8 -*- capitales_dict = { "Aguascalientes" : "Aguascalientes", "Baja California" : "Mexicali", "Baja California Sur" : "La Paz", "Campeche" : "Campeche", "Chihuahua" : "Chihuahua", "Chiapas" : "Tuxtla Gutiérrez", "Coahuila" : "Saltillo", "Colima"...
a = b = 2 # A esto se le llama "asignación encadenada". Asigna el valor 2 a las variables "a" y "b". print("a = " + str(a)) # Explicaremos la expresion str(a) despues en el curso. por ahora es utilizado para convertir la variable a en una cadena. print("b = " + str(b)) greetings = "saludos" print("saludos = " + st...
import os import time import socket import threading import tkinter as tk import tkinter.messagebox import tkinter.scrolledtext as sct client = socket.socket() # Client's socket object for, well, being a client ui = tk.Tk() ...
''' This is the NN project applied to MNIST. The initial goal is to practice NN concepts with the MNIST lib of images. First test will be composed of simple backpropagation machines. The algorithm for this simple, backpropagation, perceptron based NN is as follows: * Retrieve input files (MNIST in this cas...
#!/usr/bin/python3 # 《Python语言程序设计》程序清单7-检查点练习 # Programed List 7-Checkpoint Programme # 第七章 检查点练习程序 7.1~7.18 # 7.1 # 7.2 # 7.3 # 7.4 # 7.5 # 7.6 # 7.7 # 7.8 # 7.9 # class A: # def __init__(self, i): # def __init__(self, i = 0): # self.i = i # def main(): # a = A() # print(a.i) # main() # ...
#!/usr/bin/python3 # 《Python语言程序设计》程序清单1-5 # Programed List 1-5 # Draw OlympicSymbol import turtle # Import turtle module turtle.color("blue") turtle.penup() turtle.goto(-110, -25) turtle.pendown() turtle.circle(45) turtle.color("black") turtle.penup() turtle.goto(0, -25) turtle.pendown() turtle.circle(45) turtle...
#!/usr/bin/python3 # 《Python语言程序设计》程序清单2-9 # Programed List 2-9 # Compute distance between the two points # Enter the first point with two float values x1, y1 = eval(input("Enter x1 and y1 for Point 1: ")) # Enter the second point with two float values x2, y2 = eval(input("Enter x2 and y2 for Point 2: ")) # Compute ...
#!/usr/bin/python3 # 《Python语言程序设计》程序清单6-1 # Programed List 6-1 # 返回两个数中较大的数 # Return the max of two numbers def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result def main(): i = 5 j = 2 k = max(i, j) # Call the max function print(i, "与", j, ...
# This is NOT the correct answer for this assessment. # You MUST modify this code and make it satisfy the specification. # Do NOT modify anything inside the quotation marks "". score1 = 95 score2 = 90 score3 = 70 score4 = 50 grade1 = "A+" grade4 = "A" grade3 = "B" grade7 = "C" grade5 = "Fail" c...
number_1 = int(raw_input("please enter number: ")) number_2 = int(raw_input("please enter another number: ")) print number_1 * number_2 print number_2 - number_1 print number_1 + number_2 print number_1 / number_2 print number_1 % number_2
# -*- coding: utf-8 -*- from bitarray import bitarray class Protein: """ Representing a protein instance in the simulated cell. Contains the state of the protein in it, a pointer to the protein-type and the neccesary methods for protein interaction. """ def __init__(self, name, protein_po...
# EJERCICIO 1 print("hola Mundo") # EJERCICIO 2 saludo = "hola Mundo" print(saludo) # EJERCICIO 3 nombre = input("Cual es tu nombre?") print("hola" , nombre) # EJERCICIO 4 resultado = ((3+2)/(2*5))**2 print(resultado) # EJERCICIO 5 print("Calculadora de pago de un dia de trabajo") horas = int(input("Proporcione el ...
# Escribir un programa que almacene las materias de un curso (por ejemplo Matemáticas, # Física, Química, Historia y Lengua) en una lista, pregunte al usuario la nota que ha sacado en # cada materia, y después las muestre por pantalla con el mensaje En <materia> has sacado # <nota> donde <materia> es cada una de las as...
# Escribir un programa que almacene las materias de un curso (por ejemplo Matemáticas, # Física, Química, Historia y Lengua) en una lista, pregunte al usuario la nota que ha sacado en # cada materia y elimine de la lista las materias aprobadas. Al final el programa debe mostrar # por pantalla las materias que el usuari...
# Escribir una función que calcule el área de un círculo y otra que calcule el volumen de un # cilindro usando la primera función. def area(radio , h=1 ): areaCirculo = 3.14*(radio**2)*h return areaCirculo print(area(5 , 5))
frase = input("Ingrese una frase: ") vocal = input("ingrese una vocal: ") print(frase.replace(vocal , vocal.upper()))
# Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el # número de años, y muestre por pantalla el capital obtenido en la inversión cada año que dura # la inversión. cantidad = int(input('Ingrese la suma a invertir: ')) interes = int(input('Cual es el interes anual: ')) anos = in...
# Escribir un programa que pida al usuario un número entero y muestre por pantalla si es par # o impar. num = int(input("Ingrese un numero: " )) if num%2 == 0: print("Es par") else: print("No es par")
month = 12 day = 24 if (month == 12): if (day == 24): print('今天是平安夜') elif (day == 25): print('今天是圣诞节') else : print('今天既不是圣诞节,也不是平安夜')
def tax_calc(amount, state): tax = 0 total = '' if state == 'WI': tax = 5.5 / 100 total += f'The subtotal is ${amount}. \n' total += f'The tax is ${tax}. \n' total += f'The total is: ${amount+tax}' return total def main(): try: amount = float(input('What is the ...
import numpy as np import pandas as pd from itertools import combinations INFINITY = 10e9 def take_input(): # print("Enter the number of variables in the objective function") n = int(input()) # print("Enter the number of constraints") m = int(input()) # print("Enter the coefficients o...
""" This module contains the necessary classes for formulating a problem for the general problem solver (GPS) implemented in gps.py. In particular, a problem is composed of: 1. A goal: a set of Condition objects 2. A starting state: a set of Condition objects 3. Allowable operations: a set of Operation objects """...
def sum_of_digits(n): print(sum(int(i) for i in str(2 ** n))) sum_of_digits(1000)
def fact(n): fact = 1 for i in range(1, n + 1): fact = fact * i return fact def bc(a, b): return (fact(a+b)//(fact(a)*fact(b))) def path(a,b): paths = bc(a, b) return paths print(path(20,20))
import random import itertools class Dice(object): def __init__(self, dnumber=6): self.dnumber = dnumber def roll(self, n=1): for _ in range(n): yield random.randint(1, self.dnumber+1) def possibilities(self, n=1): return list(itertools.combinations_with_...
# -*- coding: utf-8 -*- """ Created on Sun Jun 19 12:24:09 2016 @author: Administrator """ import numpy as np # import packages import math import mpl_toolkits.mplot3d import matplotlib.pyplot as plt # class BASEBALL will compute the trajetory of the baseball with air resistance # where # ...
class Bus: #List,NumOfPassengers def __init__(self,num): self.List=['Free' for i in range(num)] self.NumOfPassengers=0 def getOn(self,name): for i in range(len(self.List)): if self.List[i]=='Free': self.List[i]=name self.NumOfPassengers+=1 ...
list=[i for i in range(1,11)] list1=list[7:] print(list1) print(list[::-1]) print(list[::2]) list2=list[::2] print(list2) num1=int(input("Enter a new number: ")) num2=int(input("Enter a new number: ")) num3=int(input("Enter a new number: ")) list[4:6]=[num1,num2] list.append(num3) print(list) list3=[list[i]*2 for i in ...
num = int(input("Enter choose of num: ")) i = 1 serial = i max = num while (i < 7): if num > max: max = num serial = i num = int(input("Enter choose of num: ")) i += 1 if max > num: print("The serial max number: " + str(serial)) else: max = num serial = i print("The serial ma...
count=0 list=[] grade=int(input("Enter yout new grade: ")) while grade!=0: list.append(grade) grade=int(input("Enter the next grade: ")) for i in list: if i<60: count+=1 print("The number of fail grades:"+str(count)+"\nThe number of success grades: "+str(len(list)-count))
num1 = int(input("Enter num: ")) num2 = int(input("Enter num2: ")) if num1 >= num2: for num2 in range(num2 + 1, num1): if num2 % 2 == 0: print(num2) else: continue # לא חובה else: for num1 in range(num1 + 1, num2): if num1 % 2 == 0: print(num1) ...
num = int(input("Input a positive number: ")) num2 = int(input("Input a positive number: ")) divi = 1 mudu = 0 while num2 > num: num2 = int(input("Input a little number: ")) nnum = num2 while num2 + nnum <= num: divi += 1 num2 += nnum mudu = num - (nnum * divi) print("The divided is: " + str(divi) + " " + "...
class Circle: #Radius,Pi def __init__(self,Radius): self.Radius=Radius self.Pi=3.14 def area(self): return (self.Pi*self.Radius)**2 def circumference(self): return 2*self.Pi*self.Radius if __name__=='__main__': Radius=int(input("Enter a new radius: ")) Circle1=Cir...
def passfunction(grade): if grade>=70 and grade<=100: return True else: return False if __name__=='__main__': for i in range(5): grade=int(input("Enter a new grade: ")) if passfunction(grade)==True: print("You passed the test") else: print("Sor...
def FloatToInt(num1): num2=int(num1) sum = 1 - (num1 - num2) if(num1-num2>=0.5): num1+=sum num1=int(num1) else: num1=int(num1) return num1 if __name__=='__main__': num1=float(input("Enter the first number: ")) num2=float(input("Enter the second number: ")) print(F...
from OriHasinClasses2.T2Class import * if __name__=='__main__': seats=int(input("Enter number of seats: ")) Bus1=Bus(seats) num=int(input("Enter a number you want to do on the bus . 1 - get on passenger on the bus , 2 - get off passenger from the bus , 0 - stop program: ")) while num!=0: name=in...
def minfunction(num1,num2): if num1>=num2: return num2 else: return num1 def maxfunction(num1,num2): if num2>=num1: return num2 else: return num1 from OriHasinFunctions.Targil6 import * if __name__=='__main__': num1=int(input("Enter a new number: ")) num2=int(inpu...
import ast def rawStringSize(string): return len(string) def calcStringSize(string): return len(ast.literal_eval(string)) def calcEncodeSize(string): return rawStringSize(string) + string.count('\\') + string.count('\"') + 2 representationSize = 0 actualSize = 0 recodeSize = 0 with open('Day08/InputStrin...
#!/usr/bin/python3 """ locked boxes """ def canUnlockAll(boxes): """ INPUT a list of boxes with it's keys OUTPUT true if every box can be open false otherwise """ keys = [x for x in range(1, len(boxes))] for i in range(len(boxes)): for key in boxes[i]: if key in keys and k...
import sys #导入sys库 script, encoding, error, languages = sys.argv #赋值三个变量参数给sys.argv模块 #定义主函数main,对参数进行处理。 参数依次为:文件、编码类型、错误处理 def main(language_file, encoding, errors): print(">>>> in main ",repr(language_file), encoding, errors) line = language_file.readline() #赋值变量line为逐行读取文件 print(">>>line:", line) if...
#赋值ten_things变量为字符串 ten_things = "apples oranges crows telphone light sugar" #这个列表中没有10个元素,可使用代码修改下并实现。 print("wait there are not 10 things in that list . let's fix that.") #定义stuff变量,赋值为ten_things的split分割方法,使用空格分割为列表 stuff = ten_things.split(' ') print(stuff) #根据输出结果,可以看出stuff是一个列表。 print(type(stuff)) #使用type函...
# 定义一个变量,赋值为4个可接收格式化参数的空值,如果变量只给三个{}参数,而下面的参数引入了4个值,就只打印从左往右的前三个。 formatter = "{} {} {} {} " # 执行format方法的时候从左往右。 print(formatter.format(1, 2, 3, 4)) print(formatter.format("one", "two", "three", "four")) # 参数为布尔值,format后变为字符串 print(formatter.format(True, False, False, True)) # 直接打印布尔值,也不会报错,但是修改比如False为false就会报...
print('the game name is "eat what"?') eat = input("please tell me ,what do eat? Such as noodles, rice, dumplings... > ") if eat == "noodles": print("Okay, but you need to choose again, chow mein or noodle soup.?") print("enter '1', choose chow mein.") print("enter '2', choose noodle soup.") noodles_choose...
# 定义变量days是一个字符串。 months变量赋值字符串,但是使用\n进行了换行操作。 days = "mon tue wed the fri sat sun " months = "\njan\nfeb\nmar\napr\nmay\njun\njul\naug" print("here are the days: ", days) print("here are the months: ", months) # 三个连续的引号可以输入一整段的字符串,且随意换行。可以在每行前增加\t标识制表符tab,使得每行缩进8个空格?也有可能4个。。。 print(""" \tthere's something ...
#Write a function called num_factors. num_factors should #have one parameter, an integer. num_factors should count #how many factors the number has and return that count as #an integer # #A number is a factor of another number if it divides #evenly into that number. For example, 3 is a factor of 6, #but 4 is not. As su...
def dict_construct(keys, values) -> dict: return dict(zip(keys, values)) if __name__ == "__main__": cort_keys = (1, 2, 3, 4, 5) cort_values = ("orange", "apple", "banana", "grapefruit", "watermelon") coin = ('Bitcoin', 'Ether', 'Ripple', 'Litecoin') code = ('BTC', 'ETH', 'XRP', 'LTC') fruits...
def temp_calc(degree: float, temp_type: str): if temp_type == 'C': celsius = degree kelvin = celsius + 273.15 fahrenheit = celsius * 1.8 + 32 elif temp_type == 'K': kelvin = degree celsius = kelvin - 273.15 fahrenheit = kelvin * 1.8 - 459.67 elif temp_type == ...
letter_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] num_list = [1, 2, 3, 4, 5, 6, 7, 8] print(""" Введите шахматный ход для вашего коня. Важно! Вводите ход в формате настоящих шахмат! Напрмер: A2 - D7 И не забудь верхний регистр и англ раскладку, ну будь ты человеком, а? """) start = input("Начальная точка фигуры: ...
def symb_amount(x): return len(x) def words_amount(x): x = x.split() return len(x) some_string = input("Input your sentence: ") print("Your sentence contains {0} words and {1} symbols" .format(words_amount(some_string), symb_amount(some_string)))
#Calculator Project def add(a,b): return a+b def subtract(a,b): return a-b def multiply(a,b): return a*b def divide(a,b): return a/b operations = { "+":add, "-":subtract, "*":multiply, "/":divide } def calculator(): num1 =float(input("What's your first number?: ")) for symbol in operations: ...
price = 490 while True: #In Prozent discount_input = input("Wie hoch ist der Rabatt?: (in Prozent) ") discount = price / 100 * float(discount_input) price = price - discount text = "Dein finaler Preis lautet: " print(text + str(price))
companies = ["VW","Audi","Tesla"] while True: companies.sort() print(companies) new_company = input("Gib eine Automarke ein:") companies.append(new_company)
name = input('Wie ist dein Name?') if name == "Philipp": print('Hallo Administrator') elif name == "Julia": print('Hallo Max') else: print('Du bist kein Administrator')
class Person: def __init__(self, name, height, weight): self.height = height self.weight = weight self.name = name self.bmi = weight / (height * height) def printBMI(self): print(self.name + '\'s BMI ist: ' + str(self.bmi)) def getHeightIn(self,metric): if ...
import random guess = 0 secret = random.randint(1, 5) while True: guess = int(input('Rate meine Zahl!')) if (guess == secret): print('Super!') break elif (guess > secret): print('Deine geratene Zahl ist größer als meine geheime Zahl!') elif (guess < secret): print('Deine...
class Diff(object): def __init__(self, f, h=1E-5): self.f = f self.h = float(h) class Forward1(Diff): def __call__(self, x): f, h = self.f, self.h return (f(x+h) - f(x))/h class Backward1(Diff): def __call__(self, x): f, h = self.f, self.h return (f(x) - f(x...
number = float(raw_input("Give me a number: ")) if number % 4 == 0: print("Your number is a multiple of 4.") elif number % 2 == 0: print("Your number is even.") else: print("Your number is odd. Get it? :P")
# Import statement import math # ORGANIZE CODE BEFORE PROCEEDING FURTHER # implement images in text # print if a monster attacks def printMonsterImage(): print("███████████████████████████") print("███████▀▀▀░░░░░░░▀▀▀███████") print("████▀░░░░░░░░░░░░░░░░░▀████") prin...
from Stack import * from StackIter import * if __name__ == '__main__': s1 = Stack() for i in range(5): s1.push(i) """ s2-s5 same as s1 """ s2 = s1 s3 = s1 s4 = s1 s5 = s1 """ test the stack operations """ s3.pop() s5.pop() s4.push(2) s5....
import socket import time #define address & buffer size HOST = "www.google.com" PORT = 8001 BUFFER_SIZE = 1024 #get host information def get_remote_ip(host): print(f'Getting IP for {host}') try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: print ('Hostname could not be ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn import preprocessing from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split class wealthPredict: # Read CSV file into DataFrame df #XPredic...
def main(): print fact_loop(4) # added note def fact_loop(d): fact = 1 for i in range(1,d+1): fact = fact * i return fact if __name__ == "__main__": main() # added another note