text
stringlengths
5
121k
speed = 61 is_birthday = False if not is_birthday: if speed < 31: print("no ticket") elif speed > 30 and speed < 51: print("small ticket") else: print("big ticket") else: if speed < 36: print("no ticket") elif speed > 35 and speed < 56: print("small ticket") ...
import sys def get_change(m): answer = m//10 answer = answer + (m%10)//5 answer = answer + (m%10)%5 return answer if __name__ == '__main__': m = int(sys.stdin.read()) print(get_change(m))
import sys def DPchange(money, coins): MinNumCoins = [0] * (money+1) for m in range(1, money+1): MinNumCoins[m] = sys.maxsize for coin in coins: if m >= coin: change = MinNumCoins[m-coin] + 1 if change < MinNumCoins[m]: MinNumCoins...
def validate_credit_card_number(card_number): card=str(card_number) l=[] if len(card)==16: for i in card[-2::-2]: n=int(i)*2 if n>9: n1=n%10+n//10 l.append(n1) else: l.append(n) return (sum(l)+sum(list...
def sms_encoding(data): vowel = "aeiouAEIOU" list1 = data.split() list2 = [] for i in list1: length=len(i) if length == 1: list2.append(i) list2.append(" ") else: count=0 for a in i: if a in vowel: ...
''' Created on Apr 17, 2018 @author: Sualeh Ali ''' import csv def main(): directory = "F:/Drive/Books/Bioinformatics/assignments" pollutant = "sulfate" id = range(1,11) pollutantmean(directory, pollutant, id) """ Calculates the mean of a pollutant (sulfate or nitrate) across a speci...
import sys import glob import re file_list = None search_term = None replace_term = None if len(sys.argv) < 4: print(""" Usage: srep <searchterm> <replaceterm> <filespec> ... Notes: * All arguments are required. * searchterm and/or replaceterm can be regular expressions. * filespec can be a file name or ...
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False): np.random.seed(1) costs = [] parameters = initialize_parameters_deep(layers_dims) for i in range(0, num_iterations): A...
def fac(x): if x==1: return 1 else: return (x * fac(x-1)) num = 4 print (fac(num))
def countOnNumber(data=[], number=0): summary = 0 counter = 0 for i in data: if summary + i <= number: counter += 1 summary += i return summary, counter with open("27888.txt") as file: data = file.read().split() for i in range(len(data)): data[i] = int(d...
import random f= 1 g= 99 a = random.randint(f,g) print(a) b= input("please inter: ") while b != 'd': if b == 'k': g= a-1 a = random.randint(f,a-1) print(a) b= input("please inter: ") continue elif b == 'b': f= a+1 a= random.randint(f,g) ...
def v(): print('Yep, this shit works.') dic = { 'a' : 'val', 'test' : v, 23 : '23 as strting', 'b' : 'some value here too' } print(dic.get('a')) result = dic.get('b', 'Not available!') print(result) print ('---------------------------------------') for key in dic : print('{} <===> {}'.form...
num_list = [] result = [] for i in range(100,1000): for j in range(100,1000): num_list.append(i * j) word_list_str = map(str, num_list) for element in word_list_str: element_reverse = ''.join(reversed(element)) if element == element_reverse: result.append(element_reverse) ...
class Employee(): def __init__(self,id,name,desgn,salary,exp): self.id=id self.name=name self.desgn=desgn self.sal=salary self.exp=exp def printval(self): print("\n id:",self.id,"\n","name:",self.name,"\n","desgn:",self.desgn,"\n","salary:",self.sal,"\n","exp:",se...
import re x='[klKL]\d{2}[a-zA-Z]{2}\d{4}' vname=input("variable name= ") match=re.fullmatch(x,vname) if(match!=None): print("valid") else: print("invalid")
dob=input("birth year dd-mm-yy: ") byr=dob.split("-") today=int(input("recent year:")) age=(today-int (byr[2])) print(age)
n1=int(input("n1=")) n2=int(input("n2=")) try: res=n1/n2 print(res) except Exception as f: print(f.args) n2 = int(input("another n2=")) res = n1 / n2 print(res) finally: print("exception is abnormal situation") print("program terminate the execution")
class Student: def __init__(self,rollno,name,course,tmark): self.rollno=rollno self.name=name self.course=course self.tmark=tmark def printval(self): print("rollno:",self.rollno,"\n","name:",self.name,"\n","course:",self.course,"\n","total mark:",self.tmark) f=open("studd...
import random class Spell: def __init__(self, name, cost, dmg, magic_type): self.name = name self.cost = cost self.dmg = dmg self.magic_type = magic_type def generate_damage(self): min_wartosc = self.dmg - 15 max_martosc = self.dmg + 15 return ra...
file = open("textfile.txt","r") line =file.read() c=0 for i in line: word=i.split(" ") if i=="A" or i=="a" or i=="E" or i=="e" or i=="I" or i=="i"or i=="O"or i=="o"or i=="U"or i=="u": c+=1 print ("count of vowels is ",c) file.close()
print('Welcome to Dharavi Bank ATM') restart=('Y') chances = 3 balance = 100.00 while chances >= 0: pin = int(input('Please Enter You 4 Digit Pin: ')) if pin == (1234): print('You entered you pin Correctly\n') while restart not in ('n','NO','no','N'): print('Please Press 1 For Your ...
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i_index, i_val in enumerate(nums): for j_index, j_val in enumerate(nums): if i_index != j_index: if i_...
class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: window = [] temp = head for i in range(n+1): if temp is None: return head.next window.append(temp) temp = temp.next ...
def BinarySearch(arr, search): high = len(arr) low = 0 index = ((high - low)//2) for i in range(len(arr)): if search > arr[index]: low = index index = index + ((high - low)//2) if i == (len(arr)-1): print("Number is not present in the input arr...
''' LAB16v2: Another approach to the Pick 6 problem that utilizes a function that calls another function. Also, instead of comparing if each of the ticket numbers is in the list of winning numbers, regardless of position, this new version requires ticket and winning numbers match the same index. This mirrors the actual...
adjective01 = input("Enter an adjective. > ") noun01 = input("Name a noun. > ") verb_past_tense = input("And now a past tense verb. > ") adverb = input("How about an adverb? > ") adjective02 = input("One more adjective. > ") noun02 = input("And finally, one last noun. > ") print("Today I went to the zoo and saw a...
''' v3 Allow the user to also enter the units. Then depending on the units, convert the distance into meters. The units we'll allow are inches, feet, yards, miles, meters, and kilometers. ''' def number_crunch(): selected_unit = input("Pick a unit of measurement: inches, feet, yards, miles, meters, or kilometers. ...
''' LAB15: Write a program that decrypts a message encoded with ROT13 on each character starting with 'a', and displays it to the user in the terminal. ''' alphabet = 'abcdefghijklmnopqrstuvwxyz ' key = 'nopqrstuvwxyzabcdefghijklm ' def encrypt(word): encrypted = '' for letter in word: index = alph...
import numpy as np import matplotlib.pyplot as plt def lorenz(x, y, z, s=10, r=28, b=2.667): x_dot = s*(y - x) y_dot = r*x - y - x*z z_dot = x*y - b*z return x_dot, y_dot, z_dot dt = 0.01 num_steps = 10000 xs = np.empty(num_steps + 1) ys = np.empty(num_steps + 1) zs = np.empty(num_steps + 1) xs[0], ...
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt def evaluate_cost_function(data, output, thetas): m = len(output) return np.sum((data.dot(thetas) - output) ** 2) / (2 * m) def evaluate_gradient_descent(data, output, initial_thetas, alpha, iterations): cost_history = [...
''' Created on Jul 18, 2019 The module contains one function. The function needs two input parameters. The first input parameter is a list. The second input parameter is txt file operating. The function is to handling the list and save the comments to txt file. @author: ekexigu ''' from re import sub as s def creat...
def lectura(): p = open("paises.txt","r") paises = [linea.rstrip() for linea in sorted(set(p))] p.close() c = open("colores.txt","r") colores= [linea.rstrip() for linea in sorted(set(c))] c.close() a = open("animales.txt","r") animales= [linea.rstrip() for linea in sorted(s...
import re def read_common_words(filename): ''' Reads the commmon words file into a set. If the file name is None returns an emtpy set. If the file cannot be opened returnes an empty set: ''' words = set() if filename != None: try: with open(filename) as fp: ...
class User: users = [] def create(self, username, role, email, password): new_user = {"user_id": len(User.users) + 1, "username": username, "role": role, "email":email, "password":password } Use...
from typing import List, Dict T = int(input()) case: List[int] = [list(map(int, input().split())) for _ in range(T)] for i in range(T): R: List[int] = case[i][1] L: List[int] = case[i][0] for j in range(R): print(j)
from tabulate import tabulate COLORS = ['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'purple', 'grey', 'white', 'gold', 'silver'] TOLL = { 'gold': 5.0, 'silver': 10.0, 'brown': 1.0, 'red': 2.0, 'orange': 3.0, 'green': 0.5, 'blue': 0.25, 'purple': 0.1, 'grey': 0.05, } HEADER = ['Colors', 'Resu...
''' Given a string S, check if it is palindrome or not. Input: The first line contains 'T' denoting the number of test cases. T testcases follow. Each testcase contains two lines of input. The first line contains the length of the string and the second line contains the string S. Output: For each testcase, in a new l...
num1=int(input('enter a numb\t')) num2=int(input('enter a number\t')) print(type(num1)) print(type(num2)) print(num1+num2) num=int(input('enter a number\t')) if num%2==0: print(num,'is an even number') else: print(num,'is an odd number') num=int(input('enter a number\t')) if num>=0: if num==0: print('ze...
import calendar print(calendar.calendar(2018,8))
from itertools import product def gen_sets(set1, set2): x1 = len(set1) y1 = len(set2) tmp_lst = [] for item in set1: x = set1.index(item) set1[x]=int(item) for item in set2: x = set2.index(item) set2[x]=int(item) for i in range (y1...
print("Hi there! Welcome to Monica's first coding project, 'The Python Number Guessing Game'!") print("Let's see if you can guess the number in fewer steps than the computer openent. Let's begin!") def computerGuess(lowval, highval, randnum, count=0): if highval >= lowval: guess = lowval + (highval ...
from pandas import read_csv from numpy import set_printoptions from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 path = r'..\csv_data\pima-indians-diabetes.csv' headernames = ['preg', 'glucos', 'pres', 'skin', 'insulin', 'mass', 'diabetes', 'age', 'class'] dataframe = r...
import numpy import pandas from matplotlib import pyplot as plt from pandas.plotting import scatter_matrix pandas.set_option('display.max_columns', None) pandas.set_option('display.max_rows', None) filename = 'forestfires.csv' names = ['X', 'Y', 'month', 'day', 'FFMC', 'DMC', 'DC', 'ISI', 'temp', ...
""" This is a followup question for Geohash. Convert a Geohash string to latitude and longitude. Try http://geohash.co/. Check how to generate geohash on wiki: Geohash or just google it for more details. Example Given "wx4g0s", return lat = 39.92706299 and lng = 116.39465332. Return double[2], first double is lati...
a = [1, 10, 15, 20] b = [2, 3, 5, 10, 11, 14] c = [100] d = [10, 20, 30, 40, 50] e = [1, 2, 3, 4, 5, 6, 7, 8] arr = [a, b, c, d, e] def heapify(arr, i, n): left = 2 * i right = 2 * i + 1 large = None if left < n and arr[left] > arr[i]: large = left else: large = i if right < n ...
import textwrap def wrap(string, max_width): for i in range(0, len(string), max_width): newLine = [string[i:i+max_width]] print(newLine[0]) return "" if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
n = int(input()) lis = [] temp1, temp2 = 0, 0 for _ in range(n): line = input().split() if line[0] == "print": print(lis) elif line[0] == "sort": lis.sort() elif line[0] == "pop": lis.pop() elif line[0] == "reverse": lis.reverse() elif line[0] == "append": ...
def add(x: float, y: float) -> float: """Returns the sum of two numbers.""" return x + y def subtract(x: float, y: float) -> float: """Returns the subtraction of two numbers.""" return x - y def multiply(x: float, y: float) -> float: """Returns the multiplication of two numbers.""" return x ...
import random class MinimaxState(object): """ Abstract base class of game states suitabe for minimax. Games that fit this model have two players, and a set of terminal states with well-defined values. One player tries to minimize the final value (min), and one tries to maximize it (max). The...
import sys def part1(): with open(filename, "r") as f: lines = f.readlines() numbers = [int(str(line).strip()) for line in lines] for i in range(len(numbers)-2): for j in range(i+1, len(numbers)-1): if numbers[i] + numbers[j] == 2020: retu...
import streamlit as st st.title('LiRA - The Linear Regression App') st.header('H1') st.write("Hello Streamlit World") st.write('To start with we will simulate a Linear Function which will be used to generate our data. In order to do so please select the number of samples:') n = st.slider('Number of samples', 50,...
""" One frequent need when writing interactive console applications is to obtain an integer from the user. Here is a function that does just that: This function takes one argument, msg . Inside the while loop the user is prompt- ed to enter an integer. If they enter something invalid a ValueError exception w...
a = input("请输入字符:") b = [] for n in a : if "a"<= n <= "z": b.append(n.upper()) elif n == " " : b.append('_') else: b.append(n) print("".join(b))
''' Python code that creates dictionaries corresponding to some simple examples of graphs. Implement two short functions that compute information about the distribution of the in-degrees for nodes in these graphs. ''' EX_GRAPH0 = {0:set([1,2]), 1:set([]), 2:set([]) } EX_GRA...
x=2 print(type(x)) title=input("Tell me the title of the book: ") author=input("Tell me the author of the book: ") print(title, "was write for ", author) print(f"{title} was write for {author}") alto=int(input("Dime el alto del rectángulo...:")) ancho=int(input("Dime el ancho del rectángulo...:")) area=alto*ancho ...
import time def visualize_algorithm(maze, canvas, generator, speed): def inner(): maze.draw(canvas) for action, (c1, c2) in generator(maze): if action == 'connect': maze.connect(c1, c2) maze.draw_line_between(canvas, c1, c2, color='white') eli...
num=input("Enter a number:") size=len(num) num=int(num) temp=num sum1=rem=0 while temp!=0: rem=temp%10 sum1+=rem**size temp//=10 if sum1==num: print(num,"is a armstrong number") else: print(num,"is not a armstrong number")
''' Breadth first traversal for binary tree ''' class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self): return self.queue.pop(0) def isEmpty(self): return len(self.queue) == 0 class Node: def __init__(self, value = None): self.value = va...
''' sammy = { 'username': 'sammy-shark', 'online': true, 'followers': 987 } 1- Escreva um dicionário sobre o perfil de um usuário do Gitbub. 2- Adicione novos campos a esse dicionários 3- Exiba esse dicionário mostrando cada chave e valor. ''' username = { 'username': 'Evelyn', 'repositorios': '19', 'follo...
import pygame as pg from game.sprites.sprite_sheet import SpriteSheet import game.tools.constants as c class PointsSprite(pg.sprite.Sprite): """Create a sprite of the 100 points text. Attributes: pointsImage: A Surface object to be used as the sprite's image. passingDirection: A Directions E...
import os import game.tools.constants as c def getHighScore(): """Get the current high score saved in a text file in the game folder. This function only acknowledges the six rightmost digits of a high score (i.e., it reads 1234567 as 234567, or 6 as 000006). If highScoreFile does not exist, this fun...
def mostrar_lista(nodo): for i in 5: print(nodo) nodo = nodo.siguiente def mostrar_backward(list): if list is None:return cabeza = list cola = list.siguiente mostrar_backward(cola) print(cabeza, end=" ") class Nodo: def __init__( self , dato=None , siguiente=None ): self.d...
number=int(input("Enter a number: ")) sum46 = 0 while(number > 0): sum46=sum46+number number=number-1 print("The sum of first n natural numbers is",sum46)
while True: try: num = int(input("Get Integer: ")) break except ValueError: print("Your Input is not integer") numbers = [3,6,5,8] def returnIndex(listNum, num): for i in range(len(listNum)): if listNum[i] == num: return i return -1 print(f"Index o...
def rsa_encrypt(e:int, n:int, msg: str): cypher_text = '' for ch in msg: ch = ord(ch) cypher_text += chr((ch ** e) % n) return cypher_text def rsa_decrypt(d:int, n:int, cipher_t: str): plain_text = '' for ch in cipher_t: ch = ...
import sys import stdarray import stddraw import stdrandom import stdstats class Histogram: def __init__(self, n): self._freqCounts = stdarray.create1D(n, 0) def addDataPoint(self, i): self._freqCounts[i] += 1 def draw(self): stddraw.setYscale(0, max...
import stdio stdio.writeln('1st Hello') stdio.writeln('2nd Hello') stdio.writeln('3rd Hello') i = 4 while i <= 10: stdio.writeln(str(i) + 'th Hello') i = i + 1
import sys import stddraw import luminance from picture import Picture pic = Picture(sys.argv[1]) for col in range(pic.width()): for row in range(pic.height()): pixel = pic.get(col, row) gray = luminance.toGray(pixel) pic.set(col, row, gray) stddraw.setCanvasSize(pic.width(), pi...
stuff = ["abc", "def", "ghi", "jkl", "mno", "pqr"] def example(i, x={}): x[i] = stuff[i] print(x) return x def another(i): x = {} x[i] = stuff[i] print(x) return x if __name__ == "__main__": for i in range(6): mydict = example(i) print() for i in range(6): m...
number = 1 for i in range(0,20): number *= 2 print(number) sum1 = 0 for x in range(1,101): sum1 += x print(sum1,sum1/100) sum1 = 0 count = 1 while count <= 100: sum1 += count count += 1 print(sum1,sum1/100) sum1 = 0 for x in range(1,101): if x % 3 == 0: sum1 += x print(sum1) sum1 = 0 c...
print("Enter the principal amount, rate and time period: ") princ=int(input()) rate=float(input()) time=float(input()) si=(princ*rate*time)/100 print(f"The simple interest for given data is: {si}.")
''' Created on July 15, 2020 @author: charles newman https://github.com/26point2Newms ''' from collections import OrderedDict class LRUCache(object): ''' Implementation of a Least Recently Used Cache (LRU Cache) which discards the least recently used items first. ''' def __init__(self, capacity)...
''' Created on Aug 3, 2020 @author: charles newman https://github.com/26point2Newms ''' import unittest import CNQuickSort class Test(unittest.TestCase): def setUp(self): self.numbers = [54, 789, 1, 44, 789, 321, 852, 32456, 2, 88, 741, 258, 369, 951, 753] def testQuickSort(self): print("Before sort:") prin...
from question_model import Question from data import question_data from quiz_brain import QuizBrain question_bank = [] for dictionary in question_data: text_q = dictionary["question"] text_a = dictionary["correct_answer"] question_bank.append(Question(text_q, text_a)) quiz = QuizBrain(question_bank) ...
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"] n = int(input("Enter year: ")) m = int(input("Enter month: ")) n1 = n % 4 n2 = n % 100 n3 = n % 400 if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m == 10 or m == 12: print(months[m-1],n,"has 31 days") elif m == 4 ...
import math option = """ Choose either 'investment' or 'bond' from the menu below to proceed:\n Investment - to calculate the amount of interest you'll earn on interest Bond - to calculate the amount you'll have to pay on a home loan\n """ print(option) choice = input("Enter option:\t").lower() while (choic...
def isValidSubsequence(array, sequence): array_index = 0 sequence_index = 0 while array_index < len(array) and sequence_index < len(sequence): if array[array_index] == sequence[sequence_index]: sequence_index += 1 array_index += 1 return sequence_index == len(sequence)
celsius=int(input("Enter the temperature in celcius:")) f=(celsius*1.8)+32 print("Temperature in farenheit is:",f)
from tkinter import * import random root = Tk() root.geometry('400x400') root.resizable(0,0) root.title('DataFlair-Rock,Paper,Scissors') root.config(bg ='seashell3') Label(root, text = 'Rock, Paper ,Scissors' , font='calibri 20 bold', bg = 'violet').pack() user_take = StringVar() Label(root, text = 'choose any one...
import sys def get_change(m): n = 0 iter = 0 while (m != 0): if iter == 2: n = n + m m = 0 elif iter == 1: fives = m // 5 n = n + fives m = m % 5 iter = 2 else: tens = m // 10 n = n + te...
import queue class Node(object): def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors class Solution(object): def cloneGraph(self, node): """ :type node: Node :rtype: Node """ visited = dict() def dfs(target): ...
class Solution: """ @param matrix: A list of lists of integers @param target: An integer you want to search in matrix @return: An integer indicate the total occurrence of target in the given matrix """ def searchMatrix(self, matrix, target): count = 0 if matrix is None o...
class Solution: """ @param num: A list of integers @return: An integer """ def longestConsecutive(self, num): numSet = set(num) maxLength = 0 for i in numSet: if (i - 1) not in numSet: currentNum = i currentLength = 1 ...
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the root @return: the tilt of the whole tree """ def findTilt(self, root): self.totalTilt = 0 self...
from collections import OrderedDict class MyValue: def __init__(self, value, frequency): self.value, self.frequency = value, frequency class LFUCache: """ @param: capacity: An integer """ def __init__(self, capacity): self.capacity = capacity self.minFreq = 0 ...
def triangle(n): return recursive_triangle(n, n) def recursive_triangle(k, n): if n > 0 and k > 0: if k <= n: if k == 1: returnString = "" for numberOfSpaces in range(n-1): returnString += " " ret...
class MaxHeapPriorityQueue: def __init__(self): self.heap=[] self.size = 0 def __len__(self): return len(self.heap) def parent(self,index): if index <= 1 or index > len(self): return None else: return self.heap[(index // 2)-1] def sw...
def merge(list1, list2): indexOne, indexTwo, currentCount = 0,0,0 outputList = [] while currentCount < len(list1) + len(list2): if indexOne < len(list1) and indexTwo < len(list2): if list1[indexOne] < list2[indexTwo]: ...
from __future__ import absolute_import, division, print_function, unicode_literals import itertools as it def take(items, indices): r""" Selects a subset of a list based on a list of indices. This is similar to np.take, but pure python. Args: items (list): some indexable object indic...
import webbrowser class Movies(): ''' The class movie contains the basic data of the movie, as title, storyline, trailer url and poster image url''' VALID_RATINGS = ["G","PG","PG-13","R"] def __init__(self, title, storyline, trailer_youtube_url, poster_image_url): self.title = title s...
i = 100 2 + 2 == 4 def math_block(): num = int(raw_input("enter a number >>> ")) a = "1 + 1 = __" math_block()
year=int() if(year%4): print("is a leap year") else: print("is not leap year")
import random print("-------------------------------------") print(" GUESS THE NUMBER") print("-------------------------------------") print() number = random.randint(0, 100) guess = -1 name = input("Name, please. ") while guess != number: guess_text = input("Guess a number between 0 and 100: ") gue...
number = 9999 if (number>=1000): print(4) elif (number>=100): print(3) elif (number>=10): print(2) else: print(1)
def roots(a,b,c): D = (b*b - 4*a*c) print() print("D = " + str(D)) if(D >= 0): print("REAL ROOTS") D = D**0.5 x1 = (-b + D) / (2*a) x1 = (-b - D) / (2*a) print("x1 = " + str(x1) + " x2 = " + str(x2)) elif(D < 0): D = (D * -1)**0.5; print("IMAGINARY ROOTS") print("x1 = -" + str(b/(2*a)) + " - "...
import tkinter as tk window = tk.Tk() window.title('test window') window.geometry('500x300') e = tk.Entry(window) e.pack() def add(): s = e.get() t.insert(1.0, s) def insert(): s = e.get() t.insert('insert', s) def append(): s = e.get() t.insert('end', s) b1 = tk.Button(window, text='a...
''' Perceptron Learning Algorithm ''' import numpy as np import matplotlib.pyplot as plt def runPLA(num): a,b,c = np.random.rand(3)*100-50 f = [a,b,c] x = np.array([-55,55]) y = eval('(-a*x-c)/b') fig = plt.plot(x,y,'c-') points = np.random.rand(num,2)*100-50 offset = np.ones...
''' tutorial (4) - function, recursive function, module 2016/06/15 David Hsu ''' def factorial(n): fact = 1 for i in range(1,n+1): fact *= i return fact def factorialRecursive(n): if n == 0 : return 1 else: return n*factorialRecursive(n-1) def fibonacci(n): if n=...
import os verbose = True class RenameFile: def __init__(self, src, dest): self.src = src self.dest = dest def execute(self): if verbose: print(f"[renaming '{self.src}' to '{self.dest}']") os.rename(self.src, self.dest) ...
class Pizza: def __init__(self, builder): self.garlic = builder.garlic self.extra_cheese = builder.extra_cheese def __str__(self): garlic = 'yes' if self.garlic else 'no' cheese = 'yes' if self.extra_cheese else 'no' info = (f'Garlic: {garlic}', f'Extra cheese: ...