text
stringlengths
37
1.41M
# abc_lower = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', # 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', # 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # abc_upper = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', # 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', # 'S', 'T', ...
total_count = int(input()) colored_eggs = {'red': 0, 'orange': 0, 'blue': 0, "green": 0} for _ in range(total_count): color = input() colored_eggs[color] += 1 max_color = 0 max_count = 0 for color, count in colored_eggs.items(): if count == max(colored_eggs.values()): max_count = count max...
exam_hour = int(input()) exam_minute = int(input()) student_hour = int(input()) student_minute = int(input()) exam_time = exam_hour * 60 + exam_minute student_time = student_hour * 60 + student_minute time_difference = exam_time - student_time abs_time_difference = abs(time_difference) abs_hour_difference = 0 abs_minu...
import sys n = int(input()) max_num = -sys.maxsize while n > 0: n -= 1 num = int(input()) if num > max_num: max_num = num print(max_num)
class store_results: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): res = self.func(*args, **kwargs) with open('results.txt', 'a') as file: file.write(f"Function '{self.func.__name__}' was add called. Result: {res}\n") # @store_results # de...
string = input() digits = [] letters = [] other = [] for char in string: if char.isdigit(): digits.append(char) elif char.isalpha(): letters.append(char) else: other.append(char) print(''.join(digits)) print(''.join(letters)) print(''.join(other))
size = input() color = input() count = int(input()) prices = {"Large": {"Red": 16, "Green": 12, "Yellow": 9}, "Medium": {"Red": 13, "Green": 9, "Yellow": 7}, "Small": {"Red": 9, "Green": 8, "Yellow": 5}} total_price = prices[size][color] * count * 0.65 print(f"{total_price:.2f} leva.")
import re PATH = 'text.txt' PATTERN = r"[-,!?'.]" REPLACEMENT = '@' def replace_bad_chars(line): return re.sub(PATTERN, REPLACEMENT, line) def get_even_lines(ll): return [ll[i].rstrip().split() for i in range(len(ll)) if i % 2 == 0] def reverse_order(ll): return [line[::-1] for line in ll] def prin...
from abc import abstractmethod, ABC class Shape(ABC): @abstractmethod def calc_area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def calc_area(self): return self.width * self.height class Triangle(Sh...
def find_smallest_int(n1, n2, n3): return min(n1, n2, n3) number_1 = int(input()) number_2 = int(input()) number_3 = int(input()) print(find_smallest_int(number_1, number_2, number_3))
number_str = input() for n in reversed(number_str): num = int(n) for i in range(num): if num != 0: char = chr(num+33) print(char, end='') if num == 0: print('ZERO') else: print()
MATRIX = [ [11, 2, 4], [4, 5, 6], [10, 8, -12], ] LOCAL_TEST = False def get_matrix_input(is_test=False): if is_test: matrix = MATRIX else: rows = int(input()) matrix = [] for row in range(rows): row = [int(x) for x in input().split(' ')] mat...
phonebook = {} the_input = None while True: the_input = input() if the_input.isnumeric(): break name, number = the_input.split('-') phonebook[name] = number n = int(the_input) for _ in range(n): contact = input() if contact in phonebook: print(f'{contact} -> {phonebook[contact]}...
from math import sqrt def calculate_distance_from_center(x, y): d = sqrt((x ** 2) + (y ** 2)) return d def check_closest_point(point1, point2): x1, y1 = point1 x2, y2 = point2 distance_1 = calculate_distance_from_center(x1, y1) distance_2 = calculate_distance_from_center(x2, y2) if distance_1 <= distance_2: ...
def min_number(*args): return min(args) def max_number(*args): return max(args) def sum_number(*args): return sum(args) def print_output(ll): print(f'The minimum number is {min_number(*ll)}') print(f'The maximum number is {max_number(*ll)}') print(f'The sum number is: {sum_number(*ll)}') ...
#!/usr/bin/env python3 from math import log num = int(input()) base = input() if base == 'natural': print(f'{log(num):.2f}') else: print(f'{log(num, int(base)):.2f}') for i in base: if i == '5': print('wahts up') else: if not i: if i == '1': if i: ...
import unittest from project.vehicle import Vehicle class VehicleTest(unittest.TestCase): fuel = 50.0 horse_power = 100.0 def setUp(self) -> None: self.v = Vehicle(self.fuel, self.horse_power) def test_vehicle_init(self): self.assertEqual(self.fuel, self.v.fuel) self.assertE...
from math import ceil count_of_students = int(input()) count_of_lectures = int(input()) initial_bonus = int(input()) all_bonuses = [] best_student = {"bonus": 0, "attendances": 0} for student in range(count_of_students): attendances = int(input()) bonus = attendances / count_of_lectures * (5 + initial_bonus) if b...
from collections import deque BIGGEST_ORDER = 0 MIN_OREDER = 0 food_quantity = int(input()) orders_input = [int(s) for s in input().split(' ')] orders = deque(orders_input) if orders: orders_copy = orders.copy() best = MIN_OREDER while orders_copy: el = orders_copy.popleft() if el >= best...
movie_title = input() hall_type = input() tickets_sold = int(input()) prices = { "A Star Is Born": {"normal": 7.5, "luxury": 10.5, "ultra luxury": 13.5}, "Bohemian Rhapsody": {"normal": 7.35, "luxury": 9.45, "ultra luxury": 12.75}, "Green Book": {"normal": 8.15, "luxury": 10.25, "ultra luxury": 13.25}, ...
from math import ceil, floor rocket_price = float(input()) rocket_count = int(input()) sneakers_count = int(input()) sneakers_price = 1/6 * rocket_price total = rocket_count * rocket_price + sneakers_count * sneakers_price total += total * 0.2 novac_costs = 1/8 * total sponsors_costs = 7/8 * total print(f"Price to be...
def collect(inv, i): if i not in inv: inv.append(i) return inv def drop(inv, i): if i in inv: inv.remove(i) return inv def combine_items(inv, i): old, new = i.split(":") if old in inv: inv.insert(inv.index(old) + 1, new) return inv def renew(inv, i): if i in inv: inv.remove(i) inv.append(i) ret...
class Animal: sound = '' def make_sound(self): return self.sound class Cat(Animal): sound = 'meow' class Dog(Animal): sound = 'bark' class Lion(Animal): sound = 'roar' def animal_sound(animals: list): for animal in animals: print(animal.make_sound())...
class MovieWorld: def __init__(self, name: str): self.name = name self.customers = [] # list of customers objects self.dvds = [] # list of dvd objects def __repr__(self): rep = '' for customer in self.customers: rep += f'{customer}\n' for dvd in sel...
def print_title(text): print("<h1>") print(f" {text}") print("</h1>") def print_content(text): print("<article>") print(f" {text}") print("</article>") def print_comment(text): print("<div>") print(f" {text}") print("</div>") title, content, comment = input(), input(), input() print_title(title)...
snowballs = int(input()) best_value = 0 best_snowball = {} for snowball in range(snowballs): snow = int(input()) time = int(input()) quality = int(input()) value = int((snow / time) ** quality) if value > best_value: best_value = value best_snowball = {'best_snow': snow, 'best_time...
def process_data(d): """Takes the input and returns processed values for command, index and value.""" com, i, v = d.split() return com, int(i), int(v) def is_valid_index(index, t_list): """Checks if the given index is in the range of the list.""" if index in range(len(t_list)): return True def shoot(index, ...
string = input() stack = [] for char in string: stack.append(char) result = "" while stack: result += stack.pop() print(result) # print(string[::-1])
#!/usr/bin/python3 # read in input data data = [] group = [] with open("input.txt", "r") as f: for line in f: line = line.strip() if line != "": group.append(line) else: data.append(group) group = [] data.append(group) group = [] f.close() # str...
#David Lupea #IntroCS2 pd5 #HW34 -- End ofEndOfFiles #2018-5-08 #Reads a .csv file consisting of 3 rows: a last name, a first name and an unknown number of letter grades: #A being 4, B being 3, C being 2, D being 1 and F being 0 points. Computes and prints the grade point average #of each student. def gradep...
#Team David + Kevin #David Lupea and Kevin Mesta #IntroCS2 pd 5 #Labwork 07 #2018-02-12 #Checks if the given year is a leap year def isLeapYr(year): if (year % 400 == 0): #Checks if the century is one of a multiple of 400 return True if (year % 4 == 0) and (year % 100 != 0): #checks to see ...
#David Lupea #IntroCS2 pd<5 #HW7 -- PassJudgement #2018-2-26 def pythTriple(a, b, c): #Checks to see if they are all integers(all triples are integers) if type(a) == int and type(b) == int and type(c) == int: #Tries the three cases as to whether or not the sum of the square of the length of two sides ...
#Write code to swap the value of two numbers without using literals x = 2 y = 3 print "x is equal to %s" %x, "y is equal to %s" %y print "Switch" #a = x #b = y #x = b #y = a x, y = y, x print "x is equal to %s" %x, "y is equal to %s" %y
#David Lupea #IntroCS2 pd5 #HW 8 -- Script Writing #2018-02-27 #largest_odd.py num1 = int(raw_input("Enter an integer: ")) #Takes in the inputs num2 = int(raw_input("Enter another integer: ")) num3 = int(raw_input("Enter a final integer: ")) if num1 % 2 == 1 or num2 % 2 == 1 or num3 % 2 == 1...
#Mimics the bash command wc # $wc filename -> number of lines, number of words, number of characters, filename #filename filename = 'Tom_Sawyer_Preface.txt' #create a dile object to read from fileIn = open(filename, 'r') #Initialize variables numlines, numwords, numchars = 0,0,0 for line in fileIn: ...
number = raw_input("Enter a number: ") total = 0 for i in number: x = int(i) total += x print total
text = 'Ala ma kota' # for char in text: # print(char) # length = len(text) # for idx in range(length): # print(text[idx]) # something something something some_range = range(length) print(some_range) is_loop_done = False for value in some_range: print(value) # the bad way, check forelse.py if value...
value = int(input('Podaj liczbe:')) # value = int(value) # @TODO: wyswietl kolejne liczby parzyste bez instrukcji warunkowych start = 0 stop = value step = 2 for idx in range(start, stop, step): print(idx)
data = input('Podaj liczbe lub litere: ') while not data.isalpha() and not data.isdigit(): print('Podales zle dane, podaj jeszcze raz') data = input('Podaj liczbe lub litere: ') if data.isdigit(): print('Podales liczbe') elif data.isalpha(): print('Podales litere') print('bye!')
#!/usr/local/bin/python3 from functools import reduce from itertools import product EMPTY = 'L' FLOOR = '.' OCCUPIED = '#' class Seating(list): @staticmethod def from_file(input_file): seating = Seating() with open(input_file) as f: for line in f.readlines(): seat...
import sys def is_valid(args): char, pos_1, pos_2, password = args extracted = [password[p - 1] for p in [pos_1, pos_2]] return extracted.count(char) == 1 def parse_line(line): char_poses, char_colon, password = line.split() pos_1, pos_2 = [int(i) for i in char_poses.split("-")] char = char_c...
def validate_passports(input_string): failed = 0 passports = input_string.split("\n\n") required_fields = [ "byr:", "iyr:", "eyr:", "hgt:", "hcl:", "ecl:", "pid:", # "cid", ] for passport in passports: for field in required_fie...
def get_seat_id(code): row = code[:7] col = code[7:] row = row.replace('F', '0').replace('B', '1') col = col.replace('L', '0').replace('R', '1') row = int(row, 2) col = int(col, 2) seat_id = row * 8 + col return seat_id def get_highest_seat_id(input): highest = 0 for line in inp...
''' This file implements the platformer rules. ''' import numpy as np from numpy.random import uniform from util import vector def bound(value, lower, upper): ''' Clips off a value which exceeds the lower or upper bounds. ''' if value < lower: return lower elif value > upper: re...
from queue import Queue class ContactTracer: def __init__(self): self.contacts = {} self.counts = {} def addContact(self, num1, num2): if num1 not in self.contacts: self.contacts[num1] = {num2} self.counts[num1] = 1 else: if num2 not in s...
def uneven_nums_gen(last_num): for num in range(1, int(last_num) + 1, 2): yield num nums = uneven_nums_gen(input('Введите макс. значение генератора: ')) print(*nums)
""" :type words: List[str] :rtype: int """ words = ["gin", "zen", "gig", "msg"] for x in range(97,123): letter = chr(x) alphabet = "" + letter morseCode = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","...
# SOLUTION FOR QUESTION 5 BY ENG19CS0044 """ 5 A Input : 3 1 2 2 2 8 7 2 3 3 4 4 So the error is that when the key does not exist in data 1, the key value pair is not added to it. """ # 5 B def uniqueUpdate(data1, data2): # Initially empty dictionary dupKeys = {} # Examine eve...
""" Desktop : Sudeep R Dodda Date created : 09/15/2017 Description : Python script performs BLE advertisement scan and prints MAC address, RSSI, Flags, UUID, Major, Minor and TX PWR. Also defines two methods : hex...
# Extracting Data from XML # In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/geoxml.py. # The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the # comment counts from the XML data, compute the sum of the num...
##Write a function called middle that takes a list and returns a new list that ##contains all but the first and last elements. mylist = [1,2,3,4] def middle(mylist): leng = len(mylist) mylist.pop(leng-1) mylist.pop(0) return mylist print (middle(mylist))
# The program prompts for a web address, then opens the web page, reads the data # and passes the data to the BeautifulSoup parser, and then retrieves all of the # anchor tags and prints out the href attribute for each tag. # To run this, you can install BeautifulSoup # https://pypi.python.org/pypi/beautifulsoup4 # O...
##Write another program that prompts for a list of numbers as above ##and at the end prints out both the maximum and minimum of the numbers instead ##of the average. count = 0 total = 0 max_num = None min_num = None while True: inp = input('Enter a number: ') if inp == 'done': print (count, max_num, min...
##Write a program to prompt the user for hours and rate per hour to ##compute gross pay. hrs = input('Enter hours: ') rate = input('Enter rate: ') hrs = float(hrs) rate = float(rate) Pay = hrs*rate print (Pay)
def factorize(num): factors = [] for i in range(1,num/2+1): if i > num / i: break if num % i == 0: factors.append(i) if num/i != i: factors.append(int(num/i)) return sorted(factors) def triangle_number_generator(): tri = 1 inc = 2 while True: yield tri tri = tri + inc inc ...
def max_solutions_for_triangle_perimeter_range(max_perimeter): """Returns the perimeter p that has the most integral side solutions for right triangles, for p <= max_perimeter""" import euler009 import functools perimeter_solutions = [] for p in range(1, max_perimeter+1): perimeter_solutions.append((p,len(...
import math import fractions def find_closest_smaller_fraction(max_denom, target_fraction): target_n,target_d = target_fraction frac = target_n/target_d ans = 0 for d in range(2,max_denom+1): absolute = d * frac min_num = math.floor(absolute) max_num = math.ceil(absolute) #print(absolute,min_num...
def sqrt_two_gen(iterations): d,n = 3,2 for i in range(iterations): yield d,n d,n = n + n + d, n + d yield d,n ans = sum([1 for n,d in sqrt_two_gen(1000) if len(str(n)) > len(str(d))])
x = int(input("please enter valid input x")) if(x <0): print("x is negative number") elif(x >0): print("x is positive number") elif(x==0): print("x is equal to zero ") else: print("x is not defined ") if True: print("PASS") else:# dead code , never come inside print("FAIL") a = 100 b= 200 c=...
name = "Avery" subjects = ["English", "Science", "Math", "History", "French"] print ("My name is " + name) for i in subjects: print("I take " + i + " as one of my classes.") placesilove = ["Paris", "Punta Mita", "Gordes", "NYC", "Palm Beach", "Nantucket", "Cassis", "Fairlee", "Venice", "Croatia",...
#Lase kasutajal sisestada arvud ning salvesta need muutujasse, samuti muuda kohe stringid numbriteks - int() number1 = int(input("Sisesta esimene number: ")) number2 = int(input("Sisesta teine number: ")) number3 = int(input("Sisesta kolmas number: ")) #kasutan andmetüüpi "array", et salvestada numbrid üheks muutujaks...
arr = [1, 23,3 ,434,54,545,65,54,54,45,23,54,23] arr_1 = set(arr) from collections import Counter def counter(arr): return Counter(arr).most_common(len(arr_1)) if Counter(arr).most_common(len(arr_1)) else None for x in counter(arr): print('{}出现的次数为{}'.format(x[0], x[1]))
from nltk.corpus import names from nltk import NaiveBayesClassifier from nltk import classify from nltk import accuracy from nltk import DecisionTreeClassifier from nltk.classify.svm import SvmClassifier import sklearn.svm import random import nltk nltk.download('names') gender = [(n,'Male') for n in names.words('mal...
a=2 b=3 c=4 if b<a: print("é menor") elif a==b: print("é igual") else: print("é maior") print("è menor") if a < b else print("E maior") if(a<b) and (b!=c): print("Ok") if(a<b) or (b!=c): print("Não") while(c<10): print("Aumentando c") c=c+1 minhaLista=["eu","realdo","justino"] for x i...
def get_weight_kg_of_plastic(plastic_type): if plastic_type == "film": return 0.01 elif plastic_type == "textiles": return 0.1 elif plastic_type == "rigid beverage container": return 0.2 elif plastic_type == "rigid non-beverage container": return 0.3 elif plastic_type...
# -*- coding: utf-8 -*- def select_unassigned_variable(csp): """Selects the next unassigned variable, or None if there is no more unassigned variables (i.e. the assignment is complete). For P3, *you do not need to modify this method.* """ return next((variable for variable in csp.variables ...
# -*- coding: utf-8 -*- """ Created on Thu Dec 13 15:18:31 2018 @author: RV """ class Car(object): def __init__(self,position,direction): self.position = position self.direction = direction self.crossMode = 0 self.alive = True def __lt__(self, other): return self.po...
num1 = int(input("Enter 1st number:")) num2 = int(input("Enter 2nd number:")) def num_checker(num1,num2): total = num1 + num2 if num1 == 3 or num2 == 3: if '3' in str(total): return True else: return False else: return False print(num_checker(num1,num2))
class Controller: ''' The Controller class is abstract class for implement basic command to play MOBA game. ''' pass class HeroItem(Controller): ''' Control hero about item. Example: 1.Hero item using. 2.Hero item selling. 3.Hero item buying. 4.Hero item c...
""" Draw a call stack for the Tower of Hanoi problem. Assume that you start with a stack of three disks. 缺陷:不能显示栈的内容 只能显示数目 改进:可用list模拟栈 """ from pythonds.basic.stack import Stack #print('请输入汉诺塔的层数') #N = int(input()) N = 3 global A, B, C, step A = Stack() B = Stack() C = Stack() x = [] step = 0 lst = list(range(1, N ...
#Number guessing game import random salaNumero=random.randint(1, 20) print('Arvaa oikein numero 1 ja 20 välillä') #arvuutetaan kuusi kertaa for arvaukset in range(1, 7): print('Arvaa') try: arvaus=int(input()) if arvaus == salaNumero: print('Oikein!') print...
data = raw_input("enter input: ") a = data.split() s = set(a) data1 = list(s) #print(data1) output = sorted(data1) print(output)
name1string = input("pls enter first name : ") namestring = input("pls nter last name : ") print(name1string[::-1] +" " + namestring[::-1]) a = int(input("enter first number: ")) b = int(input("enter second number: ")) sum = a + b diff = a - b mul = a * b div = a / b rem = a % b print("sum:", sum) print("diff:", ...
""" Player class represents a player of the game """ class Player: def __init__(self, name = "", totalMoney = 16): self.name = name self.totalMoney = totalMoney self.currentPos = 0 # Each players current position represented as an index of the square the player is currently on def ...
def partition(arr, low, high): i = low - 1 pivot = arr[high] for j in range(low, high): if arr[j] < pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 def quickSort(arr, low, high): if low < high: p...
def CountSort(arr, expElem): size = len(arr) output = [0] * size count = [0] * 10 for i in range(0, size): index = (arr[i] // expElem) count[int(index % 10)] += 1 for i in range(1, 10): count[i] += count[i - 1] i = size - 1 for i in range(size -1, -1, -1): ...
def ShellSort(arr): size = len(arr) gap = size // 2 while gap > 0: for i in range(gap, size): temp = arr[i] j = i while j >= gap and arr[j - gap] > temp: arr[j] = arr[j - gap] j -= gap arr[j] = temp gap //= 2 ...
def InsertionSort(arr): size = len(arr) for i in range(1, size): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key def display(arr): for i in range(len(arr)): print(arr[i], end = " ") # D...
#words = ["Lol", "Kek", "Cheburek"] #print(sum(words)) #how work sum # a=[1,2,3] # temp = 0 # temp+=a[0] # temp+=a[1] # temp+=a[2] x1= int(input()) y1= int(input()) x2= int(input()) y2= int(input()) if (x1+2 == x2 and y1+1==y2) or (x1+2 == x2 and y1-1==y2) or (x1-2 == x2 and y1+1==y2) or (x1-2 ==...
#! /usr/bin/env python # This converts a binary file into a text file written in hexadecimal with each # byte on a single line. # This is used to initialize memory. # # Usage: ./bin2hex.py <source> <dest> import sys infilename = sys.argv[1] outfilename = sys.argv[2] result = [] a = open(infilename, "rb") for c in ...
##### # bouncing_ball.py # # Creates a Scale and a Canvas. Animates a circle based on the Scale # (c) 2013 PLTW # version 11/1/2013 #### import Tkinter #often people import Tkinter as * ##### # Create root window #### root = Tkinter.Tk() ##### # Create Model ###### speed_intvar = Tkinter.IntVar() speed_intvar.set(...
def mouse(x,y): if x > 20 and x < 100 and y > 20 and y <100: return "YAY you're smart" else: return "Try again" def report_grade(percent): if percent >= 80: return "mastery" else: return "get good" def vowel(guess,word): if guess in word: return "correct" ...
# Topic : what are the words used in bad reviews. # For this research, you could add more juicy explorations such as # "among the common bad words used in bad reviews, what are those worst words, and what are not that bad". # To achieve this purpose, you could do a text classification to predict bad reviews using t...
""" 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 示例 1: s = "abc", t = "ahbgdc" 返回 true. 示例 2: s = "axc", t = "ahbgdc" 返回 false. 后续挑战 : 如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >...
""" Input:5 Output: True Explanation: 1*1 + 2*2 """ def judgeSquareSum(number): i, j = 0, number while i <= j: now = i*i + j*j if now == number: return True elif now < number: j -= 1 else: i += 1 return False
import unittest def fib(num :int) -> int: if num == 0: return 0 if num == 1: return 1 fib_n_minus_one = 1 fib_n_minus_two = 0 fib_n = 0 for i in range(num-1): fib_n = fib_n_minus_one + fib_n_minus_two fib_n_minus_two = fib_n_minus_one fib_n_minus_one...
class TreeNode(object): def __init__(self, name=None, parent=None, child=None, data=None): super(TreeNode, self).__init__() self.name = name self.parent = parent self.child = child if child else dict() self.data = data def get_child(self, name, defval=None): ret...
# reference:-https://www.geeksforgeeks.org/python-program-to-create-bankaccount-class-with-deposit-withdraw-function/ class bankAccount: def __init__(self, owner, balance): self.owner = owner self.balance = balance def deposit(self): amount = float(input("Enter amount to be deposited: ")) self.bala...
# -*- coding: utf-8 -*- ''' Coral Python 1 - DAT-119 Dice roller module example ''' import random def d4(): """gives us a random number from 1-4""" return random.randint(1, 4) def d6(): """gives us a random number from 1-6""" return random.randint(1, 6) def d8(): """gives us a random number from 1-8""" re...
print("Giá căn nhà dự án 1") d = float(input()) r = float(input()) print("Dài = ", str(d)) print("Rộng = ", str(r)) s = round(float(d) * float(r),2) print("Diện tích = " + str(s)) print("---") print("Nhập Công thức tính tiền mua nhà từ diện tích và giá nhà đã cung cấp: ") print("Nhập giá nhà mặt tiền Quận 9: "...
def addDB(dic,str1,str2): if str1 in dic: dic[str1] += [str2] else: dic[str1] = [str2] if str2 in dic: dic[str2] += [str1] else: dic[str2] = [str1] def findDB(dic,key): if key in dic: return dic[key] else: return [] def removeDB(dic,str1,str2):...
import random class Bug: def __init__(self,pos = 0): self.position = pos self.direction = 1 def move(self): if self.position >= 0: if self.direction == 1: self.position += 1 else: self.position -= 1 else: self....
import numpy as np A = np.array([[1,2,3],[4,5,6],[7,8,9]]) B = np.array([[1,2,3],[4,5,6],[7,8,9]]) newmatrix = [] i = 0 while i < len(A): eachrow = [np.sum(A[i]*B[:,j]) for j in range(len(A))] i += 1 newmatrix.append(eachrow) print(np.array(newmatrix)) print(np.dot(A,B))
import turtle turtle.showturtle() def Drawcircle(radius): turtle.speed(0) scaled_radius = radius/100 #bluecircle turtle.penup() turtle.left(180) turtle.forward(300*scaled_radius) turtle.left(90) turtle.pensize(7) turtle.pendown() turtle.color("blue") turtle.circle(radius) ...
class measure: def __init__(self,feet = 0, inches = None): if inches == None: self.inches = feet self.feet = 0 if feet >= 12: self.feet = feet // 12 self.inches = feet % 12 else: if inches < 12: self.feet...
import os import csv def phonebook(menu): if menu == 0: return False # Adding New address when menu = 1 elif menu == 1: newName = input("Enter New Name: ") newNum = int(input("Enter New Phone Number: ")) newAge = int(input("Enter New Age: ")) newAddress = input("Enter ...
import random import turtle def direction(): d = random.randint(1,4) if d == 1: turtle.left(0) turtle.forward(20) elif d == 2: turtle.left(90) turtle.forward(20) elif d == 3: turtle.left(180) turtle.forward(20) elif d == 4: turtle.left(270) ...
def emul(a,b): product = 0 if a < 0 and b < 0: a = -1 * a b = -1 * b if a >= b: big = a small = b else: big = b small = a while small != 0: if small%2 == 0: product = product else...
import turtle import random import math class Shape: def __init__(self,x = 0,y = 0,col = "",fill = False): self.x = x self.y = y self.color = col self.fillcolor = fill def setFillcolor(self,string): self.color = string def setFilled(self,bool): self.color =...
def slope(x1,x2,y1,y2): y_d = y2 - y1 x_d = x2 - x1 if x_d != 0: slope = y_d / x_d return slope else: return 0 def main(): a = float(input(str("Enter first x value: "))) c = float(input(str("Enter first y value: "))) b = float(input(str("Enter second x value: "))...