text
stringlengths
5
121k
""" Created on Thu Apr 11 08:10:49 2019 @author: prakhar prakash """ mat1 = [[1,2,3],[4,8,2],[1,5,3]] m = int(input('Enter the value of m')) n = int(input('Enter the value of n')) def mincostpath(mat1,m,n): dp = [[0 for x in range(len(mat1[0]))] for x in range(len(mat1)) ] dp[0][0]...
''' Write a program apply scaling on the image of the apple with scaling factor 2 on both x and y axes. ''' import cv2 as cv import numpy as np img = cv.imread('apple.jpg',0) rows,cols = img.shape dst = cv.resize( img,None, fx = 3, fy = 1, interpolation = cv.INTER_CUBIC ) cv.imshow(...
x = 3.14159 x_round = str(round(x)) x_point = x_round.find(".") print(x_round[:x_point]) s = "CidatyUcityda" print('1',s[6]+s[-2:]+s[7:12]) print('2',s[6]+s[-2:]+s[7:11]) print('3',s[6]+s[2:4]+s[7:13]) print('4',s[-7]+s[2:4]+s[7:11]) print('5',s[6]+s[-2]+s[3]+s[:-2]+s[4:6]) print('6...
spy = [1,2,2] def replace_spy(x): x[0] = x[0] x[1] = x[1] x[2] = x[2]+1 return x print(replace_spy(spy))
names=["sai","roshan","vishal","ranjan","ankit","shabid"] ages=[23,23,20,22,21,22] lenn=len(names) lena=len(ages) print(len(names)) print(len(ages)) n_a=[names,ages] print(n_a) print(len(n_a)) index=0 if lenn==lena: while index<lenn or lena: print(names[index],":",ages[index]) index+=1 print()
numbers=[50, 40, 23, 70, 56, 12, 5, 10, 7] index=count=0 while index<len(numbers): if numbers[index]>20 and numbers[index]<40: count+=1 else: pass index+=1 print(count) print()
a=[1,1,2,2,3,3,4,5,5,6,6,6,7,7,8,8,9] b=[i for i in a if a.count(i)>1] print(b) print() a=[1,1,2,2,3,3,4,5,5,6,6,6,7,7,8,8,9] b=[] for i in a: if a.count(i)>1: b.append(i) print(b) print() a=[1,1,2,2,3,3,4,5,5,6,6,6,7,7,8,8,9] b=[i for i in a if a.count(i)<2] print(b) print() a=[1,1,2,2,3,3,4,5,5,6,...
from operations import create, delete def main(): print("Please type an option from the following:") print("'create' or 'delete' records, or 'get' all records: ") option = input("create, delete or get: ") if option == "create": create() elif option == 'delete': delete() else...
import random as rnd import copy class SolutionDE: '''Defines particle for population''' def __init__(self, D): self.D = D self.Solution = [] self.numActiveFeatures = 0 self.F = 1.0 self.Cr = 0.9 self.Fitness = float('inf') self.gene...
""" __dict__ 是将对象所有的属性和其值变成字典的形式输出。 当我们定义新类的时候,如果是从object继承而来的,那么就也会继承__dict__这个属性 从而实现__dict__的功能。 但是并不是所有的对象都定义了__dict__这个属性。比如一些built-in对象,列表,字典 """ from __future__ import print_function def example1(): class Person(object): def __init__(self, name, date_of_birth): self.name = ...
""" ref = https://docs.python.org/2.7/library/pickle.html ref = https://docs.python.org/3.4/library/pickle.html 说明: python2和python3的pickle所产生的文件不能互通(虽然理论上 是可以通过设定protocol来兼容,但是由于写操作的作用机理不同, 所以很容易导致不可预见的错误) 用法: pickle.dump(object, open("fname.p", "w")) """ from __future__ import print_...
def isSolved(board): finish_or_not = True for line in board: winner, finish_or_not = check_line(line, finish_or_not) if winner == 1 or winner == 2: return winner for col in range(0, 3): winner, finish_or_not = check_line([board[0][col], board[1][col], board[2]...
scores = {'x\n' : -1, 'o\n' : 1, '\n' : 0} def summarize(file): summary = [] total = 0 count = 0 for line in open(file): count += 1 total += scores[line] if count == 1000: summary.append(total / float(count)) total = 0 count = 0 return s...
import random def random_phone_number(): second = [3, 4, 5, 7, 8][random.randint(0, 4)] third = { 3: random.randint(0, 9), 4: [5, 7, 9][random.randint(0, 2)], 5: [i for i in range(10) if i != 4][random.randint(0, 8)], 7: [i for i in range(10) if i not in [4, 9]][rand...
def extended_gcd(n1, n2): """Return (bezout_a, bezout_b, gcd) using the extended euclidean algorithm.""" x, lastx = 0, 1 y, lasty = 1, 0 while n2 != 0: quotient = n1 // n2 n1, n2 = n2, n1 % n2 x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y bezout_a...
def spin_words(sentence): index=1 my_array=[] while index < (len(sentence) + 1): my_array.append(sentence[(len(sentence)- index)]) index += 1 my_array="".join(my_array) return my_array print(spin_words('sroirraw wollef yeH'))
def split_into_digits(number): digits = [] while number: digit = number % 10 digits.append(digit) number //= 10 digits.reverse() return digits def is_matching(digits): found_twins = False for d in range(1, 6): if digits[d] < digits[d-1]: re...
import math grid_size = 10000 def combined_distance_to_first_crossing(lines): line1 = draw_line(lines[0]) line2 = draw_line(lines[1]) crossings = find_all_crossings(line1, line2) distances = [] for crossing in crossings: combined_distance = distance_til_crossing(line1, crossing) + distanc...
array = ["rock", "scissor", "paper"] player_1 = input("Player-1, Enter your name: ") player_2 = input("Player-2, Enter your name: ") def game(): while True: shoot_1 , shoot_2 = input(player_1 + " and " + player_2 + " shoot-- ").lower().split(',') if shoot_1 and shoot_2 in array: ...
""" Created on Tue Aug 21 23:59:02 2018 @author: Gerson """ """ ======================================== Create 2D bar graphs in different planes ======================================== Demonstrates making a 3D plot which has 2D bar graphs projected onto planes y=0, y=1, etc. """ from mpl_toolkits.mplot3d import ...
print("Ingresa el primer valor:") Num1 = int(input()) print("Ingresa el segundo valor:") Num2 = int(input()) Suma = Num1 + Num2 Resta = Num1 - Num2 Multiplicacion = Num1 * Num2 Division = Num1 / Num2 print("El resultado es:" * Suma)
import turtle def sur_draw(size, n): if n == 0: turtle.forward(size) else: sur_draw(size / 3, n - 1) turtle.right(75) sur_draw(size / 3, n - 1) turtle.left(120) sur_draw(size / 3, n - 1) turtle.right(75) sur_draw(size / 3, n - 1) ...
def sevens(): num = 7 while True: num = num*10+7 yield num if __name__ == '__main__': K = int(input()) for i, sv in enumerate(sevens()): if sv%K==0: print(sv) print(i+2) quit() if K<=i: print(-1) quit() ...
import time import effects when = input("Current 24 hr time: ") hr = int(str(when)[:2]) min = int(str(when)[-2:]) hr *= 3600 min *= 60 when = hr + min print(hr, min, when) length = input("How long in minutes? ") length *= 60 start = time.time() end = time.time() firstRun = True diff1 = time.time() diff2 = time.time() ...
import csv import sys def get_actions_list(data_doc): """Load CSV and format data. Args: data_doc ([.CSV]): [.csv file with invest data] Returns: [list]: [name, price, profit] """ with open(data_doc) as csv_file: csv_list = list(csv.reader(csv_file)) actions_li...
print("hello world") nums = [1,2,3,4] answerList = [] def DecompressRLElist(list): lengthOfList = len(nums) for i in enumerate(nums): counter = nums[i] while counter != 0: an print (len(nums))
candies = [2,3,5,1,3] extraCandies = 3 boolList = [] for i in candies: currentKidCandyCount = i + extraCandies if currentKidCandyCount >= max(candies): boolList.append(True) else: boolList.append(False) print(boolList)
def add(x,y): return x+y def subtract(x,y): return x-y def multiply(x,y): return x*y def divide(x,y): return x/y print("Select operation:") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: choice = input("Enter a choice(1/2/3/4):") if choice in ('...
year = int(input("Enter a leap year:")) if (year%4 == 0 and year%100 !=0 or year%400==0 ): print("The year is a leap year") else: print("The year is not a leap year")
s=str(input("dati sirul: ")) import string sm=0 smic=0 sp=0 special_chars=string.punctuation for i in s: if i in string.ascii_uppercase: sm=sm+1 elif ((ord(i)<=57) and (ord(i)>=48)): smic=smic+1 if i in special_chars: sp=sp+1 print("Nr de majuscule este ",sm) print("...
import math import random class tree: def _insert(self, root, num): if num < root[1]: if root[0]: return 1 + _insert(root[0], num) else: root[0] = [None, num, None] return 1 else: if root[2]: return...
import random highest = 10 num = random.randint(1, highest) guess = -1 while guess != num: guess = int(input("Guess number between 1 and {}: ".format(highest))) if guess > num: print("Lower...") elif guess < num: print("Higher....") else: print("Got it!")
import random def word_check(wch): word_list = list(wch) new_word = "" for i in word_list: if i in ['0', '1']: new_word += i return new_word def triad_check(word): word_list = list(word) for i in range(3, len(word)): tri = word_list[i - 3] + word_list[i - 2] + wor...
def FindContinuousSequence(tsum): if tsum < 3: return [] small = 1 big = 2 middle = tsum + 1 / 2 res = [] while small < middle and small < big: curSum = (small + big)*(big-small+1)/2 if curSum == tsum: res.append([i for i in range(small,big+1)]...
import random import math def get_andomNumber(num): lists=[] i=0 while i<num: lists.append(random.randint(0,100)) i+=1 return lists def adjust_heap(lists, NodeI, size): """ NodeI: 节点的序号 lchild: 该节点左孩子的序号 rchild: 该节点右孩子的序号 ...
""" Created on Thu Aug 29 15:28:51 2019 @author: amanz """ import time start = time.time() def read_file_and_make_set(): file_set = set(open('words_alpha.txt').read().split()) return file_set ...
''' Is the way you wrote the second program influenced by writing the first? The two questions are quite similar, so I could've written one answer function for two questions. However, The entries in the two questions are still different, for example a number might contain a '*' in one file but not in the other, so I d...
class SelectMenu: def __init__(self, items): self.items = items def __str__(self): return '\n'.join(self.get_menu_items()) def get_menu_items(self): menu_items = [] for index, item in enumerate(self.items, start=1): menu_items.append(f"{index}. Movie title: {ite...
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Dropout, Flatten, Dense from tensorflow.keras.models import Model from tensorflow.keras.layers import PReLU def CNN(input_shape=(48, 48, 1), n_classes=8): """ 参考论文实现 A Compact Deep Learning Model for Robust Facial Expression Recognition ...
""" 10-701 Introduction to Machine Learning Final Project Generalized Disjunctive Programming (GDP) Reformulation Classification using Neural Network Neural Network Implementation using TensorFlow """ from __future__ import print_function import numpy as np import pandas as pd import matplotlib.pyplot as plt random...
message = "Hello Eric, would you like to learn some Python today?" print(message) name = "Eric" print(name.upper()) print(name.lower()) first_name = "Eric" full_name = f"{first_name} " message = f'Albert Einsten once said, "A person who never made a mistake never tried anything new.", {full_name.title()}!' ...
import argparse import requests def scan_cves(affected_operating_systems_file): with open(affected_operating_systems_file, 'r') as f: affected_operating_systems = [line.strip() for line in f] url = 'https://services.nvd.nist.gov/rest/json/cves/1.0' params = { 'resultsPerPage': '20', ...
def insert(): try: employeeid = raw_input("Enter Employee Id:") employeename = raw_input("Enter employee Name") db.employees.insert_one( { "id": employeeid, "name": employeename } ) except Exception as ex: print("exc...
print('Number Guessing Game') print('Guess a Number (between 1 and 9):') import random number = random.randint(1,9) print(number) for i in range(0,5,1): userInput = int(input('Enter your Guess :- ')) if userInput < 3: print('Your guess was too low: Guess a number higher than 3') elif userInput < 5...
x = int(input("Ingrese un numero:")) exp = int(input("Ingrese su exponente:")) producto = x for i in range(exp-1): print(x, producto, i) producto = producto*x print("%s^%s = %s" % (x, exp, producto)) print("Comprobacion", x**exp)
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("./mnist/data/", one_hot=True) x_train = mnist.train.images y_train = mnist.train.labels x_val = mnist.test.images y_val = mnist.test.labels prin...
from abc import ABCMeta, abstractmethod class Queue(metaclass = ABCMeta): @abstractmethod def enqueue(self,data):pass @abstractmethod def dequeue(self):pass @abstractmethod def first(self):pass @abstractmethod def size(self):pass @abstractmethod def isEmpty(self):pass
""" Created on Fri Oct 4 10:05:22 2019 Project Euler 8: Largest product in series @author: zentai Given a list, 1000 long. Multiply the near 4 elements, and determine the biggest value given sequence. New N is 13 here. How to loop properly throug of the list with 4 elements. kell egy 4 len multiply resz, ami tudja...
""" Created on Thu Oct 3 16:25:32 2019 Project Euler 10: Summation of primes @author: zentai Loop for 2 million, and detect all primes, and during the loop, sum them up. """ import math import time start = time.time() def is_prime(number): if number > 1: if number == 2: return 2 ...
import pygame import math import time pygame.init() white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (0,255,0) blue = (0,0,255) displayWidth = 800 displayHeight = 600 myfont = pygame.font.SysFont("arial", 25) clock = pygame.time.Clock() gameDisplay = pygame.display.set_mode((displayWidth,displayHe...
def encrypt(contents, key): result = "" for n in range(1, key + 1): if n == 1: distance = 2 * key - 3 count = 0 for letter in contents: if count == 0: result += letter if count == distance: ...
def Display(iNo): while(iNo>0): print("*") iNo-=1 def main(): iNo = int(input("Enter a number :\n")) Display(iNo) if __name__ == '__main__': main()
def standardize_keyword(token): """ In returned result, all keywords are in upper case.""" return token.upper() def join_tokens(lst, token): """ While joining each element in 'lst' with token, we want to make sure each word is separated with space. """ _token = token.strip(' ') if ...
""" This script print time in hours """ def minutes_to_hours(minutes, seconds): hours = minutes / 60 + seconds / 3600 return hours print(minutes_to_hours(70, 300))
""" Numeric Integer: Positive or negative whole numbers (without a fractional part) Float: Any real number with a floating point representation in which a fractional component is denoted by a decimal symbol or scientific notation Complex number: A number with a real and imaginary component represen...
""" Created on Thu Nov 14 14:20:42 2019 @author: sullia4 """ def clear_board(): board= [] for a in range(6): board.append(['.'] * 7) return board def row_num(col, board): n = int(len(board) - 1) while True: if board[n][col] == ".": return n n-...
def main(): while(True): print(">>") text = str(input("Enter cmd: ")).upper() text = get_new_hex(text) print(text) def add_colon(text): text = text.strip() if(text[0] != ':'): text = ':' + text return text def get_new_hex(text): try: text = add_colon...
""" Fill out the functions to calculate the area and circumference of a circle. Print the result to the user. """ import math def area(r): return math.pi * r ** 2 def circumference(r): return math.pi * 2 * r radius = float(input("Circle radius: ")) circle_area = area(radius) circle_circumference = circu...
def Calc(a,b ): x = a + b y = a - b z = a * b u = a / b return (x, y, z, u) result = Calc(10, 5) print(result)
import json from urllib.request import urlopen class LoadJsonData: data = [] def getData(self): return self.data '''Reading json file''' class ReadJsonFile(LoadJsonData): def __init__(self, fileName): self.fileName = fileName def read(self): with open(self.fileName, "r", e...
from threading import * class MyThread(Thread): def run(self) -> None: print(current_thread().getName()) i = 0 while (i < 10): print(i) i += 1 t = MyThread() t.start() print(current_thread().getName())
num = int(input('Enter a number: ')) if num == 0: print('Zero') elif num%2 == 0: print('Even number') else: print('Odd number')
'''Load Json to Dictionary, loads raw Json data into Multivalue dictionary''' import operator from functools import reduce from itertools import chain from collections import defaultdict '''Merge two dictionaries''' def Merge(dict1, dict2): res = {**dict1, **dict2} return res '''Retaining key, and appending ...
from threading import * from time import * class Producer: def __init__(self): self.products =[] self.c = Condition() def produce(self): self.c.acquire() for i in range(1, 5): self.products.append("Product_" + str(i)) sleep(1) print("Product ...
import flask app=flask.Flask(__name__) @app.route("/", methods =['GET']) def helloworld(): return "Helloworld" if __name__ == '__main__': app.run()
def findMid(head): slow = head fast = head while( temp_fast.next &temp_fast.next.next): temp_slow = temp_slow.next temp_fast = temp_fast.next.next if not(temp_fast.next): return temp_slow else: return temp_slow.next ...
def checkBalanced(str): s=[] res= True top=-1 for e in str: if top==-1: s.append(e) top+=1 else: if e == "{" or e=="[" or e=="(": s.append(e) top+=1 else: if (e=="...
class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def build(pS,pE,iS,iE): if pE-pS<=0: return None for i in range(iS,iE): if postorder[pE-1]==inorder[i]: return TreeNode(postorder[pE-1]...
__author__ = 'harineem' import math def isPrime(n) : if(n==2 or n==3 or n==5 or n==7 or n==11): return True if(n%2==0 or n%3==0 or n%5==0 or n%7==0 or n%10==0): return False x = int(n/2); for k in range(11,x,1): if(n%k==0): return False return True n = 600851475143 m = int(math.sqrt(n)...
def frequency_dict_from_collection(collection): """ This is a useful function to convert a collection of items into a dictionary depicting the frequency of each of the items. :param collection: Takes a collection of items as input :return: dict """ assert len(collection) > 0, "Cannot perform the ope...
from numpy import * class Kalman(object): """The standard implementtation of the object tracking using Kalman filters""" def __init__(self): """Initialising constants required for calculations""" self.F = matrix([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],dtype = 'float') self.H = matrix([[1,0,0,0],[0,1,0,0]...
print("hello im your doctor") temperature = input("Temperature = \n" ) if int(temperature) >= 38: print("Got COVID!") else: print("Demam biasa2") print("Thanks For Coming To Our Clinic")
def outer_func(mg): def inner_func(): print(mg) return inner_func hi_func = outer_func('hi') hello_func = outer_func('hello') hi_func() hello_func() def decorator_func(original_func): def wrapper_func(*args, **kwargs): print(f"wrapper function executed {original_func.__n...
def square_nums(nums): result = [] for i in nums: result.append(i * i) return result sq_nums = square_nums([1, 2, 3, 4, 5]) print(sq_nums) def square_nums(nums): for i in nums: yield (i * i) sq_nums = square_nums([1, 2, 3, 4, 5]) print(sq_nums) print(next(sq_nums)) for num...
def square(x): return x * x f1 = square(5) f = square print(f) print(f(5)) print(f1) def square(x): return x * x def my_map(func, arg_list): result = [] for i in arg_list: result.append(func(i)) return result squares = my_map(square, [1, 2, 3, 4]) print(squares) ...
from turtle import Turtle, Screen window = Screen() window.bgcolor("black") elsa = Turtle() elsa.speed("fastest") elsa.pencolor("White") elsa.fillcolor("White") elsa.penup() def DrawFlower(nPetals): elsa.pendown() for Petal in range(nPetals): for i in range(2): elsa.forward(50) ...
import random CLOCKWISE = 1 COUNTERCLOCKWISE = 0 class StepperMotor: def __init__(self): self.counter_A = 0 self.counter_B = 0 self.counter_I = 0 self.cur_rel_pos = 0 self.last_signal_A = False def reset(self): while not self.check_end(): ...
def start_hangman(): print("Let's Start playing Hangman!") def start_hangman(): print("Let's Start playing Hangman!\n") man1 = """ ____ | | | | | _|_ | |_____ | | |_________| """ man2 = """ ____ | | | o | ...
A = [3, 2, -2, 5, -3] def solution(A): positive = [] negative = [] result = [] for n in A: if n > 0: positive.append(n) elif n < 0: negative.append(n) for ne in negative: if abs(ne) in positive: result.append(ne) if len(result) == 0...
def multiple(n, a): if(n == 1): return a return multiple(n-1, a) + a result = multiple(4, 5) print(result)
import requests from bs4 import BeautifulSoup def crawl(codeNum): url = "https://finance.naver.com/item/main.nhn?code={}".format(codeNum) data = requests.get(url) return data.content def getCompanyInfo(string): bsObj = BeautifulSoup(string, "html.parser") wrapCompany = bsObj.find("div", {"clas...
import requests from bs4 import BeautifulSoup def crawl(url): data = requests.get(url) print(data, url) return data.content def parse(pageString): bsObj = BeautifulSoup(pageString, "html.parser") noToday = bsObj.find("p", {"class":"no_today"}) blind = noToday.find("span", {"class":"blind...
splitted = "hello world bye".split(" ") print(splitted[1]) targetString = "aa=19" start = len(targetString) - 3 end = len(targetString) result = targetString[start:end] print(result.replace("=", ""))
def f(param1): return param1 + 10 def g(param1): return param1 * 20 print(f(g(10)))
import pandas as pd from r2de.constants import ( CORRECT_HEADER, DESCRIPTION_HEADER, QUESTION_ID_HEADER, QUESTION_TEXT_HEADER, ) def generate_correct_answers_dictionary(answers_text_df: pd.DataFrame) -> dict: """ Given the dataframe containing the text of the answers (i.e. possible choices), i...
print("Learning Python is fun and enjoy it.") a = 2 print("The value of a is", a) print(1, 2, 3, 4) print(1, 2, 3, 4, sep='+') print(1, 2, 3, 4, sep='+', end='%') print()
"""Retrive and print words from a URL. Usage: python3 words.py <url> """ import sys def fetch_words(url): """Fetch a list of words from a URL. Args: url: The url of UTF-8 text document. Returns: A list of strings containing the words from the document. "...
to_sort_list = [1, 10, 9, 4, 5, 3] def quick_sort(sort_list): left_list, middle_list, right_list = [], [], [] if len(sort_list) == 0: return [] pivot = sort_list[0] for item in sort_list: if item < pivot: left_list.append(item) elif item == pivot: midd...
with open('input.txt', 'r') as f: nums = [int(n) for n in f.readlines()] for i in range(len(nums)): for j in range(len(nums)): for k in range(len(nums)): if nums[i] + nums[j] + nums[k] == 2020: print(nums[i]*nums[j]*nums[k]) exit()
""" Is it Time for Milk and Cookies? Christmas Eve is almost upon us, so naturally we need to prepare some milk and cookies for Santa! Create a function that accepts a Date object and returns True if it's Christmas Eve (December 24th) and False otherwise. Examples: time_for_milk_and_cookies(datetime.date(2013, 12, 24...
""" Return the Factorial Create a function that takes an integer and returns the factorial of that integer. That is, the integer multiplied by all positive lower integers. Examples: factorial(3) ➞ 6 factorial(5) ➞ 120 factorial(13) ➞ 6227020800 Notes: Assume all inputs are greater than or equal to 0. """ def facto...
""" Index Multiplier Return the sum of all items in a list, where each item is multiplied by its index (zero-based). For empty lists, return 0. Examples: index_multiplier([1, 2, 3, 4, 5]) ➞ 40 # (1*0 + 2*1 + 3*2 + 4*3 + 5*4) index_multiplier([-3, 0, 8, -6]) ➞ -2 # (-3*0 + 0*1 + 8*2 + -6*3) Notes All items in the lis...
from abc import ABC, abstractmethod from typing import Dict from src.domain.models import Accounts class WithdrawAccount(ABC): """Interface for Withdraw Account use case""" @abstractmethod def withdraw(self, account_id: int, amount: float) -> Dict[bool, Accounts]: """Withdraw Account use case""" ...
import pygame import random pygame.init() class Fallingobject(pygame.sprite.Sprite): def _init_(self): pygame.sprite.Sprite._init_(self) self.timecreated = pygame.time.get.ticks() self.image = pygame.Surface({30,30}) ...
def heapify(the_list, length, i): largest = i left = 2*i+1 right = 2*i+2 if left<length and the_list[i]<the_list[left]: largest = left if right<length and the_list[largest]<the_list[right]: largest = right if largest!=i: the_list[i],the_list[largest]=the_list[largest],the_list[i] heap...
class node(object): def __init__(self, data, next_node = None): self.data = data self.next_node = next_node def get_next(self): return self.next_node def set_next(self, next_node): self.next_node = next_node def get_data(self): return self.data def set_data(self,data): self.data = data clas...
A = True B = True expressao = not (A and B) if expressao: print ("Deu certo!"); print ("Terminou.");
A = True B = True resultado = A or (not B) A = False B = True resultado = A or (not B) A = False B = False resultado = (not A) or B A = True B = False resultado = (not A) and B A = True B = False resultado = (not A) and (not B) A = False B = False resultado = not ((not A) and (not B)) A = True B = True resu...
r1={ "#":1, "name":"huy", "level":25, "hour":14, } r2={ "#":2, "name":"hoa", "level":20, "hour":7, } r3={ "#":3, "name":"tam", "level":15, "hour":20, } salary_list=[r1, r2, r3] total_wage =0 wage_list= [] for salary in salary_list: name = salary["name"] ...
menu_items = ["pho bo", "my xao", "com rang"] n =int(input("vi tri ma ban muon update ")) new =input("ban muon thay doi gi :") menu_items[n-1] =new print(*menu_items, sep=" ")