text
stringlengths
37
1.41M
def carga(): art=[] pre=[] for x in range(5): valor1=raw_input('Nombre del articulo: ') art.append(valor1) valor2=float(input('Precio: ')) pre.append(valor2) return [art,pre] def imprimir(v1,v2): print('Listado de productos') print(v1,v2) def imprimir_mayor(...
cont = 0 valor = int(input('Valor del 1 al 10: ')) for r in range(12): cont = cont + valor print(cont)
#!/usr/bin/env python # -*- coding: utf-8 -*- from copy import deepcopy AVAILABLE_COLORS = { "y": "yellow", "b": "blue", "g": "green", } # If the received color is one of the available colors, # this function will return a recipe with color ingrediant # and apropriate instructions. Otherwise, the unchang...
from challenge import * from Tests_December_1_2017a import * def inverse_captcha(input): """ This function takes of string of numbers. The function returns the sum of the matching indices and assumes the list is circular.""" index_in_input = 0 next_index_in_input = index_in_input + 1 sum_of_matched = 0...
def cheker_N(): while True: try: argument = int(input()) if (argument > 0 ): break except ValueError: print('НАСТУПНОГО РАЗУ ВВЕДІТЬ НАТУРАЛЬНЕ ЧИСЛО:') continue return argument def cheker_X(): while True: try...
# -*- coding: utf-8 -*- import sys codes = input() pre = '' for code in codes: if pre == code: print('Bad') sys.exit() pre = code print('Good')
""" Author:: hossain mishu Date:5/3/2020 Follow:: https://github.com/Hossain-Mishu """ class Queue: '''#to initialized a queue constractor just make an instance of Queue class.''' #initializing constructor FUNCTION def __init__(self): self.items = [] #METHODE for adding item in Queue...
def quick_sort(the_list): if len(the_list) < 2: return the_list else: mid_value = the_list[0] less = [item for item in the_list[1:] if item < mid_value] great = [item for item in the_list[1:] if item >= mid_value] return quick_sort(less) + [mid_value] + quick_sort(great) print (quick_sort([34,1,65,77,1...
""" COMP30024 Artificial Intelligence Semester 1, 2021 Project Part B David Peel 964682 Kevin Russell 1084088 """ from state.game_state import GameState from strategy.minimax import minimax_paranoid_reduction from strategy.evaluation import greedy_choose from strategy.book import book_first_four_moves from time import...
""" COMP30024 Artificial Intelligence Semester 1, 2021 Project Part B David Peel 964682 Kevin Russell 1084088 """ from heapq import heappush from state.game_state import GameState from state.token import defeats from state.location import distance """ Generic components of the greedy implementation """ def opponent_...
range_low = "264793" range_high = "803935" positions = [0,1,2,3,4] def check_doubles(code): for pos in positions: if code.count(code[pos])==2: return(True) return(False) def check_increasing(code): for pos in positions: if code[pos] > code[pos+1]: r...
money = input("How much is your money on hand?") amount = input ("How much is the iPhone X?") print ("You can avail",money/amount) print (" iPhone X, and will have an extra" , money%amount," pesos") print ("You'll need", amount-(money%amount)," pesos to avail another iPhone X.")
import re import random stepCounter = 0 board = ({1: {1:" ", 2:" ", 3:" "}, 2: {1:" ", 2:" ", 3:" "}, 3: {1:" ", 2:" ", 3:" "}}) def whosFirst(): if random.randint(0, 1) == 0: return 'O' else: return 'X' def checkEmpty(board, row, col): if board[row][col...
print('Grocery list:') print('"add" to add items and "view" to view list') grocery_list = [] while True: command = input('Enter command: ') if command == 'add': to_add = input('Enter new item: ') grocery_list.append(to_add) # elif stands for "else if" elif command == 'view': for ...
""" Program for a challenge at hackerrank.com We're going to make our own Contacts application! The application must perform two types of operations: add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a pa...
#%% # Import dependencies import pandas as pd # %% file_path = "./Resources/shopping_data.csv" df_shopping = pd.read_csv(file_path, encoding="ISO-8859-1") df_shopping.head(5) # %% # Look at what data we have df_shopping.columns df_shopping.dtypes # %% # Find null values for column in df_shopping.columns: print(...
print('Welcome to the Ramasedi Central Bank') Bank_account_balance = 1000 trials = 0 while trials <= 3: pin = int(input(' Enter your banking pin ')) if pin == 1234: print('you have entered your pin correctly') print('press 1 for balance ') print('press 2 to withdraw cash') ...
#High scores scores = [] choice = None while choice != 0: print( """ High scores 0- exit 1- show scores 2- add a score 3- delete a score 4-sort scores """) choice = input("Choice: ") print() #exit if choice == 0: print('Good-bye.') elif choice == 1: #...
# -*- coding:utf-8 -*- total = 0 a = '1.23,2.4,3.123' for c in a: if c.isnumeric(): total = total + int(c) print(total)
# -*- coding:utf-8 -*- def getGrades(fname): try: gradesFile = open(fname, 'r') except IOError: raise ValueError('getGrades could not open ', fname) grades = list() for line in gradesFile: try: grades.append(float(line)) except: raise ValueError('...
# -*- coding:utf-8 -*- from m100401 import mergeSort def lastNameFirstName(name1, name2): arg1 = name1.split(' ') arg2 = name2.split(' ') if arg1[1] != arg2[1]: return arg1[1] < arg2[1] else: return arg1[0] < arg2[0] def firstNameLastName(name1, name2): arg1 = name1.split(' ') ...
'''student=['666','555','mail'] print(student[-1]) student.append('51zxw') print(student) student.insert(0,'hello') print(student) student.pop (1) print(student) #元组(tuple) course=('chinese','English','math','computer') print(course) print(course[-1]) print(course[1:3]) print(course[:2]) print...
def CountDigit(number, digit ): count = 0 for i in str(number): if i.isalnum(): if int(i) == digit: count+=1 return count number,digit=input().split() number=int(number) digit=int(digit) count=CountDigit(number,digit ) print("Number of digit 2 in "+str(number)+":",count...
class Entity: transparent = "T" # This character is ignored when drawing the ASCII art def __init__(self, x, y, ASCII, overworldChar): self.x = x self.y = y # defines the origin at the top left of the ASCII art. Example of 3x3 ASCII art below. "O" is the position of the x, y values ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class InvertBT: # def __init__(self, root): # self.root = root def invertBinaryTree(self, root): def helper(root): if not root: ...
class Solution: # nums: List[int] def searchInsert(self, nums, target): if len(nums) == 1: if target > nums[0]: return 1 return 0 low, high = 0, len(nums)-1 while low < high: mid = (high+low)//2 ...
""" Reference:--https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/""" class Node: def __init__(self,key): self.value=key self.left=None self.right=None def __str__(self): return str(self.value) def insert0(root,node): current_node=root if node....
class Min_heap: def __init__(self,maxsize): self.size=0 self.maxsize=maxsize self.arr=[0]*(maxsize+1) self.front=0 def parent(self,pos): return pos-1//2 def left_child(self,pos): return pos*2+1 def right_child(self,pos): return pos*2+2 def inse...
from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__() self.shape('circle') self.color('white') self.move_speed = 0.1 self.penup() self.x = 10 self.y = 10 def move(self): self.move_speed = 0.01 new_x = self....
""" gaussian_blur_image.py This code will use the function gaussianblur(src, ksize, sigmaX) to blur an image with an intesity of the gaussan kernel, which is affected by an equation where the sigma affects the blurriness. When only the x sigma is specified, the y sigma is given the same value. Same parameters a...
dict = {'name': 'Bob', 'ref': 'Python', 'sys': 'Win'} print('Dictionary: ', dict) print( '\nReference:', dict['ref']) print( '\nKeys:', dict.keys()) del dict['name'] dict['user'] = 'Tom' print('Dictionary: ', dict) print( '\nIs there a name key?:', 'name' in dict)
# Initialize a variable with a user-specified value user = input( 'I am Python. What is your name? : ') # Output a string and a variable value print( 'Welcome', user) # Initialize another variable with a user-specified value lang = input( 'Favourite programming language? : ') # Output a string and a variable value p...
"""A back-end module to use with Google Authenticator mobile app, written in Python 3 An implementation of two factor authentication provided by Google Authenticator mobile app More info on the app: http://en.wikipedia.org/wiki/Google_Authenticator Allows to set up the app to work with your user accounts via manual i...
#return all partitions of a string def partitions(string): l=len(string) i=0; while(i<l): str1 = string[0:i+1] str2 = string[i+1:] print (str1," ",str2) partitions(str1) #partitions(str2) i += 1 string = input() partitions(string) ...
""" 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 leads to [1...
""" Description: Your task is to create a function that does four basic mathematical operations. The function should take three arguments - operation(string/char), value1(number), value2(number). The function should return result of numbers after applying the chosen operation. Examples: basic_op('+', 4, 7) ...
def lovefunc(flower1, flower2): if flower1 % 2 == 0 and flower2 % 2 != 0: return True elif flower1 % 2 != 0 and flower2 % 2 == 0: return True return False def lovefunc2(flower1, flower2): return (flower1 + flower2) % 2
def open_or_senior(data): result = [] for i in data: if i[0] >= 55 and i[1] > 7: result.append("Senior") else: result.append("Open") return result # List comprehensions are ridiculous. def openOrSenior(data): return ["Senior" if age >= 55 and handicap >= 8 else "Op...
""" There is an array with some numbers. All numbers are equal except for one. Try to find it! find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 It’s guaranteed that array contains at least 3 numbers. """ def find_uniq(arr): # Sorts the given array. arr.sort() # Returns the fi...
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ self.char2Ind = {} for i in range(1,10): self.char2Ind[str(i)] = 1 << (i-1) r,c,s = [0] *...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ...
# Definition for a undirected graph node class UndirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): # Empty graph if node == Non...
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ self.s1 = s1 self.s2 = s2 self.s3 = s3 if len(s3) != (len(s1) + len(s2)): return False res = ...
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] # to facilate express and compute,change the char to num nums = [] charToNum = {"(":1, ")":2, "[":3, "]":4, "{":5, "}":6} for i in range(len(s)...
# Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ res = [] ...
def greatestCommonFactorForTwo(a, b): if b == 0: return a else: return greatestCommonFactorForTwo(b, (a%b)) def greatestCommonFactorForN(arr = []): number = arr[0] for i in range(len(arr)): number = greatestCommonFactorForTwo(number, i) return number def lcmForTwo(a, b): ...
# !/bin/python3 # Program Name - candiesV2.py # Written by - Ella Blackledge # Date - 09/21/2018 # # Problem Statement: # # Alice is a kindergarten teacher. She wants to give some candies to # the children in her class. All the children sit in a line and each # of them has a rating score according to his or h...
# -*- coding: utf-8 -*- # 2019.01/03 from random import * def is_updown(num, target): if num < target: print('Go Up!') return 1 elif num > target: print('Go Down!') return 1 else: print('Good Job~!') return 0 answer = randint(1, 100) count = 1 while True:...
#-*- coding: utf-8 -*- import sys import math import functools # classes class ComPlex: '''Complex Class Definition''' def __init__(self, x=0, y=0): self.re = x; self.im = y; def Real(self): return self.re; def Imag(self): return self.im; def Conjugate(self): return Com...
# -*- coding: utf-8 -*- """ TODO """ from commands.Command import command import keyboard #pylint: disable=E0401 FORWARD = 'w' BACKWARD = 's' LEFT = 'a' RIGHT = 'd' STOP = 'esc' FORWARD_NEWLINE = 'w\n' BACKWARD_NEWLINE = 's\n' LEFT_NEWLINE = 'a\n' RIGHT_NEWLINE = 'd\n' FORWARD_BYTE = FORWARD_NEWLINE.encode("UTF-8") ...
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. # You may assume that the array is non-empty and the majority element always exist in the array. # Example 1: # Input: [3,2,3] # Output: 3 # Example 2: # Input: [2,2,1,1,1,2,2] # Output: 2 ...
#!/usr/bin/env python # -*- coding_utf-8 -*- """ Author: Zhenghan Lee Date: """ def is_bianxing(str1,str2): dic = {} for i in str1: if i in dic: dic[i] += 1 else: dic[i] = 1 for j in str2: dic[j] -= 1 if dic[j]<0: return False ...
# This decorator function does nothing. def do_nothing(function): return function # This is a function that adds two numbers. def add(x, y): return x + y # The decorator modifies the add function to... do nothing. @do_nothing def add(x, y): return x + y print('Result of calling the add function with the d...
from math import * import random grid_list = [ [1,2,3,4,5,6], [7,8,9,10,11,12], [13,14,15,16,17,18], [20,21,22,23,24,25], ] monthConversion = { "jan": "January", "feb": "February", "mar": "March", "apr": "April", } x = { "a": 1, "b": 2, "c": 3, "d": 4, } print(x.get(...
from colored import fg,bg, attr import random ''' This short program will count the letters in the words and only print those that are greater then 14 ''' words = ["elephant","monkey","buildings","people"] color = fg('green') for count in words: if len(count) > 14: bigWord = ("This word " + count.upper() ...
import random from math import * # this program looks for a secret word. You only get 3 try's. secrete_word = "monkey" guess = "" guess_limit = 3 attempts = 0 out_of_guesses = False while guess != secrete_word and not (out_of_guesses): if attempts < guess_limit: guess = input("Enter the secrete word plea...
from random import * import time import os import math # change this value to experiment with spawning ONE_SPAWNING_PROBABILITY = 0.85 TWO_SPAWNING_PROBABILITY = 1.75 probs = { 0: 0.60, 1: 0.25, 2: 0.15 } # TODO: add error checking class Board: """ Matrix that holds integer valu...
""" project.py ------------ Cartoon Network inspired graphic program Utilizing the original cartoon network animation logo as inspiration in accordance with what we learn in lecture 10 and lecture 11 - bouncing balls and moving images """ import tkinter import time import random import math import numpy as np import m...
class SortStack(): def __init__(self): self.sort_stack = [] self.helper_stack = [] def push(self, value): if self.sort_stack: while self.sort_stack and value > self.sort_stack[-1]: self.helper_stack.append(self.sort_stack.pop()) self.sort_stack.append(value) while self.helper_stack: ...
class ThreeInOne(): def __init__(self, size): self.size = size self.stackArray = [None] * self.size self.ends = [0,1,2] def push(self, stack_number, value): for index in range(self.size-2, self.ends[stack_number], -1): self.stackArray[index + 1] = self.stackArray[index] self.stackArray[self.ends[stack...
class Node(): def __init__(self, value, children=None): self.value = value self.visited = False self.children = [] if children: self.children = children def addChild(self, child): self.children.append(child) def addChildren(self, children): for child in children: self.addChild(child) def remove...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 2 14:56:55 2021 @author: mahir """ from tkinter import * #rules def printRules(): rules=Tk() x=10 rules.title('TIC TAC TOE: Rules') rules['bg']='black' Label(rules, text=' Snake ', font=('Helvetica',1...
x=list(input('enter string:')) x.sort(reverse=True) print("".join(map(str,x)))
l1=[1,2,3,6,8,4] l2=[2,4,1,3,8] if len(l1)==len(l2): print('all element is present') else: for x in l1: if x not in l2: print(x,'not present in l2') ''' print(sum(l1)-sum(l2))
import sys input_filename = sys.argv[1] file = open(input_filename,'r') stream = file.read() index = 0 group_level = 0 score = 0 garbage = False amount_of_garbage = 0 while index < len(stream) and stream[index] != "\n": char = stream[index] if char == '{' and not garbage: group_level += 1 elif cha...
#!/usr/local/bin/python import sys from math import floor no_of_elves = int(sys.argv[1]) def solve_circle(elves): offset = 2 no_of_elves = len(elves) if no_of_elves % 2 == 1: offset = 1 digital_half = int(floor(no_of_elves/2)) index = digital_half next_elves = [] for i in range(no_of_elv...
#!/usr/local/bin/python import sys import math import re import operator import copy file = open(argv[1],'r') # Parsing grid = [] for i,line in enumerate(file): grid.append([]) for char in line: if char == '#': grid[i].append(1) else: grid[i].append(0) def printGrid(): for x in range(100): ...
#!/usr/local/bin/python import sys part = int(sys.argv[1]) input_filename = sys.argv[2] file = open(input_filename,'r') instructions = list(map(int, file.read().splitlines())) pc = 0 steps = 0 while pc >= 0 and pc < len(instructions): oldpc = pc pc += instructions[pc] if part == 1 or instructions[oldpc] <...
import os def print_grid(grid): for row in grid: print(''.join(map(str, row))) def manhattan_distance(a, b): return abs(b[0] - a[0]) + abs(b[1] - a[1]) class CircularList: def __init__(self): self.l = list() def __init__(self, initlist): self.l = initlist ...
#!/bin/python3 import math import os import random import re import sys # Complete the climbingLeaderboard function below. def binarySearch (arr, l, r, x): if r >= l: mid = int(l + (r - l)/2) if arr[mid] == x: return mid elif arr[mid] < x: return binarySearch(...
#!/bin/python3 import math import os import random import re import sys # Complete the stones function below. def stones(n, a, b): x = [] l = 0 h = n-1 for i in range(n): temp = a*h + b*l x.append(temp) l+=1 h-=1 x = list(set(x)) x.sort() return x if __name...
#!/bin/python3 import math import os import random import re import sys # Complete the gameOfThrones function below. def gameOfThrones(s): arr = s temp=[] while len(arr)>0: temp.append(arr[0]) arr = arr.replace(arr[0], "") count=[] print(temp) for j in temp: c =0 ...
import getpass user_credentials = ['begueradj', 'password'] def get_user_credentials(): username = input('Username: ') password = getpass.getpass('Password: ') return username, password def check_user_credentials(user_credentials): username, password = get_user_credentials() return use...
# -------------- Exercise 3 ---------------------------------------------------- # Write a function that computes cosine of the angle between two d-dimensional vectors. # -------------- Code --------------------------------------------------------- # importing to project numpy library import numpy as np # filling v...
# -------------- Exercise 5 ---------------------------------------------------- #Write a program that for two lists x and y (possibly of different sizes) returns a list of #elements that are common between the lists. # -------------- Code --------------------------------------------------------- # two lists of diff...
import random import pygame class Food(object): """ A Food object. Members: x, y: store the position of the food. size: size of the food. """ def __init__(self, x, y, size=10): """ Initialize block at given x, y position """ self.x = x self.y = y ...
def sorting(dic): return " ".join([key for key, val in sorted(dic.items(), key=lambda x: x[1])]) if __name__ == '__main__': n = int(input()) dic = {} for i in range(n): student = input().split() dic[student[0]] = int(student[1]) print(sorting(dic))
import json def register(): print("You must register to view student information.") qerar = input("Press 1 to continue, otherwise press 2 : ") if qerar == "1": WritingTeacher() else: print("Bye!") def WritingTeacher(): def readData(_filename): with open(_filename, "r") as ...
#Comma Code spam = ['apples', 'bananas', 'tofu', 'cats']#define the lists that will need to be used to create the sentence, or multiple lists if desired schedule = ['IT75' , 'IT100' , 'IT105' , 'IT110'] #secondary list to further test function def corrected(list): #corrected will be defined as a function t...
def read_lines(): with open('students.txt') as f: new_names = f.read() list_of_words = new_names.split() new_dict = dict() for key in list_of_words: new_dict[key] = '' print (new_dict) read_lines()
a = int(input("Nhap so thu 1: ")) b = int(input("Nhap so thu 2: ")) print("\nSo da nhap a: "+str(a)+" b:"+str(b)) print("\nPhep cong: "+str(a+b)) print("\nPhep tru: "+str(a-b)) print("\nPhep nhan: "+str(a*b)) print("\nPhep chia: "+str(a/b))
print("-----------Tinh thue cho nhan vien-----------") a = int(input("Nhap so gio lam viec: ")) b = int(input("Luong theo gio: ")) if a > 40 : tienThemGio = (a - 40)*b*1.5 luongTruocThue = 40 * b + tienThemGio print("Muc luong truoc thue: " + str(luongTruocThue)) print("\nMuc luong sau thue: " + str(luong...
""" Module contains class which parses CLI parameters. """ import argparse class ArgParser: """Class for parsing CLI arguments Attributes: args (Namespace): Parsed arguments """ def __init__(self): parse = argparse.ArgumentParser() parse.add_argument("-c", "--config", typ...
import random a = random.randrange(1, 1001) b = 0 t = 0 while True: print("try: " + str(t+1)) t=t+1 b = int(input()) if a > b: print("answer is more big") elif a == b: print("the answer!") break else: print("answer is more small") print("the end")
#! /usr/bin/env python # -*- coding:utf-8 -*- from structure.stack import Stack prece = { '*': 3, '/': 3, '+': 2, '-': 2, '(': 1 } def infix2postfix(exp): opstack = Stack() items = exp.split(' ') res = list() for item in items: if item not in '+-*/()': res.append(item) elif item == '(': opstack.p...
#! /usr/bin/env python3 # -*- coding:utf-8 -*- class Queue: def __init__(self): self.queue = list() def is_empty(self): return self.size() == 0 def enqueue(self, item): self.queue.insert(0, item) def dequeue(self): return self.queue.pop() def ...
from threading import Thread from threading import Lock i=0 lock = Lock() def thread1(): global i for j in range(0,99999): lock.acquire() i += 1 lock.release() def thread2(): global i for j in range(0,99998): lock.acquire() i -= 1 lock.release() def main(): mainThread_1 = Thread(target = thread1, ...
def miller_rabin(n, k): """ Miller Rabin primality test for n Will fail when n is a carmichael number :param n: an integer greater than 1 :param k: number of random trials :return: True if "probably prime", False otherwise """ if n % 2 == 0: # return false if even number return ...
########################## # 输入右斜杠是转义字符 ########################## #print('\n\\\t\\') ################################ # 如果有很多的转义字符需要输出 ################################3 #print(r'\\\n\\\abc') ################################### # 换行的转义字符是 \n #2016-02-16 ################################### #print('a\nb') # 如果...
### 1 使用@property 进行类的属性定义并进行属性验证 #class Student(object): # # @property # def sex(self): # return self.sex # # @sex.setter # def sex(self,value): # if value >= 100 or value <=0 : # raise ValueError("年龄只能是1到99之间") # self._sex = value # # #kui = Student() #kui.sex = 1000 ...
# -*- coding: utf-8 -* ############################### #python 高级特性 ################################ ########################### # 切片的应用 2016-08-18 ############################ #获取列表的某一部分的值 #list = ["a","b","c"] #print(list[0:3]) #如果是从第一个元素取值的开始的,第一个元素可以不填 #print(list[:3]) #从第二个元素开i #print(list[1:3]) #切片也支...
def first_user_input(): choice = input("Select an option 1, 2, 3, 4, 5 or (Q)uit: ") return choice def user_description(): description = input("Enter task description to search for: ") return description def time_taken(): time = int(input("Enter task duration: ")) return time def add_already_...
#!/usr/bin/env python3 class Polynomial(): """ Class for basic mathematical operations with polynomials Operations : Add, Pow, derivative, at_value """ def __init__(self, *args, **kwargs): """ There are several ways to create class instances pol1 = Polynomial([1,-3,0,2]) pol2 = Poly...
import webbrowser class Movie(): """This class store movie related information""" def __init__(self, title, story_line, poster, movie_trailer, review): """this function will be called when a movie object is created keyword argument: self -- as a reference which called the constructor ...
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): total = 0 if "th" not in word: retu...
# -*- coding: utf-8 -*- print "Hello this is km to mile converter" while True: km = int(raw_input("Enter Km: ")) convertion = 0.621371 miles = km * convertion print "The distance in miles is:",miles more = raw_input("Another conversion (y/n):".lower()) if more == "n": break print "en...
# 创建字典 like_numbers = { 'yang yahu': [666, 777, 888, 999, 111, 222, 333, 444, 555], 'gao xiangzhou': [777, 675, 256, 342, 278, 999], 'yang yuhang': [888, 111, 125, 567, 789], 'li jianfeng': [999, 123, 234, 345, 456, 567, 678], 'yuan li': [256, 356, 456, 567, 678], } # 打印名字及喜欢的数字 for n...
# 编写函数 def make_shirt(size, typeface): """显示T恤的尺寸和标志""" print(f"\nThe size of the T-shirt is: {size} and the words of the T-shirt are: {typeface.title()}.") make_shirt('XXL', 'I love you!') make_shirt(size='XXL', typeface='I love you!')
def find_file(filename): """ 尝试读取文件,将其内容打印到屏幕上。 并在文件不存在时,捕获异常,打印一 条友好的消息。 """ try: with open(filename) as file_object: contents = file_object.read() except FileNotFoundError: pass else: print(contents.rstrip()) # 文件列表 filenames = ['/home/yyh/Documents...
# 创建字典 rivers = {'nile': 'egypt', 'Yangtze river': 'china', 'Yellow river': 'china', } # 为每条河流打印一条消息 for river, country in rivers.items(): print(f"The {river.title()} runs through {country.title()}.") # 打印每条河流的名字 for river in rivers.keys(): print(river.title()) # 另一种...