text
stringlengths
37
1.41M
meal_completed = True sub_total = 100 # tip = sub_total * 0.2 tip = sub_total * 1/5 # can use fractions as well total = sub_total + tip receipt = "Your total is " + str(total) print(receipt) # bill calculator for Overview of Python Data Types ''' - Booleans - Numbers - Strings - Bytes and byte arrays - None - Lists - ...
# What Does it Mean to Return a Value from a Python Function? # print vs return statement # how to pass values around in py # only use print when using debuggin when want to see output of a fn # in program print just prints to the logs not to like a front end React app # input and output of process -> very clear w/ fn'...
# How to Nest Functions in Parent Functions in Python # py diff from other languages since it allow u to put a fn inside another fn def greeting(first, last): def full_name(): # since nested in greeting doesnt need both arugments return f'{first} {last}' print(f'Hi {full_name()}!') greeting('Kr...
# Guide to Nested Collections in Python Dictionaries # key value pair can have collection of values : # key-value pair can only be 1-1 pair but the value can have a collection like an [] # helpful--> break elements to lowest form possible look and dissect into to chunk to know how to work with ea elem...
# Intro To Python Tuples # Data Types: # List: [] # Dictionary: {} # Tuple: () # Differences btween tuples and lists # why u would use tuple or list # is this a data structure I want to change or not ???? # Tuple: immutable - cannt change # List: mutable - can change # machine learning m...
# Overview of Python Conditionals # if conditional: # age = 25 # if age < 25: # print(f"I'm sorry you need to be atleast 25 years old") # nothing happens becuase age was 25 ... condition is False # age = 15 # if age < 25: # print(f"I'm sorry you need to be atleast 25 years old") # return statement because 15...
def guessing_game(): # user guesses until right answer is guessed while True: print('What is your guess?') guess = input() # sets up prompt into terminal and store what evers written into it if guess == '42': print('You guess correctly') return False # continues t...
#squares = [num for num in range(1,11)] for num in range(1,21): print(num**3)
import sys import csv #open file reader = csv.reader(open('grades.csv','rb')) reader.next() #do mission avg =0 sum=0 for row in reader: avg = avg + float(row[2]) sum = sum + 1 print row print "the avg is: " ,(float(avg/sum))
ch=int(input(enter a char)) if(ch=="a"or ch=="e"or ch=="i"or ch=="o"or ch=="i"): print(vowels) else print(consonants)
""" C R E D I T C A L C U L A T O R Owner : https://github.com/veena-LINE Python version : 3.8.1 Last Modified : File Created : 2020 Jul 17 File History : 2020 Jul 17 - File created """ from math import ceil, log from sys import argv class CreditCalculator: """ Utility to ...
## Q4 # Create a Vehicle parent class, initialise it with, wheels, colour and a method to display all this information. # i. Create a Tesla (or any car) child class # and add a method to get the miles and a method to display all this information. # ii. Change the colour of the vehicle. # iii. Delete the wheels. ...
# Q6 # Create a function that can accept a series of numbers and a mathematical operand. # Return the result of calculating the expression. E.g.: # calculate(1, 2, 3, 4, operand = "multiply") # calculate(65, 200, 84, 12, operand = "add")` def calculate(*args, operand = "plus"): # set default operand if non is passed ...
## Q1 # Create a Person class, initialise it with a name. # Create a method for the Person class that will say hello to the name. class Person: def __init__(self,name): self.name = name def hello_name(self): print("Hello " + self.name) name = Person(input("What is your name?")) # set variabl...
# Q2 # Create a restaurants menu with 5 items. Store this information in a dictionary inside a list. Each item in the menu # should have the name of the item, the price and if it's vegetarian friendly (make at least one vegetarian friendly # dish). # 1 - Print out the entire menu. # 2 - Print out the name of the vegeta...
'''Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: 1. If the number is a multiple of 4, print out a different message. 2. Ask the user for two numbers: one number t...
def yrange(n): i = 0 while i < n: yield i i += 1 y = yrange(3) print(y)
guests = ["mama", "papa", "girby"] print("Dear " + guests[0].title() + ", you are invited to dinner!") print("Dear " + guests[1].title() + ", you are invited to dinner!") print("Dear " + guests[2].title() + ", you are invited to dinner!")
person1 = { 'first_name' : 'Gianna', 'last_name' : 'Saludo', 'age' : 17, 'city' : 'Butuan' } person2 = { 'first_name' : 'Girby', 'last_name' : 'Saludo', 'age' : 15, 'city' : 'Butuan' } person3 = { 'first_name' : 'Cristina', 'last_name' : 'Saludo', 'age' : 46, 'city' : 'Butuan' } person4 = { 'first_name'...
pizzas = ['hawaiian', 'margherita', 'veggie'] for pizza in pizzas: print("I love " + pizza.title() + " Pizzas!") print('Bro, I really loved pizza back then.\n') friend_pizzas = pizzas[:] pizzas.append('mushroom') friend_pizzas.append('all-meat') print('My favorite pizzas are: ' + str(pizzas)) print("My friend's fa...
gianna = 'cute' print("Is gianna == 'cute'? I predict True.") print(gianna == 'cute') print("\nIs gianna != 'panget'? I predict True.") print(gianna != 'panget') print("\nIs gianna == 'cute' or gianna == 'panget'? I predict True.") print(gianna == 'cute' or gianna == 'panget') print("\nIs gianna == 'cute' and gianna...
l={} for _ in range(int(input())): name = input() score = float(input()) l.update({name:score}) slist=sorted(l.values()) #print(slist) for i in range(0,len(slist)): if(i==0): minval=slist[i] elif(slist[i]>minval): minval=slist[i] #print(minval) break #print(l) f...
import random import Utils import Score import Live # returns a list of numbers between one and difficulty def generate_sequence(difficulty): sequence = [] for x in range(difficulty): rand_num = random.randint(1, 101) sequence.append(rand_num) return sequence # returns a list of numbers ...
# encoding: utf8 """ python3.7 sorted func by 2 elements """ class T(object): def __init__(self, a, b): self._a = a self._b = b def __repr__(self): return f'T({self._a}, {self._b})' T1 = T(1, 300) T2 = T(2, 200) T3 = T(3, 200) T4 = T(3, 100) T5 = T(2, 100) def func_cmp(x,y): if...
# Problem # Given an integer array, output all the * *unique ** pairs that sum up to a specific value k. def pair_sum(arr, k): pairs = [] for indx, el1 in enumerate(arr): for indx2, el2 in enumerate(arr): if indx2 == indx: continue else: if arr[i...
def anagram2(s1, s2): word1 = sorted(s1.replace(" ", "")) word2 = sorted(s2.replace(" ", "")) if word1 == word2: print("True") else: print("False") def anagram1(s1, s2): word1 = s1.replace(" ", "") word2 = s2.replace(" ", "") letter_count = dict() for char in word1: ...
#fibonacci numbers naive algorithm def fibRecurs(n): if n<=1: return n else: return fibRecurs(n-1) + fibRecurs(n-2) def fibBetter(n): f=[0,1] for i in range(2,n+1): f.append(f[i-1] + f[i-2]) return f[n] print(fibBetter(1000))
#Given a square matrix, calculate the absolute difference between the sums of its diagonals. import os import random import re import sys def diagonalDifference(arr): sum1=0 sum2=0 for i in range(0,n): for j in range(0,n): if i==j: sum1=sum1+arr[i][j] if i== n ...
""" Author: Brent martin Date: Version: 1.0 This code will allow users to test their passwords against a database of stolen passwords in order to check whether their passwords are secure. The database is in the form of the website 'PWNED passwords' which is a database of all passwords which have already been broken int...
# 온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 프로그램을 작성하시오. N = (int(input())) arr = [] for _ in range(N) : x,y = input().split() arr.append((int(x),y)) arr.sort(key=lambda x : int(x[0])) for i in arr : print(i[0],i[1])
def insertionSort(lst): size = len(lst) for i in range(1, size): val = lst[i] j = i-1 # Shifting the element by one position if val i small while j>=0 and val<lst[j]: lst[j+1] = lst[j] # changing position till val is greater j -= 1 ...
jine = input("请输入金额:") # 获取输入金额,赋值给jine这个变量 print("输入的金额为:",jine) # 打印jine num = jine.count(".") # 统计jine这个字符串中,有多少个小数点 if num == 0 or num == 1: # 判断小数的个数,只有小数点为0或者为1个的情况,才认为是正常的数字 hstr = "0123456789." for i in jine: if i not in hstr: # 判断jine这个字符串中,是否存在非数字和小数点的值 print("输入的值不合法,请输入数...
import csv from matplotlib import pyplot def get_y(v, max_v): """ assume v is x_coordiante, method returns its y_coordinate :param v: the x coordinate :param max_v: maximum label in input graph :return: the y coordinate """ x = v - max_v / 2 return x ** 2 def get_color(c): """ ...
# -*- coding: utf-8 -*- from __future__ import division from numbers import Number from math import log class DualNumber: def __init__(self, real, dual): """ Constructs a dual number: z = real + dual * e: e^2 = 0 Parameters: ---------- real: Number The real co...
# A fun, but ultimately failed experiment. import time import os import msvcrt # get the character typed by the player for movement def getch(): return msvcrt.getch() # the player player = " -^-" # welcome message welcome = """ # ========== ~ ~ ~ ~ ~ ...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def invertTree(root): if not root: return None root.left, root.right = root.right, root.left root.left = invertTree(root.left) root.right = invertTree(root.right) return root root =...
def sortArrayByParity(A): i, j = 0, len(A)-1 while i <= j: if A[i] % 2 == 1 and A[j] % 2 == 0: # odd, even A[i], A[j] = A[j], A[i] if A[i] % 2 == 0: i += 1 if A[j] % 2 == 1: j -= 1 return A print(sortArrayByParity([3, 1, 2, 4]))
def moveZeroes(nums): lastNonZero = 0 for i in range(len(nums)): if nums[i] != 0: nums[lastNonZero], nums[i] = nums[i], nums[lastNonZero] lastNonZero += 1 nums = [0, 1, 0, 3, 12] moveZeroes(nums) print(nums) # [1, 3, 12, 0, 0] nums = [4, 2, 4, 0, 0, 3, 0, 5, 1, 0] moveZeroes(nu...
def reverseWords(s): def reverseSubstring(i, j): while i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1 s = list(s) start = 0 for i in range(len(s)): if s[i] == " ": reverseSubstring(start, i-1) start = i+1 ...
class ListNode: def __init__(self, x): self.val = x self.next = None # O(s) time, O(1) space, two-pass def removeNthFromEnd(head, n): i, j = head, head # "Given n will always be valid." for _ in range(n): j = j.next # n == len(head) aka remove first element ...
class ListNode: def __init__(self, x): self.val = x self.next = None # O(n) time, O(1) space def mergeTwoLists(l1, l2): if l1 and not l2: return l1 if l2 and not l1: return l2 if not l1 and not l2: return None p1, p2 = l1, l2 if p1.val <= p2.val: l3 = p1 ...
def isBadVersion(version): return [False, False, False, True, True][version-1] def firstBadVersion(n): lo, hi = 1, n while lo <= hi: m = (lo+hi)//2 if isBadVersion(m): if m == 1 or not isBadVersion(m-1): return m else: hi = m-1 ...
def search(nums, target): def binarySearch(lo, hi): while lo <= hi: mid = (lo+hi)//2 if nums[mid] == target: return mid elif nums[mid] < target: lo = mid+1 elif nums[mid] > target: hi = mid-1 re...
class Node: def __init__(self, data): self.data = data self.nxt = None def __str__(self): s = [] p = self while p: s += str(p.data) p = p.nxt return "[" + ", ".join(s) + "]" # O(n) time, O(1) space def reverseList(head): ...
def bubbleSort(array): for i in range(len(array)): for j in range(i+1, len(array)): # Check when two side-to-side elements should be swapped if array[i] > array[j]: array[i], array[j] = array[j], array[i] def insertionSort(array): for i in range(1, len(array)): ...
from heapq import heappush, heappop class Graph: def __init__(self, amt): self.vertices = [chr(ord("a")+c) for c in range(amt)] self.edges = {k: set() for k in self.vertices} def addUndirectedEdge(self, a, b, w): self.addDirectedEdge(a, b, w) self.addDirectedEdge(b, a,...
def majorityElement(nums): d = dict() for n in nums: if n not in d: d[n] = 0 d[n] += 1 for k, v in d.items(): if v > len(nums)//2: return k print(majorityElement([3,2,3])) # 3 print(majorityElement([2,2,1,1,1,2,2])) # 2
a = [1, 2, 3, 4] b = [4, 2, 3, 1] c = [4, 3, 2, 1] def sort_in_place(array): j = 0 for i in range(len(array)): if array[i] < array[j]: j, i = i, j array[j], array[i] = array[i], array[j]
class CategoryTree: def __init__(self): """ Initialize a CategoryTree with an empty dict. """ self.categories = {} def add_category(self, category, parent): """ Add a category if it satisfies the validity criteria. """ if not self._valid_category...
from pymath.algebra.linear.matrix import Matrix class Vector(Matrix): """ Class for representation Normal Vector (Column Vector) """ def __init__(self, *values): Matrix.__init__(self, len(values), 1, list(values)) def __mul__(self, other): if isinstance(other, Vector): ...
# print "Hello World" import RPi.GPIO as GPIO import time def blink(pin): print "GPIO " + str(pin) + " HIGH" GPIO.output(pin,GPIO.HIGH) time.sleep(1) GPIO.output(pin,GPIO.LOW) print "GPIO " + str(pin) + " LOW" time.sleep(1) return print "Hello World" # to use Raspberry Pi board pin numbers GPI...
class CodigoCesar: #Definimos la clase def __init__(self): #Definimos el metodo constructor pass def cifradoDesifrado(self): #metodo que cifrara y descifrara respuesta="S" #variable que ayudara al ciclo while cifrado="" #variable ayudara a guardar el texto cifrado desifrado="" ...
'Clase maestra' class Banco: def __init__(self): print("Cajeros") print("ventanilla") print("compañia") print("dueño") print("atencion a clientes") def pagar(self): print("Pagar") def consultar(self): print("consultar") 'Subclase 1' class BancoComercial(Banco): def __init__(self): ...
# 2. # Given a list lst and a number N, # create a new list that contains each number of lst at most N times without reordering. # For example if N = 2, and the input is [1,2,3,1,2,1,2,3], # you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, # and then take 3, which ...
# The drawing below gives an idea of how to cut a given "true" rectangle into squares ("true" rectangle meaning that the two dimensions are different). # # alternative text # # Can you translate this drawing into an algorithm? # # You will be given two dimensions # # a positive integer length (parameter named lng) # a ...
# 有问题来不起了 # In # this # challenge, the # user # enters # a # string and a # substring.You # have # to # print # the # number # of # times # that # the # substring # occurs in the # given # string.String # traversal # will # take # place # from left to # # right, not # from right to # # left. # # NOTE: String # letters...
''' [1 ponto] Escreva um programa que conte quantas palavras diferentes, quantas palavras repetidas e quantas frases existem em um texto. Uma frase é delimitada por um ponto final, ponto de exclamação ou ponto de interrogação. Para palavras repetidas, considerar o número de repetições. Uma palavra que aparece: ...
''' [1 ponto] Escreva uma função print_dict_rec que recebe um dicionário e imprime o seu conteúdo de forma tabulada e hierárquica. Se um valor no dicionário não é outro dicionário, imprima a chave e o valor de forma direta; Se um valor no dicionário é outro dicionário, imprima a chave e os seus conteúdo...
''' [2.5 pontos] Uma molécula de RNA mensageiro é utilizada como base na síntese de proteínas, num processo denominado de tradução. Uma trinca de bases RNA corresponde a um aminoácido na proteína a ser produzida pela combinação ordenada dos aminoácidos. Faça um função traducao_rna que receba um nome de arquivo de ent...
#Escreva um programa que nos mostre o maior e o menor número dentre 5 números reais fornecidos. lista = [float(i) for i in input().split()] for i in range(len(lista)): if i == 0: M = lista[0] m = lista[0] if M < lista[i]: M = lista[i] if m > lista[i]: m = lista[i] print('%.2f %.2f' %(M, m))
''' [2 pontos] A ferramenta do baldinho de tinta: existente em vários softwares de desenho (como o photoshop, paintbrush, etc...). Caso nunca tenha usado nada disso, o balde funciona da seguinte maneira: o usuário clica em um pixel da tela e ele "espalha" a nova cor dele por todos pixels da mesma cor original do pixe...
#(Questão 1) Dado um número x, 1000<=x<=10000, impria x com os números na ordem inversa: num = input() num1 = '' for i in range(len(num)): a = num[-i-1] num1 = num1+a print(num1)
''' [2 pontos] Faça um programa que processe uma sequência de tuplas com origens e destinos de uma companhia aérea, representados pelo código do aeroporto. O seu programa deve montar um dicionário com os trechos que não possuem volta direta. Nesse dicionário as chaves são a origem, e os valore são listas contendo os ...
#Faça um programa que calcule as raízes reais de uma equação do segundo grau f(x)=ax2+bx+c f(x) = ax^2 + bx + c f(x)=ax2+bx+c usando a fórmula de Bhaskara. import math as mt a,b, c = input().split() a, b, c = float(a), float(b), float(c) Delta = b**2-4*a*c if Delta < 0 : print('No real roots.') if Delta == 0: x1 = -...
x=int(input("enter only number")) if x<0: print('NEGATIVE') elif x==0: print('ZERO') elif x>100000: print('enter value below 100000') else: print('POSITIVE')
# implement an algorithm to print all valid (e.g. properly opened and closed combinations of n paired paranthesis) def paren_options(num_open, num_closed): options = [] if num_open > 0: options.append('(') if num_closed > num_open: options.append(')') return options def paren_combos(n): combos = [] first_com...
''' Say you overheard your friend’s password but don’t know how they spell it (e.g., if it is “password,” it could be spelled “pAsSwOrD,” “p455w0rD,” etc.). Given a word and a mapping from letters to characters (e.g., a maps to a, A, 4, @, etc.), print out all the possible passwords for that word. ''' maps = { 'p'...
def tidy_number(n): # return the last number that each and every element in the number has to be placed from low to high etc: 132 must return 129 #pre-requisites: make a new string of the integer so that we can loop through it # make a cache list_type varibale so we can store individual nu...
def tribonacci(signature, n): while signature[-1] < n: if sum(signature[-3:]) > n: break signature.append(sum(signature[-3:])) return signature print tribonacci([1,1,1], 6)
#----------------------------------------- # EXCEPT #----------------------------------------- # Don’t forget that: # the except branches are searched in the same order in which they appear in the code; # you must not use more than one except branch with a certain exception name; # the number of different e...
#-------------------------------------- # Declaration: # lambda parameters : expression two = lambda : 2 sqr = lambda x:x*x pwr = lambda x, y : x ** y for a in range(-2, 3): print(sqr(a), end=' ') print(pwr(a, two())) print('-'*20) #-------------------------------------- print('Standard Functions:') def prin...
# BaseException ← Exception ← ArithmeticError # An abstract exception including all exceptions caused by arithmetic operations # like zero division or an argument’s invalid domain print('-'*5, 'ArithmeticError:') #---------------------------------------------------------------- # BaseException ← Exception ←...
#---------------------------------------------------------------- # \n - line feed - LF print('a'*3) print(3*'a') #---------------------------------------------------------------- # ord() - to know specific character’s ASCII/UNICODE code point value # requires one character string or TypeError exceptio...
str1 = 'Hello World' #-------------------------- # capitalize() - change letters case, 1st -> Upper, others -> lower print('-'*5,'capitalize()') print(str1.capitalize()) #-------------------------- # lower() - make a string copy, replace all upper case letters into lower case print('-'*5,'lower()') print(str1.lower()...
#!/usr/bin/python3 """ queries the Reddit API and returns the number of subscribers """ import requests def number_of_subscribers(subreddit): """returns the number of subscribers""" if subreddit is None: return 0 url = "https://www.reddit.com/r/{}/about.json".format(subreddit) response = requ...
l = [1,2,3,4,5,6] d = 3 def ReverseArray(l, s, n): if (n-s) <= 2: print('s is {} and n is {} '.format(s,n)) l[s],l[n-1] = l[n-1], l[s] else: for i in range(s,(s + n)//2): l[i],l[n-(1+i)] = l[n-(1+i)], l[i] ReverseArray(l,0,len(l)) ReverseArray(l,0...
class Element(object): def __init__(self,value): self.value= value self.next = None class LinkedList(object): def __init__(self): self.head = None self.tail = None def append(self,object): if self.head: current = self.head whil...
import math factors = [] def factor(number): if number == 0: return [] for i in xrange(2, number+1): if number % i == 0: factors.append(i) factor(number/i) break return factors def main(): number = 600851475143 factors = factor(number) print sorted(factors) if __name__ == "__main__": main()
from random import randint from alg.sortingalgs import quickSort, mergeSort, bubbleSort, insertSort, selectSortMin, selectSortMax #check if the array is sorted def checkIfSorted(arr): return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def createTest(size): return [randint(0,size) for _ in range(size)] ...
#!/usr/bin/env python # -*- coding: utf8 -*- # Start print (" ") print ("*************************************") print ("* ¿Eres Colombiano? *") print ("*************************************") print (" ") # Saludo print ("Hola soy CHackA,") print (" ") # Description print ("Este programa te ...
#!/usr/bin/env python # -*- coding: utf8 -*- # Start print (" ") print ("***************************************************") print ("* CLASE DE TABLA DE MULTIPLICAR *") print ("***************************************************") print (" ") # Saludo print ("Hola soy CHackA,") print (" ")...
# -*- coding: utf8 -*- # Mi primer script para saludar y declaracion de variables # Start print (" ") print ("*************************************") print ("* Hola soy CHackA!!! *") print ("*************************************") print (" ") # Saludo print ("Hola soy CHackA,") print (" ") # D...
from urllib.request import urlopen as ureq from bs4 import BeautifulSoup as soup import os.path import re cache_directory = "html_cache\\" #function to get make html soup from url def get_soup_from_url(url_string): #if the html file doesn't already exist in the cache, open a connection #and then return the soup...
a,b = 2,2 if a == b: print(True) if a != b: print(True) if a < b: print(True) if a > b: print(True) if a <= b: print("This is true") if a >= b: print(True) # not => if a == b and b > 1: print(True)
while True: print("Welcome to Rock-Paper-Scissors game") player1 = input("Enter choice for player1: ") player2 = input("Enter choice for player2: ") if player1 == "rock": if player2 == "scissors": print("Congratulations, Player1. You are the WINNER!") elif player2 == "...
""" from statistics import mean, mode, median n = int(input()) arr = [map(int, input().split())] avg = mean(arr) med = median(arr) mod = mode(arr)[0] print("{:.1f}".format(avg)) print("{:.1f}".format(med)) print(mod) """ import numpy as np from scipy import stats size = int(input()) numbers = list(map(int, input().s...
name = 'John' age = 29 #print('My name is ' + name + '. I\'m ' + str(age)) #print('My name is %(name)s. I\'m %(age)d' %{'name': name, 'age': age})
def calculator(): print("calculator") operators = input(''' + for additon - for subtraction * for multiplication / for divison ** for power % for reminder ''') num1 = int(input("Enter the first number:")) num2 = int(input("Enter the second number:")) if operators == "+...
def div(lower, upper, divide): empty = [] for i in range(lower, upper): if i % divide == 0: empty.append(i) return empty print(div(1,50,5))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 4 21:04:16 2017 @author: michael """ def remove_dups(L1, L2): L1_copy = L1[:] for e in L1_copy: if e in L2: L1.remove(e) def remove_dups2(L1, L2): for e in L1: if e in L2: L1.remove(...
digits = '0123456789' result = 0 for digit in digits: result = result + int(digit) print(result) digits = '0123456789' result = 0 for digit in digits: result = digit print(result) digits = '0123456789' result = '' for digit in digits: result = result + digit * 2 print(result) message = 'Happy 29th!...
import unittest # import the Movie class from app.models import Movie # get the movie class # Movie = movie.Movie ''' Define a variable - Movie assign it to movie.Movie movie represents module file -- movie.py Movie represents the class -- Movie ''' # create a test class class MovieTest(unittest.TestCase): ''' ...
# 3 - BOOK MEMBERS OR CANCEL BOOKINGS import re from clear import clear def getBookings(loginEmail, cursor, conn): print('Offer/Cancel a Booking') print('-----------------------------------------------------------') print('1 - Book a member') print('2 - Cancel a booking') print('3 - Go Back') w...
# -*- coding: utf-8 -*- """ Created on 2017/03/11 21:20 @author: lguduy # Data Structure and Algorithms in Python ## Chapter 3 ### 表的应用 #### Josephus 问题 """ # 基于顺序表 def Josephus(n, k, m): """ parameters: ----------- n: 共n个人 k: 从第k个人开始报数 m: 报m的人退出 """ people = range(1, n+1) # 编号从1到n ...
from collections import defaultdict, namedtuple, Counter, deque import csv from urllib.request import urlretrieve movie_data = 'https://raw.githubusercontent.com/pybites/challenges/solutions/13/movie_metadata.csv' movies_csv = 'movies.csv' urlretrieve(movie_data, movies_csv) # Define a named tuple with fields that we...
#! bin/env/user python 3 # imports: # Definitions: class Consensus(object): def __init__(self, filename): """ Initializes the objects attributes: self.filename = the input name of the file self.data = the data present in the file self.transposedata = the transposed DNA str...
#CSci 127 Teaching Staff #A program that uses functions to print out days. #Modified by: --YOUR NAME HERE-- , --YOUR EMAIL HERE-- def dayString(dayNum): """ Takes as input a number, dayNum, and returns the corresponding day name as a string. Example: dayString(1) returns "Monday". As...
# Name: Martin Czarnecki # Email: martin.czarnecki99@myhunter.cuny.edu # Date: October 11, 2021 def main(): LOL = int(input("Enter a number: ")) for x in range(LOL): print("Hello, Functions!") if __name__ == "__main__": main()
# Name: Martin Czarnecki # Email: martin.czarnecki99@myhunter.cuny.edu # Date: August 26, 2021 # This program takes an input phrase, reprints # the phrase in 3 variations, and searches for # the number of times a character appears phrase = input(print("Enter a message: ")) letterToSearch = input(print("Enter a...
import util def is_valid(password): words = password.split() return len(words) == len(set(str(sorted(word)) for word in words)) def test(): invalid = [ 'abcde xyz ecdab', 'oiii ioii iioi iiio' ] valid = [ 'abcde fghij', 'a ab abc abd abf abj', 'iiii oiii ...