text
stringlengths
37
1.41M
# https://leetcode.com/problems/next-greater-element-ii/ # Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which...
# https://leetcode.com/problems/course-schedule/ # There are a total of n courses you have to take, labeled from 0 to n-1. # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # Given the total number of courses and a list of prerequ...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: # Iterative Solution using stack # def isValidBST(self, root: TreeNode) -> bool: # stack = [] # pr...
x = int(input("")) y = int(input("")) minnum = min(x, y) maxnum = max(x, y) for i in range(minnum, maxnum, 1): if i%5 in (2, 3): print(i)
# %% def selection_sort(L): L2 = {} for k, v in list(L.items()): current_min = k value_min = v for k2, v2 in list(L.items())[1:]: if current_min > k2: current_min = k2 value_min = v2 # print(current_min) # L2[current_min] = val...
# %% import datetime # %% class Person(): def __init__(self, DoB, Name): self.DoB = DoB self.Name = Name def getName(self): return self.Name def getDoB(self): return self.DoB class NonMember(Person): def __init__(self, DoB, Name): Person.__init__(self, DoB,...
def pot(n): if n==1: return True if n%3!=0 : return False return pot(n/3)
#Same problem as above using bit vector(Space efficient): #Assumption- String contains only lowercase letters s=input() checker=0 val=0 i=0 while(i<len(s)): val=ord(s[i])-ord('a') if not((checker & 1<<val)==0): print ("Not Unique") break else: checker=checker|1<<val i+=1 if(i==le...
def study_schedule(start_time, end_time, target_time): count = 0 for i, number in enumerate(start_time): if start_time[i] <= target_time <= end_time[i]: count += 1 return count
import math # ------------------------------------------------------- ### Heuristics class ### # two different admissible (or consistent) heuristic functions (h1 and h2) # one should dominate the other: heuristic h1 dominates h2 if h1(n) > h2(n) for all n # Heuristics class that defines methods # that compute the h...
from environment import * def main(): print("Creating a new environment") env = newEnvironment() print("The environment is ") displayAll(env) print("Adding variable x with value 3") populate('x',3,env) print("The environment is ") displayAll(env) print("Extending the environment wit...
import decimal from fractions import Fraction # 定义小数精度位数 decimal.getcontext().prec = 2 #处理小数 def my_decimal(x,y): result = decimal.Decimal(x)+decimal.Decimal(y) return result #处理分数 def my_fraction(x,y): a = Fraction(x,y) print(a) b = Fraction(0.25) print(b) return a,b # 有一分数序列:2/1,3/2,5/...
# coding=utf-8 # https://www.cnblogs.com/itcomputer/articles/4578769.html # import timeit # import math # import pprint # # 为了输出美观,使用了pprint这个有意思的模块 # # def myfun(): # for i in range(100): # for j in range(2, 10): # math.pow(i, 1/j) # # n = 100 # # t1 = timeit.timeit(stmt=myfun, number=n) # ppr...
from itertools import chain sunday_temps = [68, 75, 72, 80] monday_temps = [71, 80, 75, 81] tuesday_temps = [70, 82, 77, 79] for temps in zip(sunday_temps, monday_temps, tuesday_temps): min_temp = min(temps) max_temp = max(temps) avg_temp = sum(temps) / len(temps) print(f"Min: {min_temp}; Max: {max_t...
r = float(input("Jari-jari lingkaran: ")) pi = 22/7 area = float(pi*r*r) txt = "Luas lingkaran dengan jari-jari {} cm adalah {:06.2f} cm\u00b2".format( r, area) print(txt) # done
n1 = int(input("Digite o primeiro número: ")) #primeira entrada n2 = int(input("Digite o segundo número: ")) print() print("""1) Adição 2) Subtração 3) Multiplicação 4) Divisão """) op = int(input("Qual a operação desejada? ")) if op == 1: resultado = n1 + n2 print(f"{n1} + {n2} = {resultado}") elif op == 2: ...
from functools import reduce def maior(a, b): if a > b: return a else: return b def pares(a): if a % 2 == 0: return a array = [10, 43, 21, 100, 12] print(reduce(maior, array)) print(list(filter(pares, array)))
class newNode: def __init__(self, data): self.data = data self.left = self.right = None def isSumProperty(root): # If current element is null, return true. if not root: return 1 d1 = 0 d2 = 0 if root.left: d1 = root.left.data if ro...
class newNode: def __init__(self, data): self.data = data self.left = self.right = None def isFoldable(root): if not root: return True return isSubtreeFoldable(root.left, root.right) def isSubtreeFoldable(x1, x2): # If both left and right nodes are not none, return true....
import csv def readMyFile(filename): city = [] museumName = [] state = [] with open(filename) as csvDataFile: csvReader = csv.reader(csvDataFile) for row in csvReader: museumName.append(row[1]) city.append(row[7]) state.append(row[8]) return mus...
import math import random def getDistance(p1, p2): """ Get distance between two 3d points @param p1: (list) : First point coord (list[float(x), float(y), float(z)]) @param p2: (list) : Second point coord (list[float(x), float(y), float(z)]) @return: (float) : Distance between p1 and p2 """...
#!/usr/bin/env python # -*- coding: utf8 -*- """This module contains all game functionality.""" import argparse from board import Board from script import Script from human import Human class Game: """ Game controller. This class will either allow users to play or make calls to the engine scripts, de...
def main(): print ("Hi im chatbot") print("let's get to know each other!") intro() ask() color() place() vac() game() number() dog() bye() def intro(): answer = input("whats your name?--\n") print("Hi",answer,":)") def ask(): ans = input("\nHow...
#%% def fizzbuzzwhiz(num): if num == 0: return "undefined" elif num % 3 == 0 and num % 5 == 0: return "FizzBuzz" elif num % 3 == 0 and num != 3: return "Fizz" elif num % 5 == 0 and num != 5: return "Buzz" elif num >=1: for i in range(2, num): if (...
# Create a list of Squares from 1 to 10 squares=[] for i in range(1,11): squares.append(i**2) squares # List Comprehension # Append... Condition Squares=[i**2 for i in range(1,11)] # Create a list from 1 to 10 negative numbers Neg=[i*-1 for i in range(1,11)] Neg # Names ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 1 17:37:28 2021 @author: philip """ #Initialize all the markers face_north = "^" face_south = "v" face_east = ">" face_west = "<" gold = "G" pit = "P" beacon = "B" import random #Create the Agent class, this will be the player of the game class A...
def longestCommonPrefix(s): 'Written by myself' if not s: return "" str0 = min(s) str1 = max(s) for i in range(len(str0)): if str0[i] != str1[i]: return str0[:i] return str0 'Answer' ans = '' for i in zip(*s): if len(set(i)) == 1: ans...
# -*- coding: utf-8 -*- """ Created on Fri Nov 04 12:06:07 2016 Project Euler Problem #576 @author: gargi chakraborty """ import math import numpy as np import matplotlib.pyplot as plt import time #Hard coded values circumference = 1 # Get all prime numbers less than n def is_prime(num): for i in ...
# encoding: UTF-8 # Autor: Sergio Hernandez # Descripcion: Calcula el IMC a partir del peso y la estatura def calcularIMC(peso,estatura): #Calcula el IMC y devuelve el estado de la persona IMC = peso / estatura**2 if (IMC < 18.5): estado = "Bajo peso" elif (IMC >= 18.5 and IMC <= 25): estad...
class Flower(): """ Simulate a flower Defult name = Rose , 5 petals, price = 1.0 """ def __init__(self, name='Rose', petals_num=5, price=1.0): """ initializes variable """ self.name = name if isValid(petals_num, ['Petal','Number']): self.petals_num = petals_num ...
# -*- coding: utf-8 -*- """ Created on Sun Jan 13 02:19:12 2019 @author: Bill Liu """ decimal_number = eval(input('Please input the decimal number:')) base = 2 number_fractional_postions = 10 integer_part = int(decimal_number) fractional_part = decimal_number - integer_part target_interger = list() while integer_par...
def legal_input(number): # The number should be all digit and can't start with 4, 5, 6, 37. if number.isdigit() and len(number) > 12 and len(number) < 17: if number[0] in ['4','5','6'] or number[:2] == '37': return True def isValid(number): # Count the totalSum to find out whether is it...
fruits = {"grapes", "apples", "oranges"} # Looping through set elements for x in fruits: print(x) print("\n") # Construct set using constructor function animals = set(("lion", "tiger", "bear")) for y in animals: print(y) print("\n") print(len(animals)) print("\n") # add() - Adds an element to set fruits.add...
# Defining and calling of a function def sum(x, y): print(x + y) a = 75 b = 25 sum(a, b) # Return value in a function def sub(x, y): return x - y print(sub(56, 36)) # Using default parameter value def students_name(names="Billu"): print("Hello " + names) students_name() students_name("John") stude...
# Encapsulation in Python # class Cars: def __init__(self, speed, color): self.__speed = speed self.__color = color def setSpeed(self, value): self.__speed = value def getSpeed(self): return self.__speed def setColor(self, value): self.__color = value def...
'''Input''' # How the input() Function Work message = input("Tell me something, and I will repeat it back to you. ") print(message) name = input("Please enter your name: ") print("Hello, " + name + " !") height = input( "How tall are you, in inches? ") height = int(height) if height >= 36: print("\nYou...
'''Functions: Try it Yourself 8-3 - 8-5''' # 8-3 T-Shirt print("\nT-Shirt") def make_shirt(size, text): print("The size of the shirt is " + size + " with a print of \"" + text + "\".") make_shirt('medium', 'Instant Human, Just add Coffee') make_shirt(size='medium', text='Instant Human, Just add Coffee...
'''Dictionaries Try it Yourself 6-4 - 6-6''' # 6-4 Glossary 2 # 6-5 Rivers rivers = { 'nile': 'egypt', 'amazon': 'africa', 'yangtze': 'china', } for river, place in rivers.items(): print("The " + river.title() + " river runs through " + place.title() +".") for river in rivers.keys(): prin...
"""Classes Try it Yourself 9-6 - 9-9""" # 9-6 Ice Cream Stand print("\nIce Cream Stand") class Restaurant: """Make a Restaurant Profile""" def __init__(self, restaurant_name, cuisine_type): """Initiate Restaurant Name and Cuisine Type""" self.restaurant_name = restaurant_name ...
'''If Statements: Try it Yourself 5-3 - 5-4''' # 5.3 Alien Colors #1 alien_color = 'green' if alien_color == 'green': print('You earn 5 points.') # 5.4 Alien Colors #2 alien_color = 'green' if alien_color == 'green': points = 5 else: points = 10 print("You earn " + str(points) + " points.") ...
# -*- coding: utf-8 -*- """ Created on Mon Feb 11 22:39:36 2019 @author: shkim """ # Initializing parameters import numpy as np #%% def initialize_with_zeros(dim): """ This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0. Argument: dim -- size of the w vector w...
import datetime import mysql.connector as connector class Note: def __init__(self, title, desc, date_exp): self.title = title self.desc = desc self.date_exp = date_exp def print_note(self): print("Name: {}".format(self.title)) print("Description: {}".format(self.desc)...
""" STRING Y mas """ esto_es_string="HOLA como estas" esto_es_otro_string = "MUNDO" #concatenar print (esto_es_string+ '' + esto_es_otro_string) #hola mundo #MAYUS print(esto_es_string.upper()) #minus print(esto_es_string.lower()) #minus print(esto_es_string.capitalize()) #primera letra de cada palabra print(esto_e...
'''Created this function to convert a list of integers into a list of strings''' def numtostr_range(): startrange = int(input("Please enter START number of the range:")) endrange = int(input("Please enter END number of the range:")) steprange = int(input("Please enter STEP of the range:")) numrange = li...
# pandas 数据源下载地址:https://video.mugglecode.com/data_pd.zip,下载压缩包后解压即可 # -*- coding: utf-8 -*- """ 明确任务:比较咖啡厅菜单各饮品类型的产品数量,平均热量 """ import os import pandas as pd import matplotlib.pyplot as plt datafile_path = './data_pd/Beijing_PM.csv' # 结果保存路径 output_path = './output' if not os.path.exists(output_path): os.ma...
# 人工智能数据源下载地址:https://video.mugglecode.com/data_ai.zip,下载压缩包后解压即可(数据源与上节课相同) # -*- coding: utf-8 -*- """ 任务:房屋价格预测 """ import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import ai_utils DATA_FILE = './diabetes.csv' # 使用的特征列 FEAT_COLS = ['SE...
from singleton import Cars Ford = [] Ford = Cars("Ford","zielony",2002) print Ford.__repr__() Ford =("Ford","czarny",2001) print Ford.__repr__() Mercedes = Cars("Mercedes","czarny",2013) print Mercedes.__repr__() Mercedes.__set__("Mercedes","yellow",1999) print Mercedes.__repr__()
# Linear logistic regression classifier # # The task is to predict whether to admit a person to a university based on # their scores in 2 entrance exams using a linear decision boundary. We use # scipy's optimize library to determine the parameters that minimise the cost # function (rather than implementing our own gr...
from gensim.models.word2vec import * if __name__ == '__main__': file_name = raw_input("Enter model file name:") model = Word2Vec.load(file_name) try: w1 = raw_input("Enter word1 : ").lower() w2 = raw_input("Enter word2 : ").lower() print "Similarity : " print model.simi...
from game.dealer import Dealer class Director: def __init__(self): self.playerScore = 300 self.current_card = 0 self.next_card = 0 self.dealer = Dealer() self.keepPlaying = True def startGame(self): # Jeremy does this one while (self.keepPlaying):...
import pafy print("\t\t\t\t#### Welcome to the youtube Downloader ####") url = input("\t\t\t\tEnter the video link here: ") url.strip() print("\n\t\t\t\t*1: Download video without audio.") print("\t\t\t\t*2: Download audio without video.") print("\t\t\t\t*3: Download video + audio.") choice = int(input("\t\t\t...
''' MAZE RACE ''' import random ''' SETUP GLOBALS ''' size = 10 board = [[0 for x in xrange(size)] for y in xrange(size)] ''' INITIALIZE A PLAYABLE BOARD v1.1 ''' def init_board(size): for x in xrange(size): for y in xrange(size): board[x][y] = random.choice([0,0,0,1]) # RANDOM CHOICE FROM board[size-1][...
print("PAYMENT COMPUTATION FOR EMPLOYEES") print("----------------------------------") def pay(hour, rate): if hour>10: print ((hour*rate)+200) elif hour< 10: print (hour*rate) hour= int(input("Enter Hours:")) rate = int(input("Enter Rate:")) pay(hour,rate) print (f'Bayaran kamu adalah {pay}'...
print ("Selamat Datang di Kalkulator Bersama") tries=0 while tries != 3: Angkapertama = int(input("Silahkan ketik angka pertama:")) Angkakedua = int(input("Silahkan ketik angka kedua:")) print ("Mau diapain angkanya?") pilihan = input ("1(+) , 2(-), 3(*), 4(/):") if pilihan == "1": Hasil_...
from java.lang import Math class Shape: def perimeter(self): pass def area(self): pass class Triangle(Shape): def __init__(self, a, b , c): self.a = a self.b = b self.c = c def perimeter(self): return self.a + self.b + self.c def area(self): ...
""" Select a number randomly from a given list such that its probability is proportional to its magnitude. Example- a = [0, 5, 27, 6, 11] f(x) = probability of picking x f(27) > f(11) > f(6) > f(5) > f(0) """ """ Approach: 1. Sort the list in ascending order 2. If smallest element is 0 or negative, add offset to make i...
""" You are given a mxn matrix of zeroes and ones. The zeroes are land while the ones are water (river units). Any 'one' which is adjacent to another 'one' constitute one river. Calculate the length of the longest river. """ field = [ [0,2,1,0,0,1,0,0,0,0,0,0,0,2,0], [0,0,1,0,0,0,1,0,0,0,1,1,1,0,2], [0,3,2...
def rank(a, start, end): if(start != end): if(start < end): step = 1 counter = 1 else: step = -1 counter = end - start + 1 for i in range(start, end, step): a[i] = counter counter = counter + step # print('i:...
## Dayanara Benitez #September 26,2019 #Period 6 #Practice3.py week = input("What day of the week is it?") if week == "Monday": print ("Its Monday, the weekend is over") elif week == "Friday": print ("It's Friday, the weekend is close") elif week == "Saturday": print ("It's the weekend, time to relax"...
# Conditional print("Welcome to Ticket Box") print("You must be at least 18 to see and R rated movies") age = int(input("How old are you")) if age > 17: print("You can go see an R rated movie") else: print("You cannot go see an R rated movie") print("Thank you") mysteryNum = 6 guess = int(input("G...
import random num = random.randint(0, 100) print "The random number is: " + str(num) rand = 0 guess = 50 inc = 25 while guess != num : if guess > num: print "Try again computer your guess was " + str(guess) guess -= inc rand+=1 inc/=2 elif guess < num: print "Try again ...
"""" Implement an Dijkstra's algorithm for searching shortest path in the graph. Input: the number of vertices and the number of edges: two numbers in the first line. Next come the line with the description of the ribs. Their number is equal to the number of edges. Each line contains 3 numbers: the top of the outgoing...
"""" Write reducer, which implements the symmetric difference of the sets A and B (ie, leaves only those elements that are only in one of the sets). At the entrance to the reducer come pairs key / value, where key - element of the set, value - sets the marker (A or B) Sample Input: 1 A 2 A 2 B 3 B Sample Output: 1 3 ...
# coding: utf-8 __author__ = 'Alex Gerdom' import re BRACKET_PAIRS = ( ("paren", "(", ")"), ("brace", "[", "]"), ("curlybrace", "{", "}"), ) REQ_ESCAPE_TO_INC_NESTING_DEPTH = ( ("triple double quote", '"""', '"""'), ("triple single quote", "'''", "'''"), ("single quote", "'", "'"), ("doub...
class Laptop: count = 0 def __init__(self , id , name , kho, gia): self.id = id self.name = name self.kho = kho self.gia = gia Laptop.count += 1 #def set_id(self, id): # self.id = id def get_id(self): return self.id def set_Name(self, name): ...
class Node: def __init__(self,data): self.data=data self.next=None class CLL: #CLL---> Circular Linked List def __init__(self): self.last=None def add_data(self,data): temp=Node(data) if self.last==None: self.last=temp self....
array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8] for i in range(1,len(array)): for j in range(i, 0, -1): #인덱스 i부터 1까지 1씩 감소하며 반복하는 문법 if array[j] < array[j - 1]: # 작으면 한칸씩 왼쪽으로 이동 array[j], array[j - 1] = array[j-1] , array[j] #스와프 else: #자기보다 작은 데이터를 만나면 그 위치에서 멈춤 break pri...
#계수정렬 : 데이터의 크기가 한정되어 있는 경우에만 사용이 가능하지만 매우 빠르게 동작한다. #모든 원소의 값이 0보다 크거나 같다고 가정 array = [7,5,9,0,3,1,6,2,9,1,4,8,0,5,2] # 모든 범위를 포함하는 리스트 선언(모든값은 0으로 초기화) count = [0] * (max(array) + 1) #0부터 시작하기 때문에 for i in range(len(array)): count[array[i]] += 1 # 각 데이터에 해당하는 인덱스의 값 증가 for i in range(len(count)): # 리스트...
import math a=float(input()) b=float(input()) c=float(input()) print("canh dai nhat:",max(a,max(b,c))) print("chu vi:",a+b+c) x=(a+b+c)/2 print("dien tich:",math.sqrt(x*(x-a)*(x-b)*(x-c)))
#!/usr/bin/env python3 """Import wait_random from 0-basic_async_syntax. Write a function (do not create an async function, use the regular function syntax to do this) task_wait_random that takes an integer max_delay and returns a asyncio.Task. """ import asyncio def task_wait_random(max_delay: int) -> asyncio.Task: ...
#!/usr/bin/env python3 """Annotate the below function’s parameters and return values with the appropriate types def element_length(lst): return [(i, len(i)) for i in lst] """ from typing import Iterable, Sequence, List, Tuple def element_length(lst: Iterable[Sequence]) -> List[Tuple[Sequence, int]]: """Itera...
#!/usr/bin/env python3 """From the previous file, import wait_n into 2-measure_runtime.py. Create a measure_time function with integers n and max_delay as arguments that measures the total execution time for wait_n(n, max_delay), and returns total_time / n. Your function should return a float. Use the time module to ...
class TwoSum(object): def __init__(self): """ Initialize your data structure here. """ self.elements = [] def add(self, number): """ Add the number to an internal data structure.. :type number: int :rtype: void """ if number == Non...
import math class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x == None: return None if x < 0: sign = -1 x = -x else: sign = 1 reversed_digits = [] while x > 0:...
class recipeItems(object): #Recipe items class #Method to create Initial listof recipe items and Read What it contains def __init__(self,lst=None): self.lst = lst or [] #Method to add recipe item list def add_to_recipe_item_list(self,item): self.lst.append(item) return se...
""" 7. Дан список чисел. Если в нем есть два соседних элемента одного знака, выведите эти числа. Если соседних элементов одного знака нет — не выводите ничего. Если таких пар соседей несколько — выведите первую пару. """ def find_pairs(lst): for i in range(1, len(lst)): if lst[i - 1] * lst[i] > 0: ...
# 1.简述普通参数、指定参数、默认参数、可变长参数的区别 # 2.写函数,计算传入字符串中单个【数字】、【字母】、【空格] 以及 【其他】的个数 # def statistics(s): # num = 0 # sum1 = 0 # space = 0 # other = 0 # for n in s: # a = ord(n) # if 48 <= a <= 57: # num += 1 # elif (65 <= a <= 90) or (97 <= a <= 122): # sum1 +...
# 1. 输出10行内容,每行的内容都是“*****”。 # i=0 # while i<=10: # i+=1 # print("*"*10) # 2. 输出10行内容,每行的内容都不一样,第1行一个星号,第2行2个星号,依此类推第10行10个星号。 # for i in range(1,11): # print(i*"*") # 3. 输出9行内容,,第1行输出1,第2行输出12,第3行输出123,以此类推,第9行输出123456789。 # i=0 # sum=" " # while i<9: # i+=1 # sum=sum+str(i) # print(sum) # 4...
# 静态方法 (就是一个简单的函数 不关注函数内的对象)可以在类中被调用self.方法名() 或者 类名.方法名() # 在类外被调用 类名.方法名() class A: def __init__(self): pass def a(self): A.test() @staticmethod def test(): print("zhoujainaan") i = A() i.a() A.test() class A: number = 0 obj = None def __init__(self, value):...
def outer(func): def inner(): print("*"*30) func() return inner @outer def f(): print("这是一个函数;") f() def our_decorator(func): """ 进行管理员操作前进行判断 该用户是否拥有管理员权限 :param func:要进行装饰的函数 :return: """ dict1 = {"zhou": "952368", "feng": "123456"} def wrap(name, password...
#创建一个手机类,要求有型号、颜色、价格、运行内存4个属性,行为有打电话、玩游戏、看视频。 # 在打电话中输出:颜色为XX的XX手机可以打电话,价钱是XX。在玩游戏中输出:XX手机可以玩游戏, # 运行内存中共有XX,价钱是XX。看视频自由发挥。创建对象并调用函数执行。 class phone: def __init__(self,xinghao,color,price,yunxin): self.xinghao=xinghao self.color=color self.price=price self.yunxin=yunxin def daia...
""" 求1+2+3.......100的和 """ sum = 0 a = 1 while a <= 100: sum += a a += 1 print(sum) z=1 while z<=5: j=1 while j<=2*z-1: print(" ",end="") j+=1 i=1 while i<=11-2*z: print("*",end="") i+=1 z+=1 print(end="\n") z=1 while z<=5: j=1 while j<=11-2*z: ...
""" 循环结构 for循环 while循环 循环:重复的做某一件事情 占位符 : %d 整型 %f(%.2f 保留两位小数 保留一位回知道四舍五入) 小数 %s 字符串 break: 结束整个循环 continue:结束本次循环 进行下次循环 pass:空函数 在模块中不知道写什么的时候可以使用 让程序运行起来 循环条件:1,定义起始值 2,些循环条件 3, 初值递增(递减) 注意:在程序中0代表False 其他数字都代表True while.....else:在循环正常结束的时候执行else语句 非正常结束(break)就不会执行else语句 for循环 for 变量名称 in 列表 for回结合range()函数...
a = int(input('a=')) b = int(input('b=')) c = a a = b b = c print ('a='),a print ('b='),b
from replit import clear from art import logo #HINT: You can call clear() to clear the output in the console. print(logo) print("Welcome to the secret auction program.") repeat = True auction_bids = {} def find_highest_bidder(bidding_record): highest_bid = 0 #('name': number, 'name2': number2) for bidder in bi...
import matplotlib.animation as animation import matplotlib.pyplot as plt from math import exp, sin, pi import numpy as np # Solve heat equation # # T_t = kappa*laplace(T) # # in [0, 1]^2 with temperature prescribed # as a jump of width eps on each side. Magnitude of jump # is Ti/eps. # T3 # -----[ ]----...
#! /usr/bin/python3 # Program Name: PPC---Challenge-15.py # Author:Thomas Morrissey # Date Written: 9/30/2014 #Pratice Task: Password = "changeme" Attempt = input("Enter password: ") count = 1 while Attempt != Password: print("Denied") Attempt= input("Enter password: ") count += 1 if count >= 5: ...
x=int(input("enter 1 value")) y=int(input("enter 2 value")) z=int(input("enter 3 value")) print(x,y,z)
import time import csv def read_csv(): with open('datos.csv', mode='r') as csv_file: csv_reader = csv.reader(csv_file, delimiter = ',') return list(csv_reader) def ordenamiento_burbuja(lista): n = len(lista) for i in range(n): for j in range(0, n - i - 1): if list...
if __name__ == "__main__": vocals = ['a', 'e', 'i', 'o', 'u'] word = input('Write any word, it will be translated to Pig Latin: ') word = word.lower() if word[0] in vocals: word = word.capitalize() + 'way' print(word) else: word = (word[1:] + word[0] + 'ay').capitalize() ...
if __name__ == "__main__": print('Welcome, you will know how old were you last years and how old you are going to be next year.') name = input('Write your name: ') age = int(input('Write your age: ')) f_age = age + 1 p_age = age - 1 print(f'{name}, you were {p_age} years old last year and you ...
def do_n(func, n): """Executes the a function n times func function object n int>0 """ if n <= 0: return else: func() do_n(func, n - 1) def print_hello(): print('hello!') print(print_hello) print(type(print_hello)) do_n(print_hello, 6)
# Nuevamente pide a tu usuario que indique 3 números: un límite superior, un límite inferior y uno de comparación. # Si el número de comparación se encuentra entre los 2 primeros, comunicarlo en pantalla. # En caso estar por debajo del límite inferior o por arriba del límite superior, también mostrarlo en pantalla. ...
from math import pi, sqrt def circle_area(xc, yc, xp, yp): """Calculates the area of a circle given the center point of the circle and a point in the circle's perimeter xc int >= 0 yc int >= 0 xp int >= 0 yp int >= 0 returns area(distance(xc, yc, xp, yp)) """ distance_c_p = distan...
if __name__ == "__main__": print('Welcome, sum the first two numbers, then multiply the result by a third number.\ \n\n**The numbers will only have 4 decimals.') num_1 = round(float(input('\nWrite a number: ')), 4) num_2 = round(float(input('Write a second number: ')), 4) num_3 = round(float(inp...
import random def generate_dices(number_of_dices): dices = [] for _ in range(number_of_dices): dices.append([1, 2, 3, 4, 5, 6]) return dices def throw_dices(dices): throws = [] for dice in dices: throw = random.choice(dice) # print(throw) throws.append(throw) ...
def check_fermat(a, b, c, n): """ Checks if Fermat Last Theorem is right or wront and prints it for any positive integers given a int > 0 b int > 0 c int > 0 n int > 2 """ if a**n + b**n == c**n: print('Holy smokes, Fermat was wrong!') else: print('No, that doesn\'t w...
from math import sqrt number = int(input('Insert a number: ')) decimals = int(input('How many decimals do you need in the result?: ')) square_root = round(sqrt(number), decimals) print(f'The square root of {number} = {square_root}')
"""Keyboard Interrupt Error""" try: inp = input() print('Press Ctrl+C or Interrupt the Kernel: ') except KeyboardInterrupt: print('Caught KeyboardInterrupt') else: print('No exception occurred') """Zero Division Error""" try: a = 100 / 10 print(a) except ZeroDivisionError: print("Zero D...
# 2.Write a function that prompts students for how many credits they have. # Print whether or not they have enough credits for graduation (At UoW 360 credits are needed for graduation). def students_credit_checker(score): if (score >= 360 ): print("Congrats, you made it") else : print("Sorry y...