text
stringlengths
37
1.41M
import random class BinaryHeap(object): def __init__(self): self.heap = [] # * * * * * # Pushes an element into the heap # * * * * * def push(self, x): self.heap.append(x) self.heapifyUp(self.size() - 1) # * * * * * # Pops an element out of the heap ...
class MyStack: def __init__(self): self.__myStack = [] def show(self): return self.__myStack def isEmpty(self): return self.__myStack == [] def push(self, x): self.__myStack = [x] + self.__myStack def pop(self): self.__myStack = self.__myStack[1:] de...
from pyfirmata import Arduino, util import time # Class for handling calls to the soil sensor. class SoilSensorValues(object): temperature = 0.0 humidity = 0.0 def __init__(self, board): '''Set up the board callbacks''' self.board = board self.board.add_cmd_handler(0x04, self.hand...
import itertools def dict_cross_product(atosetb): """Takes a dictionary mapping values of type a to sets of values of type b (think of it as having buckets of bs labeled with as) and return an iterable of dicts representing all possible combinations of choosing one element out of each bucket. """ ...
""" Вычисление среднего суммы и количества """ import random def random_list(length): """ full random list with length length""" numbers = [] for num in range(length): numbers.append(random.randint(0,100)) return numbers def average(values): average = 0.0 for value in values: average+=value return (ave...
friends = ['andrey','tanya','ira'] for friend in friends: print ('Happay',friend) print ('Done') import random def mini(values): smallest = None for value in values: if smallest is None or value<smallest: smallest=value return smallest count = 0 total = 0 largest = 0 for iterval in range(10): count = coun...
#get name and age and output year they will turn 100 years old name = str(input("Enter in your name: ")) age = int(input("Enter in your age: ")) hunnid = 100 - age print("Your name is ", name, " and you will be 1 hundred year old in the year ", str(int(2018 + hunnid))) #extras 1: output = int(input("Enter in a n...
''' Purpose :- To get more familier with if else logic Author :- Dipayan Dutta ''' #read first number first_number = input("Enter First Number[integer only] ") #read second number second_number = input ('Enter second number [integer only] ') #now checking starts if (first_number == second_number): print "Both...
value = input().split() a, b = value a = int(a) b = int(b) if a>b: if a%b == 0: print("Sao Multiplos") else: print("Nao Sao Multiplos") if b>a: if b%a == 0: print("Sao Multiplos") else: print("Nao Sao Multiplos") if a==b: print("Sao multiplos")
x = input().split() x = list(map(float,x)) a, b, c = sorted(x)[::-1] go = True if a>=b+c: print("NAO FORMA TRIANGULO") go = False if a**2 == ((b**2)+(c**2)) and go: print("TRIANGULO RETANGULO") if a**2 > ((b**2)+(c**2)) and go: print("TRIANGULO OBTUSANGULO") if a**2 < ((b**2)+(c**2)) and go: p...
import turtle turtle.goto(0,0) up = 0 down = 1 right = 2 left = 3 direction = None def UP(): global direction direction = up print("you pressed the UP key") on_move() turtle.onkey(UP, "Up") #turtle.listen() def DOWN(): global direction direction = down print("you pressed the DOWN ke...
text = input("Enter Your Text: \n").title() for i in ['.' , '?' , '/' , '!' , '<' , '>' , ','] : text = text.replace(i," ") words_list , counter = list(filter(lambda x : x !="", text.split(" ") )) , dict() for i in set(words_list) : counter[i] = words_list.count(i) for i in counter : print(f" {i} : {counter[i]} ") ...
import tkinter as tk from tkinter import StringVar import math win = tk.Tk() win.title("Calculator") win.resizable(False, False) xPos = int(win.winfo_screenwidth()/2 - win.winfo_reqwidth()) yPos = int(win.winfo_screenheight()/2 - win.winfo_reqheight()) win.geometry("+{}+{}".format(xPos, yPos)) win.geometry...
import datetime now = datetime.datetime.now() pre = datetime.datetime(2018,9,8) print(now) print(pre) print(now>pre) #최근 날짜가 더 큼 print(type(now)) print(type(pre)) test_date = "2018-09-07 18:58:09" convert_date = datetime.datetime.strptime(test_date, "%Y-%m-%d %H:%M:%S") print(convert_date) print(type(convert_date))...
# Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. # https://drive.google.com/file/d/1HukSj3fYH8tXmKDe1MjwcJUlp58W1QMs/view?usp=sharing number = int(input("Введите трёхзначное число")) a = number%10 number = number//10 b = number%10 number = number//10 c = number%10 print(a+b+c) print(a...
import re pattern = '^[aeiou]\w*[^aeiou]$' #pattern starts with vowel, any alphanumeric in between and ends with cons def isGoodWord(inStr): res = inStr.split() #splits the string using any delimiter. default is space for i in range(0,len(res)): if(re.match(pattern, res[i].lower())): #matches the pa...
twice = '' print(type(twice)) freq_dict = {} frequency = 0 while isinstance(twice, int) == False: with open('adventofcode1_input.txt','r') as file: for lines in file: lines = lines.rstrip("\n") frequency += int(lines) if frequency not in freq_dict: f...
words = input().split(' ') searched_word = input() palindromes_words = list(filter(lambda x: x == x[::-1], words)) count = palindromes_words.count(searched_word) print(palindromes_words) print(f'Found palindrome {count} times')
def command(a): result = [] if a == 'even': for even in numbers: if even % 2 == 0: result.append(even) elif a == 'odd': for odd in numbers: if odd % 2 != 0: result.append(odd) elif a == 'negative': for negative in numbers...
size = int(input()) current = 1 step = 1 for row in range(size * 2): for col in range(0, current): print('*', end='') if current == size: step = -1 current += step print()
command = input() coffees_count = 0 while command != 'END' and coffees_count <= 5: if command.islower(): if command == 'coding': coffees_count += 1 elif command == 'dog' or command == 'cat': coffees_count += 1 elif command == 'movie': coffees_count += 1 ...
def fix_calendar(nums): while True: counter = 0 for i in range(len(nums)): if i < len(nums) - 1: if nums[i] > nums[i + 1]: nums[i], nums[i + 1] = nums[i + 1], nums[i] break else: counter += 1 ...
n = int(input()) for i in range(1, n + 1): digit = i sum = 0 while i: sum += i % 10 i //= 10 if sum == 5 or sum == 7 or sum == 11: print(f'{digit} -> True') else: print(f'{digit} -> False')
even = set() odd = set() for i in range(1, int(input()) + 1): name_sum = sum([ord(x) for x in input()]) // i if name_sum % 2 == 0: even.add(name_sum) else: odd.add(name_sum) if sum(even) == sum(odd): arg = list(map(str, even.union(odd))) print(", ".join(arg)) elif sum(even) < sum(...
n = int(input()) open = False balanced = True for i in range(n): letter = input() if open: if letter == ')': open = False continue if letter == '(': open = True if letter == ')': balanced = False if not open and balanced: print('BALANCED') else: pr...
word = input() while word != "end": print(f"{word} = {word[::-1]}") word = input()
class Party: def __init__(self): self.party_people = [] self.party_people_counter = 0 party = Party() people = input() while people != 'End': party.party_people.append(people) party.party_people_counter += 1 people = input() print(f'Going: {", ".join(party.party_people)}') print(f'T...
queue = list(reversed(input().split(', '))) wolf_found = False if queue[0] == 'wolf': print('Please go away and stop eating my sheep') wolf_found = True if not wolf_found: for animal in range(len(queue) - 1, -1, -1): if queue[animal] == 'wolf': print(f'Oi! Sheep number {animal}! You ar...
year = int(input()) + 1 year = str(year) not_happy_year = True while not_happy_year: is_valid = True for digit in year: if year.count(digit) > 1: year = int(year) + 1 year = str(year) is_valid = False break if is_valid: not_happy_year = Fals...
def smallest_number(num1, num2, num3): smallest = min(num1, num2, num3) return smallest number_1 = int(input()) number_2 = int(input()) number_3 = int(input()) print(smallest_number(number_1, number_2, number_3))
word_to_remove = input() sequence = input() while word_to_remove in sequence: sequence = sequence.replace(word_to_remove, '') print(sequence)
cars_in_parking = set() for _ in range(int(input())): direction, car_number = input().split(", ") if direction == "IN": cars_in_parking.add(car_number) else: cars_in_parking.remove(car_number) if cars_in_parking: print("\n".join(cars_in_parking)) else: print("Parking Lot is Empty"...
longest_intersection = [[]] for i in range(int(input())): data = input().split("-") first_start, first_end = list(map(int, data[0].split(","))) second_start, second_end = list(map(int, data[1].split(","))) first = set(x for x in range(first_start, first_end + 1)) second = set(x for x in range(seco...
import math, random print 'Rounded Up 9.5:', math.ceil(9.5) print 'Rounded Down 9.5:', math.floor(9.5) num = 4 print num, 'squared:', math.pow(num, 2) print num, 'squared root:', math.sqrt(num) # 6 random numbers from list nums = random.sample(range(1, 49), 6) print 'Lucky numbers are:', nums # inaccurate item = 0....
class Node(object): def __init__(self,value): self.value=value self.nextnode=None self.prevnode=None a=Node(1) b=Node(2) c=Node(3) a.nextnode=b b.nextnode=c c.prevnode=b b.prevnode=a
def insertion_sort_recursive(A,n,next_el): if(next_el>=n-1): return pos = next_el temp = 0 while (pos > 0 and A[pos] < A[pos - 1]): temp = A[pos] A[pos] = A[pos - 1] A[pos - 1] = temp pos = pos - 1 insertion_sort_recursive(A,n,next_el+1) return print(ins...
'''Recursive Version of Binary Search def rec_bin_search(arr,ele): # Base Case! if len(arr) == 0: return False # Recursive Case else: mid = len(arr)/2 # If match found if arr[mid]==ele: return True else: # Call again on second half ...
'''Sentence Reversal Problem Given a string of words, reverse all the words. For example: Given: 'This is the best' Return: 'best the is This' As part of this exercise you should remove all leading and trailing whitespace. So that inputs such as: ' space here' and 'space here ' both become: 'here space' ...
''''Finding the sum of n numbers recursively''' def recursion_n_num(n): if(n==1): return 1 elif(n==0): return 0 else: return n+recursion_n_num(n-1) print(recursion_n_num(4))
#implementation of Deques in Python class Deque(): def __init__(self): self.items=[] def addFront(self,item): return self.items.append(item) def addRear(self,item): return self.items.insert(0,item) def removeFront(self): return self.items.pop() def removeRear(self): ...
# save actual stdin in case we need it again later STD_IN = [ '5', '2 3 6 6 5', ] def input(): return STD_IN.pop(0) from itertools import product if __name__ == '__main__': n = int(input()) data = map(int, input().split(' ')) data = sorted(list(set(data))) print(data[-2])
""" Implement a function that replaces 'U'/'you' with 'your sister' Handle duplicate 'u's smartly. """ import re TARGET = 'u' TOKEN = '*' REPLACE_STRING = 'your sister' # def autocorrect(input): # Alternative with regexes! # return re.sub(r'(?i)\b(u|you+)\b', "your sister", input) def autocorrect(input_string):...
# coding=utf-8 # Kata: Simulate the game 'SNAP!' # Features: # - Allow variable number of standard 52-card decks # - Allow for several 'matching' conditions: either match just suit, or just rank, or match on both. # ---- # Thanks to (awesome!) 'Fluent Python' book for inspiration for the Deck class. # see: Fluent ...
""" Implement a function to check if a Mongo database ID is valid """ from datetime import datetime from collections import namedtuple Mongo_id = namedtuple('Mongo_id', ['timestamp', 'machine_id', 'process_id', 'counter']) class Mongo(object): MONGO_ID_LEN = 24 @classmethod def length_valid(cls, s): ...
from collections import defaultdict, Counter def runoff(voters): """ a function that calculates an election winner from a list of voter selections using an Instant Runoff Voting algorithm. https://en.wikipedia.org/wiki/Instant-runoff_voting Each voter selects several candidates in order of preference. ...
""" Given 2 points find the slope of the line between them. """ UNDEFINED_SLOPE = "undefined" def calculate_slope(x1, x2, y1, y2): return (y2 - y1) / (x2 - x1) def find_slope(points): x1, y1, x2, y2 = points try: r = calculate_slope(x1, x2, y1, y2) return str(r) except ZeroDivision...
#List to act as stack to hold the opening brackets stack = [] #string holding the set of parentheses string = '()[]{}' #validity check validState = False for char in string: if char in '[({': stack.append(char) elif char in '])}': if len(stack) == 0: validState = False ...
# https://www.interviewcake.com/free-weekly-coding-interview-problem-newsletter import random def shuffle(l): for i in range(len(l)): swap_index = random.randint(0, len(l) - 1) if swap_index != i: tmp = l[i] l[i] = l[swap_index] l[swap_index] = tmp return ...
def solution(arr: []): start = arr[-1] curr = start for _ in range(len(arr)): print('going to the loo') curr = arr[curr] number_in_loop = curr loop_len = 1 while arr[curr] != number_in_loop: curr = arr[curr] loop_len += 1 curr1 = start curr2 = start ...
def add(a: str, b: str) -> str: x, y = int(a, 2), int(b, 2) print('a:', x, 'b:', y) while y: print('x:', bin(x), 'y:', bin(y)) answer = x ^ y carry = (x & y) << 1 x, y = answer, carry return bin(x)[2:] result = add('11111', '1111') print('answer:', result, '({0})'.fo...
from math import floor, sqrt # def simple_sieve(n): # sieve = [True] * (n + 1) # sieve[0] = sieve[1] = False # # for i in range(2, int(sqrt(n)) + 1): # while i**2 <= n: # if sieve[i]: # if i is still potentially composite # for k in range(i ** 2, n + 1, i): # sieve[k]...
from math import sqrt, floor # coins 1..n # initially all coins showing heads # n people turn over coins as follows: person i flips coins with numbers that are multiples of i # count the number of coins showing tails after all people have had a turn def coins(n): count = 0 # True - tails, False - heads ...
from typing import List # we'll present a single (particular) solution by a list of col positions with indices representing rows # e.g. [1, 3, 0, 2] - queen at row 0 is at column, queen at row 1 is at column 3, etc. def n_queens(n: int) -> List[List[int]]: # find all the ways we can put the n queens result: Li...
def gcd(a, b): if b == 0: return a return gcd(b, a % b) # gdc(x, y) will contain the common prime factors of x and y # when we start dividing x and y to the greatest common divisor we will reach either 1 or a primer factor that is # not in gdc(x, y) def solution(A, B): count = 0 for a, b in ...
import math from typing import List class Point: def __init__(self, x, y): self.x = x self.y = y def dist_to(self, p: 'Point'): d_pow_2 = (self.x - p.x)**2 + (self.y - p.x)**2 return math.sqrt(d_pow_2) def __add__(self, p: 'Point'): return Point(self.x + p.x, sel...
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. import collections from python_toolbox import sequence_tools class SelectionSpace(sequence_tools.CuteSequenceMixin, collections.abc.Sequence): ''' Space of possible selections of any number of items f...
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. from python_toolbox.misc_tools import is_legal_ascii_variable_name def test(): '''Test `is_legal_variable_name` on various legal and illegal inputs.''' legals = ['qwerqw', 'wer23434f3', 'VDF4vr', '_4523ga', 'AGF___43___4_'...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: out=None while head: temp=head head=h...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findMode(self, root: TreeNode) -> List[int]: cnts = collections.Counter() mv =...
import math def vol(rad): volume = (4/3)*(math.pi)*(rad**3) return volume print (vol(8)) def ran_check(num,low,high): if num >= low and num <= high: return f"{num} is in the range between {low} and {high}!" else: return f"{num} is not in the range between {low} and {high}." print(ran_check(5,2,4)) def up_lo...
from turtle import Turtle, Screen import time def snake(): screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake in Python") screen.listen() screen.tracer(0) game_is_on = True snake_bits = [] positions = [(0, 0), (-20, 0), (-40, 0)] f...
# Write a program to read through the mbox-short.txt and # figure out the distribution by hour of the day for each # of the messages. You can pull the hour out from the 'From ' line # by finding the time and then splitting the string a second time using a colon. # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16...
''' 3.1 Функции Задача 2 Напишите функцию modify_list(l), которая принимает на вход список целых чисел, удаляет из него все нечётные значения, а чётные нацело делит на два. Функция не должна ничего возвращать, требуется только изменение переданного списка, например: lst = [1, 2, 3, 4, 5, 6] print(modify_list(lst)) # N...
# built-in python library for interacting with .csv files import csv # natural language toolkit is a great python library for natural language processing import nltk # built-in python library for utility functions that introduce randomness import random # built-in python library for measuring time-related things import...
import tkinter from tkinter import messagebox from tkinter import * import ImageTk, PIL, Image, os from random import sample import datetime import random Lotto = Tk() Lotto.title("Lotto") Lotto.iconbitmap("images/nlc-logo-1.ico") #LOGO of lotto plus img = Image.open("images/south-african-lotto.jpg") ...
from classes import Budget print("\n---iSaveMore Budget App---\n") def errorMsg(): print("Invalid input!") pincode = input("Please enter your 4-digit PIN code: ") if pincode == "0000": selection1 = input("\nPlease select an option: \n1.) Set Budget \n2.) Use Current Budget\n") def overwriteBudget (): ...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("./MNIST_data", one_hot=True) img_length = 784 classes = 10 learning_rate = 1e-3 epochs = 30 batch_size = 100 x = tf.placeholder(tf.float32,[None,img_length]) y = tf.placeholder(tf.float32,[None,class...
import getpass """ 输入用户名密码 """ name = input("name :") passwd = int(input("passwd :")) info ="""++++++++++++++++info {_name}+++++++++++++++++ name={_name} passwd={_passwd} """.format(_name=name, _passwd=passwd) print(type(name)) print()
#!/usr/bin/env python3 #james liu """ 字典的使用 01-字典是一个无序的,唯一的key=value 的类型对象 """ #创建字典 dictionary1={'name':"james.liu",'age':'23'} #查看字典 print(dictionary1["name"]) print(dictionary1) print(dictionary1.items()) print(dictionary1.get('name')) """ 区别 dictionary1.get(key) #key 不存在的时候return None dictionary1[key] #key 不存在的时候...
# latihan projek python daftarBuah = {'apel' : 5000, 'jeruk' : 8500, 'mangga' : 7800, 'duku' : 6500} while True: # tampilkan menu print('-'*50) print('Menu: ') print('1. Tambah data buah') print('2. Hapus data buah') print('3. Beli buah') print('4....
# latihan projek python 3,4 # input kode = input('Masukkan kode karyawan: ') nama = str(input('Masukkan nama karyawan: ')) gol = str(input('Masukkan golongan : ')) nikah= int(input('Masukkan status (1: menikah; 2: blm): ')) if nikah == 1: anak = int(input('Masukkan jumlah anak : ')) stat = 'Menikah' if ni...
# latihan projek python 6 # input C = float(input('Masukkan suhu (celcius): ')) # proses # Reamur Re = 4/5*C # Romer Ro = (C * 21/40) + 7.5 # Kelvin K = C + 273 # Fahrenheit F = (C * 9/5) + 32 # Rankin Ra = (C * 9/5) + 492 # Newton N = C * 33/100 # Delisle D = (672 - (C * 9/5) + 32) * 5/6 ...
# Created on Wed Apr 1 15:43:37 2020 def main(): x = 0 x = 3 x = ((x * x) + 1) return x if __name__ == "__main__": import sys ret=main() sys.exit(ret)
class Error(Exception): """Base class for exceptions in TicTacToeBoard""" pass class InvalidKey(Error): pass class InvalidMove(Error): pass class InvalidValue(Error): pass class NotYourTurn(Error): pass class TicTacToeBoard: def __init__(self): self.state = {"A1": " ", "A2":...
# Reading an excel file using Python import xlrd import time load_start_time = time.time() # Give the location of the file loc = ("CityTemp.xlsx") print("Started") # To open Workbook wb = xlrd.open_workbook(loc) print("Opened") sheet = wb.sheet_by_index(0) print("Loaded") load_end_time = time.time() print("The datase...
from random import choice from random import random from vpython import * class Random_Walk(): def __init__(self, n=10000): self.n = n self.x = [0] self.y = [0] self.z = [0] def fill_walk(self): while len(self.x)<self.n: direction_x,direction_y,direction_z = choice([1,-1]),choice([1,-1]),choice([1,-1]) ...
''' Consider our representation of permutations of students in a line from Exercise 1. (The teacher only swaps the positions of two students that are next to each other in line.) Let's consider a line of three students, Alice, Bob, and Carol (denoted A, B, and C). Using the Graph class created in the lecture, we c...
import sqliteDB 제품입력 제품목록 제품검색 제품수정 제품삭제 종료 while True: print(''' 1. 테이블 생성 2. 데어터 입력 3. 데이터 수정 4. 데이터 삭제 5. 데이터 리스트 6. 종료 ''') menu=input() if menu=='1': sqliteDB.create_table() elif menu=='2': sqliteDB.insert_data() elif menu=='3': sqliteDB.u...
def AgeCalculate(): from speak import speak from datetime import datetime try: print("please enter your birthday") speak("Year") bd_y=int(input("Year:")) speak("Month") bd_m=int(input("Month(1-12):")) speak("Date") bd_d=int(input("Date:")) calc...
from musica import Musica # opción 1 """ A partir del archivo de texto musica.csv (creado con el módulo separado que se indicó), generar un vector de registros, de tal manera que vaya quedando ordenado por título, con todos los temas musicales. Mostrar el vector a razón de una línea por tema mostrando el género y e...
from typing import Union from binary_tree import BinaryTree from tree import Empty, Tree class BinarySearchTree(BinaryTree): """A binary search tree is a binary tree whose left child of each node contain an item less in value than itself, and the right child an item higher in value than itself. An in-order t...
from abc import ABC, abstractmethod from typing import Any, Union class Empty(Exception): pass class PriorityQueue(ABC): """A priority queue is a queue ADT that supports insertion (enqueueing) of elements at one end and removal (dequeueing) of elements from the opposite end, with the extra attribute of ...
from singly_linked_list import SinglyLinkedList class CircularlySinglyLinkedList(SinglyLinkedList): """A circularly singly linked list is a cyclic collection of nodes whose head and tail nodes are connected. Each node contains a reference to the node succeeding it. Instantiate a circularly singly linked ...
from abc import ABC, abstractmethod from typing import Any, Union class Empty(Exception): pass class PositionalLinkedList(ABC): """A positional linked list is a linked list whose nodes are identifiable by their position within the list. Using the position of a node, operations such as insertion, retriev...
class Conversion: # Code created by Luke Reddick # Please use inputs of one character, so C, F, K, c, f ,k # for celsius, fahrenheit, and Kelvin respectively convertFrom = str((input("What temperature are you converting from? (C/F/K) : " + "\n"))) convertTo = str((input("What temperatur...
try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk root = tk.Tk() # use width x height + x_offset + y_offset (no spaces!) root.geometry("240x180+130+180") root.title('listbox with scrollbar') # create the listbox (height/width in char) listbox = tk.Listbox(root, width...
# ============================================================================= # import decimal # from decimal import Decimal # decimal.getcontext().prec = 6 # d = Decimal('1.234567') # print(d) # d += Decimal('1') # print(d) # ============================================================================= from fracti...
#!/usr/bin/python3 from collections import deque class Stack(list): """Clase que representa una pila. Dado que hereda a partir de una lista, sólo se implementan los métodos push para agregar al principio de la pila y peek para ver el tope de la misma. Ejemplo de uso: pila = Stack() pila.push...
print (6+12-3) print (2*3.0) print (-4) print (10/3) print (10.0/3.0) print ((2+3)*4) print (2+3*4) print (2**3+1) print (2.1**2.0) print (2.2*3.0) a = 3 print (a+2.0) a = a+1.0 print (a) # a = 3 # print (b) print (3 > 4) print (4.0 > 3.999) print (4 > 4) print (4 > +4) print (2+2 == 4) print (True or...
# NumberList = [] # Num1 = int(input("Enter the first number: ")) # NumberList.append(Num1) # while True: # Num2 = int(input("Enter the next number, or Zero to exit: ")) # if Num2 == 0: # break # NumberList.append(Num2) # NumberList.reverse() # print(NumberList) # MessageList = [] # i = 1 # whil...
import requests from bs4 import BeautifulSoup import pandas as pd from tabulate import tabulate number_of_articles = 5 # Number of articles that we want to retrieve headline_list = [] intro_list = [] full_list = [] # Empty list that is going to be used for future iteration of the project*** # Creating a loop in ord...
''' Pavlo Semchyshyn ''' from collections import defaultdict def read_file(path): """ Reads file and returns a generator, which yields year, film and location as a tuple """ with open(path, "r", encoding="latin1") as file_to_read: line = file_to_read.readline() while not line.sta...
# -*- coding: cp1252 -*- ## Importar librerias Tkinter y Pickle from Tkinter import* import pickle ##Funcion que recibe como argumento una ventana y la muestra def mostrar(ventana): ventana.deiconify() ##Funcion que recibe como argumento una ventana y la oculta def ocultar(ventana): ventana.withdraw() ##Fun...
#Jumlah Rata-Rata Orang Bertemu Pasien Covid-19 R = int(input('Masukan Jumlah Rata-Rata Orang Bertemu Pasien Covid-19 : ')) #Peluang Tertular P = float(input('Masukan Peluang Tertular (ex 0.1, 0.01, 0.5 dst) : ')) #Jumlah Kasus Perhari Nh = int(input('Masukan Jumlah Kasus Perhari : ')) #Hari ke x x = int(input('Hari ke...
# ! /usr/bin/env python from thor.tree import TreeNode class Solution(object): ''' 1. 都为空指针返回True 2. 只有一个为空返回False 3. 递归过程 a. 判断两个指针是否相等 b. 判断A左子树和B右子树是否对称 c. 判断A右子树和B左子树是否对称 ''' def is_symmetric(self, root: TreeNode): if not root: return True else: self.func(root.left, root.right) def ...
#! /usr/bin/env python ''' 1. 变化前和变化的位数是一样的 1.1 加完后,值不小于10,需要做进位 1.1.1 进位后,首位数字不小于10,位数将增加1 1.1.2 进位后,首位数字小于10 1.2 加完后,值小于10 ''' class Solution(object): def plusOne(self, digits: [int]) -> [int]: ''' 字符串和数值之间的转化 :param digits: :return: ''' if not digits: return digits else: return [...
# coding:utf-8 from thor.linklist.ListNode import ListNode class Solution(object): """双指针+哑结点""" def rotateRight1(self, head: ListNode, k: int) -> ListNode: if head is None or head.next is None or k == 0: return head else: dummy = ListNode(-1) dummy.next = head first = dummy second = dummy l...
#! /usr/bin/env python ''' 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 ''' class Solution(object): def twoSum(self, numbers: [int], target: int) -> [int]: ''' 使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。 1. 如果两个指针指向元素的和 sum == targetsum==t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """二叉树的类实现,以及遍历等各种方法""" # 结点类 class BinTreeNode(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left # 左子树 self.right = right # 右子树 # 统计树中结点的个数 def count_bintree_nodes(node: BinTreeNode): # 递归实现 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 基于链表技术实现栈,用LNode做节点 此时栈顶为链表首端元素 """ # 定义自己的异常 class StackUnderFlow(ValueError): # 继承ValueError类 pass # 定义节点类 class LNode(object): def __init__(self, elem, next_=None): self.elem = elem # 数据域 self.next = next_ # 指向下一个节点 class LinkedSt...