text
stringlengths
37
1.41M
input = [] with open('input.txt') as my_file: for line in my_file: input.append(line.strip()) assert input[0][8] == "#" assert input[2][8] == "." def treesEncountered(map, right, down): i = 0 j = 0 trees = 0 while i < len(input)-1: j += right i += down if map[i][j%...
# I wanted to try making some classes as practice. RUNNING = True RESTING = False class Reindeer: def __init__(self, line): """ :param line: Parses line into the class. :return: nothing """ line = line.split() self.speed = int(line[3]) self.running_time = ...
import itertools data = [] """ Process inputData.txt and put it into the data array. """ with open("inputData.txt", "r") as infile: for line in infile: data.append(int(line)) valid_permutations = 0 def checkIfValid(permutation): return 1 if sum(permutation) == 150 else 0 """ Main loop This is the...
alphabet = list(map(chr, range(97, 123))) dataInput = "hxbxwxba" def increment(a): a_number = letter_number(a) if a_number == 25: return "a" return alphabet[a_number + 1] def full_increment(a): should_increment = True i = len(a) - 1 while should_increment: new_letter = incre...
"""Script for taking restaurant.json data and transferring it to MongoDB.""" import sqlite3 import pymongo import json # Username and password to be set by user. username = "TODO" password = "TODO" cluster = "TODO" group = "TODO" # Load json and select data. json_data = open("restaurant.json").read().replace("$", "...
from collections import OrderedDict item = OrderedDict() for _ in range(int(input())): j = input().rpartition(" ") item[j[0]] = int(j[-1]) + item[j[0]] if j[0] in item else int(j[-1]) for k in item: print(k, item[k])
#Read madLibText.txt and show corresponding prompt and let user enter word. #Replace corresponding word in the text and save the result. with open('madLibText.txt') as source: text = source.read() while 'ADJECTIVE' in text: adj = input('Enter an adjective. ') text = text.replace('ADJECTIVE', adj, 1) ...
# backupToZip.py - Copies an entire folder and its contents into # a ZIP file whose filename increments. import os, zipfile def backupToZip(folder): absfolder = os.path.abspath(folder) print('The folder to be zip: %s \n' % absfolder) # Name the zip file number = 1 while True: zipName = os...
#Listas podem conter qualquer tipo de variaveis e um numero infinito de variaveis #Delcarar que e uma lista mylist = [] mylist.append(1) mylist.append(2) mylist.append(3) #Ou entao poderia ser usado desta forma #mylist = [1,2,3] print(mylist[0]) print(mylist[1]) print(mylist[2]) print("---- Break ----") mylist.ap...
#O Python usa exceptions para fazer o tratamento de erros #As vezes quando encontramos erros nao queremos fazer algo por isso para resolver devemos usar um try/except block def do_stuff(n): print(n) the_list = (1, 2, 3, 4, 5) for i in range(20): try: do_stuff(the_list[i]) except IndexError: #Erro criado quando ...
#Sets sao listas que nao tem valores duplicados print(set("My name is Eric and Eric is my name".split())) print #Nota-se que o output e uma lista sem palavras repetidas #Sets sao uma ferramenta poderosa porque permite veridicar dois sets independentes e determinar se existem alguns valores repetidos entre ambos a = se...
''' A function called predict_with_network() which will generate predictions for multiple data observations. The function called predict_with_network() accepts two arguments - input_data_row and weights - and returns a prediction from the network as the output. ''' import numpy as np input_data = np....
# 1. print(3**4) # 2. def to_power(num, pow_num): return pow(num, pow_num) print(to_power(3, 3)) # 3. def to_power(num, pow_num): result = 1 for index in range(pow_num): result *= num return result print(to_power(3, 2))
sticks: int = 10 users = [] while len(users) < 2: users.append(input('please write your name: ')) cur_user = 0 while sticks > 1: while True: move = input('{user} please enter number from 1 to 3: '.format(user = users[cur_user])) if int(move) > 3 or int(move) < 1: print('wrong number'...
testcase = int(input()) i = 0 while i != testcase: a, b = [int(k) for k in input().split()] N = int(input()) n = 0 recive = "GGWP" start = a+1 #upper stop = b while (recive != "CORRECT") and recive != "WRONG_ANSWER" and n !=N: mid = int((start+stop)/2) print(mid) recive = str(input()) if re...
import math import random BOARD_SIZE = 3 PLAYER_KEY = 'x' COMPUTER_KEY = 'o' EMPTY_KEY = ' ' def create_board(size): # Creates 1-dimensional game board for storing played values. 0 is empty, # -1 is the computer played value, 1 is the player value. return [0] * size ** 2 def board_to_string(board): ...
import datetime import pandas as pd pos_orders = open("pos_orders.txt", "a") clock = datetime.datetime.now() print("Lo's Concessions!") employeeID = input("Enter employee ID: ") print("Welcome, " + employeeID + "!") print(clock) menu = {'Item': ["Hamburger", "Cheeseburger", "Hotdog", "Chili Cheese Dog",...
a score = (mean of sample1 - mean)/std_deviation print("the a score is =", a_score) mean of sampling distribution:- 50.69924 Standard deviation of sampling distribution:- 2.879529182125215 Mean of sample1:- 50.41 the a score is = -0.10044697646944323 def_random_set_of_mean(counter): dataset = [] for i in rang...
import numpy as np class Paraboloid: """ Square function. f(x,y) = \frac{x^2}{a^2} + \frac{y^2}{b^2} dx = \frac{2x}{a^2} dy = \frac{2y}{b^2} """ def __init__(self,a=1,b=1): """ Args: - a,b (int|float): Curvature controls """ self.a = a self.b = b self.dx = None self.dy = None def calculate...
# -*- encoding: utf-8 -*- print "Program za vnos dnevnega menija." jedilni_list = "meni.txt" dnevni_meni = {} while True: ime_jedi = raw_input("Vnesite ime jedi: ") cena_jedi = raw_input("Vnesite ceno jedi: ") dnevni_meni[ime_jedi] = cena_jedi print("Danes na meniju: " + ime_jedi + " " +...
''' A lambda function can take any number of arguments, but can only have one expression. to run this code: $ python3 lamda_function.py ''' def power(num): return lambda a : a**num test = power(2) test2 = test(5) print(test2)
classmates = {'Ala': 'Moja niunia', 'Konrad': 'Ziomeczek', 'Wojtek': 'Kryminalista'} for key,value in classmates.items(): print(key + ' ' + value)
import random c = int(input('What number you want to start from?\n')) d = -1 while c > d: d = int(input('What number should be the last one? (Cant be lesser than starting one)\n')) a = random.randint(c,d) b = int(input('Input a number beetwen ' + str(c) + ' and ' + str(d) + '\n')) while a != b: pr...
"""Analyze the word frequencies in a book downloaded from Project Gutenberg.""" import string def get_word_list(file_name): """Read the specified project Gutenberg book. Header comments, punctuation, and whitespace are stripped away. The function returns a list of the words used in the book as a list. A...
#연습문제 4-1 #coding=utf-8 #1 print("#1") def is_odd(num): result = num % 2 if result == 1: print("홀수") else: print("짝수") is_odd(3) is_odd(4) #2 print("#2") def avg(*args): sum = 0 for i in args: sum += i return sum / len(args) print(avg(1,2,3,4,5,6,7,8,9,10)) #3 print(...
# 연습문제 2-5 # coding=utf-8 # 1 print("#1") a = {'name': '홍길동', 'birth': '1128', 'age': '30'} print(a) # 2 print("#2") a = dict() a['name'] = 'python' a[('a',)] = 'python' # a[[1]] = 'python' 리스트는 변하는 값 a[250] = 'python' print(a) # ※ Key에는 변하지 않는 값을 사용하고, Value에는 변하는 값과 변하지 않는 값 모두 사용할 수 있다. # 3 print("#3") a = {'A': ...
from copy import deepcopy #연습문제 2-8 #coding=utf-8 #1 print("#1") a = [1, 2, 3] b = [1, 2, 3] print(a is b) #False : 각 변수가 가리키는 매모리의 주소가 다름 print(id(a)) print(id(b)) #2 print("#2") a = [1, 2, 3] b = a print(a is b) #True : 변수가 가리키는 메모리의 주소가 같다 print(id(a)) print(id(b)) #3 print("#3") a = b = [1, 2, 3] a[1] = 4 pr...
#튜플 #data=(10,20,30,40,50) # data=10,20,30,40,50 # 소괄호를 사용 안해도 괜찮다 # print(data[0]) # # data[1] = 200 / 변경이 불 가능하다 #두 수를 바꾸기 (순서) # a=10;b=20 # # temp=a # a=b # b=temp # # print(a,b) # 패킹과 언패킹 a=10;b=20; b,a=a,b print(a,b) a= 1; b=2; c=3 a,b,c=c,a,b print(a,b,c)
#모듈 # import time # print(time.localtime().tm_year,'년',time.localtime().tm_mon,'월',time.localtime().tm_hour,'시',time.localtime().tm_min,'분',time.localtime().tm_sec,'초',end='') # print(time.localtime().tm_year,'년') # print(time.localtime().tm_mon,'월') # print(time.localtime().tm_hour,'시') # print(time.localtime(...
from tictactoe import TicTacToeGame import ast from draw_board import draw_board import matplotlib.pyplot as plt if __name__ == '__main__': tt = TicTacToeGame() tie = None winner = None players = ['x', 'o'] current_player = 1 draw_board(tt.board) while winner is None and tie is None: ...
from estudiante import cargar_datos, cargar_datos_corto def verificar_numero_alumno(alumno): # Levanta la excepción correspondiente numero_alumno = alumno.n_alumno if alumno.carrera == "Ingeneria": digito_carrera = "63" elif alumno.carrera == "College": digito_carrera = "61" if n...
from funciones import checkear_apodo, crear_mapas, ranking from juego import jugar x = True class Jugador: def __init__(self,apodo,mapa): self.apodo = apodo self.mapa = mapa self.barcos_derrivados = 0 while x: # Este while corresponde al funcionamiento del programa print(" ","--...
# class math # กลุ่มคำลั่ง คณิตศาสตร์ import math #import function math มาฃใช้ num = math.pow(2,3) #คำสั่งยกกำลัง 2^3 จะได้=8 print (num) num1 = math.sqrt(25) #คำสั่งถอดราก 25 ได้เท่ากับ 5 print(num1) num2 = math.ceil(3.1) #คำสั่งปัดเศษขึ้น 3.1 เป็นเท่ากับ 4 print (num2) num3 = math.floor(3.09) ...
# LAB.8 จัดการข้อมูลด้วย Dictionary product = {101:"กล้วยทอด",102:"มันทอด",103:"เผือกทอด"} print (product[101]) food1 = {"ของว่าง":("กล้วยทอด","มันทอด","เผือกทอด"),"น้ำดื่ม":("ชานม","ชาเขียว","ชาไข่มุข")} print (food1 ["ของว่าง"]) #- ฟังก์ชั่นที่ดำเนินการกับ Dictionary
# 複数のインスタンス # menu_item1, menu_item2 class MenuItem: pass menu_item1 = MenuItem() menu_item1.name = 'サンドイッチ' print(menu_item1.name) menu_item1.price = 500 print(menu_item1.price) # MenuItemクラスのインスタンスを生成してください menu_item2 = MenuItem() # menu_item2のnameに「チョコケーキ」を代入してください menu_item2.name = 'チョコケーキ' # menu_item2のn...
x = 7 * 10 y = 5 * 6 # xが70と等しい場合に「xは70です」と出力してください if x == 70: print('xは70です') # yが40と等しくない場合に「yは40ではありません」と出力してください if y != 40: print('yは40ではありません') #===================================================================== # if x = 10 # xが30より大きい場合に「xは30より大きいです」と出力してください if x > 30: print('xは30より大きいです') ...
# Program Leap Year Checker # Description: # This program will check if input year is leap year or not. # Author: Daniel Hong # Date: 2/7/21 # Revised: # <revision date> # list libraries used # Declare constants (name in ALL_CAPS) # Declare Variable types (EVERY variable used) year = int(input("Enter a ye...
# Program: Check-In Functions # Description: This is a list of functions that will be used for checking in the patient. # Author: Chang Yeon Hong # Date: 12 May 2021 # Revised: # <revision date> # list libraries used # Declare global constants (name in ALL_CAPS) # Function checkUserAccount() # Description: This w...
import sortint import sortintmelhorado import sortintmelhorado2 import sortchar import sortcharmelhorado import sortcharmelhorado2 menuSeletor = int(input('Escolha a opção que desejar: \n[1]Ordenação de inteiros;\n[2]Ordenação de caracteres;\n[3]Ordenação de Strings.\n')) if menuSeletor == 1: resultadosortint = s...
import sortchar import sortcharmelhorado import sortcharmelhorado2 def menuchar(): menuseletor = int(input('Escolha a opção que deseja >>\n[1] Sort\n[2] Sort 1° versão melhorado\n[3] Sort 2° versão melhorado\n')) if menuseletor == 1: sortchar.ordsortchar() elif menuseletor == 2: sortcharme...
s = int(input("Enter a single digit: ")) a = str(s) n = int(input("Enter the number of repetition: ")) x = [] for i in range(1,n+1): x.append(a*i) z = [] for i in range(len(x)): z.append(int(x[i])) print(z) y = 0 for i in range(len(x)): y = y+int(x[i]) print(y)
s = str(input("Enter some words: ")) x = s.split(' ') for i in range(len(x)): for j in range(len(x)-1-i): if(len(x[j])>len(x[j+1])): t = x[j+1] x[j+1] = x[j] x[j] = t else: pass print(x)
s = str(input("Enter entries separated by space: ")) x = s.split() y = [] for i in range(len(x)): if(int(x[i])%2==0): pass else: y.append(int(x[i])**2) print(y)
############################################################# # FILE : asteroidMain.py # WRITER : Dan Kufra , dan_kufra , # EXERCISE : intro2cs ex8 # DESCRIPTION: # This is a version of the classic game "Asteroids". The goal is to control # the spaceship and destroy the asteroids. ######################################...
# import our classes and os from WordTracker import * from WordExtractor import * import os class PathIterator: """ An iterator which iterates over all the directories and files in a given path (note - in the path only, not in the full depth). There is no importance to the order of iteration. """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- isim=raw_input("senin adın ne:") if isim== "ferhat": print("ne güzel isim") else: print("ismini sevmedim")
# !/usr/bin/env python # -*- coding: cp1254 -*- alinannot1=int(raw_input("notunuzu girin:")) alinannot2=int(raw_input("ikinci notunuzu girin:")) if alinannot1 <0 or alinannot1>100 or alinannot2<0 or alinannot2>100: print "gecersiz bir not.." else: ortalama=(alinannot1 + alinannot2)/2 if ortalama <=100: ...
# -*- coding:utf-8 -*- def asal(kaca_kadar): """Asal sayı bulan fonksiyon Girdi olarak bir sayı alır Bu sayıya kadar olan asal sayıları ekrana basar. """ asallar = [2] if kaca_kadar < 2: return None elif kaca_kadar == 2: return asallar else: for i in range(3,kaca...
#!/usr/bin/env python # -*- coding: utf-8 -*- import random kntrl = "" while True: if kntrl == 'q' or kntrl== 'Q': break else: loto=random.sample(xrange(1,50),6) stopu1=random.sample(xrange(1,35),5) stopu2=random.sample(xrange(1,15),1) onnum = random.sample(xrange(1,81)...
""" Read fields to check from file like byr (Birth Year) iyr (Issue Year) eyr (Expiration Year) hgt (Height) hcl (Hair Color) ecl (Eye Color) pid (Passport ID) cid (Country ID) """ def read_fields(fname="fields.txt"): """ read fields to check """ # byr (Birth Year) ...
from gmpy import mpq,mpz from random import randint,seed from time import time def rand_matrix(n, typ=int, N=10): ''' A function to matrix with random elements ''' m = [] for i in range(n): a = [] for j in range(n): p = randint(0, N) a.append(p) m.append(a...
from sys import stdin n = int(stdin.readline()) numbers = [x for x in stdin.readline().split()] for number in numbers: sum = 0 for i in number: if i != '\n': sum += int(i) print(sum)
word = input() up = 0 lo = 0 for i in word: if i.isupper(): up+=1 else: lo+=1 if lo>=up: print(word.lower()) else: print(word.upper())
import sys import math # math.factorial() import numpy as np def debug_print(information): print("DEBUG: ", information, file=sys.stderr) # get your team & get your board team = input() first_row = input() second_row = input() third_row = input() # print out the inputs you're getting debug_print(team) debug_pr...
prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3 } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15 } # for fruit in prices: # print(".",fruit,":", prices[fruit],sep = " ") # print() what = input("which fruit do you want? ") print(".",what) if what...
# from random import choice # x = 3 # op = choice(["+", "-", "*", "/"]) # y = 7 # # result = -999 # # if op == "+": # result = x + y # elif op == "-": # result = x - y # elif op == "*": # result = x * y # else: # result = x / y # # print(result) from random import choice def calc(x, y, op): if op...
items = ["T-shirt", " Sweater"] running = True while running: want = input("Welcome to our shop, what do you want(C, R, U, D)? ") if want == "R": print("Our items: ", *items, sep = ", ") elif want == "C": new = input("Enter new item: ") items.append(new) print("Our items: ", *items, sep = ", ") ...
print("Skipping loop") pineapple = .5 for Numbers in range(7): print(Numbers) pineapple = pineapple * 2 #print (pineapple)
#!/usr/bin/env python3 # Created by: Teddy Sannan # Created on: October 2019 # This program takes user number # and displys the weekday def main(): while True: # input print("Enter a number between 1 and 7") number = int(input("1 being Monday and 7 being Sunday: ")) # process ...
word = str(raw_input("enter a word ")) new_word = "" counter = len(word) - 1 for x in word: new_word += word[counter] counter -= 1 #User enters a string print("the word you entered backwards is: ", new_word)
#!/usr/bin/env python3 import os import sys args = sys.argv if len(args) < 2: print('Usage: {} STRING'.format(os.path.basename(args[0]))) sys.exit(1) else: z=0 #not using i, worrried I will get the vowels and the count confused for letter in args[1]: if letter in 'aeiou': z+=1 if z == 1: print('There i...
import adivinhacao import forca def escolhe_jogos(): print('**************************') print('*****Escolha seu jogo*****') print('**************************') print('(1)Adivinhação -- (2)Forca') jogo = int(input('Digite o número do seu jogo: ')) if jogo == 1: print('Jogando adivi...
class User: ''' This class shall be used for the user's login information, the username and their password. Credentials shall also be saved under a user's information ''' user_list = [] #list to store our users def __init__(self,user_name,login_password): self.user_name = user_name ...
N = int(input()) #ler quantidade de repetições de caracteres for i in range(N): #executa de acordo com a quantidade informada c = input() #ler os caracteres informados diamante = 0 # variavel que irá contabilizar o número de diamantes menor = 0 #variavel que irá contabilizar a quantidade de caracter = < ...
# -*- coding: utf-8 -*- """ Created on Fri Jan 22 14:41:18 2021 @author: Dragneel """ #%% Function to return path value def pathValue(startPoint, endPoint, cost = 0): if (startPoint, endPoint) in pairList: print(str(cost + valueDict[(startPoint, endPoint)]) + ' ') for (i, j) in pairList: ...
import psycopg2 import urllib.request import json import pandas as pd # Goes to the indicated url, parses through the json and stores into a dictionary and additionally a data frame with urllib.request.urlopen("http://api.worldbank.org/v2/countries/CHN/indicators/NY.GDP.MKTP.CD?per_page=5000&format=json") as url: ...
""" 线程: api 文档:https://docs.python.org/zh-cn/3/library/threading.html 协程:Coroutine """ import threading import time ''' 创建新线程 threading.Thread(target=single()) 需要导入模块 threading ''' class MyThread(threading.Thread): # # # def __init__(self): # print("myThread init") def run(self): ...
import random """ 语句的使用 条件语句:if ... else ... 三目运算符: 循环 """ # 条件成立,执行带缩进的代码行 if True: print("name") print("james") else: print("koby") # 多重判断 if ... elif ... else # age = int(input('input age')) age = random.randint(1, 50) if age > 30: print(age) elif age > 20: print(age) else: print(age) # 三...
""" 运算符 算数运算符 赋值运算符 复合赋值运算符 比较运算符 逻辑运算符 """ ''' // 整除 % 取余 ** 指数 2**4 即2*2*2*2 ''' ''' 赋值运算符 ''' # 多个变量赋值 num, weight, name = 1, 2.3, 'james' ''' 复合赋值运算符 += c+=a 等价于 c = c + a -= *= ... ''' ''' 比较运算符 ''' ''' 逻辑运算符 and or not ''' ''' 公共操作 + 字符串, 元组, 列表 * 字符串, 元组, 列表 ''' list1 = [1, 3] lis...
# Built-Ins: from typing import Any BOOLEAN_ENV_TRUE = ("1", "enable", "enabled", "on", "true", "yes") BOOLEAN_ENV_FALSE = ("0", "disable", "disabled", "off", "false", "no") def env_to_boolean(value_str: str) -> bool: """Convert a (string) environment variable to a Python bool :raises ValueError: value_s...
import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import numpy as np df=pd.read_excel('automobile.xlsx') mean=df['highway-mpg'].mean() df['highway-mpg'].replace(np.nan,mean,inplace=True) mean=df['price'].mean() df['price'].replace(np.nan...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_predict df=pd.read_excel('automobile.xlsx') mean=df['highway-mpg']....
dias = int(input('Dias: ' )) horas = int(input('Horas: ')) minutos = int(input('Minutos: ')) segundos = int(input('Segundos: ')) totalSegundos = 0 totalSegundos += segundos totalSegundos += (minutos * 60) totalSegundos += (horas * 60 * 60) totalSegundos += (dias * 24 * 60 * 60) print ('Total em segundos ', totalSegundo...
def show(*args): print(args) total = 0 for num in args: total += num num = (1, 2, 3) # show(num) #((1, 2, 3),) Invalido show(*num)
#!/usr/bin/env python # coding=utf8 from copy import deepcopy from random import randint class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self): if self.size() == 0: return None else: va...
#1 задание Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) # и метод running (запуск). Атрибут реализовать как приватный. В рамках метода реализовать переключение # светофора в режимы: красный, желтый, зеленый. Продолжительность первого состояния (красный) составляет 7 секунд, # ...
# Brady Nokes 9/23/20 Cash Register Assignment numItems = 4 costPerItem = 10.00 taxRate= 0.08 subTotal = costPerItem * numItems taxAmount = subTotal * taxRate totalPrice = subTotal + taxAmount print("SALES RECEIPT") print("Number of Items: " + str(numItems)) print("Cost per Item : " ,"$"+ str(costPerItem) ) prin...
## Brady Nokes 9/24/20 logical expressions and IF statements ## ## Boolean Value ## Must have either True or False and they must be capitalized ## ##boolvar = True ##isAwake = True ##isInClass = True ## ## when you print it out it is not a string it will be a boolean ## ##print(type(boolvar)) ##print(isAwake) ##print(i...
#Tic Tac Toe #Plays the game of tic tac toe against a human opponent # Brady Nokes 11/20 # Global Constants X = "X" O = "O" EMPTY = " " TIE = "TIE" NUM_SQUARES = 9 # Function definitions ######################################### def display_instructions(): """Display game instructions. to use ( display_instructi...
# Calculator Program # By Abe and Brady # IMPORTS from tkinter import * # Initializing the basic settings for GUI HEIGHT = 361 WIDTH = 291 TITLE = "Calculator" BACKGROUND = "darkgrey" FONT = "Sans_Serif" class App(Frame): def __init__(self, master): super(App, self).__init__(master) self.grid() ...
def f(s): return s.title() l = ['adam', 'LISA', 'barT'] print map(f, l) l = [1, 2, 3, 4] def f(a, b): return a*b print reduce(f, l)
from bs4 import BeautifulSoup html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" class="special"> <title>First HTML Page</title> </head> <body> <div id="first"> <h3 data-example="yes">hi</h3> <p>more text.</p> </div> <ol> <li class="special">This list item is special.</li> ...
import random import math import enemy import sys class human: """大体共通するクラス""" def __init__(self,name,job,hp,mp,n_attack): self.name=name self.job=job self.max_hp=hp self.hp=hp self.max_mp=mp self.mp=mp self.n_attack=n_attack self.power=1 s...
print("Programa que converte temperaturas") print("Escolha o tipo de conversao") print("----------------------------------------") print("Codigo | Funcao") print(" 1 | Celsius para Fahrenheit") print(" 2 | Fahrenheit para Celsius") ver=0 while(ver==0): try: codigo = int(input("codigo:")...
''' An object is used to represent and encapsulate all the information needed to call a method at a later time. Client instantiates the command object and provides the information to call the method later Invoker decides when the method should be called Receiver is an instance of the class that contains the method's ...
a=[] c=[] n1=int(input("Enter number of elements:")) for i in range(1,n1+1): b=int(input("Enter element:")) a.append(b) n2=int(input("Enter number of elements:")) for i in range(1,n2+1): d=int(input("Enter element:")) c.append(d) new=a+c new.sort() print("Sorted list is:",new)
import random def generate(columns=30,max=100): result=[] for i in range(columns): result.append(random.randint(0,max-1)) return result n=1000 k=500 list1=generate(n,k) def quickSort(list1): recursive_quicksort(list1,0,len(list1)-1) return list1 def recursive_quicksort(A,p,q): if p...
# Character Picture Grid practice project, pg. 108 grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O',...
#! python3 # spiralDraw.py - a simple program to take control of the mouse and draw a square spiral # in the window of a drawing app. When run, the user has 5 seconds to position the mouse # cursor over the window of a drawing app, and the script will do the rest # Automate the Boring Stuff with Python 2e, Ch.20, pg.4...
'''There is a contest with interactive problems where N people participate. Each contestant has a known rating. Chef wants to know which contestants will not forget to flush the output in interactive problems. Fortunately, he knows that contestants with rating at least r never forget to flush their output and contest...
#There is an array with some numbers. All numbers are equal except for one. Try to find it! def find_uniq(arr): x=max(arr) y=min(arr) z=0 for i in range(3): if arr[i]==x: z+=1 if(z>=2): return y # n: unique integer in the array else: return x
''' Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A, and furthermore has not finished her cabbage. When she starts, at last, she can see that A has a 70 feet lead but B's speed is 850 feet per hour. How long will it take B to cat...
import math #Ingreso de la llave mykey=input("NOTA: Su palabra clave NO puede repetir letras \nIntroducir Clave:") mykey=mykey.upper() def encryptMessage(msg): cipher = "" k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(mykey)) # Número de c...
#!/usr/bin/python import math wheelbase = 33 print("Enter x1: ") x1 = raw_input() x1 = float(x1) print("Enter y1: ") y1 = raw_input() y1 = float(y1) radius = (x1*x1 + y1*y1 )/ (2 * x1) radius = -radius steer_angle = math.atan(wheelbase/radius) print("radius: " + str(radius) + " steering angle: " + str(steer_angle))...
import re # вариант 3 # ищем все фамилии в тексте и помещаем их в массив def find_surnames(filename): file_to_check = open(filename) test_text = file_to_check.read() surnames = re.findall(r'\b[А-Яё][а-яё]+ [А-ЯЁ].[А-ЯЁ].', test_text) return surnames # пробегаемся по тестам и выводим фамилии, обреза...
wert1 = 1 wert2 = 2 if wert1 > wert2: print(str(wert1)) elif wert1 < wert2: print(str(wert2)) else: print("Die Werte sind gleichgross")
""" Generator of fibonacci numbers input: amount of numbers """ from typing import Iterator def fibonacci(limit: int = 10) -> Iterator[int]: yield 1 yield 1 prev = 1 current = 1 limit -= 2 while limit: prev, current = current, prev + current yield current limit -= 1 d...
class Palindrome: @staticmethod def is_palindrome(word): reverse = word[::-1] if reverse.upper() == word.upper(): return True else: return False word = input() print(Palindrome.is_palindrome(word))
def solution(n): def convert_3(num): note = '012' q, r = divmod(num, 3) w = note[r] return convert_3(q) + w if q else w n_3 = convert_3(n) answer = 0 for i, v in enumerate(n_3): answer += 3 ** i * int(v) return answer
n=input("enter the number") sum=0 while(n>0): n=n-1 sum=sum+n print(sum)