text
stringlengths
37
1.41M
class Node: def __init__(self, data): self.data = data self.next = None self.previous = None class DLinkedList: def __init__(self): self.first_node = None self.last_node = None self.count = 0 def add(self, index, data): existing_node = getNode(self, index) ...
# Numbers, Lists, Tuples, Sets # numbers that look like strings # vars that look like numbers # num_1 = '100' # num_2 = '200' # this is a string lol # print(num_1 + num_2) # returns: 100200 # ~CASTING # to turn them into integers # num_1 = int(num_1) << << << < HEAD # num_2 = int(num_2) # this is a function to cr...
import logging import threading import time def thread_function(name): print("Thread {}: starting".format(name)) time.sleep(2) print("Thread {}: finishing".format(name)) # main print("Main : before creating thread") x = threading.Thread(target=thread_function, args=(1, ), daemon=True) #...
# 10. Write a Python program to reverse the digits of an integer. # Input : 234 # Input : -234 # Output: 432 # Output : -432 def reverseDigits(num): negFlag = False if(num < 0): negFlag = True num *= -1 place = 10 result = 0 while num > 0: temp = num % 10 ...
def bubble_sort(lst): length = len(lst) print(length) for i in range(length): for j in range(length - i - 1): if lst[j] > lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] print(lst) return lst lst = [124, 152, 235, -4587, 456, 357, 85, -45, 3467, 90,...
import re def validate(input): up = r"[A-Z]+" lo = r"[a-z]+" num = r"\d+" spe = r"[#$@]+" min_len = 6 max_len = 12 fails = [] val = True if len(input) < min_len or len(input) > max_len: fails.append("Password should of length 6 to 12") val = False ...
def create_matrix(): rows = int(input("Enter the number of rows for matrix: ")) columns = int(input("Enter the number of columns for matrix: ")) matrix = get_input(rows, columns) return matrix def get_input(rows, columns): matrix = [] print("Enter the matrix values: ") for i in r...
from edit_dist import distance from random import choice def find_match(source_word): """Finds the best match for a source word""" min_dist = 100 # min_dist = len(source_word) * 2 optimal_words = [] target_file = open('common_words.txt', 'r') # FIXME: Runtime of this is O(n^2). Can we improve this? for line...
# importing the modules needed for all questions import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression # Question N.1 s=np.random.rand(1000,2) #Question N.2 #Scatte...
from itertools import permutations num = [8,9,10,5] op = ['+','-','*','/','b-','b/'] opt = ('+', '-', '*') print(opt[0]) num_all = list(permutations(num)) op_all = list(permutations(op,3)) print(num_all) print(op_all) all = [] for num in num_all: num = list(num) for op in op_all: num.inser...
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt mu, sigma = 100, 15 #x = mu + sigma * np.random.randn(10000) # the histogram of the data plt.axis([amin(x),amax(x), amin(x),amax(x)]) plt.plot(x,x, 'r-') plt.show()
from math import ceil,sqrt; def prime_generator(needed, primes): def is_prime(num): '''can check if a number is prime up to 1000''' sqrt_num = ceil(sqrt(num)); for p in (prime for prime in primes if prime <= sqrt_num): if num%p == 0: return False; pr...
import sys def fizz_buzz(fizz_mod, buzz_mod, count): out = []; for num in range(1,count + 1): if num%fizz_mod == 0 and num%buzz_mod == 0: out.append("FB"); elif num%fizz_mod == 0: out.append("F"); elif num%buzz_mod == 0: out.append("B"); else:...
#!/usr/bin/env python3 # Created by: Mikayla Barthelette # Created on: Sept 2021 # This program finds the volume of a cone import math def main(): # this function calculates the volume # input radius = int(input("Enter the radius of the cone (mm): ")) height = int(input("Enter the height of the con...
# Uses python3 import sys def gcd_naive(a, b): # gcd of a,b is gcd of b%a and a ; Euclid's algorithm if a==0: return b elif b == 0: return a else: return gcd_naive(b%a,a) if __name__ == "__main__": input = sys.stdin.read() a, b = map(int, input.split()) print(gcd_naive(a, b))
# -*- coding: utf-8 -*- """ Created on Thu Apr 28 00:26:27 2016 @author: dahenriq """ import pandas as pd import Demographics as dm class MainScreen: def __init__(self): self.Badgeinput=1 self.Passwordinput=1 self.dfpopo = pd.read_csv("Police.csv",index_col='Badge')...
""" solve sudoku puzzle""" import itertools import numpy as np class sudoku_puzzle: """sudoku puzzle and solve method""" def __init__(self, init_puzzle="none"): self.olist = [0, 1, 2, 3, 4, 5, 6, 7, 8] self.ilist = list(itertools.chain.from_iterable(itertools.repeat(x, 9) for x in self.olist)...
import RPi.GPIO as gpio gpio.setmode(gpio.BOARD) gpio.setup(7, gpio.IN) gpio.setup(5, gpio.OUT) while True: input_value = gpio.input(7) if input_value == False: print('The button has been pressed...') gpio.output(5,gpio.HIGH) else gpio.output(5,gpio.LOW)
print("\n----------------------------------- BFS (Breadth-First Search) ----------------------------------- ") from collections import deque #STATION class Station: # variables def __init__(self, name): self.name = name self.neighbors = [] def add_connection(self, another_station...
n1 = int(input("digite nota 1 ")) n2 = int(input("digite nota 2 ")) n3 = int(input("digite nota 3 ")) r= (n1+n2+n3)/3 print(r)
list_val = ( 'jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec') i = raw_input("enter a value") i = int(i) end= i * 3 start= end - 3 print list_val[start:end]
n=int(input("Enter a number")) n1,n2=0,1 count=0 if n<=0: print("Enter a positive number") elif n==1: print("fibonacci sequemce upto n terms:",n) print(n1) else: print("Fibonacci series") while count<n: print(n1) nth=n1+n2 n1=n2 n2=nth count=cou...
my_set = {1,2,3} print (my_set) #set dengan dengan fungsi set my_set = set([1,2,3]) print (my_set) #set dengan data campuran my_set = {1,2,3, "python" ,(3,4,5)} print (my_set)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Implémentation d'un graphe non orienté à l'aide d'un dictionnaire: les clés sont les sommets, et les valeurs sont les sommets adjacents à un sommet donné. Les boucles sont autorisées. Les poids ne sont pas autorisés. On utilise la représentation la plus simple: une...
from abc import ABC, abstractmethod class MenuComponent(ABC): '''Item do cardápio, com sub-itens''' def append(self, item): '''incluir sub-item''' raise NotImplementedError() def remove(self, item): '''remover sub-item''' raise NotImplementedError() def __getitem__(s...
""" Um trem é um iterável com vagões. O construtor pede o número de vagões:: >>> t = Trem(3) O trem é um iterável:: >>> it = iter(t) E o iterador obtido devolve vagões:: >>> next(it) 'vagão #1' >>> next(it) 'vagão #2' >>> next(it) 'vagão #3' Somente a quantidade correta de vagões ...
#!/usr/bin/env python3.6 """ Primero preparamos el entorno, realizamos los siguientes pasos : 1 Creamos un servidor usando librería standar de PYTHON : python -m SimpleHTTPServer 5500 2 Instalamos lsof para ver todos los procesos que están abiertos Ejemplos LSOF (https://www.h...
class Student: def __init__(self, id, grades): self.__id = id self.__grades = grades def __lt__(self, obj): grade1 = 0 grade2 = 0 for grade in self.__grades: grade1 += grade grade1 /= len(self.__grades) for grade in obj.__grades: ...
d = int(input("Type in the exercise you want to run: ")) if(d == 1): # find_min function definition goes here def find_min(num1, num2): if(num1 > num2): return num2 else: return num1 first = int(input("Enter first number: ")) second = int(input("Enter second num...
def count_eights(num_list): return num_list.count(8) def adj(num_list): for i, num in enumerate(num_list): if(num == 8 and i != len(num_list)-1): if(num_list[i+1] == 8): return True return False def list_num(list_str): num_list = [] try: for element ...
def to_int(a_list): int_list = [] for i in a_list: int_list.append(int(i)) return int_list def even_list(a_list): return [i for i in a_list if not i%2] def even_sum(a_list): a_list = to_int(a_list) a_list_even = even_list(a_list) return sum(a_list_even) def get_list(): a_list...
# Constants DIM = 4 # dimension of the board DIMxDIM EMPTYSLOT = 0 QUIT = 0 def initialize_board(): ''' Creates the initial board according to the user input. The board is a list of lists. The list contains DIM elements (rows), each of which contains DIM elements (columns)''' numbers = input().split() ...
""" PW3 name: 3.student.mark.oop.math.py Use math module Use numpy Calculate GPA for given student Sort student list by GPA descending Decorate UI """ # ! usr/bin/python3 import math import numpy as np #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Classes ~~~~~~~~~~~~~~~~~~~...
#! usr/bin/python3 students = [] students_name = [] courses = [] courses_id = [] marks = [] def input_number_student(): nofstudent = int(input("Enter number of students: ")) return nofstudent def input_number_course(): nofcourse = int(input("Enter number of courses: ")) return nofcourse number_of_s...
'''enumerate_and_zip.py -- explainer for enumerate and zip functions Ben Rose 2017-06-08 Python3.6 ''' #set up lists a = [4, 5, 6, 7 , 8] name = ['Isabel', 'Liam', 'Jade', 'Mia', 'Ethan'] #show how `enumerate` works print('Example of enumerate()') for i, num in enumerate(a): print(i, num) #Loop through two list...
#! python3 # mapIt.py - Launches a map in the browser using an address from the # command line or clipboard import webbrowser, sys, pyperclip if len(sys.argv) > 1: # get address from the command line. address = ' '.join(sys.argv[1:]) else: #get address from the clipboard address = pyperclip.paste() w...
#program that counts the number of characters in a message import pprint message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for character in message: count.setdefault(character, 0) #sets the default value as 0 count[character] = count[character] + 1 #updating pp...
#the isX string methods while True: print('Enter your age: ') age = input() if age.isdecimal(): break print('Please enter a number for your age.') while True: print('Select a new password (letters and numbers only): ') password = input() if password.isalnum(): break pri...
from passlib.hash import pbkdf2_sha256 def create(conn, email, username, password_hash, date): cursor = conn.cursor() cursor.execute("""SELECT username FROM user WHERE username = ?""", [username]) result = cursor.fetchone() if result is not None and result['username'] == username: return Fals...
# extract and count paragraph <p> tags and display the count of the paragraphs as output of your program. # test on multiple sites import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # create context to ignore ctx = ssl.create_default_context() ctx.check_hostname = False ctx.ve...
#program categorizes logs email by domain name # and uses max loop to print sender with most emails fname = input('Enter file name: ') try: fh = open(fname) except: print('File not found:', fname) counts = dict() for line in fh: words = line.split() # print('Debug', words) if len(words)...
#Program reads user input #Once done is entered print out the total, count and average of the numbers inputed #Use try and except if the user enters anything other than a number or done #i = 0 largest = None smallest = None while True: value = input('Enter a number: ') if value == 'done': break...
def computegrade(score): error_msg = 'Bad score' try: score = float(score) except: return print(error_msg) quit() if score >= 0.0 and score <= 1.0: if score >= 0.9: return print('A') elif score >= 0.8: return print('B') ...
class BankAccount: def __init__(self, int_rate, balance): self.int_rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): if self.balance >= amount: self.balance -= amount e...
#globale Variable anlegen fehlstand = 0 """ Sortiert ein Array mit ganzen Zahlen mittels Insertion-Sort in O(n^2) """ def insertionSort(list): #global setzen global fehlstand for i in range(0, len(list)): wert = list[i] j = i while (j > 0) and (array[j-1] > wert): array[...
#!/usr/bin/env python #encoding:utf-8 __author__ = 'Samren' """ 二分查找算法实现:对已排序的list进行二分查找 binary_search(lst, n): 查找成功,返回位置,失败,返回-1 input: lst 要查找的list n 要查找的数 """ def binary_search(lst, n): if len(lst) == 0: return -1 low, high = 0, len(lst) - 1 while low <= high: mid = (low + high) / 2 ...
numbers = [5,2,5,2,2] for item in numbers: #for item2 in range(item): print('X'*item) numbers = [2,2,2,8] for item in numbers: output = '' for item2 in range(item): output += 'X' print(output)
weight= input('enter your weight: ') unit= input('weight in (L)bs or (K)g: ') if unit is 'L' or unit is 'l': print(f"your weight is {int(weight)*0.45} kg") elif unit is 'K' or unit is 'k': print(f"your weight is {int(weight)/0.45} lbs")
# See NestedLists.png for problem definition n = int(raw_input()) nested_list = [[raw_input(), float(raw_input())] for _ in range(n)] scores = sorted({x[1] for x in nested_list}) second_lowest = sorted(x[0] for x in nested_list if x[1] == scores[1]) print('\n'.join(second_lowest))
import re import string def is_pangram(sentence): if not sentence: return False else: alphabet = tuple(string.ascii_lowercase) return False not in [letter in sentence.lower() for letter in alphabet] return True
family_ages = { 'Nancy' : 50, 'Alan' : 49, 'Lily' : 19, 'Allison' : 23 } print(family_ages) #age = family_ages['Alan'] will print the age of Alan #print(age)
# Write a small script that : # Asks the user for its name # Asks the user for its age # Calculates the age corresponding to the next tenth # Tells the user, using his name, how many years remain before the next decade… (ex: “Luc, in 4 years you’ll be 50.”) # asks the user for its gender # if the user is a female aged ...
y=input() x=y.lower() if x=='a'or x=='i'or x=='o'or x=='u'or x=='e': print("vowel") else: print("consonant")
import pygame import math BROWN = (130, 94, 35) WHITE = (255, 255, 255) class Sword(pygame.sprite.Sprite): def __init__(self, player): #This loads the image and converts it to a format pygame can work with easier self.image= pygame.image.load("./items/woodensword_1.png").convert() ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt #ploting chicken location chicken_path = 'https://assets.datacamp.com/production/repositories/2409/datasets/fa767727ef9a7b39fb9f34bee3b1bc2f02682c81/Domesticated_Hen_Permits_clean_adjusted_lat_lng.csv' chickens = pd.read_csv(chicken_path) # Look...
from random import randint rand_num = randint(0,2) print("Rock...") print("Paper...") print("Scissors...") player1 = input("Player1 make your move: ") if rand_num == 0: computer = "rock" elif rand_num == 1: computer = "paper" else: computer = "scissors" print(f"Computer plays {computer...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import threading import time class ThreadA(threading.Thread): def __init__(self, record=False, rec_time=10): super(ThreadA, self).__init__() self.setDaemon(True) self.count = 0 def run(self): ...
# ################# NUMBER LOOP ################# # # Write a program which repeatedly reads numbers until the user enters "done". # Once "done" is entered, print out the total, count, and average of the numbers. # If the user enters anything other than a number, detect their mistake using # try and except and print an...
print("Latihan 4 Bilangan acak") from random import random n = int(input("Masukan Nilai N: ")) for i in range(n): while 1: n = random() if n < 0.5: break print(n) print("Selesai")
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. def gcd(x,y): return y and gcd(y, x % y) or x def lcm(x,y): return x * y / gcd(x,y) n = 1 for i in range(1, ...
def findMaxNum(num): # Convert to equivalent # binary representation binaryNumber = bin(num)[2:] # Stores binary representation # of the maximized value maxBinaryNumber = "" # Store the count of 0's and 1's count0, count1 = 0, 0 # Stores the total Number of Bits N = l...
#!/usr/bin/env python3 import json import re def input_intensity(): print("Please input scan intensity from 0 to 5 where:") print("\t 0 - paranoid") print("\t 1 - sneaky") print("\t 2 - polite") print("\t 3 - normal") print("\t 4 - aggressive") print("\t 5 - insane") print("Scan inten...
# -*- coding: utf-8 -*- # takes a file and returns a string of file contents from sys import argv script, filename = argv def convert(filename): with open (filename, "r") as myfile: data=myfile.read() return data
phoneBook = dict() n = int(input("Enter the total length of the dictionary: ")) i = 1 while (i <= n): a = input("Contact Name: ") b = input("Phone Number: ") phoneBook[a] = b i += 1 pre = '{:12} {:12}' print(pre.format("Name", "Phone Number")) for i in phoneBook: print(pre.format(i, phoneBook[i]))
def VowCount(str): # Defines the VowCount vow = list(str.split()) # Splits the string into list count = 0 # Initialize count vowel = "aeiouAEIOU" # Vowels in english alphabets for i in vow: # For loop to check whether the elements starts with vowels or not if...
def cal_Mean(num): n = len(num) sum = 0 for i in range(0, n): sum += int(num[i]) mean = sum/n return mean print("Enter the list of numbers: ") j = input() j = j.split() print("The mean of the list", j, "is ", cal_Mean(j))
# -- DISTANCE_METRICS -- # # -- IMPORTS -- # import numpy as np import math as m # -- ARRAYS MUST BEOF SIZE (X,1) -- # # -- DISTANCE METRICS -- # def euclidean_distance(x,y): """FUNCTION::EUCLIDEAN_DISTANCE >- Returns: The euclidean distance between the two arrays.""" return np.sqrt(np.sum(np.power(n...
#!/usr/bin/env python3 """ Main module of the Assembler for the Hack platform. It uses the Parser, Code and SymbolTable classes to read a Hack assembly language source file (.asm) and generate an executable file (.hack) It works in three steps: * An INITIALIZATION phase, in which the symbol table is generated, as ...
num=45 guess =int(input('Enter an integer: ')) if guess==num: print('congratulations,you guessed it.') print('(but you dont win prizes!)') elif guess<num: print('no it is a little higher than that') else: print('it is a little lower than that') print('Done')
#! usr/bin/env/python # -*- coding: utf-8 -*- import logging # def foo(): # r = some_function() # if r == (-1): # return (-1) # return r # def bar(): # r = foo() # if r == (-1): # print 'Error' # else: # pass # try: # bar() # except StandardError, e: # print 'error is ',e # try: # print 'try...' ...
def day3_2(data, slope): cpt=1 for i in slope: cpt*=day3_1(data,i[0],i[1]) return cpt def day3_1(data,right,down): cpt=0 i=0 j=0 while i < len(data): if data[i][j] == '#': cpt += 1 j+=right if j >= len(data[i]): j -= len(data[i]) ...
class node: def __init__(self,data): self.data = data self.next = None class linkedlist: def __init__(self): self.head = None def append(self,data): new_node = node(data) if self.head is None: self.head = new_node temp = self.head ...
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author: sadscv @time: 2019/03/15 21:12 @file: exam.py @desc: """ from typing import Any, Tuple class Exam(object): def __init__(self, exam_id, num_students): self.conflicting_exams = {} self._id = exam_id self.num_students = num_studen...
def park_new_car(parking_lot, registration_no, colour): if parking_lot is None: return 'Parking lot not initialized' else: return parking_lot.park_new_car(registration_no, colour) def car_departure(parking_lot, slot_number): if parking_lot is None: return 'Parking lot not initializ...
#! /usr/bin/python # -*- coding: iso-8859-15 -*- from pylab import * import matplotlib.pyplot as plt # import matplotlib import * import numpy as np #definimos el periodo de la grafica periodo = 2 #definimos el array dimensional x = np.linspace(0, 10, 1000) #defimos la funcion y = np.sin(2*np.pi*x/periodo) ...
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): """run test with python3 -m unittest -v tests.6-max_integer_test""" def test_module_docstring(self): moduleDoc = __import__('6-max_in...
#!/usr/bin/python3 """ Module 0-read_file Contains function that reads and prints contents from file """ def read_file(filename=""): """Read and print text from file""" with open(filename, mode="r", encoding="utf-8") as f: print(f.read(), end="")
#!/usr/bin/python3 """ Module 5-text_indentation Contains method that prints text with 2 new lines after each ".", "?", and ":" Takes in a string """ def text_indentation(text): """ Prints text with 2 new lines after each ".", "?", and ":" """ if not isinstance(text, str): raise TypeError("tex...
#!/usr/bin/python3 """ given letter pattern as param to be search val of request; print Star War names usage: ./101-starwars.py [letter pattern to match names] """ from sys import argv import requests if __name__ == '__main__': if len(argv) < 2: pattern = "" else: pattern = argv[1] url = 'h...
NUM = int(input("enter: ")) for i in range(0,NUM+1): for j in range(0,i+1): print('*', end=" ") print()
class Animal(object): def __init__(self,name,color = "白色"): self.name = name self.color = color def eat(self): print("吃东西") def setColor(self,color): self.color = color def __str__(self): msg = "颜色是%s"%self.color return msg ''' 子类没有init方法...
#10时间戳的获取方法 import time t = time.time() print(t) print(int(t)) #13位时间戳的获取方法 import time time.time() #通过把秒转换毫秒的方法获得13位的时间戳 import time millis = int(round(time.time() * 1000)) print millis #round()是四舍五入 import time current_milli_time = lambda: int(round(time.time() * 1000)) Then: current_milli_time() #13位时间 戳转换成...
sex=input('请输入你的性别:') age=int(input('请输入你的年龄:')) if sex=='男': if age<=60: print('继续努力') else: print('>60你该退休了') else: if age<=60: pritn('继续努力') else: print('你该退休了')
a=int(input('请输入:')) c=1 s=a while c<=a: print(' '*s , ' *'*c) s=s-1 c=c+1
#型参 比喻成 盒子 #变量 比喻成 盒子 def add(a,b): print(a) print(b) def add1(*anything): print(anything) def addsan(a,s,d): a+s+d def add_some(*num): global re for i in num: re=i+re print(num) a=int(input('')) add_some(1,10,20,30,40,50) add_some(1,2,3,4,5,6) #1到10的循环 a=0 for i in range(1,...
#写一个函数 #写三个数的和 #求三个数的平均数 def add(a,b,c): return a+b+c def pingjun(x,y,z): g=add(x,y,z) return g/3 def ji(z,w,e): return z*w*e f=ji(2,3,4) print(f) g=add(1,2,3) print(g) p=pingjun(2,4,6) print(p)
name = input('请输入要备份的名字:') f = open(name,'r') a=name.rfind('.') newname = name[:a]+"back"+name[a:] newname=open(newname,'w') q=f.read() newname.write(q) newname.close() f.close()
''' 1='石头' 2='剪刀' 3='布' ''' import random qw=0 while qw < 10: qw=qw+1 ef=int(input('请输入:')) if ef==99: break pc=random.randint(1,3) if ef==1: print('吕布输出了石头') elif ef==2: print('吕布输出了剪刀') else: print('吕布输出了布') if pc==1: print('貂蝉输出了石头') elif pc...
#coding=utf-8 #获取输入价格 price=float(input("请您输入西瓜的价格:")) #获取输入重量 weight=float(input("请您输入西瓜的重量:")) #把输入的str类型数据转化为float类型 #计算西瓜的总额 money=price*weight print("该西瓜的单价是%.2f元"%(price)) print("该西瓜的重量是%.2f斤"%(weight)) print("该西瓜的总额是%.2f元"%(money))
''' 1=石头 2=剪刀 3=布 ''' import random while True: 曹操=int(input('请出拳')) 刘备=random.randint(1,3) print('曹操出%d'% 曹操) print('刘备出%d'% 刘备) if (曹操==1 and 刘备==2) or (曹操==2 and 刘备==3) or (曹操==3 and 刘备==1): print('你真牛') elif 曹操==刘备: print('继续努力') else: print('你真菜')
import random a= random.randint(1,100) j=10 for i in range(j): c=int(input('请输入数字')) if a<c: print('输入的太大') elif a>c: print ('你输入的太小') else: print('输入正确') break
class Tudousi: def __init__(self): self.info='土豆丝' self.lever=0 self.Seasoning=[] def __str__(self): for i in self.Seasoning: self.info+=i+',' self.info=self.info.strip(',') return '当前的土豆丝的状态是:%s,炒土豆丝使用了%d分钟'%(self.info,self.lever,) def cook(self,t...
h=5 s=1 while h>0: print(" "*h,"*"*s) h=h-1 s=s+2
l = [] i = 0 while i < 100: i += 1 if i%3 == 0 and i%5 == 0: l.append(i) print(l)
class Father(object): a=None def __init__(self,name): self.name=name def wan(self): print('玩的很开心') def __new__(cls,*a): if cls.a == None: cls.a = object.__new__(cls) return cls.a xiao=Father('小明') print(id(xiao)) print(xiao.name) hua=Father('小花') print(id(hua)...
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def set_width(self, width): self.width = width def set_height(self, height): self.height = height def get_area(self): area = self.width * self.height return are...
#coding: utf8 def get_data_by_binary_search(target, source_list): min=0 max=len(source_list)-1 while min<=max: mid=(min+max)//2 if source_list[mid]==target: return mid if source_list[mid]>target: max=mid-1 else: min=mid+1 if __name__==...
# import the argv feature from module sys from sys import argv # unpack argv into 2 variables script, filename = argv # open a file txt = open(filename) print "Here's your file %r:" % filename # read file print txt.read() print "Type the filename again:" # get user input file_again = raw_input("> ") txt_again = op...
# Write classes for the following class hierarchy: # # [Vehicle]->[FlightVehicle]->[Starship] # | | # v v # [GroundVehicle] [Airplane] # | | # v v # [Car] [Motorcycle] # # Each class can simply "pass" for its body. The exercise is about setting up # the hie...
from datetime import datetime from database import * todos = [] def create_todo(): """ Create a new todo. """ todo_title = input("Enter a new item: ") new_todo = { "id" : len(todos) + 1, "title": todo_title, "completed": False, "date_added": datetime.now().strftime...