text
stringlengths
5
121k
def merge_list(array, start, mid, end): left = array[start:mid] right = array[mid:end] k = start i = 0 j = 0 while (start + i < mid and mid + j < end): if (left[i] <= right[j]): array[k] = left[i] i = i + 1 else: ...
import string alphabets = set(string.ascii_lowercase) inp = ['How quickly daft jumping zebras vex','How quickly daft jumping zebras'] inp_nospace =[None]*inp.__len__() for i in range(len(inp)): inp_nospace[i] = inp[i].replace(' ', '') output = ("is not a pangram","is a pangram")[set(inp_nospace[...
from queue import PriorityQueue class Node: def __init__(self, index, list_num): self.index = index self.listNum = list_num def merge(sorted_arrays): pq = PriorityQueue(0) res = [] for idx, item in enumerate(sorted_arrays): pq.put((item[0], Node(0, idx))) while not pq.e...
def gradingStudents(grades): result = [] for grade in grades: if grade < 38: result.append(grade) else: if grade % 5 == 0: result.append(grade) else: count = 0 temp = grade while temp % 5 != 0: ...
from collections import Counter def check_palindrome(s): return sum( ch % 2 for ch in Counter(s).values()) <= 1 print(check_palindrome("dokilolokido"))
def solve(string): arr = list(string) p = [arr[0:2], arr[1::-1]] for i in range(2, len(arr)): temp1 = [[]] for s in p: for j in range(len(s)): temp2 = s[:] temp2.insert(j, arr[i]) temp1.append(temp2) temp1.pop(0) p...
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing wei...
fname = input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" fh = open(fname) count = 0 for line in fh: line = line.rstrip() if not line.startswith('From:'): continue pieces = line.split() count = count + 1 print(pieces[1]) print("There were", count, "lines i...
""" 实现斐波那契数列 方法五:递归 """ def Fib_list(n) : if n == 1 or n == 2 : return 1 else : m = Fib_list(n - 1) + Fib_list(n - 2) return m if __name__ == '__main__': while 1: print("**********请输入要打印的斐波拉契数列项数n的值***********") n = input("enter:") if not ...
""" 实现斐波那契数列 方法一:生成器 """ def Fib_yield_while(max): a, b = 0, 1 while max > 0: a, b = b, a + b max -= 1 yield a def Fib_yield_for(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b yield a if __name__ == "__main__": ...
import copy import numpy as np __all__ = ['zerOut'] def zerOut(array, tol = 1e-15): r"""Takes as input an array and tolerance, copies it, in this copy, nulls out real and complex part of each entry smaller than the tolerance, returns the copy. Parameters ---------- array : numpy.ndarray ...
class Solution: def search(self, nums: List[int], target: int) -> int: n = len(nums) left, right = 0, n - 1 while left <= right: mid = left + (right - left) // 2 if nums[mid] == target: return mid ...
class Solution: def search(self, nums: List[int], target: int) -> bool: l = 0 r = len(nums)-1 while l<=r: m=(r+l)//2 if target in [nums[m], nums[r], nums[l]]: return True elif nums[m]==nums[l] or nums[m]==nums[r]: r-=1 l+=1...
class Solution: def allPossibleFBT(self, n: int) -> List[TreeNode]: if n % 2 == 0: return [] dp = [[] for _ in range(n + 1)] dp[1].append(TreeNode(0)) for count in range(3, n + 1, 2): for i in range(1, count - 1, 2): ...
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: cur = [0] * k n = len(cookies) def dfs(i, zero_count): if n - i < zero_count: return float('inf') ...
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: directions = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)] dp = [[[0] * n for _ in range(n)] for _ in range(k + 1)] dp[...
class Solution: class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.max_size = 1 def find(self, x): if x != self.parent[x]: self.parent[x] = self.find(self.pa...
class Game: def __init__(self, game_dict: dict): self.__name = game_dict["name"] self.__category = game_dict["category"] self.__year = game_dict["year"] @property def name(self): return self.__name @property def category(self): return self.__category @...
import time a = float(input("Podaj pierwszą liczbę: ")) b = float(input("Podaj drugą liczbę: ")) c = 0 add_start = time.perf_counter_ns() c = a + b add_stop = time.perf_counter_ns() mul_start = time.perf_counter_ns() c = a * b mul_stop = time.perf_counter_ns() print("czas dodawania to: {0}".format(add_stop-add_star...
def f1(A,B): """Returns the difference between the pair of values with the smallest non-negative difference, one from each input array. Args: A: A list of integers. B: A list of integers. Returns: An integer difference, or None if...
from .doubly import Doubly from collections import deque class LinkedListQueue: """Queue implemented with my doubly linked list class. Attributes: queue: A Doubly instance that simulates the queue. """ def __init__(self,loads=None): """Inits an empty LinkedListQueueQueue by de...
from random import randint from math import factorial from statistics import median, stdev def f1(lst): """Shuffles a list of length N so that all N! permutations are equally likely. The list is shuffled in place. Args: lst: A list of objects. """ for i in rang...
def minmax(arr): min = arr[0] max = arr[0] for i in arr: if i < min: min = i elif i > max: max = i else: continue print((min, max)) print(minmax([1, 9, 0, -1, 15]))
import random import numpy as np import matplotlib.pyplot as plt import sys def getLogData(logfile): logline = open(logfile, "r").readlines() cte = [0] * len(logline) x = [0] * len(logline) for i in range(len(logline)): cte[i] = float(logline[i].strip('\n')) x[i] = i return x, cte def get...
def parse_config_file(): with open('config.cfg', 'r') as f: text = f.read() lines = text.split('\n') pairs = [line.split('=') for line in lines if (not line.isspace() and not len(line) == 0)] config = {} for pair in pairs: config[pair[0].strip()] = pair[1].stri...
def readFile(filename): f = open(filename) words = f.read().splitlines() words = [int(i) for i in words] f.close() return words def candidate2Product(arr, val): i = 0 j = len(arr) - 1 arr.sort() while i < j: a = int(arr[i]) b = int(arr[j]) if a + b < val: ...
from ListNode import ListNode class LinkedList: def __init__(self): self.head = None self.tail = None self.count = 0 def insert(self, x): self.insertAtRear(x) def insertAtRear(self, x): if (self.head == None): self.head = ListNode(x, None, None) ...
""" Task 6.2a Make a copy of the code from the task 6.2. Add verification of the entered IP address. An IP address is considered correct if it: - consists of 4 numbers (not letters or other symbols) - numbers are separated by a dot - every number in the range from 0 to 255 If the IP address is incorrect...
""" Task 4.8 Convert the IP address in the ip variable to binary and print output in columns to stdout: - the first line must be decimal values - the second line is binary values The output should be ordered in the same way as in the example output below: - in columns - column width 10 characters (in binary you ne...
'Tic-Tac-Toe Mechanics' import copy class game_board(): def __init__(self): self.board = [['','',''],['','',''],['','','']] def add_element(self,element,row,column): if self.board[row][column] != '': return False self.board[row][column] = element return True ...
a=int(input("enter the position from " "which rotation to be performed")) i=a-1 n=len(list) listt=[] for num in range(i,n): listt.append(list[num]) j=0 for num in range(j,i): listt.append(list[num]) print(listt)
from re import * f=open("phonenumber","r") for num in f: rule="(91)?[0-9]{10}" matcher=fullmatch(rule,num) if matcher==None: print("invalid entry") else: print("valid entry")
from typing import List class Solution: def lengthOfLIS(self, nums: List[int]) -> int: memo = {} def recursion(nums: [int], i: int) -> int: if i in memo: return memo[i] if i == len(nums) - 1: return 1 maxSubLength ...
n1, n2 = 0, 1 count = 0 print("Fibonacci sequence:") while count < 50: print(f"term: {count} / number: {n1}") nth = n1 + n2 n1 = n2 n2 = nth count += 1
import time import RPi.GPIO as GPIO class ult(): def __init__(self): GPIO.setmode(GPIO.BOARD) self.GPIO_TRIGGER = 36 self.GPIO_ECHO = 37 GPIO.setup(self.GPIO_TRIGGER,GPIO.OUT) GPIO.setup(self.GPIO_ECHO,GPIO.IN) GPIO.output(self.GPIO_TRIGGER,False) ...
def game(gameboard, positionlist, running_position_list, turnlist): """Function calculates what turn the game is up to, assigns a player (1 or 2) to that turn, asks for userinput, analyzes whether the input move is valid, converts the player input into a valid list position, and appends the move to the nested ga...
import logging, sys class LogFile(object): """File-like object to log text using the `logging` module.""" def __init__(self, name=None): self.logger = logging.getLogger(name) def write(self, msg, level=logging.INFO): self.logger.log(level, msg) def flush(self): for handler i...
""" Created on Tue Jun 8 18:35:30 2021 @author: exlonk """ print("Ingrese el valor de compra e ingrese un valor de cero para finalizar") contador = 0 monto = None numero_compra = 1 while monto != 0: monto= float(input("Valor compra {0}: ".format(numero_compra))) if monto > 0 : contador += monto ...
from os import system system("clear") s = "Alex-David-Lopez" delimiter = "-" print(s.split(delimiter)) lista = ["Programar","es","lo","mejor"] delimiter = " " print(delimiter.join(lista)) a = "casa" b = "casa" print(a is b) c = ["a","b","c"] d = ["a","b","c"] print(c is d) num = [1,2,3] num2 = num num2[0] = 0...
import re re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))') def camel_case_to_spaces(value): """ Split CamelCase and convert to lowercase. Strip surrounding whitespace. """ return re_camel_case.sub(r' \1', value).strip().lower()
while True: reply = input('Enter txt:') if reply == 'stop': break elif not reply.isdigit(): print('Bad!'*8) else: num = int(reply) if num < 20: print('low'*4) else: print(num**2) print('Bye'*3)
mystring="This is the new change" mylist = [] for letter in mystring: mylist.append(letter) print(mylist) mystring1="Hi There" mylist1 =[letter for letter in mystring1] print(mylist1) mylist2=[num for num in range(0,11) if num%2==0] print(mylist2) mylist2=[num**2 for num in range(0, 11)] print(mylist2)
tuples1=(1,2,3,"age") print(type(tuples1)) print(tuples1[0]) print(len(tuples1)) print(tuples1[-1]) print(tuples1)
def myfunc(*args): mylist=[] for item in args: if item%2==0: mylist.append(item) else: continue print(mylist) print(myfunc(-2,4,3,5,7,8,10)) def myfunct(*args): mylist1=[] for item in args: index=args.index(item) if (item==item.uppe...
import math a = 25.0 print("Squaring a square-root:") while ( math.sqrt(a)**2 == a ): print('sqrt(a)^2 = ' + str(a) + ' = ' + str(math.sqrt(a)**2)) a *= 10 print('sqrt(a)^2 = ' + str(a) + ' != ' + str(math.sqrt(a)**2)) expo = math.floor(math.log10(a))-1.0 b = a/(10**expo) print("Ajusting decimal placement before...
a = [1,2,3,4,5,6,7] for element in a: print(element) numbers = [1,2,3,4,5,6,7,8,9,10] for number in numbers: if number % 2 == 0 : print("even number: {}".format(number)) else: print("odd number: {}".format(number))
if True: print("it's true") if False: print("it's false") number = input("input a number >>> ") number = int(number) if number % 2 == 0: print("even") if number % 2 != 0: print("odd") if number < 10: print("less than 10") elif number < 20: print("less than 20") elif number < 30: ...
import abc class Human(metaclass=abc.ABCMeta): @abc.abstractmethod def smoking(self): pass @abc.abstractclassmethod def drink(cls): pass @abc.abstractstaticmethod def play(): pass class Man(Human): def smoking(self): print("smoking") ...
l1 = [1, 8, 7, 2, 21, 15] print(l1) l1.sort() print("Sorted: ", l1) l1.reverse() print("Reversed: ",l1) l1.reverse() print("Reversed 2: ",l1) l1.append(45) print ("Append", l1) l2 = [1,5, 4, 10] l1.append(l2) print("Append 2", l1) l1.insert(0, 100) print("Inserted", l1) l1.pop(2) print("Popped", l1) l1.rem...
def remov(strg): word = input("Enter the word you want to remove: ") newStrng = strg.replace(word, "") newStrng1 = newStrng.strip() return newStrng1 strg = input("Enter your text: ") print(remov(strg))
a = int(input("Enter number one: ")) b = int(input("Enter number two: ")) c = int(input("Enter number three: ")) d = int(input("Enter number four: ")) if(a>b and a>b and a>d): print(a) elif(b>c and b>d): print(b) elif(c>d): print(c) else: print(d )
t = (1, 2, 3, 4, 5, 1, 1) print("Count", t.count(1)) print("Index", t.index(5))
a = 34 b = 4 print("the value of 3+4 is ", 3+4) print("the value of 3-4 is ", 3-4) print("the value of 3*4 is ", 3*4) print("the value of 3/4 is ", 3/4) a = 34 a += 2 print(a) b = (7>14) c = (7<14) d = (7==14) e = (7>=14) print(b) print(c) print(d) print(e) boo1 = True bool2 = False print("The value of bool1 an...
myDict = { "Pankha" : "Fan", "Darwaja" : "Door", "Hawa" : "Air", "Badal": "Clouds", "Aasmaan" : "Sky" } print("options are ", myDict.keys()) a = input("Enter the hindi word\n") print("The meaning of your word is:\n", myDict.get[a])
text = input("Enter your text: ") text1 = text.capitalize() num1 = text1.find("Harry") num2 = text1.find("harry") if (num1==-1 and num2==-1): print("Not talking about Harry") else: print("Talking about Harry")
class Employee: company = "Google" salary = 100 harry = Employee() rajni = Employee() harry.salary = 300 rajni.salary = 400 print(harry.salary) print(rajni.salary)
nome = input("Digite seu nome: ") sobrenome = input("Digite seu sobrenome: ") tamanhoNome = len(nome) + len(sobrenome) print(f'O nome tem {tamanhoNome} caracteres no total.')
""" calc.py """ def add(x, y): """ :param x: :param y: :return: sum of x and y """ return x + y def difference(x, y): """ :param x: :param y: :return: returns difference of x and y """ return x - y def multiply(x, y): """ :param x: :param y: :return:...
from collections import namedtuple class maxHeap: def __init__(self, array=None): self._heap = [] if array is not None: for i in array: self.insert(i) def insert(self, value): self._heap.append(value) _sift_up(self._heap, l...
import cv2 import numpy as np import matplotlib.pyplot as plt def canny(image): gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) blur = cv2.GaussianBlur(gray, (5,5),0) canny = cv2.Canny(blur, 50, 150) return canny def regionofinterest(image): height = image.shape[0] polygons = np.array([ [(2...
""" Created on Sat Apr 28 12:36:57 2018 @author: jkell """ import numpy as np resolution = 10 import random def intersect_line(x1,y1,x2,y2,linex): """ Determine where the line drawn through (x1,y1) and (x2,y2) will intersect the line x=linex """ if (x2 == x1): return 0 return ((...
""" Author: Varun Nair Date: 6/25/19 """ import numpy as np def sig(x): """Defines sigmoid activation function""" return (1 / (1+ np.exp(-x))) def sig_prime(x): """Defines the derivative of the sigmoid function used in backprop""" return sig(x)*(1-sig(x)) def RELU(x): """Defines ReLU activation f...
from time import time, sleep from timeit import timeit, repeat def main(): """ # measure timing # example 1 t1 = time() num = 5 num *= 2 print(time() - t1) # example 2 t1 = time() sleep(1.0) print(time() - t1) # using timeit print(timeit('num = 5; num *= 2', numb...
"""Chapter 12 - Be a pythonista""" def dump(func): """Print input arguments and output value(s)""" def wrapped(*args, **kwargs): print("Function name: %s" % func.__name__) print("Input arguments: %s" % ' '.join(map(str, args))) print("Input keyword arguments: %s" % kwargs.items()) ...
""" 1. Create a class called Product having attributes code,name,desc,manu,price having following methods addProduct(self,code,name,desc,manu,price) displayProduct(self) return product attributes 2. show the product having maximum price 3. show all products of a specific manufacturer 4. s...
import sqlite3 conn = sqlite3.connect('olympicsdb.db') conn.execute(''' CREATE TABLE if not exists olympics ( location TEXT, year INTEGER, country TEXT, gold INTEGER, silver INTEGER, bronze INTEGER, total INTEGER ) ''' ) print('table created successfully') conn.close()
""" File management Modes w - write mode - existing content will be deleted a - content gets added to the existing file r - read content of a file """ file=open("olympics.txt","w") file.write("Olympics 2020 was held in japan \n") file.write("More than 170 countries participated in it") file.close() file=open("olympic...
""" List - Dynamic array It allows duplicate values It maintains the order of insertion Elements can be accessed using index """ runs =[10,40,50,60] print('runs -list ',runs) print('runs -list - data type ',type(runs)) print("list length ",len(runs)) ''' Adding an element ''' runs.append(35) print("after append ",run...
def diff(n,ar): s1=0;s2=0 for i in range(n): s1=s1+ar[i][i] s2=s2+ar[i][n-1-i] d=abs(s1-s2) return d n=int(input("Enter the size of matrix:")) ar=[] for i in range(n): a=map(int,input().split()) ...
def uthopianTree(n): h=1 for i in range(1,n+1): if(i%2!=0): h=h*2 else: h=h+1 return h tc=int(input("Enter d no. of TestCases:")) for i in range(tc): n=int(input()) print(uthopianTree(n))
import math import numpy as np class Point: def __init__(self, x, y): self.__x = x self.__y = y def getX(self): return self.__x def getY(self): return self.__y def distanceToPoint(self, other_point): dx = self.__x - other_point.ge...
print(__doc__) import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score diabetes = datasets.load_diabetes() diabetes_X = diabetes.data[:, np.newaxis, 2] diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabet...
def primes_formula(a, b, n): return n ** 2 + a * n + b def get_primes(limit): candidates = set(range(2, limit)) for i in range(2, limit): candidates.difference_update({i * n for n in range(i, limit)}) return candidates def primes_below(end): if end < 2: return [] lng = (...
tree = [1, 2, 5, 10, 20, 50, 100] count = 0 def coinsum(total): count = 0 def make_change(current_total): nonlocal count if current_total == total: count += 1 return if current_total > total: return for c in tree: ...
import math memoize_dict = {} def step(start): if start % 2 == 0: start = int(start / 2) else: start = 3 * start + 1 return start def is_power_of_two(number): value = math.log(number, 2) return math.floor(value) == math.ceil(value) def cycle_len(start): c = 1 while st...
import random from fractions import gcd def make_data(): """Make two random natural numbers""" number1 = random.randint(1, 100) number2 = random.randint(1, 100) return { "number1": number1, "number2": number2, } def get_number1(data): """Return random natural numbers""" r...
import sys import re seats = [] rows = 128 cols = 8 def caluate_id(row, col): return (row) * 8 + (col) def calculate_seat(instructions, rows, cols): plane_rows = list(range(0, rows)) plane_cols = list(range(0, cols)) for instr in instructions: if (instr == 'F'): plane_rows = plane_rows[:len(plane_r...
import sys numbers = [] found = -1 if len(sys.argv) != 2: print("usage: part1.py input.txt") exit(1) with open(sys.argv[1]) as f: data = f.read().splitlines() for num in data: numbers.append(int(num)) for i, num1 in enumerate(numbers): if (found > -1): break for j, num2 in enumerate(numbers): ...
class Node: def __init__(self, data): self.data = data self.right = None self.left = None class BST: def __init__(self): self.root = None def __str__(self): if self.root == None: return "empty" else: return str(self.root...
position=[0,0] while True: a= input("enter the direction and steps :") if not a: break direction, steps= a.split(' ') steps=int(steps) if (direction== "up"): position[0]= position[0]+steps elif (direction=="down"): position[0]=position[0]-steps if ...
''' this programme test the compound interest calculator ''' from calc import monthly_compounding def test_tautology(): assert 3 == 3 def test_zeros(): initial = 0 monthly = 0 years = 0 annual_rate = 0 final_sum = monthly_compounding(initial, monthly, years, annual_rate) ...
""" This module contains the classes that represent the recipe book and recipe, used in the application. """ class RecipeBook: """ Represents a recipe book (collection of recipes) """ def __init__(self, recipes): self.recipes = recipes @classmethod def from_json_list(cls, recipebook): ...
import heap as H def heapSort(arr): heap = H.heap() for i in arr: heap.push(i) for i in range(len(arr)): arr[len(arr)-1-i] = heap.popMax() """#use: x= [23,2,454,6,8787,3] heapSort(x) print(x) #======== output: ============= [2, 3, 6, 23, 454, 8787] """
"""Factory classes for Dots & Co game While quite concise, the purpose of these classes is to manage creation of instances (of dots, etc.). By having a class managing this process, hooking into and extending this process becomes quite simple (through inheritance). This allows for interesting things to be done, such as...
from collections import defaultdict from common import manhattan from common import all_points from common import start_x, end_x, start_y, end_y def nearest_point(coord): nearest = None smallest = float('inf') duplicate = False for point in all_points: distance = manhattan(point, coord) ...
""" DAY 13 The map is represented as an array, containing all the track pieces, using their original character representation, with a few exceptions: 1. The carts are removed from the map and stored in a separate array. # 2. Empty space is replace by an empty string for easier conversion to bool. 3. Empty ...
from regexp import SimpleMathematicalOperationsCalculator as Calculator one_variable = 'a-=1a+=1a+=10a+=a' three_variables = 'a=1a=+1a=-1a=ba=b+100a=b-100b+=10b+=+10b+=-10b+=bb+=b+100' \ 'b+=b-100c-=101c-=+101c-=-101c-=bc-=b+101c-=b-101' raw_data = 'saf nahu haou fhj sf,aa134%...jfbak fa sd fb+=as...
def ksub(n,k): if k<=0 or k==n: return 1 elif k<0 or n<0 or k>n: return 1 else: return (ksub(n-1,k-1)+ksub(n-1,k)) def stirling(n,k): if n==k: return 1 elif k==0 or k>n: return 0 else: return k*stirling(n-1,k) + stirling(n-1,k-1) def bell...
""" Created on Fri Mar 19 16:45:19 2021 @author: RobertoFormenti """ import sqlite3 from sqlite3 import Error conn = sqlite3.Connection('file:biblio.sqlite?mode=rwc', uri=True) def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Conn...
url = "http://www.flyingbear.co/our-story.html#:~:text=Flying%20Bear%20is%20a%20NYC,best%20rate%20in%20the%20city." url_list = url.split("/") domain_name = url_list[2] print (domain_name.replace("www.",""))
''' Advent of Code 2019, Day 2, Pt2 An encoding problem with list input of ints that's an analogy for assembly language. Intcode programs work in blocks of 4 numbers at a time, with 3 commands 1: tells you to take the numbers at the indices of the next two numbers, add them, then place the result at the 3rd...
'''Code for task in chapter 10''' from collections import namedtuple from math import sqrt def get_the_most_similar_parameter( parameter, other_parameters): '''Get the most similar parameter''' the_most_similar_parameter = None, float('inf') for another_parameter, another_parameter_values...
'''Code for tasks from chapter 9''' from collections import namedtuple ThingForGrab = namedtuple( 'Thing_for_grab', ['weight', 'price'] ) def print_prices_matrix(prices, subjects_names): '''Prints prices in a beautiful way with their string's names''' max_len_for_name_in_string_names = len(max( ...
class Operation(object): def __init__(self,operation_type, value1, value2, result): self.operation_type = operation_type self.value1 = value1 self.value2 = value2 self.result = result def get_operation_type(self): return self.operation_type def get_value1(self): return self.value1 def...
a = int(input()) b = int(input()) result = a // b if result % 2 == 0: print(False) else: print(True)
class Person: def __init__(self, name, age): self.name = name self.age = age def myfun(self): print("Hello my Name is " + self.name) p1 = Person("Johan", 36) p1.myfun()
class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) class Student(Person): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.greaduationyear...
from pythonping import ping from time import sleep, localtime, strftime import sys, time print("##########################") print("........EAGLE PING........") print("##########################") print(" Made by: Jake Saunders ") print("##########################\n") logpath = "output.txt" packettotal = 2 while ...
class node: def __init__(self,dataval): self.dataval=dataval self.nextval = None class stack: def __init__(self): self.headval = None def push(self,dataval): if self.headval == None: self.headval = node(dataval) else : t = self.headval self.headval = node(dataval) self.headval....
""" Created on Mon Sep 25 12:16:24 2017 @author: norrisa """ def findVowels(word): vowels = ['a', 'e', 'i', 'o', 'u'] found = [] for letter in word: if letter in vowels: print(letter) def findVowelsV2(word): vowels = ['a', 'e', 'i', 'o', 'u'] found = [] for letter in word...