text
stringlengths
37
1.41M
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'MFC' __time__ = '2019-11-28 11:39' """ P332 26-6 遵循开放封闭原则的设计 """ # 引入以便定义抽象类 from abc import ABCMeta, abstractmethod class Animal(metaclass=ABCMeta): def __init__(self, name:str): self._name = name @abstractmethod def moving(self): ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__ = 'TesterCC' # __time__ = '17/11/18 16:36' """ geekxueyuan 零基础学Python 3.多态和封装 练习题 建立一个类,名字是Person,有关于人的基本信息 再建立一个程序员类,继承Person, 增加有关程序员的个性化信息 """ class Person(object): def __init__(self, name, age): self.name = name self.age = age ...
#!/usr/bin/env python # coding:utf-8 # http://coding.imooc.com/lesson/62.html#mid=917 # 2-1 如何在列表, 字典, 集合中根据条件筛选数据 # 1 过滤掉列表中的负数 -- 通用方式 data = [1, 5, -3, -2, 6, 0, 9] L = [3, 7, 9, -1, 20, 30, -2, -7, 18] res = [] for x in data: if x >= 0: res.append(x) print(res) resp = [] for i in L: if i >= 0...
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'MFC' __time__ = '18/8/5 23:33' """ 1.8 怎么在字典中进行一些计算操作(求最大值、最小值、排序等) """ prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } """ zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。 如果各个迭代器的元素个数不一致,则返回...
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'MFC' __time__ = '18/5/1 15:50' """ 3-1 什么是魔法函数 """ class Company(object): def __init__(self, employee_list): self.employee = employee_list # def __getitem__(self, item): # 定义这个可以迭代,支持for和切片 # return self.employee[item] def __le...
#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__ = 'TesterCC' # __time__ = '17/11/17 11:37' """ https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919344c4ef8b1e04c48778bb45796e0335839000 使用元类 type() """ class Hello1(object): def hello(self, name='world'): ...
class File: def __init__(self): self.isOpen = False self.isFile = False self.isReadable = False self.isWriteable = False self.content = '' class Directory(): def __init__(self): self.files = {} root = Directory() def mkdir(path): t = root if (path[0] !=...
def squared(number): try: integer = int(number) except ValueError: string = number * len(number) return string else: return integer ** 2 print("squared(5):") print(squared(5)) print(" ") print("squared(2):") print(squared(2)) print(" ") print("squared(\"tim\"):") print(sq...
# https://www.hackerrank.com/challenges/piling-up/problem from collections import deque if __name__ == '__main__': for i in range(int(input())): input() last = 0 res = 'Yes' d = deque(map(int, input().split())) while d: if d[-1] > d[0]: c = d.pop...
# https://www.hackerrank.com/challenges/any-or-all/problem if __name__ == '__main__': input() l = list(map(int, input().split())) n = [i > 0 for i in l] if all(n): l = [list(str(i)) == list(str(i))[::-1] for i in l] print(any(l)) else: print(False)
# https://www.hackerrank.com/challenges/html-parser-part-2/problem from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_comment(self, data): s = 'Single-line Comment' if '\n' not in data else 'Multi-line Comment' print('>>>', s) print(data) def handle_data(self...
# # @lc app=leetcode id=374 lang=python3 # # [374] Guess Number Higher or Lower # # https://leetcode.com/problems/guess-number-higher-or-lower/description/ # # algorithms # Easy (40.73%) # Likes: 295 # Dislikes: 1414 # Total Accepted: 126.8K # Total Submissions: 309.9K # Testcase Example: '10\n6' # # We are play...
#!/usr/bin/env python3 # Problem statement: # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. from pprint import pp def fSum(f,cap=1000): n = int(cap/f) if n*f==cap: ...
# # @lc app=leetcode id=693 lang=python3 # # [693] Binary Number with Alternating Bits # # https://leetcode.com/problems/binary-number-with-alternating-bits/description/ # # algorithms # Easy (58.47%) # Likes: 359 # Dislikes: 74 # Total Accepted: 52.4K # Total Submissions: 89.1K # Testcase Example: '5' # # Given...
# # @lc app=leetcode id=892 lang=python3 # # [892] Surface Area of 3D Shapes # # https://leetcode.com/problems/surface-area-of-3d-shapes/description/ # # algorithms # Easy (57.01%) # Likes: 209 # Dislikes: 270 # Total Accepted: 15.9K # Total Submissions: 27.5K # Testcase Example: '[[2]]' # # On a N * N grid, we ...
#!/usr/bin/env python3 # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. from math import sqrt,ceil def is_prime(num,f=2): if num <2: return False if num in [2,3] or f>sqrt(num): return True elif num%f==0: return False ...
# # @lc app=leetcode id=112 lang=python3 # # [112] Path Sum # # https://leetcode.com/problems/path-sum/description/ # # algorithms # Easy (39.14%) # Likes: 1253 # Dislikes: 394 # Total Accepted: 377.4K # Total Submissions: 961.7K # Testcase Example: '[5,4,8,11,null,13,4,7,2,null,null,null,1]\n22' # # Given a bin...
# # @lc app=leetcode id=746 lang=python3 # # [746] Min Cost Climbing Stairs # # https://leetcode.com/problems/min-cost-climbing-stairs/description/ # # algorithms # Easy (48.45%) # Likes: 1543 # Dislikes: 350 # Total Accepted: 122.7K # Total Submissions: 250.7K # Testcase Example: '[0,0,0,0]' # # # On a stairca...
# # @lc app=leetcode id=606 lang=python3 # # [606] Construct String from Binary Tree # # https://leetcode.com/problems/construct-string-from-binary-tree/description/ # # algorithms # Easy (52.51%) # Likes: 635 # Dislikes: 869 # Total Accepted: 71.5K # Total Submissions: 135.3K # Testcase Example: '[1,2,3,4]' # #...
# # @lc app=leetcode id=849 lang=python3 # # [849] Maximize Distance to Closest Person # # https://leetcode.com/problems/maximize-distance-to-closest-person/description/ # # algorithms # Easy (41.76%) # Likes: 626 # Dislikes: 95 # Total Accepted: 52.1K # Total Submissions: 123.5K # Testcase Example: '[1,0,0,0,1,...
# # @lc app=leetcode id=530 lang=python3 # # [530] Minimum Absolute Difference in BST # # https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ # # algorithms # Easy (51.78%) # Likes: 662 # Dislikes: 52 # Total Accepted: 73.9K # Total Submissions: 141.9K # Testcase Example: '[1,null,3,2]'...
# # @lc app=leetcode id=563 lang=python3 # # [563] Binary Tree Tilt # # https://leetcode.com/problems/binary-tree-tilt/description/ # # algorithms # Easy (47.34%) # Likes: 386 # Dislikes: 957 # Total Accepted: 63.9K # Total Submissions: 134.3K # Testcase Example: '[1,2,3]' # # Given a binary tree, return the til...
# # @lc app=leetcode id=733 lang=python3 # # [733] Flood Fill # # https://leetcode.com/problems/flood-fill/description/ # # algorithms # Easy (52.32%) # Likes: 745 # Dislikes: 146 # Total Accepted: 86.6K # Total Submissions: 163.5K # Testcase Example: '[[1,1,1],[1,1,0],[1,0,1]]\n1\n1\n2' # # # An image is repre...
# # @lc app=leetcode id=645 lang=python3 # # [645] Set Mismatch # # https://leetcode.com/problems/set-mismatch/description/ # # algorithms # Easy (41.23%) # Likes: 519 # Dislikes: 269 # Total Accepted: 61.1K # Total Submissions: 147.5K # Testcase Example: '[1,2,2,4]' # # # The set S originally contains numbers ...
# # @lc app=leetcode id=14 lang=python3 # # [14] Longest Common Prefix # # https://leetcode.com/problems/longest-common-prefix/description/ # # algorithms # Easy (34.36%) # Likes: 1743 # Dislikes: 1544 # Total Accepted: 584.1K # Total Submissions: 1.7M # Testcase Example: '["flower","flow","flight"]' # # Write a...
# -*- coding:utf-8 -*- class Solution: def jumpFloor(self, number): if(0 >= number): return 0 elif (1 == number): return 1 elif (2 == number): return 2 else: f1 = 1 f2 = 2 f3 = 0 for i in range(3,numb...
#Question 4 of Homework 1 def remainder(base, exponent, modulus): if modulus == 1: return 0 result = 1 for i in range(1, exponent + 1): result = (result * base) % modulus return result value = remainder(3, 287, 23) print(value) value = 3**287 % 23 print(value)
my_list = [1,2,3,4,5] my_list.insert(2, 'Hello World') print(my_list) # set a = {1,4,2,3,4,"Hello World"} a.update(['hello',2,3,4,54]) print(a) a = [] a.append(None) print(type(a)) print(a)
# Console input statment1 = input("Enter your name:") statment2 = int(input("Enter your Age:")) print(statment1) print(statment2) # file I/O data_write_file = input("Enter the data to write a file") with open('data.txt','w') as f: f.write(data_write_file +'\n') with open("data.txt",'a') as f: f.write(data_w...
''' :: Multi-Level Inheritance Vehicle | Car | SportsCar ''' class Vehicle: name = None brand = None speed = None color = None power = None fuel_type = None def __init__(self, name, brand): self.name = name self.brand = brand def drive(self): print('driving..'...
brands = ['suzuki', 'kia', 'bmw'] #index example car_name = brands[0] print(car_name) car_name = brands[1] print(car_name) car_name = brands[2] print(car_name) print('negative indexing') car_name = brands[-1] print(car_name) car_name = brands[-2] print(car_name) car_name = brands[-3] print(car_name) #length prin...
"""1. Написать несколько функций, которые в качестве единственного аргумента принимают список (или кортеж) целых чисел. - первая функция должна вернуть квадраты элементов коллекции; - вторая функция должна вернуть только элементы на четных позициях; - третья функция возвращает кубы четных элементов на нечетных позициях...
"""10. Write a Python program to get the difference between the two lists""" SampleList1 = list("список") print("Sample list #1", SampleList1) SampleList2 = list("лист") print("Sample list #2", SampleList2) print("The difference (1 - 2):", list(set(SampleList1) - set(SampleList2)))
"""Задание 1. Разработать класс Complex, которые бы описывал комплексные числа, позволял их складывать, вычитать, умножать, делить и получать модуль. Вывод действительной и мнимой частей должен быть с точностью до двух знаков после запятой. На вход: действительная и мнимая часть числа, разделенная пробелом. Sample Inpu...
"""1. Написать функцию, которая печатает квадраты всех нечетных чисел в произвольном интервале [0, Х]. А так же количество таких чисел. """ def is_even(number): """ :type number: int """ odd_counter = 0 i = 0 while i < number: i += 1 if i % 2 > 0: print("Нечентное ч...
import numpy as np import cv2 #Get video name from user #Ginen video name must be in quotes, e.g. "pirkagia.avi" or "plaque.avi" video_name = input("Please give the video name including its extension. E.g. \"pirkagia.avi\":\n") #Open the video file cap = cv2.VideoCapture(video_name) #Set frame_no in range 0.0-1.0 #I...
# -*- coding: utf-8 -*- # File Name: 703 # Description : # Author : LvYang # date: 2019/3/28 # Change Activity: 2019/3/28: import heapq class KthLargest(object): def __init__(self, k, nums): """ :type k: int :type nums: List[int] """ ...
# -*- coding: utf-8 -*- # File Name: 1.3 # Description : # Author : LvYang # date: 2019/8/19 # Change Activity: 2019/8/19: from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if patte...
# -*- coding: utf-8 -*- # File Name: 1.10 删除序列相同元素并保持顺序 # Description : # Author : LvYang # date: 2019/8/20 # Change Activity: 2019/8/20: # def dedupe(items): # print("items: {}".format(items)) # seen = set() # for item in items: # print("item0: {}".format...
#how to find the calender on the web page ''' from selenium import webdriver from selenium.webdriver.common.by import By import time class calender_finding(): def calender(self): driver=webdriver.Firefox() baseurl='https://www.expedia.com/' driver.get(baseurl) driver.maximize_window...
from connect_four_class import connectFour import sys print("\nWelcome to connect four, python version!") while True: start_menu = input( "Enter 1 for original size game\nEnter 2 for custom size game\nEnter 3 for rules\nEnter 4 to quit\n>> " ) if start_menu == "1": print( "Origi...
#!/usr/bin/env python ''' SQL Introducción [Python] Ejercicios de práctica --------------------------- Autor: Inove Coding School Version: 1.1 Descripcion: Programa creado para poner a prueba los conocimientos adquiridos durante la clase ''' __author__ = "Inove Coding School" __email__ = "alumnos@inove....
""" Using a Brickman (robot) as the receiver of messages. """ # Same as m2_fake_robot_as_mqtt_sender, # but have the robot really do the action. # Implement just FORWARD at speeds X and Y is enough. import tkinter from tkinter import ttk import mqtt_remote_method_calls as com import time class DriveSystem(object):...
import code import pandas as pd class Annotator: """ The Annotator class, will annotate a partially, or unlabled dataset. Parameters: * df - a pandas dataframe """ def __init__(self, df, model): self.df = df.copy() self.filtered_df = None def choose_column_to...
import math from string import digits, ascii_lowercase, ascii_uppercase def to_base_62(number, b=62): """ Encode and decode to base 62. """ if b <= 0 or b > 62: return 0 base = digits + ascii_lowercase + ascii_uppercase r = number % b q = math.floor(number / b) result = b...
''' 3. Escreva um programa para: (a) abrir uma imagem e exibir na tela os 3 canais separadamente ''' import cv2 import numpy img = cv2.imread('r2d2.jpg') # save b, g, r # Invertendo a lista invertida = img[:, ::-1] # Imprimindo a imagem cv2.imshow('Invertida', invertida) cv2.imwrite('Invertida.jpg', invertida)...
# # 基于斐波那契理论定义的公式 # # import argparse parser = argparse.ArgumentParser() parser.add_argument("-X", help="X",default=0.0) parser.add_argument("-A", help="A",default=0) parser.add_argument("-B", help="B",default=0) parser.add_argument("-C", help="C",default=0) parser.add_argument("-D", help="D",default=0) args = parser...
from random import Random def mergeSort(ls : list): if len(ls) > 1: mid = len(ls) // 2 l = ls[:mid] r = ls[mid:] mergeSort(l) mergeSort(r) i = j = k = 0 while i < len(l) or j < len(r): if j == len(r) or i < len(l) and l[i] < r[j]: ...
# -- b -- def to_camel_case(text): new_text = text.lower() lst_text = new_text.split() for i, word in enumerate(lst_text): lst_text[i] = word.capitalize() return "".join(lst_text) print(to_camel_case("tHis Is A tesT string")) print(to_camel_case("hello world")) print(to_camel_case("M...
# 示例 1: # 输入: 4 # 输出: 2 # 示例 2: # 输入: 8 # 输出: 2 # 说明: 8 的平方根是 2.82842..., # 由于返回类型是整数,小数部分将被舍去。 class Solution: # 二分查找 # 因为y=x^2是单调递增的 def mySqrtBinarySearch(self, x): """ :type x: int :rtype: int """ left = 0 right = x while left <= right: ...
# Example 1: # Input: ["flower","flow","flight"] # Output: "fl" # Example 2: # Input: ["dog","racecar","car"] # Output: "" # Explanation: There is no common prefix among the input strings. class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """...
# -*- coding: utf-8 -*- # @Time : 2020/1/3 13:19 # @Author : zhaoxuyan # @FileName: 037_解数独.py # @Software: PyCharm # https://leetcode-cn.com/problems/sudoku-solver/ def isValid(board, row, col, c) -> bool: for i in range(9): # 检查行中是否有c if board[row][i] != '.' and board[row][i] == c: ...
def square(num): result = num ** 2 return result x = square(13) print(x) sq = lambda n: n ** 2 x = sq(10) print(x) def even(n): return n % 2 == 0 e = even(11) print(e) rev = lambda s: s[::-1] r = rev("love") l = rev("evolve") print(r) print(l) len_chk = lambda item: len(item) chk = len_chk("this is...
#Ejercicio 16: Crear un programa que cree un diccionario vacío y lo vaya llenado con información sobre una persona # (por ejemplo nombre, edad, sexo, teléfono, correo electrónico, etc.) que se le pida al usuario. Cada vez que se añada un nuevo dato # debe imprimirse el contenido del diccionario. """creo diccionario ...
#Ejercicio 6: Escribir un programa que seleccione una operación de cuatro operaciones numéricas disponibles, una vez seleccionada # la operación, introducir dos números y ejecutar la operación. n1 = int(input('Ingrese el primer numero')) n2 = int(input('Ingrese el segundo numero')) operacion = int(input('Ingres...
#Ejercicio 9: Pedirle al usuario que ingrese el monto disponible en su tarjeta de crédito. Evaluar si puede realizar una compra de $2500, # si puede indicar cuánto saldo le queda luego de efectuarla. Si no puede, indicar cuánto dinero le falta para poder realizarla. disponible = int(input('Ingrese el monto disponib...
#Ejercicio 8: Crear una función que calcule cuántos litros de nafta gasta un auto que consume 2 litros x 100km, # en un viaje ida y vuelta MdP-Bue si la distancia es de 400km. Luego crear una función que, a partir de esos datos, # devuelva cuánto significa eso en pesos si el litro de nafta está 60$. def consumo_na...
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ return self.searchRange(nums, target, 0, len(nums)-1) def searchRange(self, nums, target, l, r): if l > r: return l ...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ len = sel...
class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return max, pre = nums[0], nums[0] for i in range(1, len(nums)): now = nums[i] if pre > 0: now...
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[...
# ### calculate the number of english letters, space, numbers, and other charactors # In a txt file import re import pprint def file_in(in_file): f=open(in_file) content=f.read() count={} for i in content: count[i]=count.setdefault(i,0) count[i]+=1 x=cont...
"""""" """ 1 Sample T-Testing Let's imagine the fictional business BuyPie, which sends ingredients for pies to your household, so that you can make them from scratch. Suppose that a product manager wants the average age of visitors to BuyPie.com to be 30. In the past hour, the website had 100 visitors and the average...
import pandas as pd from matplotlib import pyplot as plt import seaborn as sns gradebook = pd.read_csv("gradebook.csv") """ By default, Seaborn will place error bars on each bar when you use the barplot() function. By default, Seaborn uses something called a bootstrapped confidence interval. Roughly speaking, this i...
from matplotlib import pyplot as plt """ """ x_values = [0, 1, 2, 3, 4] y_values = [0, 1, 4, 9, 16] plt.plot(x_values, y_values) plt.show() days = [0, 1, 2, 3, 4, 5, 6] money_spent = [10, 12, 12, 10, 14, 22, 24] plt.plot(days, money_spent) plt.show() """ Plot values1 vs. values2 means that you should plot values2 o...
my_tuple = ("apple", "orange", "grapes") print(my_tuple) print(my_tuple[1]) print(my_tuple[-1]) print(my_tuple[0:2]) for val in my_tuple: print(val) # tuple object does not support item support #my_tuple[1] = "Banana" my_tuple_2 = ("name",(1,2,3),['a','b','c']) print(my_tuple_2) # it can ...
#!/usr/bin/py #https://www.hackerrank.com/challenges/pairs import math def pairs(a,k): return len(set(a) & set(x + k for x in a)) # Tail starts here if __name__ == '__main__': a = map(int, raw_input().strip().split(" ")) _a_size=a[0] _k=a[1] b = map(int, raw_input().strip().split(" ")) pri...
# https://www.hackerrank.com/challenges/two-strings/ # Enter your code here. Read input from STDIN. Print output to STDOUT n=int(raw_input()) testcases=[] for i in range(0,n): testcases.append((raw_input(),raw_input())) for (subA,subB) in testcases: result="NO" for s in range(97,123): if chr(s) in ...
from .elevator import Elevator class Admin: #globalVariables #n-> elevators, m-> floors n,m=1,1 #arrays of elevators elevators=[] # constructor of this object, set the GV n,m and fill the elevators array def __init__(self,n_,m_): self.n=n_ self.m=m_ print "Admin will handle " + str(self.n) + " elevator...
#https://www.hackerrank.com/challenges/time-conversion #!/bin/python import sys time = raw_input().strip() plus=0 if "PM" in time: plus=12 time=time.replace("PM","").replace("AM","") aTime=time.split(":") if aTime[0]== "12": if plus==0: aTime[0]="0" else: plus=0 newHour=int(aTime[0])+plus...
# https://www.hackerrank.com/challenges/word-order apearOrder=[] dicWords={} for i in xrange(long(raw_input())): word=raw_input().replace("\r","") if not word in dicWords: apearOrder.append(word) dicWords[word]=1 if not word in dicWords else dicWords[word]+1 print len(apearOrder) for word in a...
#https://www.hackerrank.com/challenges/map-and-lambda-expression/ # Enter your code here. Read input from STDIN. Print output to STDOUT n=int(raw_input()) fibo=lambda a: fibo(a-1)+fibo(a-2) if a>1 else (0 if a==0 else 1) cubeFibo=lambda a: pow(fibo(a),3) ar=map(cubeFibo,range(0,n)) print ar
#!/bin/python #https://www.hackerrank.com/challenges/big-sorting import sys n = int(raw_input().strip()) unsorted = {} for _ in xrange(n): unsorted_t = str(raw_input().strip()) len_=len(unsorted_t) if not len_ in unsorted: unsorted[len_]=[] unsorted[len_].append(unsorted_t) ...
def get_user_input_int(prompt: str, lower_imit = None, upper_limit = None): while True: user_input = input(prompt + "(oder q zum abbrechen)") try: user_input = int(user_input) break except ValueError: if user_input.lower() == 'q': ...
""" Design a calculator which will correctly solve all the problems except the following ones: 45*3= 555,56+9= 77,56/6= 4 Your programme should take operator and the two numbers as input from the user and then return the result. """ # Solution print("WELCOME TO THE CALCULATOR:") print("\nList of operat...
# -*- coding: utf-8 -*- __author__ = 'p.olifer' __version__ = '1.0' def fibogen(n): if type(n) is not int: raise TypeError('type of argument should be int!') if n <= 0: return else: f1 = 0 f2 = 1 yield 1 for i in range(2, n): result = f1 + f2 ...
from abc import ABCMeta, abstractmethod class Person: def __init__(self, name, age): self._name = name self._age = age @property def name(self): return self._name @property def age(self): return self._age @age.setter def age(self, age): self._age =...
class Vertex: def __init__(self,dist=(-1),col=(-1),par=None): self.dist=dist self.col=col self.par=par class Queue: def __init__(self): self.T=[] def enqueue(self,x): self.T.append(x) def dequeue(self): return self.T.pop(0) def Empty(self): if len(self.T)==0: return False return True class No...
from Stack import Stack def toPostfix(expr): a=expr.split() print(a) l=len(a) symb=0 while(symb != l): if (a[symb]=='*' or a[symb]=='/'): t=a.pop(symb) a.insert(symb+2,t) symb=symb+2 symb=symb+1 print(a) for symb in a: if (a[0]=='+' or a[0]=='-'): s(a) print(''.join(a)) def s(...
class Node: def __init__(self,x): self.parent=None self.value=x def Bottom_up_LPath(t): A=[None for i in range(0,len(t))] n=len(t) l=[None for i in range(0,n)] print(t) for i in range(0,n): A[i]=Node(t[i]) T=[0 for i in range(0,n)] for i in range(n-1,-1,-1): maximum=0 for j in range(i+1,n): if(...
# Day 4 Project: Rock Paper Scissors import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ __...
# Day 1: Band Name Generator # Learn print(), input(), and string formatting print("Welcome to the Band Name Generator!") city = input("What\'s name of the city you grew up in?\n") pet = input("What\'s your pet\'s name?\n") print("Your band name could be " + city + " " + pet + "!")
# Day 4 Exercise: Bank Roulette import random names_string = input("Give me everybody's names, separated by a comma. ") names_list = names_string.split(",") print(f"{random.choice(names_list)} is going to buy the meal today")
#Spencer Goldwin #Declare constants stateSalesTax = 0.05 countySalesTax = 0.025 #Ask user for purchase amount purchaseAmount = float(input('Enter purchase amount:')) #Calculate tax calcStateTax = stateSalesTax * purchaseAmount calcCountyTax = countySalesTax * purchaseAmount totalTax = calcStateTax + calcCounty...
# Author - Anantvir Singh, reference:= Data Structures in C by Seymour Lipschutz class Node: def __init__(self,info,link= None): self.info = info self.link = link class LinkedList: def __init__(self): self.head = None self.tail = None self.current_ptr = None # ma...
x = float(input()) y = float(input()) print('%.2f + %.2f = %.2f'%(x,y,x+y))
s1 = "Welcome to Python World Game." #請使用str.split以空格做分割。 s2 = "Can you can a can as a canner can can a can?" #請使用str.count 算出有幾個'a' s3 = "Few free fruit flies fly from flames." #請使用str.find 或str.index 找出"fly" 第一次出現的位子 s4 = "Czngrxtulxtizns, yzu hxve pxssed the czmpetitizn." #請使用str.replace 把'z' 替換成 'o',以及把'x'替換...
x = [] n = int(input()) for i in range(n,0,-1): print("data",i) x.append("data "+str(i)) print() for j in range(n): print(x.pop())
# for : pour une valeur de depart (1), jusqu'à une valeur d'arrivee (5) for num_client in range(1, 5): print("Vous etes le client n°", num_client) # for each : pour chaque valeur d'une liste données # lister les emails emails = ['gravenilvec@gmail.com', 'graven@graven.yt', 'gravendev@yahoo.fr', 'steelaxiss@free.f...
def main(): # creation d'une variable 'username' ayant pour valeur le mot Graven username = "Graven" username = "YouTube" # creation d'une variable 'age' ayant pour valeur 19 age = 19 # change la valeur par 25 age = 25 # afficher la nouvelle valeur age = age * age print("Salut "...
L=["Matt","Stephen","Liam"] print(L) L=["Matt","Stephen","Liam","Maia","Sam"] print(L[0]) print(L[2]) print(L[3]) print(L[-1]) print(L[-4]) print(L) print(L[-2]) L[1:4] print(L) L.remove("Liam") print(L) L[3]="Tina" print(L) print(bool("Clyde" in L)) print(bool("Stephen" in L)) print(len(L)) L.reverse() print(L) L.sort...
#Maia Reynolds #5/7/18 #quiz5.py - four functions with lists def penultimate(list1): #takes second to last item in list return list1[-2] def plusEquals(list2,integer): #makes new list with integer added to each item newlist=[] for item in list2: newlist.append(item+integer)#adds new number to newl...
# row = input('请输入行数:') # for i in range(int(row)): # for _ in range(i + 1): # print ('*',end='') # print() # for i in range(int(row)): # for j in range(int(row)): # if j < int(row) -i -1: # print(' ',end='') # else: # print('*',end='') # pr...
parrot = 'Norwegian Blue' letter = input("Enter the char: ") if letter not in parrot: print('{0} these letter didnt contain in "{1}" words'.format(letter,parrot)) else: if (letter.upper()=='i') or (letter.upper() == 'a') or (letter.upper() == 'e') or (letter.upper() == 'o') or (letter.upper()=='u'): pri...
class Circle: def __init__(self,radius): self.r=radius def area(self): return (self.r**2)*3.141592 def circumference(self): return self.r*2*3.141592 x=Circle(500) print x.area() print x.circumference()
import unittest as test a1 = ["live", "arp", "strong"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"] r = ['arp', 'live', 'strong'] class RunTest(test.TestCase): def test_cases(self): self.assertEquals(in_array(a1, a2), r) if __name__ == '__main__': def in_array(array1, array2): myl...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/10 14:02 # @Author : tanxw # @Desc : 函数使用 # 从当前目录导入模块 from . import function_module_using # 从指定目录导入模块 # from lesson103 import function_module_using """ def 函数名(): 函数封装的代码 ... """ # 1. 函数定义及使用 def say_hello(): print("hello 1") print...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/14 22:28 # @Author : tanxw # @Desc : 类的继承使用,重写,多态 class Tools(object): # 定义类属性,记录工具对象的总数 count = 0 def __init__(self, name): self.count = 5 self.name = name # 针对类属性做 +1 操作 Tools.count += 1 @classm...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/4/10 0:41 # @Author : tanxw # @Desc : 设计模式 """ 设计模式的目标是形成典型问题的解决方案,设计出可复用的软件结构。 设计模式与语言无关的,任何语言都可以实现设计模式 设计模式根据使用目的不同而分为创建型模式(Creational Pattern)、 结构型模式(Structural Pattern)、行为型模式(Behavioral Pattern) 创建型模式提出了对象创建的解决方案以及数据封装的方法。 降低了创建对象时代码实现的复杂度,使对象的创建...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/11 17:46 # @Author : tanxw # @Desc : 数据输入 """ 两种格式 ----------------------------------------- ▲语法格式: 格式一: input() # 不常用 格式二: input(“提示信息”) ▲语法格式: 格式: 变量 = input(......) """ # print() # 输出打印 输入 input() # 输入东西给程序使用 # input() # 使用input得到的数据都是str字符串类...