text
stringlengths
37
1.41M
""" https://leetcode.com/problems/linked-list-cycle/ """ from test_helper import ListNode class Solution: def hasCycle(self, head: ListNode) -> bool: """ Use two pointers to reduce the space to O(1). """ if not head or not head.next: return False slow, fast =...
""" https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/ """ from test_helper import TreeNode class Solution: def countPairs(self, root: TreeNode, distance: int) -> int: def walk(node: TreeNode) -> list[int]: nonlocal cnt if not node: return [] ...
""" https://leetcode.com/problems/max-consecutive-ones-iii/ """ class Solution: def longestOnes(self, nums: list[int], k: int) -> int: """ 1. When coming across a zero, we need to flip it to make the current window larger. 2. When the total flips exceed the maximum limit k, we ...
""" https://leetcode.com/problems/angle-between-hands-of-a-clock/ """ class Solution: def angleClock(self, hour: int, minutes: int) -> float: ANGLE_PER_HOUR, ANGLE_PER_MIN = 30, 6 # 360/12, 360/6. currMinuteAngle = minutes * ANGLE_PER_MIN currHourAngle = (hour % 12 + minutes / 60) * ANGLE...
""" https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/ """ from test_helper import TreeNode class Solution: def pseudoPalindromicPaths(self, root: TreeNode) -> int: def search(currNode: TreeNode) -> None: if currNode: freqs[currNode.val - 1] += 1 ...
""" https://leetcode.com/problems/2-keys-keyboard/ """ from typing import Iterator class Solution: def minSteps(self, n: int) -> int: def do(currSteps: int, currChars: int, copiedChars: int) -> int: if currChars > n: # Exceed. return float('inf') if currChars ==...
""" https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/ """ from collections import Counter from itertools import accumulate class Solution: def reductionOperations(self, nums: list[int]) -> int: cnt = Counter(nums) sortedKeys = sorted(cnt, reverse=True) ...
""" https://leetcode.com/problems/moving-stones-until-consecutive/ """ class Solution: def numMovesStones(self, a: int, b: int, c: int) -> list[int]: sa, sb, sc = sorted([a, b, c]) # Maximum of moves come from the number of empty positions between the # max and the min value among a, b and...
""" https://leetcode.com/problems/first-missing-positive/ """ from typing import List class Solution: def firstMissingPositive(self, nums: List[int]) -> int: # By given a list of numbers with length k, the first missing # positive number will fall in [1, k + 1]. So add one element 0 # to ...
""" https://leetcode.com/problems/bulb-switcher/ """ class Solution: def bulbSwitch(self, n: int) -> int: """ All the bulbs at first are turned on. So a bulb will stay on only when it is toggled odd times during n rounds. The ith bulb will only be toggled at the pth round, while p...
""" https://leetcode.com/problems/monotonic-array/ """ class Solution: def isMonotonic(self, nums: list[int]) -> bool: isIncreasing = isDecreasing = True for x, y in zip(nums, nums[1:]): if y > x: isDecreasing = False elif x > y: isIncreasing...
""" https://leetcode.com/problems/longest-absolute-file-path/ """ class Solution: def lengthLongestPath(self, inputStr: str) -> int: """ Clarifications: 1. \n means we are still at the same folder as the previous one. 2. \t means we are entering a sub folder of the previous one. ...
""" https://leetcode.com/problems/rectangle-area/ """ class Solution: def computeArea( self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: area1 = (C - A) * (D - B) area2 = (H - F) * (G - E) areaOverlap =\ self.calc_overlap(A, C...
""" https://leetcode.com/problems/xor-queries-of-a-subarray/ """ class Solution: def xorQueries(self, arr: list[int], queries: list[list[int]]) -> list[int]: """ x ^ y ^ x = y, so we could use prefix xors to determine the total xor for a given range. """ prefixXORs: list[in...
""" https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ """ class Solution: def removeStones(self, stones: list[list[int]]) -> int: """ 1. All the connected stones could be removed until one stone. Then the total stones - the remaining stones will be the total re...
""" https://leetcode.com/problems/maximum-number-of-balls-in-a-box/ """ from collections import Counter class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: def get_digits_sum(x: int): rslt = 0 while x: x, r = divmod(x, 10) r...
""" https://leetcode.com/problems/third-maximum-number/ """ from typing import List class Solution: def thirdMax(self, nums: List[int]) -> int: top3 = set() for num in nums: top3.add(num) if len(top3) > 3: top3.remove(min(top3)) if len(top3) < 3: ...
""" https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/ """ class Solution: def minFlips(self, mat: list[list[int]]) -> int: """ Since mat could have maximum 3 rows or columns, we could map each cell into one bit of an integer with length m * n. T...
""" https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/ """ class Solution: def numSteps(self, s: str) -> int: carry = 0 stepCnt = 0 for i in range(len(s) - 1, 0, -1): if int(s[i]) + carry == 1: # Odd number. carry ...
""" https://leetcode.com/problems/mirror-reflection/ """ from math import gcd class Solution: def mirrorReflection(self, p: int, q: int) -> int: """ Extend the original box to mutiple boxes in order to simulate the reflections as follows (p = 3, q = 2): See pics/mirror_reflec...
""" https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/ """ from heapq import heappush, heappop class Solution: def minCost(self, maxTime: int, edges: list[list[int]], passingFees: list[int]) -> int: """ Djikstra. And we need to consider paths that cost more fee but take les...
""" https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/ """ class Solution: def canBeIncreasing(self, nums: list[int]) -> bool: """ when nums[i - 1] >= nums[i]: 1. If nums[i - 2] >= nums[i], we should remove the ith number. 2. Else, we s...
""" https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ """ from typing import List class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: memo = {} for i, num in enumerate(numbers): chkNum = target - num if chkNum in memo: ...
""" https://leetcode.com/problems/triangle/ """ from typing import List class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: n = len(triangle) if not n: # Empty triangle. return 0 currRow = [0] * n currRow[0] = triangle[0][0] for row in ...
""" https://leetcode.com/problems/transpose-matrix/ """ class Solution: def transpose(self, matrix: list[list[int]]) -> list[list[int]]: """ After transpose, all rows become columns now and all columns become all rows now. """ R, C = len(matrix), len(matrix[0]) retu...
""" https://leetcode.com/problems/remove-boxes/ """ from typing import List class Solution: def removeBoxes(self, boxes: List[int]) -> int: """ Let T(start, end, k) be the maximum points gained by removing boxes among boxes[start:end + 1], which has k boxes having the same color ...
""" https://leetcode.com/problems/sort-list/ """ from test_helper import ListNode class Solution: def _cut_list(self, head: ListNode, n: int) -> ListNode: """ Cut the first n node from head and return the head of the remaining list. """ cnt, currNode = 1, head whi...
""" https://leetcode.com/problems/evaluate-reverse-polish-notation/ """ from typing import List class Solution: def evalRPN(self, tokens: List[str]) -> int: rslt, operators = [], {'+', '-', '*', '/'} for token in tokens: if token not in operators: rslt.append(int(toke...
""" https://leetcode.com/problems/day-of-the-year/ """ class Solution: def dayOfYear(self, date: str) -> int: year, month, day = map(int, date.split('-')) if (year % 4 == 0 and year % 100 != 0) or (year % 100 == 0 and year % 400 == 0): MONTH_DAYS = [31, 29, 31, 30, 31, 30, 31, 31, 30, ...
""" https://leetcode.com/problems/reverse-pairs/ """ from typing import List class Solution: def reversePairs(self, nums: List[int]) -> int: """ Use merge sort on the input list, and during each round of the merge sort, we count the number of important reverse pairs. """ ...
""" https://leetcode.com/problems/binary-tree-preorder-traversal/ """ from typing import List from test_helper import TreeNode class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: # Empty tree. return [] currNode, stack, rslt = root, [], [] ...
""" https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/ """ from collections import Counter class Solution: def minSteps(self, s: str, t: str) -> int: cntS = Counter(s) cntT = Counter(t) return sum((cntS - cntT).values())
""" https://leetcode.com/problems/max-value-of-equation/ """ from heapq import heappush, heappop class Solution: def findMaxValueOfEquation(self, points: list[list[int]], k: int) -> int: """ Since for all i < j, xi < xj, so equation yi + yj + |xi - xj| = yi + yj + xj - xi = (yi - xi) + (...
""" https://leetcode.com/problems/max-chunks-to-make-sorted-ii/ """ from typing import List class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: """ 1. First calculate the minimum numbers from index i to the end of the given list by scanning the list from right to left...
""" https://leetcode.com/problems/distribute-coins-in-binary-tree/ """ from test_helper import TreeNode class Solution: def distributeCoins(self, root: TreeNode) -> int: """ 1. Root asks the left subtree, how much do you need or you've got extra? I'll give that/take it away to/from y...
from typing import List class Solution: def isRectangleCover(self, rectangles: List[List[int]]) -> bool: """ If those rectangles could form a perfect rectangle: 1. The summary of the area of the rectangles in the input list should be the same as the final rectangle. 2. Th...
""" https://leetcode.com/problems/single-number-ii/ """ from typing import List class Solution: def singleNumber(self, nums: List[int]) -> int: """ For any number x in nums: x1 x2 -- -- x 0 0 x 0 0 So if x only occurs once, it must be stored in...
""" https://leetcode.com/problems/split-array-into-fibonacci-sequence/ """ class Solution: def splitIntoFibonacci(self, S: str) -> list[int]: """ 1. Notice that the numbers in the result set is less than 2^31 - 1, which means the length of each number should be less than 10. 2....
""" https://leetcode.com/problems/stone-game-viii/ """ from functools import reduce from itertools import accumulate class Solution: def stoneGameVIII(self, stones: list[int]) -> int: """ Suppose prefix sums p[i] = stones[0] + ... + stones[i], and suppose dp[i] is the maximum score diffe...
""" https://leetcode.com/problems/random-pick-index/ """ from typing import List from random import choice class Solution: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: return choice([i for i, n in enumerate(self.nums) if n == target])
""" https://leetcode.com/problems/basic-calculator-iv/ """ from typing import List from collections import Counter class Poly(Counter): """ Stands for a polynomial parsed from an expression: 1. Each key stands for a variable and the key is a tuple. For example, if the variable is a*b*b*c then...
""" https://leetcode.com/problems/similar-string-groups/ """ from itertools import combinations from collections import defaultdict class DSU: def __init__(self, size: int): self.parents = list(range(size)) def find(self, x: int) -> int: if self.parents[x] != x: self.parents[x]...
""" https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/ """ from bisect import bisect_left class Solution: def minOperations(self, target: list[int], arr: list[int]) -> int: """ 1. Since "target" array has distinct elements that means I can give every element an i...
""" https://leetcode.com/problems/rank-transform-of-an-array/ """ class Solution: def arrayRankTransform(self, arr: list[int]) -> list[int]: rankMap = {num: (i + 1) for i, num in enumerate(sorted(set(arr)))} return [rankMap[num] for num in arr]
""" https://leetcode.com/problems/repeated-string-match/ """ from math import ceil class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: """ 1. Suppose minCnt is the minimum repeating times a needs in order to have b as its substring, then len(b) <= minCnt * len(a), w...
""" https://leetcode.com/problems/combination-sum/ """ from typing import List class Solution: def combinationSum( self, candidates: List[int], target: int) -> List[List[int]]: def sub_sum(remain: int, path: List[int], start: int) -> None: if remain == 0: # Combination found. ...
""" https://leetcode.com/problems/keyboard-row/ """ from typing import List class Solution: def findWords(self, words: List[str]) -> List[str]: r1 = set('qwertyuiop') r2 = set('asdfghjkl') r3 = set('zxcvbnm') rslt = [] for w in words: rw = set(w.lower()) ...
""" https://leetcode.com/problems/count-numbers-with-unique-digits/ """ class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int: if not n: # n == 0 return 1 # 0 is the only unique number in [0, 1). if n == 1: return 10 # All numbers are unique in [0, 10). ...
""" https://leetcode.com/problems/available-captures-for-rook/ """ class Solution: def numRookCaptures(self, board: list[list[str]]) -> int: # Find the rook first. rookRow = rookCol = None for r, row in enumerate(board): for c, v in enumerate(row): if v == 'R': ...
import string #swaps two letters to encrypt the message wswap2 = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz','BADCFEHGJILKNMPORQTSVUXWZYbadcfehgjilknmporqtsvuxwzy') def crypt(text): return text.translate(wswap2) def main(): while True: print("Menu Driven Program") print(...
#Dictionary - Curso de Python #17 carro = { "Fabricante":"Honda", "Modelo":"HRV", "Ano":"2016", "Cor":"Prata" } #inserir items ao dicionário carro["Cor"] = "Preto" carro["Cambio"] = "Automatico" #removoer items do dicionário #carro.pop[] #del carro[] print("Tamanho do Dictionary: "+ str(len(carro))) ...
import urllib.request #Modulo que dá ao programa a capacidade de conversar com uma pagina na web# #Definindo a função para exibir o preço do grão atual.# def get_price(): page = urllib.request.urlopen("http://beans.itcarlow.ie/prices-loyalty.html") #Atribui a uma variavel a pagina web desejada# text = pag...
import urllib.request #Modulo que dá ao programa a capacidade de conversar com uma pagina na web# import time #Definindo a função para exibir o preço do grão atual.# def get_price(): page = urllib.request.urlopen("http://beans.itcarlow.ie/prices-loyalty.html") #Atribui a uma variavel a pagina web desejada# ...
#Loop FOR - Extruturas de repetição - Curso de Python #12 carros = ["HRV", "Golf", "Argo", "Focus", "Fit", "Fusion", "Polo"] for x in carros: if(x == "Fit"): break print(x) print("Fim do programa")
#Condicional If Elif Else - Curso de Python #11 clima = "sol" dinheiro = 299 lugar = "" if clima == "sol" or (dinheiro >= 300 and dinheiro <= 500): lugar = "Clube" else: lugar = "Cinema" print ("Vou ao " + lugar) #AND = # V com V = V # V com F = F # F com V = F # F com F = F #OR = # V com V = V # V com F =...
import os import sqlite3 from sqlite3 import Error #============================Conexão com o bd==================================# def conexaobd(): caminho = "C:\\Python36-32\\Aula\\banco\\inventario.db" conexao=None try: conexao=sqlite3.connect(caminho) except Error as ex: print(ex) ret...
""" Class method code sample used in Python """ class ShippingOrg: shipping_vessel_number = 1993 # Class Method @classmethod def _shipping_vessel_number_allocation(cls): result = cls.shipping_vessel_number cls.shipping_vessel_number += 5 return result # Named Constructor...
""" Global & Nonlocal Keyword Sample """ message = "global" def enclosing(): message = 'enclosing' def local_func(): global message message = 'local' print('1st Print =', message) local_func() print('2nd Print =', message) print('3rd Print =', message) enclosing() print('4th P...
from collections import Counter class Board(): """ Board class for dominos. """ def __init__(self, tiles): self.tiles = tiles self.open = True def __repr__(self): return str(self.tiles) def get_borders(self): """ Return board bo...
from collections import Counter import math import random import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt numList = [] amountList = [] for i in range(100): i = random.randint(1, 6) numList.append(i) numList.sort() def checkDuplicate(nums): counter = Count...
from collections import defaultdict from itertools import cycle default_input_file = "input.txt" UP = '^' DOWN = 'v' LEFT = '<' RIGHT = '>' def get_data(fname): instructions = [] with open(fname, "r") as fin: instructions = list(fin.read()) return instructions def update_position(position, instruction): ...
#coding=utf-8 ''' Created on Monday Oct 18 2017 K-means clustering @Author:Xu Xiaoliang function:implement K means clustering algorithm ''' import numpy as np class Kmeans(object): def __init__(self, k, numMaxIte, dataSet): self.k = k self.numMaxIte = numMaxIte self.numPo...
def maxSumSubArray (num, k): maxsum = 0 currentsum = 0 for i in range(len(num)): currentsum += num[i] if (i >= k-1): maxsum = max(maxsum, currentsum) currentsum -= num[i - (k - 1)] print ("I am going great") print ("test again") return maxsum a = [2,...
for a in range(0,10): for b in range(0,10): for c in range(0,10): if a!=b and b!=c and a!=c: print(a*100+b*10+c) input()
#!python def merge(items1, items2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" # TODO: Repeat ...
lenOfList= int(input("Enter the number of List: ")) li= [] for i in range(lenOfList): number= int(input(f"Enter the {i} value: ")) li.append(number) print("Your list is: ") print(li) s= sum(li) avg= s/2 print(f"Your Sum of list is {s} and average of list is: {avg}")
''' Script to detect language of a text. Currently includes English, Spanish, Portuguese and Italian. Additional langauges can be added in the list 'languages', no other changes required. Although, if NLTK does not have stopwords for a language then need to download that language. ''' from nltk.corpus import stopw...
class Node: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # INSERT METHOD def insert(self, data): newNode = Node(data) if(self.head): current = self.head while(...
#!/usr/bin/env python # -*- coding: utf-8 -*- ### Advent of Code 2019, Day 2 f = open('2.txt', 'r') c = f.read() def initList(codes, noun, verb): codes[1] = noun codes[2] = verb return codes[:] def processBlock(codes, pos): block = codes[pos:pos+4]; opcode = block[0] if opcode == 1: result = codes[block[1...
from tealight.art import (screen_width, color, image, line, spot, circle, box, image, text, background) from math import sin, cos, pi hue = 0 class car: "Race car class" def __init__(self,x,y,angle): self.draw(x,y,angle) def draw(self,x,y,angle): size = screen_width/24 self.points = ...
#exercise 1 a = 10 b = 15 print("Переменные a и b - ", a, b) string1 = input("Введите первую строку ") number1 = (input("Введите первое число ")) string2 = input("Введите вторую строку ") number2 = int(input("Введите второе число ")) print("Введеные значения - %10s %5d %10s %5d" % (string1, number1, string2, number2)) ...
#This program encrypts and decrypts messages with the Caesar Cipher method import random ########## Constants ########## MAX_KEY_LENGTH = 26 ########## Functions ########## def printIntro(): playerInput = '' while playerInput is not 'e' and playerInput is not 'd': print("Do you wish to (e)ncrypt or (d)ecry...
#!/usr/bin/python3 """ Output query results to file. Question: Who are the most popular article authors of all time? """ import results_from_db def results_to_file(results): """Take the results from an SQl query and writes this to a txt file.""" with open('report_2.txt', mode='wt', encoding='utf-8') as ou...
def repeat_inside(line): """ first the longest repeating substring """ print("************") cache = {} MAX_WINDOW = "" MAX_WINDOW_AMOUNT = 0 length = len(line) for i in range(len(line)-1, 0, -1): window_length = length // i for j in range(0, window_length): ...
inventory = ("sword", "armor", "shield", "potion") print("Your items:") for i in inventory: print(i) print("You have", len(inventory), "items in your possession.") if "potion" in inventory: print("\n You'll live to fight another day.") index = int(input("\nEnter the index number: ")) print("At index", index, "is...
student_list = [] class Student: def __init__(self, name): self.name = name self.marks = [] def average(self): number = len(student.marks) if number == 0: return 0 else: total = sum(student.marks) return total / number def create_...
import random WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") HINT = ("snake", "game name", "not difficult", "not easy", "AI", "never") choice = random.randrange(len(WORDS)) word = WORDS[choice] hint = HINT[choice] correct = word jumble = "" while word: position = random.randrange(len(wor...
inventory = ["sword", "armor", "shield", "potion"] print("Your items: ") for i in inventory: print(i) print("\nYou have", len(inventory), "items in your inventory.") if "potion" in inventory: print("You'll live.") index = int(input("Enter the index: ")) print("At index", index, "is", inventory[index]) start = in...
def number_of(): total = 0 count = int(input("Number of pushups: ")) while count > 0: total += count count -= 1 return total print(number_of())
def read_global(): print("From inside the local scope of read_global(), value is:", value) def shadow_global(): value = -10 print("From inside the local scope shadow_global, value is", value) def change_global(): global value value = -10 print("From inside the local scope of change_global(), value is:", value) ...
import sys def primefac(n): for i in range (2,n): if n%i==0: return False return True t = int(input().strip()) for a0 in range(t): n = int(input().strip()) primem = 0 for i in range(2, n+1): if n%i == 0 and primefac(i): primem = i print(primem)
import itertools import random #----------------------------↓solver_greedy.py------------------------------ import sys import math from common import print_tour, read_input def distance(city1, city2): return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) def solve(cities): N = len(citie...
def min(m, n): if m > n: return n else: return m def greedyMinChange(a, ds): if a == 0: return 0 elif len(ds) < 1: return 1000 else: d = ds.pop(0) if d > a: return greedyMinChange(a, ds) else: q = a/d r = a...
def prodAccum(m, n, a): if m == 0: return a else: return prodAccum(m-1, n, a+n) print ("prodAccum(10, 2, 0) = " + str(prodAccum(10, 2, 0)))
# write a while loop to check if input with following symbols *,+,-,/ is correct # if yes exit loop # while True: # var = input('Bitte gib ein Symbol an') # if '*' in var or '+' in var or '-' in var or '/' in var: # break # solution b # while True: # var = input('Bitte gib ein Symbol an') # ...
N = int(input()) unique = set() sub = set() for i in range(N): s = input() if s not in unique: if s not in sub: # どっちにもない unique.add(s) sub.add(s[::-1]) print(len(unique))
dict_of_numbers={ "0":"zero", "1":"one", "2":"two", "3":"three", "4":"four", "5":"five", "6":"six", "7":"seven", "8":"eight", "9":"nine", "00":"zero", "01":"one", "02":"two", "03":"three", "04":"four", "05":"five", "06":"six", "07...
from tkinter import * turn = 1 def clickedbtn1(): global turn if turn % 2!=0: btn1['text']='X' else: btn1['text']='O' turn=turn+1 winner() def clickedbtn2(): global turn if turn % 2 != 0: btn2['text'] = 'X' else: btn2['text'] = 'O' turn = turn + 1 ...
src = [2, 3, 4, 1, 5, 6, 7, 8] n = len(src) temp = [0]*n def mergeSort(start, end): if start < end: mid = int((start + end) / 2) mergeSort(start, mid) #왼쪽 영역 mergeSort(mid + 1, end) #오른쪽 영역 p = start q = mid + 1 idx = start while p <= mid or q <= end: ...
''' if []: pass a = [1] if a: print('full') else: print('empty') print("end") ''' ''' _list = [1,2,3] print(_list) data = 3 if data not in _list: _list.append(data) print(_list) ''' ''' a = 15 if a>=10 and a<20: print("10대") elif a >= 20 and a < 30: print("20대") elif a>...
""" Generate an environment for Euclidean 2D TSP(Travelling Sales Person). The Environments consist of two elements, node and edge. Node and Edge can be viewed respectively as city, and route. To define the relationship between nodes and edges, you should define Distance Matrix. In 2D Euclidean matric, distance mat...
class User(): ''' This is a User class that takes 2 strings name, email as 'string' the available methods are read_book, get_average_rating ''' def __init__(self, name, email): self.name = name self.email = email self.books = {} #this is a dictionary of Book:rating(i...
import turtle from turtle import Turtle, Screen from random import random, choice import colorgram tim = Turtle() ##tim.penup() ##tim.setposition(-50, 300) ##tim.pendown() tim.shape("turtle") ''' def draw_turtle(edges): R = random() B = random() G = random() tim.color(R, G, B) angle...
#playing with turtle graphics #by @jack import turtle #create window loadWindow = turtle.Screen() loadWindow.title("Test Turtle") # loadWindow.setup(width=800, height=600) #turn off draw mode turtle.speed(0) turtle.colormode(255) #create and run turtles def shape(size,sides): for i in range(sides): tur...
# Refer to the StudentClass.py file before reading this file. from StudentClass import Student student1 = Student('Ankit', 'Business', 3.3, False) # Here we created a student1, which is an object in Student class. student2 = Student('Ram', 'Finance', 3.8, True) print(student1.gpa) # We can print information abo...
''' There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered and unindexed. No duplicate members...
# Creating StudentX class for using in the 27. Object Function class StudentX: def __init__(self, name, major, gpa): self.name = name self.major = major self.gpa = gpa def on_honors(self): # Here we created a function inside the class for finding out if a student is honors or ...
# 1- The airplane has 100 seats and 100 passangers # 2- The first person has lost their boarding pass # 3- The first person goes in and they choose a seat at random # 4- Every other person goes in and: # a) sits in their seat if their seat is open # b) chooses a seat at random if their seat is taken # 5- Wha...
from plyer import notification import time secondsInput = int(input('Enter the no of seconds : \n')) while True: if secondsInput >= 1: secondsInput = secondsInput - 1 sleep = time.sleep(secondsInput) break else: break notification.notify( title='Tim...
class User(object): name = "Helen" anna = User() print anna.name anna.name = "Mikel" print anna.name bob = User() print bob.name #inherits name from parent #self refers to the individual instance of the object #notice no need to pass self through the User() object upon creation because it is implicit