text
stringlengths
37
1.41M
""" The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,...
""" The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) c...
""" Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; t...
num = int(input("Enter the number: ")) print("prime number is") primes = [] for i in range(2, num + 1): for j in range(2, int(i ** 0.5) + 1): if i%j == 0: break else: primes.append(i) print(primes)
while True: # объявляем бесконечный цикл year = int(input("year: ")) if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: print(366) else: print(365) if input("Continue? (Y/n) ") == "n": # в конце цикла условие break
""" 1. Найти наибольшую цифру числа. 2. Найти количество четных и нечетных цифр в числе. """ number = int(input("Введите число: ")) biggest = 0 # переменная для хранения наибольшей цифры even = 0 # счетчик для четных чисел odd = 0 # счетчик для нечетных чисел while number > 0: # пока число больше 0 заходи...
""" Кортежи - неизменяемые списки, но могут содержать изменяемые элементы. Доступны методы списков count() и index() """ # Создание кортежа tuple_1 = () tuple_2 = tuple("hello") tuple_3 = (1, 2, 3) tuple_4 = 1, 2, 3 print(tuple_1, tuple_2, tuple_3, tuple_4) print(type(tuple_1), type(tuple_2), type(tuple_3)...
""" Продолжение и доп примеры декораторов из lesson9/_5_decorators.py Дано функции hello и bye. Необходимо реализовать функционал, чтоб сообщения, выводимые функциями оборачивалось в html теги: [in] hello('Max') [out] <html> Hello, Max! </html> [in] ...
1 var_int = 25 var_float = 4.5 var_str = 'python' 2 var_big = var_int * 1.5 3 var_float = var_float - 1 4 result = var_big % var_float print (result) 5 var_str = "end" 6 print (var_int, var_float, var_big, var_str) 7 number = int(input("введите число :")) result = number // 10 + number % 10 print ("Число:", resu...
# Создание списков (пустого и заполненного) # Первый способ my_list = [] my_list2 = [1, 'word', False, 2.0] print(my_list, type(my_list)) print(my_list2, type(my_list2)) # Второй способ empty_list = list() list_from_str = list('some list') print(empty_list) print(list_from_str) colors = ['red', 'green', 'blue', '...
""" Необходимо написать простой калькулятор, который оперирует с двумя числами и оператором. В зависимости от введенного оператора, между числами проводится определенная операция. Результат выводится на экран. * обработать все возможные ошибки программы с помощью try-except """ try: number_1...
""" 1. Записать в файл practice.txt: числа от 9 до 17 через пробел 2. Прочитать этот файл и вывести содержимое и тип содержимого на экран 3. В файл с новой строки записать такой текст: Some text 123, @!$!@SA 4. Прочитать файл и вывести в консоль: - количество заглавных букв. - количество...
def even_range(start, end): current = start while current < end: yield current current += 2 for i in even_range(0, 10): print(i)
import functools def calc_values(x, y: int): print("X: {} Y: {}".format(x, y)) return x + y numbers = [2, 3, 5, 8, 13] # X becomes the sum of the elements then we add Y reduced_value = functools.reduce(calc_values, numbers) print(reduced_value)
import random class Character: def is_alive(self): if self.health > 0 or self.health == float('inf'): return True else: return False class Hero(Character): def __init__(self, name, health, power): self.name = name self.health = health ...
#Sum/Average Program #Your first and last name: Isaiah Bishop #Your student ID: 1288086 #Build on what you did in the 'List of Names' program #Instead of entering 10 names, enter 20 numbers (integers) #Instead of searching for a name in the list # Compute the sum of all 20 numbers # Compute the average for...
class Evaluator: @staticmethod def zip_evaluate(words,coeffs): if not isinstance(words,list) and not isinstance(coeffs,list): raise TypeError if len(words)!=len(coeffs): raise ValueError words=tuple(words) for i in words: if not isinstance(i,st...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 3 15:29:27 2021 @author: ayoub """ import sys def number(x): if str(x).isdigit(): if int(x)==0: return "I'm zero." elif int(x)%2==0: return "I'm even." elif int(x)%2==1: return "I'm ...
n = int(input()) inp = input().strip() sea_level = 0 valley = 0 for i in inp: if i == 'U': sea_level += 1 elif i == 'D': sea_level -= 1 if sea_level == 0: if prev < sea_level: valley += 1 prev = sea_level print(valley)
#!/usr/bin/env python # coding: utf-8 # ### Written by :Raksha Choudhary<br> # ### Data Science and Bussiness Analytics Internship<br> # ### GRIP The Sparks Foundation<br> # ### Task 1: Predic the percentage of marks that student expected to scores based upon the number of hours they spend # #### In this we use ...
# ghost game from random import randint print ('Ghost game') feeling_brave = True score = 0 while feeling_brave: ghost_door = randint (1, 3) print (ghost_door) print('three doors ahead') print(' A ghost behind one') print (' which door do you open ?') door = input('1 ,2 ,3?') door_num = int ...
a = int(input("Täisarv: ")) if (a % 2) == 0: print( " {0} is even" .format(a)) else: print (" {0} is odd" .format(a))
x = 8 num = range(0, 13) for y in num: if y < 13: print("8 x ", y , "=", x * y)
a = int(input("Enter number of rows")) b=0 b = a+1 for i in range (1,b): for j in range (1 , b-i): print (" " , end=' ' ) for k in range (1,i+1): print ( k , end=' ') for l in range (k-1,0, -1): print (l , end = ' ') print ()
__author__ = 'Rushil' num = 0 num_list = [] a = 0 b = 1 while a < 4000000 or b < 4000000: num += 10 #noinspection PyAugmentAssignment a = a + b b = a + b if a%2 == 0: num_list.append(a) if b%2 == 0: num_list.append(b) print(sum(num_list))
#!/bin/python3 import sys time = input().strip() def am_to_pm(time): if time == '00:00:00AM': return '00:00:00' if time == '12:00:00PM': return '12:00:00' if time == '12:00:00AM': return '12:00:00' act_time = time[:-2] time_suff = time[-2:] i...
__author__ = 'Rushil' n_test = int(input()) points = [] def str_to_cood(str): return [tuple(str.split(' ')[:2]) , tuple(str.split(' ')[2:])] def get_sym_point(p_list): point_1 = p_list[0] point_2 = p_list[1] point_3_x = 2*int(point_2[0]) - int(point_1[0]) point_3_y = 2*int(point_2[1]...
__author__ = 'Rushil' import math div_num = {1:1 , 2:2 , 3:2 , 4:3 , 5:2 , 6:4 , 7:2 , 8:4 , 9:3 , 10:4 , 11:2 , 12:6} def triang_num(n): return int((n*(n+1))/2) print(triang_num(5)) def main_1(): n = 1 while True: num = triang_num(n) s = 1 for i in range(1,nu...
import random options = ['Rock', 'Paper', 'Scissors'] computer = random.choice(options) user = input("Enter 'r' for Rock, 'p' for Paper & 's' for scissors: ") print("") if user == "r": print("You chose Rock!") if user == "p": print("You chose Paper!") if user == "s": print("You chose Scissors!") print(f...
board = { 'A1':'A1','B1':'B1','C1':'C1',\ 'A2':'A2','B2':'B2','C2':'C2',\ 'A3':'A3','B3':'B3','C3':'C3' } status= 'Playing' turn = 1 def print_board(b): print() print(b['A1'] + '|' + b['B1'] + '|' + b['C1']) print('--+--+--') print(b['A2'] + '|' + b['B2'] + '|' + b['C2']...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the s...
"""Our knot hashing algorithm""" import numpy import operator def convert(a, lengths, pos=0, skip=0): """Twist of ring, return array, pos, skip""" num_elements = len(a) for length in lengths: a = numpy.append(numpy.flip(a[0:length], 0), (a[length:])) a = numpy.append(a[(length + skip) % ...
def get_largest_num(list_of_nums): list_of_nums = list_of_nums.sort() last_index = len(list_of_nums) - 1 return list_of_nums[last_index] print(get_largest_num([5, 2, 17, 8, 3]))
# Link =>>> https://leetcode.com/problems/search-in-rotated-sorted-array # Given an integer array nums sorted in ascending order, and an integer target. # Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # You should search for target in nums a...
#! /usr/bin/env python def ingresa_edades(edades=10): edadesValidadas=0 result=[] while edadesValidadas<edades: edadAsString=input("Inserte la edad de una persona: ") try: edad=int(edadAsString) edadesValidadas+=1 result.append(edad) except ValueError as e: print("La edad ingresada debe ser un num...
a=int(input("Give me one number: ")) b=int(input("Give me another number: ")) print("If you sum those numbers, the values is: ",a+b); print("If you rest those numbers, the values is: ",a-b); print("If you multiply those numbers, the values is: ",a*b); print("If you raise the first number to a power of the second number...
a=["Juan", "Pedro", "Pablo", "Luis", "Gerardo"] b=0 # A simple iteration arround the list print("Starting simple iterarion for",a) for x in a: print("Element[",b,"]=",x) b+=1 # An itteration modifying the elements into the original list print("Starting to modify the original list") b=0 for x in a[:]: a[b]=x+" D." ...
import csv class Lecturer: def __init__(self, course, lecturer): self.course = course self.lecturer = lecturer class Student: def __init__(self, course, user): self.course = course self.user = user class NumberStudents: def __init__(self, course, count): self.co...
import math def reward_function(params): ''' Example of rewarding the agent to follow center line ''' # Read input parameters all_wheels_on_track = params['all_wheels_on_track'] # flag to indicate if the agent is on the track x = params['x'] # ...
import re class PasswordValidation: def __init__(self, user, password): self.user = user self.password = password def validate(self): username = self.user.cleaned_data.get('username') email = self.user.cleaned_data.get('email') lower = re.findall('[a-z]', self.passwo...
# task1 # num1 = input("введите первое число: ") # num2 = input("введите второе число: ") # res = None # try: # num1 = int(num1) # num2 = int(num2) # res = num1 / num2 # print(res) # except ZeroDivisionError: # raise Exception('на ноль делить нельзя') # task2 # num1 = input("введите первое число...
car = {'make': 'BMW', 'model': '550i', 'year':1989} print(car) print(car['make']) d = {} d['one'] = 1 print(d) sum_1 = d['one'] + 8 print(sum_1)
""" Author: Rajiv Malhotra Program: set_membership.py Date: 10/14/20 Set Assignment """ def in_set(some_set, some_value): """ Function accepts a set and returns a boolean value stating if the element is in the set. :param some_set: This is a set :param some_value: This is a string :return: Boolea...
import sys from typing import Pattern sys.path.append('W2') sys.path.append('W3') from W2_7_1 import neighbor_again from Seven import DistanceBetweenPatternAndStrings def MedianString(Dna, k): """Input: An integer k, followed by a collection of strings Dna. Output: A k-mer Pattern that minimizes d(Pattern, Dna) a...
# EXAMPLE-6 # Write a function named "translate" that performs RNA to amino acid translation. # # RNA codon table is simplified to contain only five codons: # 'UUU' -> 'Phenylalanine' # 'UUA' -> 'Leucine' # 'AUU' -> 'Isoleucine' # 'GUU' -> 'Valine' # 'UCU' -> 'Serine' # RNA se...
# EXAMPLE-3 # Write a script which will take the input as a list in the first line and 3 strings in the next 3 lines. # Elements of the list are either a string or an empty list. # You will put those 3 strings into the empty lists in the main list and print the output list. # SAMPLE INPUT/OUTPUTs: # == Input == #...
# Write a function named all_orderings which takes a list of size N and # returns all the permutations (orderings) of order N. # >>> all_orderings([1,2,3]) # [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] # >>> all_orderings(['a','b', True, False]) # [['a', 'b', True, False], ['a', 'b', False, Tru...
from typing import List def list_equals(lst1: List, lst2: List) -> bool: return len(list(set(lst1).difference(set(lst2)))) == 0 and len(list(set(lst2).difference(set(lst1)))) == 0 def list_contains(lst: List, elements: List) -> bool: return all([elem in lst for elem in elements]) def list_to_str(sep: str,...
import pygame from pygame.sprite import Sprite import random #Список,в который будет содержать изображения вкусняшек yummie_img = [] def load_yum_img(): '''Функция загрузки изображений вкусняшек''' for i in range(3, 7): yummie_img.append(pygame.image.load('images/' + str(i) + '.png').convert_alpha()) class Yummie...
import pygame import math from time import sleep, time import random import copy pygame.init() class TicTacToeAI(): def __init__(self, competitor): self.competitor = competitor self.board = competitor.board def make_decision(self): original_board = self.competitor.board # pri...
# Sarah Sides # 7/10/18 # Student Database import time done = 1 want_to_view = 3 student_list = [] while done == 1: student_data = [] name = input("What is the name of the student? ") year = int(input("What grade year is the student currently in? Please enter a number. ")) grade...
class State(object): def __init__(self, board, agent, opponent, agent_score, opponent_score): self.board = board self.agent = agent self.opponent = opponent self.agent_score = agent_score self.opponent_score = opponent_score def turn(self, board, agent_reward, opponent_...
# -*- coding: utf-8 -*- def sort(*args, key=lambda x: x, reverse: bool = False, counter: list = [0]) -> list: """ Сортировка выбором. :param args: список значений :param key: функция, применяемая к каждому значению :param reverse: обратный порядок сортировки :param counter: количест...
# This program will try to guess the word the user is thinking of within 16 guesses. def compPick(lower,higher,count): with open('usa.txt') as f: lines = f.readlines() index = round((higher+lower)/2) # Finds the number inbetween the two indexes guess = lines[round(index)] # Index number for t...
#Given a non-empty array of digits representing a non-negative integer, increment one to the integer. #The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. #You may assume the integer does not contain any leading zero, except the n...
import sqlite3 class Database: def __init__(self, db): self.conn = sqlite3.connect(db) self.cur = self.conn.cursor() self.cur.execute("""CREATE TABLE IF NOT EXISTS cosing (Ref_No INTEGER PRIMARY KEY, INCI_name TEXT, INN TEXT, PhEur TEXT, CAS_No TEXT, EC_No TEXT, ...
#!/usr/bin/python3.5 # -*- coding: UTF-8 -*- import argparse import os """ rename a group of files """ def batch_rename(work_dir, old_ext, new_ext): """ rename a group of files """ for filename in os.listdir(work_dir): split_file = os.path.splitext(filename) file_ext = split_fil...
class Vector(list): def __init__(self, *v): super().__init__(v) def __abs__(self): from math import sqrt return sqrt(sum(x ** 2 for x in self)) def __add__(self, other): if len(self) != len(other): raise ValueError("Mismatching vetor lenghts ({} != {})".format(l...
def naj(xs): maximum = xs[0] for num in xs: if num > maximum: maximum = num return maximum def naj_abs(xs): maximum = abs(xs[0]) max_real = xs[0] for num in xs: if abs(num) > maximum: maximum = abs(num) max_real = num return max_real ##...
number = int(input("Vnesi število: ")) delitelj = 2 vsota = 1 while delitelj < number: if number % delitelj == 0: vsota += delitelj delitelj += 1 delitelj = 2 vsota2 = 1 while delitelj < vsota: if vsota % delitelj == 0: vsota2 += delitelj delitelj += 1 if vsota2 == number: print...
#!/usr/bin/env python import dump import optparse as op import numpy import sys def diffDumps(fileName0,fileName1,allowedRelativeDifference,thresholdValue,out): """Checks to see if the two dump files differ """ dumpFile0=dump.Dump(fileName0) dumpFile1=dump.Dump(fileName1) #check headers [headersMa...
import turtle def drawSquare(x, sz): for i in range(4): x.forward(sz) x.left(90) wn = turtle.Screen() wn.bgcolor("Navy Blue") turt = turtle.Turtle() turt.color('yellow') turt.pensize(4) for i in range(5): drawSquare(turt, 40) turt.penup() turt.fo...
def get_prep_words(filename): set_of_prep_words = set() f = open(filename, 'r') for line in f: line_strip = line.strip('\n') line_strip = line.strip() line_lowercase = line_strip.lower() set_of_prep_words.add(line_lowercase) f.close() return set_of_pre...
# -*- coding: utf-8 -*- # %% 51 from collections import Counter text = 'python programming - introduction' cnt = Counter(text) print(cnt.most_common(3)) # %% 52 from collections import Counter import re text = """"Python is fast enough for our site and allows us to produce maintainable features ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 13 16:43:52 2019 @author: trn2503 """ class QueueIsEmpty(Exception): pass class Queue: def __init__(self): self._queue = [] def add(self, item): self._queue.append(item) def pop(self): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 14 15:33:06 2019 @author: trn2503 """ #a = list(map(lambda x:x*x, range(10))) #print(a) #Equivalent print('List comprehension example 1') a = [ x*x for x in range(10) ] print(a) #Cartesian product print('Another example, Cartesian product') b = ...
import obd import time connection = obd.OBD() # auto-connects to USB or RF port def obd_speed(): cmd = obd.commands.SPEED # select an OBD command (sensor) response = connection.query(cmd) # send the command, and parse the response print(response.value) # returns unit-bearing values thanks to Pint ...
import logging logging.basicConfig(filename="new11.log", format='%(asctime)s %(message)s', filemode='w') logger=logging.getLogger() logger.setLevel(logging.DEBUG) logger.info("New file is created") a = int(input("Enter A : ")) b = int(input("Enter B : ")) if a>10 or b>10: ...
#!/usr/bin/env python import math import sys class Grid: """Representation of a sheet of grid paper. Initialized as a three-dimensional N x N x 1 grid. N must be a power of 2. Cells are numbered from 1 to N * N, going in order from left to right, then top to bottom, then front to back. """ ...
# Objective: demonstration of linear regression in Python for machine learning # Source: Siraj Raval, How to Make a Prediction - Intro to Deep Learning #1 # Notes: script prepared for Python 3.6.0 import pandas as pd from sklearn import linear_model import matplotlib.pyplot as plt # read data dataframe = pd.read_csv...
UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) class Direction(object): def __init__(self, direction=UP): self._direction = direction def turn_up(self): return self._turn_direction(UP) def turn_down(self): return self._turn_direction(DOWN) def turn_left(self): ...
import sys, string num = int(input()) if num % 13 == 0 : print('yes') else : print('no')
import sys, string num = int(input()) value = 0 while num : value += num%10 num //= 10 print(value)
#sum of n natural nos import sys num = int(input('enter N : ')) sum = 0 for i in range(1,num+1) : sum += i print(sum)
import sys, string, math n = int(input()) p = 1 for i in range(1,n+1) : p = p * i print(p)
number=int(input("enter the value:")) sum=[] for i in range(0,number): value=int(input('')) a=sum.append(value) print sum sum.sort() print(sum)
#check odd or even import sys num = int(input('enter a no : ')) if num%2==0 : print('Even') else : print('Odd')
''' Pivot data Pivoting data is the opposite of melting it. Remember the tidy form that the airquality DataFrame was in before you melted it? You'll now begin pivoting it back into that form using the .pivot_table() method! While melting takes a set of columns and turns it into a single column, pivoting will creat...
''' Custom functions to clean data You'll now practice writing functions to clean data. The tips dataset has been pre-loaded into a DataFrame called tips. It has a 'sex' column that contains the values 'Male' or 'Female'. Your job is to write a function that will recode 'Male' to 1, 'Female' to 0, and return np.nan...
''' Many-to-many data merge The final merging scenario occurs when both DataFrames do not have unique keys for a merge. What happens here is that for each duplicated key, every pairwise combination will be created. Two example DataFrames that share common key values have been pre-loaded: df1 and df2. Another DataFr...
''' Converting data types In this exercise, you'll see how ensuring all categorical variables in a DataFrame are of type category reduces memory usage. The tips dataset has been loaded into a DataFrame called tips. This data contains information about how much a customer tipped, whether the customer was male or fe...
''' The power of SQL lies in relationships between tables: INNER JOIN Here, you'll perform your first INNER JOIN! You'll be working with your favourite SQLite database, Chinook.sqlite. For each record in the Album table, you'll extract the Title along with the Name of the Artist. The latter will come from the Artist...
''' Loading and exploring a JSON Now that you know what a JSON is, you'll load one into your Python environment and explore it yourself. Here, you'll load the JSON 'a_movie.json' into the variable json_data, which will be a dictionary. You'll then explore the JSON contents by printing the key-value pairs of json_da...
# !/usr/bin/env python # -*-coding:utf-8 -*- """ # File : 练习题.py # Time :2021/4/18 10:15 # Author :yhy # version :python 3.7 """ l = [1, 3, 45, 39, 9, 66] def test1(list, n): print(list) for i in range(n): list.insert(0, list.pop()) print(list) def test2(list, n): print(...
# -*- coding: utf-8 -*- import re # for validating an Email def validate_email(email): regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' if(re.search(regex,email)): return True else: print("Invalid Email") return False ...
import random import pygame pygame.init() display = pygame.display.set_mode((400, 400)) display.fill((255, 255, 255)) pygame.display.update() font = pygame.font.Font(None, 18) t = None color = (0, 0, 0) health = int(100) enemyHealth = int(100) action = " " potion = True shot = int(0) attack = int(0) shield = False en...
#87 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. def...
""" Olympics. You're given list of lists where each list is the countries that won the gold, silver and bronze for that activity. Return the countries and their medal counts, prioritizing first gold, silver then bronze. If its a full tie in all 3 categories, alphabetize. sample input: [["ITA", "JPN", "AUS"], ["KOR"...
# Write a function that helps cashier to give change back in as little coins as possible. Input is change need to be given back, output is minimum # of coins needed. def change(amount): quarter = 0.25 q_count = 0 dime = 0.1 d_count = 0 nickel = 0.05 n_count = 0 penny = 0.01 p_count = 0...
def str_to_num(string): int_list = [] final_num = 0 string_list = list(string) for char in string_list: if 48 <= ord(char) <= 57: int_list.append(ord(char)-48) else: return False for i in range(len(int_list)): value = int_list[-i-1] place = 10...
""" Tree traversal. BFS and DFS (pre, in, post) """ class BinaryTree: def __init__(self,data): self.key = data self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: ...
""" Little Bob loves chocolates and goes to the store with a $N bill with $C being the price of each chocolate. In addition, the store offers a discount: for every M wrappers he gives the store, hell get one chocolate for free. How many chocolates does Bob get to eat? Input Format: The first line contains the number o...
""" Implement a simple tree in 2 representations: - list of lists - nodes and references. """ # List of lists # example of list of lists: ['a',['b',['d', [], []],['e', [], []] ],['c',['f', [], []], [] ]] def BinaryTree(r): return [r, [], []] def insertLeft(root,newBranch): t = root.pop(1) if le...
weight = int(input("Please input your weight: ")) converter = input("(L)bs or (K)g: ") if converter.upper() == "L": print(f"you weigh {float(weight) * .45} kgs!") elif converter.upper() == "K": print(f"you weigh {float(weight) / .45} lbs!") else: print("I'm sorry, that is not a valid response...
#!/usr/bin/python3 class Calendar: def __init__(self): self.to_do_list = ToDoList() # input_date=input("Please enter today's date in mm/dd/yy format: ") date='4/20/18' date=date.split('/') self.__month=int(date[0]); self.__day=int(date[1]); self.__year=int(date[2]); self.__day_names=["Monday","Tuesday",...
roman=input("Enter number in the simplified Roman system: ") total=0 for letter in range(len(roman)): if (roman[letter] == "M"): total+=1000 elif (roman[letter] == "D"): total+=500 elif (roman[letter] == "C"): total+=100 elif (roman[letter] == "L"): total+=50 elif (roman[letter] == "X"): total+=10 elif ...
side1=float(input("Length of first side: ")) side2=float(input("Length of second side: ")) side3=float(input("Length of third side: ")) if (side1 == side2 and side1 == side3): print(str(side1) + ", " + str(side2) + ", " + str(side3) + " form an equilateral triangle") elif (side1 == side2): if (abs(side1**2 + side2**2...
weightPounds=float(input("Please enter weight in pounds: ")); heightInches=float(input("Please enter height in inches: ")); weightKilos=(weightPounds*0.453592); heightMeters=(heightInches*0.0254); BMI=(weightKilos/heightMeters**2); print("BMI is: ", BMI);
print("Please enter a non-empty sequence of positive integers, each one in a separate line. End your sequence by typing 'done':") total=0 counter=0 num=input() while (num != 'done'): total+=int(num) counter+=1 num=input() print("The geometric mean is:", total**(1/counter))
years=int(input("Input number of years: ")) seconds=years*365*24*60*60 population=307357870 population=population+int((1/7)*seconds)+int((1/35)*seconds)-int((1/13)*seconds) print("Estimated population:", population)