text
stringlengths
37
1.41M
# data structures # list ---> this chapter # ordered collection of items # you can store anything in lists int, float, string numbers = [1,2,3,4] print(numbers[1]) words = ['word1', 'word2', 'word3', 'word4'] print(words[:2]) mixed = [1, 2, 3, 4, "five", "six", 2.3, None] print(mixed[-1]) mixed[1:] = ['three', 'fo...
# you have to have a complete understanding of functions, # first class function / closure # then finally we will learn about decorators def square(a): return a**2 s = square # assign square function to another variable # print(s(7)) print(s.__name__) # gives function name i.e square print(square.__name__) # give...
# generators # generators are iterators # create your first generator with generator # 1. generator function # 2. generator comprehension def nums(n): for i in range(1, n+1): yield i numbers = nums(10) # generator # print(numbers) # <generator object nums at 0x03150570> for i in numbers: print(i...
# add and delete data user_info = { 'name' : 'harshit', 'age' : 24, 'fav_tunes' : ['alan walker', 'shakira'], 'fav_movies' : ['minions', 'spiderman'] } # how to add data # user_info['fav_foods'] = ['biryani', 'chicken nuggets'] # print(user_info) # pop() method # popped_item = user_info.pop('fav_tun...
name = "Harshit" # in keyword # if with in if 'b' in name: print("a is present in name") else: print("not presents")
import time # list vs generator # memory usage , time # when to use list , when to use generator # t1 = time.time() # l = [i**2 for i in range(10000000)] # 10 million # t2 = time.time() # print(t2-t1) t1 = time.time() g = (i**2 for i in range(10000000000)) # 10 million t2 = time.time() print(t2-t1)
def is_palindrome(s): n = len(s) if n == 0 or n == 1: return 1 return s[0] == s[n - 1] and is_palindrome(s[1:n - 1])
class Account: # linked to setup.py def __init__(self, cnx, username): self.cnx = cnx self.username = username # method to delete user account. calls MySQL procedure within def delete_account(self): while True: try: action = input("Are you s...
""" Example of bubble sort, in this example, Complexity is O(N*(N+1))= O(N^2+N)~=O(N^2) """ def bubbleSort(array): for i in range(len(array)): for j in range(len(array)-1): if array[j] > array[j+1]: array[j],array[j+1] = array[j+1],array[j] return array print(bubbleSort(...
from bs4 import BeautifulSoup as bs from splinter import Browser import pandas as pd import time # Initialize browser def init_browser(): executable_path = {'executable_path': '/usr/local/bin/chromedriver'} return Browser('chrome', **executable_path, headless=False) def scrape(): # # NASA Mars News ...
from typing import List, Dict from itertools import product class Person(object): """A person that is going on the trip""" _name: str def __init__(self, name: str, gender: str = "hello", days_staying: int = 1): """A person that will be there during the holiday :type name: str :par...
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ARRAYS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> An array is collection of items stored at contiguous memory locations. The idea is to store multiple items of same type together. This makes it easier to calculate the position of each element by si...
dict = {'jason':'dichoso','gloria':'tran'} listConvert = dict.items() #print(str(dict)) print(str(listConvert)) for firstName, lastName in listConvert: print(firstName + ' ' + lastName)
import pygame from pygame import gfxdraw import sys,time, math pygame.init() screen = pygame.display.set_mode((600,480)) running = 1 blue = 0,0,255 white = 255, 255, 255 black = 0,0,0 while running: event = pygame.event.poll() if event.type == pygame.QUIT: running = 0 screen.fill(black) for i in range(20): ...
#Considerações: o preço do produto sepre será positivo. from firebase import firebase firebase=firebase.FirebaseApplication('https://ep-design-software.firebaseio.com/', None) result=firebase.get('EP',None) loja=input('Nome da loja:') dicionario=result acao=int(input(''' Controle do estoque 0 - sair 1 - adicionar ite...
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'Emmanuel Barillot' # exemple pris ici : http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key import collections my_dict = {'carl': 40, 'alan': 2, 'bob': 1, 'danny': 3} my_items = my_dict.ite...
# -*- coding: utf-8 -*- import platform def polydiv(A,B): """ Calcul de la division de deux polynomes A / B Retourne [Q,R] le quotient et le reste de telle façon que A = B*Q+R """ Q = [0] # quotient R = A # reste while (polydegre(R) >= polydegre(B)): #print ("degr...
import math as m from decimal import Decimal def develop_dyad(x, n=10): """ Calcul du développement dyadique propre à l'ordre n """ dd = [] x0 = 0. x1 = int(2.0*x) print (x0,x1) dd.append(x1) for i in range(1,n): x0 = x0 + x1 / (2.0**(i)) # attention, ne pas mettr...
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'Emmanuel Barillot' """ Code expérimental pour tester les différentes façon de voir si un objet est iterable """ from traceback import print_exc # Duck typing def is_iterable(theElement): try: iterator = iter(theElement) except Ty...
def creat(user,password): with open('account.txt','a') as file: file.write(f'{user} {password}\n') def loginfunction(user,password): logininfo = f'{user} {password}' with open('account.txt','r') as file: users = file.readlines() loop = True f= 0 while loop:...
#!/usr/bin/env python3 """ In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem. Here are data files describing three graphs: g1.txt g2.txt g3.txt The first line indicates the number of vertices and edges, respectively. Each subsequent line describes an edge (the fir...
#!/usr/bin/env python3 """ This file describes an undirected graph with integer edge costs. It has the format [number_of_nodes] [number_of_edges] [one_node_of_edge_1] [other_node_of_edge_1] [edge_1_cost] [one_node_of_edge_2] [other_node_of_edge_2] [edge_2_cost] ... For example, the third line of the file is "2 3 -...
import math start = input("Do you wanna know the volume of your theoretical ball? Yes (y) or no (n)?") b = "Bye." i = "Invalid answer." while start == "y": radius = input("Input the radius you wanna use.") volume = ((4/3)*(math.pi))*(int(radius)*int(radius)*int(radius)) print("The volume of your theoretica...
num = float(input()) print('{0:.6f}'.format(num % 1))
hamlet = int(input()) dist1 = list(map(int, input().split())) shelter = int(input()) dist2 = list(map(int, input().split())) dist_ham = [] for i in range(dist1): list_hamlet = (dist1[i], i) dist_ham.append(list_hamlet) dist_shelt = [] for i in range(dist2): list_shelter = (dist2[i], i) dist_shelt.append...
def power(a, n): if n == 0: return 1 if a == 0: return 0 num = a if n % 2 == 1: num = num * power(a, n - 1) return num if n % 2 == 0: return power(a, n / 2) ** 2 a = float(input()) n = int(input()) print(power(a, n))
high = int(input()) dayDist = int(input()) nightDist = int(input()) generalDist = 0 days = 0 while True: # print("Dist is:", generalDist) generalDist = generalDist + dayDist days = days + 1 if generalDist < high: generalDist = generalDist - nightDist else: break print(days)
hour1 = int(input()) minute1 = int(input()) second1 = int(input()) hour2 = int(input()) minute2 = int(input()) second2 = int(input()) print((hour2-hour1)*3600 + (minute2-minute1)*60 + second2 - second1)
# Variable # autograd.Variable is the central class of the package. It wraps a Tensor, # and supports nearly all of operations defined on it. Once you finish your # computation you can call .backward() and have all the gradients computed automatically. # # You can access the raw tensor through the .data attribute, whil...
# -*- coding: utf-8 -*- """ Created on Sun Sep 13 16:19:35 2020 @author: striver """ def heapify(tree, n, i): if i>=n: return c1 = 2*i+1 c2 = 2*i+2 max_=i if c1 < n and tree[c1] > tree[max_]: max_ = c1 if c2 < n and tree[c2] > tree[max_]: max_ = c2 if max_ != i: ...
class XML_Validator(object): """ This class contains all the static methods necessary to check an XML file's validation. #XML documents must have the version number #and the language encoding on the first line #XML documents must have a root element #XML elements must have a closing tag #XM...
i = 1 while i < 9: print(i) i += 1 else: print("i is no longer less than 9")
balance=20000 card= input("enter the card") language= input("enter the language") account= input("enter the account") password=int(input("enter the password")) amount= int(input("enter the amount")) receipt= input("enter the receipt") if card=="debit card": if language=="enghish": if account== "saveing": ...
print("AREA OF CIRCLE!!") r = input("Radius: ") r = float(r) def area(r): pi = 3.142 return pi*( r * r ) print("The area of the circle of radius {1} is {0}".format(area(r), r)) print("___________________________________") print("PRIME NUMBERS!!") p = input("Prime numbers upto: ") p = int(p) for i in range (1, p+1...
# coding: utf-8 def length_of_words(s): return [len(x.rstrip(",")) for x in s.split(" ")] if __name__ == "__main__": s = "Now I need a drink, alcoholic of course, " +"after the heavy lectures involving quantum mechanics." length_list = length_of_words(s) print(length_list)
# coding: utf-8 def pick_odd_chars(s): return s[::2] if __name__ == "__main__": s = "パタトクカシーー" print(pick_odd_chars(s))
def txt_reader(file_name): txt_lst = [] with open(file_name, 'r') as f: for line in f.readlines(): txt_lst.append(line.split('\t')) return txt_lst def get_most_played(file_name): txt = txt_reader(file_name) maxi = 0 game_name = '' for line in txt: if float(line[...
import tensorflow as tf from tensorflow import keras ########################## #最简单的模型使用Sequential只有一个输入一个输出 model = keras.Sequential() # Adds a densely-connected layer with 64 units to the model: model.add(keras.layers.Dense(64, activation='relu')) # Add another: model.add(keras.layers.Dense(64, activation='relu')) #...
import numpy as np a=np.array([1,3,2,4]) c=np.array([0,1,1,0]) b=np.argsort(a)#从小到大排序,并返还原来的索引 print(b) print(c[b])
n = int(input()) m = float(input()) print("%0.3f"%(n/m),"km/l")
while 1: n = int(input()) if (n==2002): print("Acesso Permitido") break else: print("Senha Invalida")
import pandas import argparse parser = argparse.ArgumentParser(description='Value count for columns.') parser.add_argument('file', metavar='F', help='source file') parser.add_argument('col', metavar='C', help='column to count values') args = parser.parse_args() data = pandas.read_csv(args.file) print(data[args.col].v...
#!/usr/bin/python3 """ Here we have a class called rectangle which inherits our base class from our models.base module (this dicrectory) """ from models.base import Base def raise_exc(attribute="", error=""): """ raises an exception based on attribute and error information Args: attribute (str): w...
#!/usr/bin/python3 """prints a square""" def print_square(size=None): """prints out our square using size in stdout with #""" if isinstance(size, int) is not True: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") for i in range(0, size): ...
#!/usr/bin/python3 """ module that contains a function using json encoding """ import json def save_to_json_file(my_obj, filename): """ writes an python Object to a text file, using a JSON representation """ with open(filename, mode="w+", encoding="utf-8") as file: json.dump(my_obj, file)
#!/usr/bin/python3 def common_elements(set_1, set_2): set_3 = list() for i in set_1: for x in set_2: if i == x: set_3.append(i) return set_3
#!/usr/bin/python3 """module contains a def to add new lines to a given text""" def text_indentation(text=None): """The def that adds the new lines""" new_string = "" print_string = "" if type(text) is not str: raise TypeError("text must be a string") for i in range(len(text)): new...
#!/usr/bin/python3 """ module that contains a function using json encoding """ import json def from_json_string(my_str): """ returns the python representation of a JSON string """ return json.loads(my_str)
#!/usr/bin/python3 """ Description: Here we have a program that opens a MySQL database from arguments passed on exectution. Host name and port number are static to local host system. =================================================================== MySQL Execution: Will print results from query in ascending order by ...
#print(3+6) #print("3+6") #被引号括起来的内容是字符串,原样输出 ''' 这是一段注释 这是一段注释 ''' """ 这也是一段注释 这也是一段注释 """ jay = ((3+6)/5) gay = (jay*5) print(gay*5)
counts=dict() line=input('enter a text') words=line.split() print(words) for word in words: counts[word]=counts.get(word,0)+1 print(counts)
# ============================================================================ # Name : day_3_part1.py # Author : PS # Date : 6.4.20 # Description : Day 3: Crossed Wires, part1 # Description : To fix the circuit, you need to find the intersection point # closest to the central port. Because the w...
# oh soldier pretiffy my folder # input path as a input , file having the words that are not to be changed , format # captilize the first letter of all the folders # if the word is in the text file don't rename them # change the name of the files from the format then rename it with numbers import os def soldier(p...
from collections import deque def is_equals(origin, inp_str): return origin == inp_str def is_valid_command(origin_type, input_type): if origin_type == "NUMBER": return input_type.isdigit() elif origin_type == "STRING": return input_type.isalpha() def solution(program, flag_rules, comm...
import math from itertools import permutations def is_prime_number(n): for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def solution(numbers): answer = [] numbers = list(numbers) for i in range(1, len(numbers) + 1): per = permutations(...
def solution(nums): return len(nums) // 2 if len(set(nums)) >= len(nums) // 2 else len(set(nums)) solution([3, 1, 2, 3]) solution([3, 3, 3, 2, 2, 2]) solution([3, 3, 3, 3])
import turtle lenght = 300 a = [0, 0] b = [lenght, 0] c = [lenght/2, ((3*0.5)/2)*lenght] def middle_point(a, b): x = (a[0] + b[0])/2 y = (a[1] + b[1])/2 point = [x, y] return point def sierpinski (a, b, c, n): mid_a = middle_point(a, b) mid_b = middle_point(b, c) mid_c = middle_point(a, c) turtle.up() tur...
import unittest from string_calculator import StringCalculator class TestStringCalculator(unittest.TestCase): def test_empty_string(self): self.assertEqual(StringCalculator.add(''), 0) def test_single_number(self): self.assertEqual(StringCalculator.add('10'), 10) def test_if_separated_comma(self): self.ass...
import time class Clock(): def __init__(self): self.start_game = time.time() def duration_of_games(self): current_time = time.time() duration = time.strftime("%H:%M:%S", time.gmtime(current_time - self.start_game)) return duration def set_time(recharge): return time.time(...
class TV(): def __init__(self, volume=5, channel=""): self.volume=volume self.channel=channel def plus(self): zvp=int(input("На сколько вы хотите увеличить громкость телевизора?")) self.volume+=zvp if self.volume>30: print("Рекомендуется сниз...
#user needs to type their name to start the game. print("IN ORDER FOR THIS GAME TO BEGIN...") name = input("Please type your name: ") def welcome():#Welcomes the User to the game print("Welcome to the Island Game!") print("Hello,", name,"! Welcome and now let's go to the customizing station!") def avatar1():...
#Vowel Counter #For large data files with open('vowel_count.txt') as f: c = f.readlines() # .read() statements breaks the line into words and here we want to calculate the vowels in a line. #for storing no. of vowels in each line count = [] for line in c: vowels = 0 #checking each letter...
"""This version is without the time filter and the other is with time filter, city filter.""" import csv import pandas as pd import time import datetime import collections from collections import Counter def get_city(): '''Asks the user for a city and returns the filename for that city's bike share data. ...
import cv2 from matplotlib import pyplot as plt # reading the image img = cv2.imread(r'C:\Users\Jawhar\Downloads\einstein.jpg', 0) # displaying the original image plt.figure() plt.imshow(img, cmap = 'gray'),plt.title("Original Image"),plt.axis("off") # performing gaussian filtering with kernels of size 5 and 9...
#!/bin/python3 import sys def birthdayCakeCandles(n, ar): # Complete this function tallest = max(ar) # Generator expression return sum(1 for x in ar if x == tallest) # List comprehension #return len([1 for x in ar if x == tallest]) # List comprehension v2 #return len([x for x in a...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0): self.val = val self.left = None self.right = None # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition fo...
def eightqueen(test): queen_x =[] for i in test: queen_x += i print(queen_x) #print(queen_x[0]) new_queen_x1 = [] for i in range(0,len(queen_x),2): #print(queen_x[i]) new_queen_x1.append(queen_x[i]) print(new_queen_x1) new_queen_x2 = [] for i...
for i in range(1,51): if i==2: print(i,"是質數") for j in range(2,i): if (i%j)==0: break elif i%j!=0 and j+1==i : print(i,"是質數")
class Car: def __init__(self, name): self._speed_name_map = { "BMW": 250, "Mercedes": 350 } self._max_speed = self._define_max_speed(name) def _define_max_speed(self, name): return self._speed_name_map.get(name, 0) def distance_on_max_speed(self, dis...
def replace(words, old_word, new_word): """ this function replace(words, old_word, new_word): that replaces all occurrences of old with new in a string :param words: :param old_word: :param new_word: :return: string """ return new_word.join(words.split(old_word)) print(replace("Mis...
dict = {} # ---------------- ONE ---------------- # 1. Function to create the dictionary, the Function should ask for the length of the dictionary # According the length defined should ask to the user for the key and for the value. def askElementsIntoDictionary(): print("Insert the quantity of elements in th...
#The function replaces all occurrences of old with new in a string def replace(song, origen, after): varArr= song.split(origen) strfinal=after.join(varArr) print(strfinal) replace("Mississippi", "i", "I")
# OPERATOR == print('---------------- OPERATOR == ----------------') variableOne = 'circle' variableTwo = 'circle' if variableOne == variableTwo: result = 'EQUALS' else: result = 'NOT EQUALS' print("{0} == {1} ==> ARE {2}".format(variableOne, variableTwo, result)) # OPERATOR != print('---------------- OPERATOR...
# ---------------- ONE ---------------- # 1. Function that will create a dictionary with a list of userID and userName, # the userID should be only numbers between 1 to 100. # Username should be only lowercase (nor more than 8 digits) def createDictionary(): dict = {} print("Insert the quantity of elements in ...
#Practice Operators #Create python script applying at least one time each one of the operators learned. #Print the values and the condition that give you the result obtained. print("Practice 3: Operators") print("1. Comparison operators") #Use of == print("Use of operator ==:") def equals(string1, string2): print(...
from tkinter import * import tkinter.messagebox as tmsg def getval(): tmsg.showinfo("Money Added",f"The Money {myslider.get()} has been added to Your account") root = Tk() root.geometry("720x720") root.title("Slider") Label(text="Get Free Dollars",font="timesnewroman 12 bold").pack() myslider = Scale(root,f...
# -*- coding: utf-8 -*- # @author Nathan Frazier from functions import * def kruskals(wG, showSteps): # Take a graph object V = wG.vertex_set() # Vertex set of subgraph is the same as the vertex set of main graph sortedE = sortEdges(wG.edge_set(), wG) # Sorts all edges by weight E = [] # Make an emp...
import unittest from upper import StringMethod class TestStringMethod(unittest.TestCase): def setUp(self): foo = StringMethod('foo') def test_upper(self): self.assertEqual(foo.upper(), 'FOO') def test_isupper(self): if __name__ == '__main__': unittest.main()
""" Doubled """ # Create a method that decrypts the duplicated-chars.txt def decrypt_doubled(file_name): f = open(file_name, 'r') contents = f.readlines() new_contents = [] for j in range(len(contents)): temp = "" i = 0 while i < len(contents[j]) - 2: temp = te...
#Quick sort original_quick = [4, 1, 3, 2, 8] def quicksort(array): if len(array) >= 2: left = [] right = [] value = array[len(array) // 2] array.remove(value) for i in array: if i > value: right.append(i) else: left.appe...
import unittest from Animal import Animal class test_Animal(unittest.TestCase): def setUp(self): self.animal1 = Animal() def test_animal_hunger(self): self.assertEqual(self.animal1.hunger, 50) def test_animal_eat(self): self.assertEqual(self.animal1.eat(), 49) def test_anima...
""" Sorting Algorithm """ #Bubble sort original_bubble = [5, 1, 4, 2, 8] def bubble(array): for j in range(len(array) - 1): for i in range(len(array) - 1): if array[i] > array[i+1]: array[i], array[i+1] = array[i+1], array[i] return array bubble(original_bubble)
import unittest from Fibonacci import fibonacci class test_fibonacci(unittest.TestCase): def test_fibonacci_3(self): self.assertEqual(fibonacci(3), [0, 1, 1]) def test_fibonacci_2(self): self.assertEqual(fibonacci(2), [0, 1]) def test_fibonacci_error(self): self.assertEqual(fibona...
class Counter: def __init__(self, value = 0): self.counter = value def add(self, number = 1): self.counter += number def get(self): print(f"The current value is {self.counter}") def reset(self): self.counter = 0
import random class DiceSet(object): def __init__(self): self.dices = [0, 0, 0, 0, 0, 0] def roll(self): for i in range(len(self.dices)): self.dices[i] = random.randint(1, 6) return self.dices def get_current(self, index = None): if index != None: ...
""" You can find some posts and their comments in this file. Now you need to find the post which got the most popular comments. Most popular comments mean the sum of the likes on the comments. """ import json #Read file.json by using json #with open(filename, 'rb') as f #jsondata = json.loads(f.read()) d...
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 15:24:34 2019 @author: sridhar """ import math def cci(a,b,c): if (a+b)>c and (b+c)>a and (c+a)>b: s = (a+b+c)/2 area = math.sqrt(s*(s-a)*(s-b)*(s-c)) cicr = (a*b*c)/(4*area) inr = (2*area)/(a+b+c) print("area of...
import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gs import matplotlib.colors as mcolors class Engine(object): def __init__(self): #The context defines how far the agent can see self.context = 3 #set the range on how tall the map can be self....
# -*- coding: utf-8 """String utilities""" __all__ = ('startswith_token', 'prefix') def startswith_token(s, prefix, sep=None): """Tests if a string is either equal to a given prefix or prefixed by it followed by a separator. """ if sep is None: return s == prefix prefix_len = len(prefix) return s.startswit...
# Declaring and initializing a variable. # Taking input from the user in floating point number. number = float(input("Enter a number:\n")) # Using an if statement to check if the number if positive. # If the number given by the user is greater than 0, then it is Positive. if number > 0: print("Positive nu...
kolor = input('Jaki kolor lubisz?\n').lower() if kolor == 'czerwony': print('Ja też lubię czerwony') else: print(f'Nie lubie koloru {kolor}, wolę kolor czerwony') rainy = input("Is it raining?\n").lower() if rainy == 'yes': windy = input('Is it windy?\n').lower() if windy == 'yes': print('It`s ...
''' 1. Having a non-empty array of non-negative integers of length N, you need to return the maximum sum of subset of array elements such that you never take any two adjacent elements. 1 <= N <= 10^9 Example 1: input - [1,2,3,1], output - 4. You take 1st and 3rd elements Example 2: input - [2,7,9,3,1], output - 12. ...
# buggy.py # silly program that does nothing to improve mankind!!! import random number1 = random.randint(1,10) number2 = random.randint(1,10) print('What is ' + str(number1) + ' + ' + str(number2) + ' ?') answer = int(input()) if answer == number1 + number2: print('Correct!') else: print('Nope!! The answer is...
#!/usr/bin/python """ Program: getConcertInfo.py Author: Devin McGinty This pulls information from the WXPN concert calendar and displays it using in two windows (using ncurses). The left window displays the list of artists and the right window displays artist concert information. Uses:...
name = input('Coloque seu nome: ') test1 = float(input('Coloque a nota da primeira prova: ')) test2 = float(input('Coloque a nota da segunda prova: ')) average = (test1 + test2)/2 print('Olá {} seja bem-vindo. A nota da sua primeira prova é {:.2f}'.format(name, test1), end=' ') print('A nota da sua segunda prova é {:.2...
def sum_list(p): sum = 0 for e in p: sum = sum + e return sum print sum_list([1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,0,0,8,67,5,5,4,3,3]) def has_duplicate_element(p): res = [] for i in range(0, len(p)): for j in range(0, len(p)): if i != j and p[i] == p[j]: ...
# def bigger(a,b): # if a > b: # return a # else: # return b # # def smaller(a,b): # if a < b: # return a # else: # return b # # def biggest(a,b,c): # return bigger(a,bigger(b,c)) # # def smallest(a,b,c): # return smaller(a,smaller(b,c)) # # def median(a,b,c): # ...
#!/usr/bin/python -tt import sys import httplib import HTMLParser import urllib,urllib2 from urllib2 import urlopen ''' Valid is a datastructure that stores a url together with a val parameter which is set to true or false depending on whether the url is a valid one or not ''' class Valid: ''' I suppose keeping a ...
#!/usr/bin/env python3 """add duntion""" def add(a: float, b: float) -> float: """add Args: a (float): first numbre b (float): second number Returns: float: their sum as a float. """ return a + b
#!/usr/bin/env python3 """ basic async syntax""" import asyncio import random async def wait_random(max_delay: int = 10) -> float: """wait_random Args: max_delay (int, optional): integer. Defaults to 10. Returns: float: randon number between 0 and mas_dalay """ i = random.unifo...