text
stringlengths
5
121k
import math import os import random import re import sys def migratoryBirds(myArr): migStats = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} maxBird = 0 maxCount = 0 for birdType in myArr: migStats[birdType] = migStats[birdType] + 1 if migStats[birdType] > maxCount: ...
import math import os import random import re import sys def kangaroo(x1, v1, x2, v2): if (v1 != v2): jump = (x2 - x1) // (v1 - v2) rem = (x2 - x1) % (v1 - v2) print("Kangaroo 1 starts at ", x1, " and jumps ", v1, " m/j.") print("Kangaroo 2 starts at ", x2, " an...
def dataBuah(): print('>>>>DAFTAR HARGA BUAH<<<<') for x,y in buah.items(): print('-',x,'(Harga: Rp.', y,')') print('') def tambah(): print('Masukkan nama buah yang ingin ditambahkan:',end='') nama=input() if nama in buah: print('Buah',nama,'sudah ada di dalam daftar') else:...
print(' DAFTAR NILAI MAHASISWA') print('----------------------------------------------------') nilaiMhs = [{'nim' : 'A01', 'nama' : 'Amir', 'mid' : 50, 'uas' : 80}, {'nim' : 'A02', 'nama' : 'Budi', 'mid' : 40, 'uas' : 90}, {'nim' : 'A03', 'nama' : 'Cici', 'mid' : 50, 'uas' : ...
myName = input("What is your name? ") print("Hi " + myName + ", you have chosen to book a horse riding lesson, press enter to continue") input("") print("please answer the following 2 questions to ensure that you will be prepared on the day of your lesson.") input("") QuestionOne = None while QuestionOne not in...
import sys import os from github import Github from getpass import getpass path = "/Users/nikourriola/Desktop/projects/" username = input("username: ") password = getpass("password: ") def make(): """ Create a Github repository at specified path Parameters: None Returns: None "...
import re text = "av" pattern = r"a+" res = re.match(pattern, text) print(res)
thisdict = {1:"a",2:"b"} for x, y in thisdict.items(): print(x * x, y)
from pathlib import Path import sys def wordcount(path): with path.open() as fh: lines = 0 words = 0 chars = 0 for line in fh: chars += len(line) words += len(line.split()) lines += 1 print(f"chars={chars} words={words} lines={lines} {pat...
px, py = map(int, input("enter coord of p: ").split()) qx, qy = map(int, input("enter coord of q: ").split()) print("eucledian distance between 2 pixels is:",((px-qx)**2 + (py-qy)**2)**(0.5)) print("manhattan distance between 2 pixels is:",abs(px-qx) + abs(py-qy)) print("chess-board distance between 2 pixels i...
import copy import json def load_table(table_path): """ Load table from table_path. Args: table_path: Path to the source table json file. Returns: table, a datastructure converted from json file. """ with open(table_path, 'r') as f: return json.load(f) def convert_p...
def returnSum(numberOne, numberTwo): return(numberOne + numberTwo) numberOne = 10 numberTwo = 20 additionResult = returnSum(numberOne, numberTwo) print(additionResult)
import operator x = int(input("how many students are present in class?")) name = [] marks = [] dic ={} if x>=3: for i in range(0,x) : n = input("Name of student {} = ".format(i+1)) name.append(n) m = int(input("Marks of student {} = ".format(i+1))) marks.append(m)...
import bluetooth target_name = "AL HydraMotion" target_address = None nearby_devices = bluetooth.discover_devices() print(nearby_devices) for bdaddr in nearby_devices: if target_name == bluetooth.lookup_name( bdaddr ): target_address = bdaddr break if target_address is not None: print("foun...
fruits = ['banana','apple','mango'] for index in range(len(fruits)): print('当前水果 : %s'%fruits[index]) print ('Good bye!')
top = ('physics','chemistry',1997,2000) print(top) del top print('After deleting top:',top)
top1 = ('physics','chemistry',1997,2000) top2 = (1,2,3,4,5,6,7) print('top1[0]:',top1[0]) print('top2[1:5]:',top2[1:5])
num = int(input()) if num ==3: print('boss') elif num ==2: print('user') elif num ==1: print('worker') elif num <0: print ('error') else: print ('rodman')
''' ДЗ 1. сделать автомат с разменом монет на циклах 2. найти произведение элементов списка, минимальный и максимальный элемент списка 3. найти 2 одинаковых элемента в списке 4. поменять местами мин и макс элементы списка 5. Сдви...
a= 21 b= 30 c= a print(a==b) print(c==a) print(a>=b) print(a<=b) print(a<b) print('------------------------------------') print(a == b and b == c) print(a == b or a == c) print(not a == 21) print(True and True ) print(not False)
print("**********dictionary in python") students_dic = {1 : 'Atishay' ,2 : 'Vikas' ,3 : 'Aakash' } print(students_dic) print("**********fetch value in python") print(students_dic[2]) print("**********nested list in dictionary in python") students_dic[4] = ['107 Simran sun' , 'indore' ,'mp'] print(students_dic...
a = 5 print(a) print("-----------") print (a+a) print("-----------") a = 15 ; print(a) print("-----------") a=a + a print (a) print("----Power-------") print(5**5) print("-----Yearly Income calcultor------") income = 15000 months_in_a_year = 12 yearly_income = income * months_in_a_year print(yearly_inc...
class Person: def __init__(self,name,mob_no,address): self.name = name self.mob_no = mob_no self.address = address def eat(self): print('I eat food') class Employee(Person): def __init__(self,name,mob_no,address,company_name): Person.__init__(self,name,mob_no,add...
def sort_by_name(sort_list): return sorted(sort_list, key=lambda dct: dct['name']) def sort_by_price(sort_list): return sorted(sort_list, key=lambda dct: dct['price']) products = [ {'name': 'Mobie', 'price': 12}, {'name': 'Camera', 'price': 20}, {'name': 'Flask', 'price': 5}, {'name': 'Cof...
import random import os chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!$%&/#*=" class colors: BLUE = '\033[94m' CYAN = '\033[96m' WARNING = '\033[93m' GREEN = '\033[92m' FAIL = '\033[91m' ENDC= '\033[0m' def optionMenu(): g_password = gener...
import math import heapq def dijkstras(graph, start): distances = {} for vertex in graph: distances[vertex] = math.inf distances[start] = 0 vertices_to_explore = [(0, start)] while vertices_to_explore: distance, vertex = heapq.heappop(vertices_to_explore) ...
days = ["Mon", "Tue", "Wed", "Thu", "Fri"] print(days) days.append("Sat") days.reverse() print(days)
import time import random def print_pause(message_to_print): print(message_to_print) time.sleep(2) def intro(): print_pause('Welcome to New Jersey, some people say that you can find the portal to hell \n') print_pause('luckly for you that your grandfather is a archyologist. \n') print_pause('You mak...
age = input("What is your current age?") int_as_age = int(age) remaining_years = 90 - int_as_age remaining_days = remaining_years * 365 remaining_weeks = remaining_years * 52 remaining_months = remaining_years * 12 print(f'You have {remaining_days} days, {remaining_weeks} weeks and {remaining_months} months left....
class DraftYear: teamName = '' year = '' picks = [] def __init__(self, name, year): self.teamName = name self.year = year self.picks = [] def add_pick(self, pick_num, pick_round, position, player): temp = [pick_num, pick_round, position, player] self.pi...
variable = "Tengo un conejo "; print(variable); variable2 = "llamado POL"; print(variable2); print(variable + variable2); print(variable*2); length_variable = len(variable); print("La variable "+variable+", tiene ",length_variable); print(variable[0]); variable3 = variable+variable2; print(variable3.title()...
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" print(full_name) full_name = f"Hell0, {full_name.title()}!" print(full_name) full_name = "{} {}".format(first_name, last_name) print("Python") print("\tPython") print("Languages:\nPython\nC")
""" Created on Tue Feb 23 11:26:26 2021 @author: szymo """ from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer ps = PorterStemmer() def process_word(word): word = ps.stem(word) word = word.lower() word = word.strip() return word if __name__ == '__main__': categories = {...
""" Alexander Urbanyak CS4720(01) Created: 01-25-2019 Python 3.6 """ def read_file(file_name): assert file_name is not None file = open(file_name, "r") result = file.readlines() file.close() return result def to_upper_case(lines): for line in lines: lines[line...
import math import os import random import re import sys def sockMerchant(n, ar): socks_data = {} for item in ar: old_count = socks_data.get(item,0) socks_data[item] = old_count+1 count = 0 for value in socks_data.values(): count += value//2 return count if _...
n=int(input("The value of n")) fact=1 for each in range(1,n+1): fact=fact*each print(fact)
a=int(input("Enter a No")) fact=1 for i in range(1,a+1): fact=fact*i print(fact)
import glob from itertools import chain def filelist(root: str, recursive: bool = True) -> [str]: """ Defines a function used to retrieve all of the file paths matching a directory string expression. :param root: The root directory/file to begin looking for files that will be read. :param recursive...
my_stuff = {'firstName': 'Ramesh', 'lastName': 'Anandhan', 'address': {'city': 'Bangalore', 'pin': 560043}} print(my_stuff['lastName']) print(my_stuff['address']['pin']) my_stuff['age'] = 35 print(my_stuff)
def new_decorator(func): def wrap(): print('before') func() print('after') return wrap @new_decorator def func_need_decorator(): print('i need decorator') func_need_decorator() def localFunction(): varLocal = 10; print(locals()) print(globals()) localFunction(...
def sum_of_intervals(intervals): from collections import Counter interval = [] length = 0 for i in range(len(intervals)): for j in range(len(intervals[i])): for x in range(intervals[i][j], intervals[i][j+1]): interval.append(x) break numbers = Counter...
"""Password check Program checks user input length and and print * password if valid, BUT with functions""" minimum_length = 3 def main(): password = get_password(minimum_length) convert_password(password) def convert_password(password): """converts password input to an equal length "*" output""" fo...
"""Intermediate Exercise 1, making a simple class.""" class ProgrammingLanguage: """class to store the information of a programing language.""" def __init__(self, field="", typing="", reflection="", year=""): """initialise a programming language instance.""" self.field = field self.ty...
n = int(input("Introduce la altura del triangulo (entero postitivo): ")) for i in range(n): print("*"*(i+1))
import datetime import hashlib import json from flask import Flask ,jsonify class Blockchain: def __init__(self): self.chain = [] self.create_block(proof =1, previous_hash ='0') def create_block(self,proof, previous_hash): block={'index':len(self.chain)+1 , 'timestamp'...
def bubbleSort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr1 = [64, 34, 25, 12, 22, 11, 90] arr2 = [64, 34, 25, 12, 22, 11] arr3 ...
""" Given an unsorted array of size N of positive integers. One number 'A' from set {1, 2, …N} is missing and one number 'B' occurs twice in array. Find these two numbers. Note: If you find multiple answers then print the Smallest number found. Also, expected solution is O(n) time and constant extra space. In...
from itertools import product, permutations parenthesis = ["(", "(", ")", ")"]+[" "]*6 parenthesis_combinations = set(list(permutations(parenthesis, 6))) for parenthesis_list in parenthesis_combinations: operation = "".join( [ parenthesis_list[0], str(2), "*", parenthesis_li...
import itertools def next_bigger2(n): num = str(n) num1 = set(int(x) for x in str(num)) if num == num[0] *len(num): return -1 lis = set(int(''.join(nums)) for nums in itertools.permutations(num, len(num))) lis = sorted(lis) try: return int(lis[lis.index(n)+1]) exce...
def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements for i in range(0, len(merged_arr)): if not arrA: merged_arr[i] = arrB[0] del arrB[0] elif not arrB: merged_arr[i] = arrA[0] del arrA[0] ...
def cal_average(a): avg = sum(a)/len(a) return avg """ userInt = list(map(int, input("Enter elements: ").split())) print(cal_average(userInt)) """
def converter_binary(number): a = [] while number > 0: a.append(number % 2) number = int(number / 2) print_backward(a) print (" 2") def converter_decimal(number): decimal = 0 for digit in str(number): decimal = decimal*2 + int(digit) print (decimal, "10") ...
luku = int(input("Anna kokonaisluku: ")) if luku > 1000: print("Luku on suurempi kuin 1000") elif luku > 100: print("Luku on suurempi kuin 100") elif luku > 10: print("Luku on suurempi kuin 10") else: print("Luku on 10 tai pienempi")
sentence = input("Enter a Sentence: ") screen_width = 80 text_width = len(sentence) box_width = text_width + 6 margin = (screen_width - box_width)// 2 print() print(' ' * margin + '+' + '-' * (box_width - 2) + '+') print(' '* margin + '|' + ' ' * (box_width - 2) + '|') print(' ' * margin + '|' + ' ' * 2 + sentence ...
from Guess_game import enter_cmd def help(): print("There are 4 rooms, Just flow with the game") print("type 'play' to play 'a dark room'") print("type 'quit' to quit playing") print("type 'help' to see this message again") def play(): while True: print("You enter a dark room with four doo...
import pprint import math def gen_primes(n): primes = [2] for i in range(3,n): for k in range(2,int(math.sqrt(i)) + 1): if i % k == 0: break else: primes.append(i) return primes pprint.pprint(gen_primes(1000))
import shelve def store_person(db): """Query user for details to store in database""" pid = input("Enter your unique ID: ") person = {} person["name"] = input("Enter your name: ") person["age"] = input("Enter your age: ") person["phone"] = input("Enter your phone: ") db[pid] = person def lo...
from CreditCard import CreditCard class PredatoryCreditCard(CreditCard): OVERLIMIT_FEE = 5 SURCHARGE = 1 def __init__(self, customer, bank, account, limit, apr): super().__init__(customer, bank, account, limit) self._apr = apr self._count = 0 def charge(self, price): ...
a = "Hello" print(a) a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a)
import random def random_list(ran, elements): return random.sample(range(ran), elements) def selection_sort(list): for i in range(0, len(list)-1): min = 1 for j in range(i+1, len(list)): if(list[min] > list[j]): min = j if(min != i): list[mi...
"""Functions handling currency.""" from forex_python.converter import CurrencyCodes, CurrencyRates, RatesNotAvailableError rates = CurrencyRates() codes = CurrencyCodes() def check_currency_code(code): """Is currency code valid? >>> check_currency_code("USD") True >>> check_currency_co...
name = input("Enter the name") email = input("Enter the Email") password = input("Enter the password") dob = input("Enter the D.O.B.") import mysql.connector mydb = mysql.connector.connect( user="root", passwd = "", host = "localhost", database = "first_database", ) cursor = mydb...
from tkinter import * class Main: def __init__(self): self.tk = Tk() height = self.tk.winfo_screenheight() width = self.tk.winfo_screenwidth() y = (height - 600)//2 x = (width - 600)//2 self.tk.geometry('600x600+'+str(x)+'+'+str(y...
import stuff import trace_goto loop = 1 name = input("Name? ") content = input("content? ") place = input("place? ") while(loop < 2): Next = input("next? ") if Next == "commands": print("""commands: New Save: Create a new save Veiw Save: Veiw saves end: end the program""") if name != "" and conten...
import math import os import random import re import sys def isValid(s): char_dict = {} for char in s: if char in char_dict: char_dict[char] += 1 else: char_dict[char] = 1 min_count = char_dict[char] max_count = char_dict[char] count_d...
list1 = [2,4,5,6,72,17,54,1,3,2,2,44] print(list1[2]) print(list1[1:3]) print(list1[:3]) print(list1[3:]) print(list1[-1]) print(len(list1)) list1.append(69) print (list1) list1.extend([3,4]) ''' list1.extend('yes')#stores as 'y', 'e', 's' print (list1) list1.extend(['yes'])#stores as 'yes' print (list1) list1.ex...
def pizza_maker(): print('How many pizzas do you want to order?') quantity_pizza = int(input()) ind_pizza = range(1,(quantity_pizza+1)) print(ind_pizza) print(pizza_maker())
import pandas as pd import matplotlib.pyplot as plt font_param = {'size': 12, 'fontweight': 'semibold', 'family': 'serif', 'style': 'normal'} col_names = ['Sepal_length', 'Sepal_width', 'Petal_length', 'Petal_width', 'Species'] iris = pd.read_csv('iris.csv', names=col_names) print(iris.head()) print...
""" Created on Sun Jun 11 12:18:09 2017 @author: jcuartas - Juan Manuel Cuartas Bernal Inputs n integer s integer Output polysum float """ from math import * def polysum(n, s): area = (0.25*n*s**2)/(tan(pi/n)) perimeter = n * s return round(area + peri...
""" Created on Sun Jul 2 04:02:34 2017 @author: jcuartas """ def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ LCount = {} largestKey = None ...
n1=int(input("enter the 1st number:")) n2=int(input("enter the 2nd number:")) sign=input("enter the operation [+,-,*,/]:") if sign == "+":print(n1 + n2) elif sign == "-":print(n1-n2) elif sign == "*":print(n1*n2) elif sign == "/":print(n1/n2)
import pylab import math def compute_interval(min, max, number_of_samples): while max > min: sample_points = [] interval_separation = float((max - min)/number_of_samples) for i in range(number_of_samples): sample_points.append(round(max - i*interval_separation, 4)) retu...
s = 0 with open("./input.txt") as f: group = set() first = True for line in f: if line != "\n" and line != "": if first: first = False [group.add(c) for c in line if c != "\n"] else: newgroup = set([c for c in group if c in line...
actions = open("input.txt").readlines() turn = {"E" : { "L" : "N", "R" : "S"}, "N" : { "L" : "W", "R" : "E"}, "W" : { "L" : "S", "R" : "N"}, "S" : { "L" : "E", "R" : "W"}} current_direction = "E" current_x = 0 current_y = 0 for action in actions: a = action[0] m = int(action[1:]) ...
'''Set Matrix Zeroes 1. Time complexity O(m * n) 2. Inplace ''' def setZeroes(matrix): """ Do not return anything, modify matrix in-place instead. """ is_col = False nrows = len(matrix) ncols = len(matrix[0]) for r in range(nrows): ...
import heapq '''Sorting k arrays 1. Use heap time O(n) space O(n) ''' def merge_arrays(arrays): heap = [(lst[0], i,0) for i, lst in enumerate(arrays) if lst] heapq.heapify(heap) merge = [] while heap: min_num, lst_index, ele_index = heapq.heappop(heap) merge.append(min_num)...
import networkx as nx G = nx.read_graphml('FrankMcCown-Facebook.graphml') my_friends = len(G.nodes) print(f'Total Friends: {my_friends}') friends_of_friends_total = 0 for friend in G.nodes: if ('friend_count' in G.node[friend]): friends_of_friends_total += G.node[friend]['friend_count'] ...
from tkinter import * from tkinter import ttk import subprocess def button_pressed(value): number_entry.insert("end",value) print(value,"pressed") def insertNum_on(): txt.insert(100, "On") subprocess.call('gpio -g write 21 1',shell=True) def insertNum_off(): txt.insert(100, "Off") subprocess.c...
from cs50 import SQL import csv import sys def main(): if len(sys.argv)!= 2: print("Usage: python import.py characters.csv") sys.exit() db = SQL("sqlite:///students.db") with open("characters.csv", "r") as students: reader = csv.DictReader(students, delimiter=",") ...
from time import clock def puzzle_input(): with open("input.txt", "r") as f: return [int(i) for i in f.read().strip().split()] def solve(instructions): "Return the number of steps required to 'escape' the instructions." i = 0 steps = 0 length = len(instructions) while (i...
def prefixTable(pattern): prefix_table = [0] for i in range(1, len(pattern)): j = prefix_table[i-1] while(j > 0 and pattern[j] != pattern[i]): j = prefix_table[j-1] prefix_table.append(j+1 if pattern[j] == pattern[i] else j) ...
import datetime class UserObj: def __init__(self, name: str, phone: str, pokemon: str, image: str) -> None: """ Create an object of type UserObj, besides that will be create an ID based on the date of the creation time :param name: Contact name :param phone: Contact phone ...
def search(graph, visited, current=0): if visited[current] == 1: return visited[current] = 1 print("Visit :", current) for vertex in graph.get_adjacent_vertices(current): search(graph, visited, vertex)
import Graph_Algorithm.priority_dict as priority_dict def build_distance_table(graph,source): distance_table = {} for i in range(graph.numVertices): distance_table[i] = (None,None) distance_table[source] = (0, source) priority_queue = priority_dict.priority_dict() priority_queue[source] = ...
""" Name: Vicente James Perez Date: 1/09/2020 Assignment: Module 1: Secret Code Due Date: 1/10/2020 About this project: Using a dict structure, take user input and translate to "coded" version Assumptions:NA All work below was performed by Vicente James Perez """ import string alphabet_reversed = string.as...
import Game_Tree class MiniMax: def __init__(self, game_tree, curChoice): self.game_tree = game_tree self.root = game_tree.root self.currentNode = None self.successors = [] self.curChoice = curChoice self.countH = 0 return def minimax...
from __future__ import absolute_import import pandas as pd import numpy as np __all__ = [ 'get_numeric_columns' ] def get_numeric_columns(X): """Get all numeric columns from a pandas DataFrame. This function selects all numeric columns from a pandas DataFrame. A numeric column is defined as a col...
nested_list = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'] ] class FlatIterator: def __init__(self, my_list): self.my_list = my_list self.position = -1 def __iter__(self): return self def __next__(self): new_list = sum(self.my_list, []) if len(new_list) - 1 == self.po...
n = int(input()) for i in range(n): str = input() length = len(str) if length <= 10: print(st) else: print(st[0], l - 2, st[l - 1], sep="")
"""Takes in a list of entrants from a .csv and finds the winner or winners.""" from argparse import Namespace import logging import random from typing import List from models.entrants_collection import EntrantsCollection logger = logging.getLogger(__name__) def find_winning_entries(entrants_collection: Entrants...
day = int(input('Day (0-6)? ')) if day >= 5 and day < 7: print('Sleep in') elif day >= 0 and day <= 4: print('Go to work') else: print('You are outside the range of available days of the week!')
import random class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue...
import logging from time import time class Timer: """ A class to investigate code runtime. """ def __init__(self, seed): """ Timer Initialisation :param seed: The seed of the world being timed """ self.logger = logging.getLogger(__name__) self.logger.set...
def gen(): yield from subgen() def subgen(): while True: x = yield yield x + 1 def main(): g = gen() next(g) retval = g.send(1) print(retval) g.throw(StopIteration) main()
def showNumbers(limit): for i in range(1 ,limit + 1): if i % 2 == 0: print(f'{i} EVEN') else: print(f'{i} ODD') showNumbers(10)
def interpolate(val, low, high): if val <= low: return 0 if val >= high: return 1 return (val - low) / (high - low) def interpolate_power(val, power): sign = 1 if val > 0 else -1 after = abs(val ** power) return sign * after
def monotonic(arr, if_true_false=False): """ Check whether array is monotonic or not :param arr: array of different numbers :return: string "Monotonic" / "Not monotonic" or if True / False """ decreasing = False increasing = False idx = 0 while not increasing and idx < len(arr)-1: ...
def lengthOfLIS(nums: 'List[int]') -> int: """ https://leetcode.com/problems/longest-increasing-subsequence/submissions/ Given an integer array nums, return the length of the longest strictly increasing subsequence. """ n = len(nums) ends_arr = [None] * (n) ends_arr[0] = 0 length = 1...
def partition(arr): pivot = (arr[0] + arr[len(arr)//2] + arr[-1]) // 3 ls, gr, eq = [], [], [] for x in arr: if x > pivot: gr.append(x) elif x < pivot: ls.append(x) else: eq.append(x) return ls, eq, gr def quicksort(arr): while len(arr) > 1: ls, eq, gr = partition(ar...
class Node: size = 0 def __init__(self, value): self.value = value self.prev = None self.next = None class DoubleLinkedList: def __init__(self): self.head = None self.tail = None def setHead(self, node): if not self.head: self.head = node ...