text
stringlengths
37
1.41M
# coding=utf-8 # TASKS:================================================================================================================ # Exploring Ensemble Methods # In this homework we will explore the use of boosting. For this assignment, we will use the pre-implemented gradient # boosted trees. You will: # - Use P...
def plus_multiples_of_3_and_5(limit): result = 0 i = 1 while i <= limit: if (i % 3) or (i % 5): result += i i += 1 return result print(plus_multiples_of_3_and_5(1000))
# while문의 기본 구조 # while <조건문>: # <수행할 문장1> # <수행할 문장2> # ... treeHit = 0 while treeHit < 10: treeHit = treeHit + 1 print("나무를 %d번 찍었습니다." % treeHit) if treeHit == 10: print("나무 넘어갑니다.") prompt = """ 1. Add 2. Del 3. List 4. Quit Enter number: """ number = 0 while True: print(pro...
def oddeven(x,y): if(y%2 == 0): even.append(x[y]) else: odd.append(x[y]) from tkinter import Tk,simpledialog,messagebox root = Tk() root.withdraw() messagebox.showinfo('Information','this is an encrypter and decrypter software for me and my friends') a=int(simpledialog.askstring('...
import random from faker import Faker fake = Faker() def generate_fake_names(n): names = set() while len(names) != n: name = fake.name().split(" ")[0].lower() if "." not in name: names.add(name) return list(names) def names_used(s): ret = set() for n1, n2 in s: ...
import random NOT_CONNECTED = 0 def empty_dogenet(n): return [[NOT_CONNECTED for i in range(n)] for j in range(n)] def random_coordinate(n): return random.randint(0, n-1), random.randint(0, n-1) def can_reach_all(net, start_row): seen = set() def visit(row): for doge, weight in enumerate(ro...
class Graph: def __init__(self): self._g = {} def connect(self, u, v): if u not in self._g: self._g[u] = set() self._g[u].add(v) def connect_bidirectional(self, u, v): self.connect(u, v) self.connect(v, u) def __getitem__(self, u): return se...
import sys from array import array """ The purpose of this program is to ensure that everyone who registered has participated Instructions: Simply write your name and then write your ID # """ names = [] numbers = [] names.append('Horatiu') numbers.append(0) num = "-1" name = "" #Clear the screen def clear(): print...
from collections import deque class Node: def __init__(self, k): self.key = k self.left = None self.right = None def printLevelOrderLine(root): if root == None: return q = deque() q.append(root) q.append(None) while len(q) > 1: curr = q....
class minHeap: def __init__(self, c): self.arr = [None for _ in range(c)] self.size = 0 self.capacity = c def left(self, i): return 2*i + 1 def right(self, i): return 2*i + 2 def parent(self, i): return int((i-1)/2) def decreaseKey(i, x): arr[i] = x # if parent is bigger swap while i != 0 and a...
class minHeap: def __init__(self, c): self.arr = [None for _ in range(c)] self.size = 0 self.capacity = c def left(self, i): return 2*i + 1 def right(self, i): return 2*i + 2 def parent(self, i): return int((i-1)/2) def insert(self, x): if self.size == self.capacity: # full return self.size +=...
import queue class Node: def __init__(self, k): self.key = k self.left = None self.right = None def printLeft(root): if root == None: return q = queue.Queue() q.put(root) while q.empty() == False: count = q.qsize() for i in range(...
class Node: def __init__(self, k): self.key = k self.left = None self.right = None # time: O(h) # aux space: O(h) def delNode(root, x): if root == None: return None if root.key > x: root.left = delNode(root.left, x) else if root.key < x: root.right = delNode(root.right, x)...
# -*- coding: utf-8 -*- # Author: BellaWu # Date: 2021/2/17 11:25 # File: zip_lambda_map.py # IDE: PyCharm # zip: 接受多个任意序列为参数,合并后返回一个tuple列表 a = [1,2,3] b = [4,5,6] ab = zip(a,b) print(list(ab)) for i, j in zip(a,b): print(i/2, j*2) # lambda:简单的函数,实现简化代码的功能 func = lambda x, y: x+y x = int(input('Please input a...
# -*- coding: utf-8 -*- # Author: bellawu # Date: 2021/2/21 11:51 # File: multiprocessing_pool.py # IDE: PyCharm # pool用来完成多进程,将要运行的东西直接放入进程池中。 import multiprocessing def job(x): return x*x def multi_process(): pool = multiprocessing.Pool(processes=3) res = pool.map(job, range(10)) print(res) ...
# -*- coding: utf-8 -*- x = 3 y = 2 z = 0 if x > y: print("x is greater than y.") else: print("x is less than y.") worked = False # 通过行内表达式完成类似三目操作符 result = 'done' if worked else 'not yet' print(result) if x > 1: print('x>1') elif x < 1: print('x<1') else: print('x=1')
def rotate(a, n, k): i = 0 for item in range(len(a)): if i < n: print(a[(i+n-k)%n], end = " ") else: print(a[i], end = " ") i += 1 #main function s = str(input()) s = s.split(' ') size = int(s[0]) i = 0 array = [] while i < size: array.append(int(s[i+1])) ...
from screen import screen #sub class of screen class class myScreen(screen): #constructor contains attributes (size of screen , type of screen and color of screen def __init__(self,sizeScreen,typeScreen,colorScreen): super(myScreen, self).__init__(sizeScreen,typeScreen,colorScreen) #abstract method ...
from states import * import time from levels import * def bfs(start): #Performs a breadth first search from the start state to the goal # Start Timer startTime = time.time() print("BFS start") # Vector with boards already seen, so there is no cicles seen = [] # Initial node ...
def new_Password(oldPassword, newPassword): return newPassword != oldPassword and len(newPassword) >= 6 oldPassword = input("Oude Password: ") newPassword = input("Nieuwe Password: ") x = new_Password(oldPassword, newPassword) print(x)
def BMI(gewicht, lengte): bmiWaarde = (gewicht * 703) / lengte**2 return bmiWaarde gewicht = int(input("Hoeveel weeg je? (pounds) ")) lengte = int(input("Hoe lang ben je? (inches) ")) print(round(BMI(gewicht, lengte), 2)) if BMI(gewicht, lengte) < 18.5: print('Underweight') elif BMI(gewicht, lengte) < 25...
import pandas as pd import numpy as np from pandas import DataFrame, Series def groupby1(): df = DataFrame({'key1':['a', 'a', 'b', 'b', 'a'], 'key2':['one', 'two', 'three', 'four', 'five'], 'data1': np.random.randn(5), 'data2': np.random.randn(5)}) pr...
''' http://en.wikipedia.org/wiki/Hypotrochoid ''' import numpy as np import pylab as pl def hypotorochoids(R=5, r=3, d=5): t = np.linspace(-4*np.pi, 4*np.pi, 300) x = (R-r) * np.cos(t) + d * np.cos((R-r)*t / r) y = (R-r) * np.sin(t) - d * np.sin((R-r)*t / r) return x, y def draw(): x, y = hypotoro...
def findprimes(b): A=[] for i in range(0,b+1): A.append(i) for j in range(2,(b//2)+1): n=2 if A[j]==0: pass else: while n <= b/j: A[j*n]=0 n=n+1 k=0 L=len(A) while k<L: if A[k]==0: del ...
import pandas as pd import json def cleanList(): #Open file f = open("city.list.json", encoding="utf8") content = f.read() f.close() #Load to dataframe df = pd.read_json(content) #Set all city name (keys) to lower case df["name"] = df["name"].str.lower() df["c"] = df["country"]....
def is_prime(_number): for x in range(2, _number): if _number % x == 0: return False return True def next_prime(prime): next = prime + 1 while not is_prime(next): next += 1 return next if __name__ == '__main__': count = 1 prime_number = 1 while count < 10...
choose = input() if choose == 'paper': print("Sorry, but the computer chose scissors") if choose == 'scissors': print("Sorry, but the computer chose rock") if choose == 'rock': print("Sorry, but the computer chose paper")
#Funcion de potenciacion en python def potenciacion(numero,expn): if expn==0: print 1 potencia=numero for i in range(expn-1): potencia=potencia*numero print potencia potenciacion(4.6,1.2) def suma(self): decimal.Decimal('0.1')+decimal.Decimal('0.2') return suma('0.3') def Division(numero): return...
from random import randint number =randint(1,9) if number %2==0: raise NameError("%d is even "% number) else: raise NameError("%d is odd"%number)
sum = 0 for i in range(10): sum += float(input("number " + str(i+1) + ": ")) print(sum/10)
# -- coding:utf-8 -- # filter是筛选器,参数有两个,第一个是函数,第二个是列表,作用是将列表中每个元素执行函数,根据返回值时True or False决定是否保留,删除返回true的值 # 本程序实现删除1-100中的素数 def is_su(m): fin = False if(m==1): fin = True else: for i in range(2,m): if(m%i==0): fin = True return fin l = range(1,101) print l print filter(is_su, l)
# --coding:utf-8-- # --test git push-- i = 0 number = [] while i < 6: print "At the top i is %d" % i number.append(i) i = i + 1 print "Number now: " , number print "At the bottom i is %d" % i print "The number:" for num in number: print num
def main(x): for i in range(x): print(fibonacciLoop(i)) def fibonacciLoop(number): fib1,fib2,result = 1,1,1 if(number == 1 or number == 2): return 1 for i in range(3, number, 1): result = fib1 + fib2 fib1 = fib2 fib2 = result return result main(15)...
# A palindrome is a series of characters that read the same forwards as backwards such as "hannah", "racecar" and "lol". # For this Kata you need to write a function that takes a string of characters and returns the length, # as an integer value, of longest alphanumeric palindrome that could be made by combining the c...
# coding: utf-8 """ Project Euler problem #50. """ import itertools as it def problem(): u""" Solve the problem. The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred...
""" Project Euler problem #22. """ import os.path as op def problem(): """ Solve the problem. Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alp...
""" Project Euler problem #18. """ def problem(): """ Solve the problem. Find the maximum total from top to bottom of the triangle below. Answer: 1074 """ triangle = """ 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 ...
""" Project Euler problem #17. """ def problem(): """ Solve the problem. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?. Answer: 21124 """ cnv = { 0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'fiv...
# coding: utf-8 """ Project Euler problem #X. """ import itertools as it def problem(): u""" Solve the problem. The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility proper...
""" Project Euler problem #10. """ import math as mt def problem(): """ Solve the problem. The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. Answer: 142913828922 """ return sum(prime_numbers(2000000)) def prime_numbers(_max): """ ...
import unittest from main import LinkedList, Solution class SumTwoNumbersTestCase(unittest.TestCase): @staticmethod def setup_test_case_one(): list_one = LinkedList() list_one.push(3) list_one.push(4) list_one.push(2) list_two = LinkedList() list_two.push(4)...
departure = ["Auckland", "Wellington", "Christchurch"] destinations = ["Sydney", "Tonga", "Shanghai", "London"] print ("welcome to my travel system") print ("please enter your departure location") print ("Auckland") print ("Wellington") print ("Christchurch") departure_location=input ("") if departure_location=="Auckl...
#!/usr/bin/env python3 import sys #couldnt find a use case , too lazy to delete #representation of a tic-tac-toe board theboard={ 'top-l':"",'top-mid':"",'top-r':"", 'mid-l':'','mid-mid':'','mid-r':'', 'dwn-l':'','dwn-mid':'','dwn-r':'' } def printboard(board): ''' function to print the state of...
def fibonacci(n): a = 0 b = 1 if n < 0: print("Incorrect input") elif n == 0: return a elif n == 1: return b else: for i in range(2,n): c = a + b a = b b = c return b def fizzbuzz(): for...
import sys arg1 = sys.argv[1] def myfunc(arg1): """return first char that is not repeated in the string ignore case when counting but return original char. if all repeating, return empty string. """ check = "" for char in arg1: if arg1.lower().count(char.lower()) == 1: check = char break ...
import sys class Sphere: Pi = 3.14 def __init__(self, radius): self.radius = radius # self.PI = 3.14 def get_surface_area(self): return 4*self.Pi*self.radius**2 def get_volume(self): return 4/3*self.Pi*self.radius**3 def set_radius(self, x): self.radius = x n=Sphere(int(sys.argv[1...
# class TicTacToe(): """ This is the well-known game of Tic-Tac-Toe. Players X and Y take turns choosing a square on the board until one player scores three in a row. """ def gameBoard(currentlst): # A new game will start with blank inputs. Every time a user input is added to currentlst, this function will be r...
import copy def compute(myinput): i = 0 operation = myinput[i] while i < len(myinput) and operation != 99: val1, val2, pos = myinput[myinput[i+1]], myinput[myinput[i+2]], myinput[i+3] if operation == 1: myinput[pos] = val1 + val2 elif operation == 2: myinput[...
# -*- coding: utf-8 -*- """ Created on Mon Dec 25 18:04:36 2017 @author: User """ class LinkedStack: class Node: def __init__(self): self.item = None self.next = None def __init__(self): self.first = None def isEmpty(self): return self.first == Non...
import sys number = int(input("\nEnter the number of Primes to compute: ")) if number == 1: print("The first prime is 2") sys.exit(0) m = 3 PrimeList = [2] def isPrime(m, L): for L in PrimeList: if m < L**2: PrimeList.append(m) return m if m%L == 0: re...
import calendar print(calendar.weekheader(3)) print() print(calendar.firstweekday()) print() print(calendar.month(2021, 8)) print() print(calendar.calendar(2021)) day_of_the_week_=calendar.weekday(2021, 9, 9) print(day_of_the_week_) is_leap=calendar.isleap(2021) print(is_leap) how_many_leap_days= calendar.leapd...
from Deck import Deck from Hand import Hand import time class Blackjack: def __init__(self): self.deck = Deck() self.deck.shuffle() self.balance = 0 self.start() def start(self): while True: self.balance = input("How much would you like to deposit?: ") ...
def main(): q=nr() for i in range(0,q): if q-i-1>0: for j in range(0,q-i-1): print(" ",end="") j+=1 for j in range(j,q): print("#",end="") print() else: for j in range(q): print('#',end='...
import csv import math import numpy as np import pandas as pd with open('data.csv', newline = '') as f: reader = csv.reader(f) filedata = list(reader) data = filedata[0] def mean(data): n = len(data) total = 0 for x in data: total += int(x) mean = total / n return mea...
# Prakriti Kharel import random #final array that stores the mancala board with the correct values #at the beginning, all the holes have rocks # of stones in them rocks = 4 al = [0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks] first = [0,...
######################################################### # Exercice 4 : #Votre fenêtre graphique doit contenir un canevas de couleur de fond blanche et de taille 500x500 ainsi qu’un bouton avec le texte “Pause” placé en dessous du canevas. #Afficher un carré rempli de rouge de côté 50 au milieu du canevas. #Si l’uti...
# Create a two integer variables a and b a=3 b=4 # if a is greater than b print a-b else a+b if a > b: print (a-b) else: print (a+b) # Create a list of squared numbers squares_list = [0, 1, 4, 9, 16, 25] # Store the length of squares_list in square_len square_len = len(squares_list) # if square_len is less ...
price_of_trip = float(input()) puzzles = float(input()) talking_doll = float(input()) bears = float(input()) minions = float(input()) truck = float(input()) puzzle_price = 2.6 talking_doll_price = 3 bear_price = 4.1 minions_price = 8.2 truck_price = 2 first_price = puzzles*puzzle_price+talking_doll*talking_doll_price...
name = input() count = 1 grade = 0.0 while count <= 12: curr = float(input()) if curr >= 4: grade = grade + curr count += 1 average = grade / 12 if average >= 4: print(f'{name} graduated. Average grade: {average:.2f}')
budget = float(input()) begin = budget balloons_count = 0 ribbon_size = 0 flowers_count = 0 candles_count = 0 while True: if budget<=0: break stock = input() if stock == 'stop': break count_stock = float(input()) if stock == 'balloons': balloons_count+=count_stock ...
temperature = int(input()) time = input().lower() if 10<=temperature<=18: if time == "morning": print(f'It\'s {temperature} degrees, get your Sweatshirt and Sneakers.') elif time == 'afternoon': print(f'It\'s {temperature} degrees, get your Shirt and Moccasins.') elif time == 'evening': ...
l = float(input()) w = float(input()) h = float(input()) percent = float(input())/100 volume= l*w*h*0.001 volume = (volume-volume*percent) print(f'{volume:.3f}')
num1 = float(input()) num2 = float(input()) num3 = float(input()) if num1==num2 and num2==num3: print('yes') else: print('no')
value_type = input() val1 = input() val2 = input() def compare_values(a, b): if a > b: printable(a) else: printable(b) def printable(greater_value): print(greater_value) compare_values(val1, val2)
sentence, sub = input().lower(), input().lower() occurrences = 0 index = 0 while index!=-1: index = sentence.find(sub, index) if index is not -1: occurrences+=1 index+=1 print(occurrences)
money_for_vacation = float(input()) curr_money = float(input()) days = 0 all_days = 0 while True: action = input() transfer_money = float(input()) all_days += 1 if action == 'spend': days += 1 if days == 5: print(f'You can\'t save the money.') print(days) ...
import math hour_exam = int(input()) minute_exam = int(input()) hour_arrive = int(input()) minute_arrive = int(input()) all_minute_exam = hour_exam * 60 + minute_exam all_minute_arrive = hour_arrive * 60 + minute_arrive if all_minute_arrive <= all_minute_exam: if all_minute_exam - all_minute_arrive <= 30: ...
name = input() age = int(input()) town = input() salary = float(input()) print(f'Name: {name}') print(f'Age: {age}') print(f'Town: {town}') print(f'Salary: ${salary:.2f}') if age<18: print(f'Age range: teen') elif age<70: print(f'Age range: adult') else: print(f'Age range: elder') if salary<500: prin...
import math all_Steps = float(input()) dancers = float(input()) days_For_Learning = float(input()) steps_per_day = math.ceil(((all_Steps/days_For_Learning)/all_Steps)*100) steps_per_dancer = steps_per_day/dancers if steps_per_day<=13: print(f'Yes, they will succeed in that goal! {steps_per_dancer:.2f}%.') else: ...
number = int(input()) bonus = 0 if number<=100: bonus = 5 elif number >100 and number<=1000: bonus=number*0.2 else: bonus = number*0.1 if number%2 == 0: bonus = bonus+1 elif number%10 == 5: bonus=bonus+2 print(bonus) print(number+bonus)
town = input().lower() sell_count = float(input()) if 0<=sell_count<=500: if town == "sofia": comission = sell_count*0.05 print(f'{comission:.2f}') elif town=="varna": comission = sell_count * 0.045 print(f'{comission:.2f}') elif town == "plovdiv": comission = sell_c...
def is_inside(first_rectangle, second_rectangle): if first_rectangle.top <= second_rectangle.top and first_rectangle.bottom >= second_rectangle.bottom and \ first_rectangle.left >= second_rectangle.left and \ first_rectangle.right <= second_rectangle.right: print("Inside") else: ...
passengers_start = int(input()) stops = int(input()) curr_stop = 0 while True: if stops == curr_stop: break curr_stop += 1 passengers_off = int(input()) passengers_in = int(input()) if curr_stop % 2 != 0: passengers_start = passengers_start - passengers_off + passengers_in + 2 ...
from _ctypes import Array num = float(input()) a = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] if num == 1: print(a[int(num) - 1]) elif num == 2: print(a[int(num) - 1]) elif num == 3: print(a[int(num) - 1]) elif num == 4: print(a[int(num) - 1]) elif num == 5: pri...
num_list = list(map(float, input().split())) dict = {} for x in num_list: if x in dict: dict[x] += 1 else: dict[x] = 1 # sorted(dict) for key in sorted(dict): print('%s -> %s times' % (key, dict[key]))
class Str_List_Converter: def __init__(self):pass def get_remove_list(self,remove_word,string): words = string.split() try: words.remove(remove_word) except ValueError as e: print(e) return words def get_all_words_starting_from(self,starting_word,string): words = string.split() word...
def isPrime(n): if n<=1: return False elif n ==2 : return True else: for i in range(2,int(n**.5)+2): if(n%i==0): return False return True # print(isPrime(4)) for i in range(100): print(str(i)+" -> "+str(isPrime(i)))
class Node(object): def __init__(self, val=None, children=None): self.val = val self.children = children class Solution(object): def levelOrder(self, root): if not root: return [] import collections queue = collections.deque() res = [] queue.append(root) ...
# 301 # TLE class Solution: def removeInvalidParentheses(self, s): if not s: return [''] l, r = self.invalid_count(s) res = [] self.dfs(s, l, r, res) return res # """ smart way to count unbalanced open and closing paren """ def invalid_count(self, s): ...
# memo def longest_increasing_subsequence(nums): def dfs(nums, start, cur, dic): if start == len(nums): return 0 if nums[start] in dic and dic[nums[start]] > 0: return dic[nums[start]] mx = float('-inf') for i in range(start, len(nums)): ...
""" three templates """ # 1 # [l, r] def binary_search_i(nums, target): if not nums: return -1 left, right = 0, len(nums)-1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 els...
#Exercise 2 - Part 3 #Tapio Koskinen asking = True while asking: try: number_of_exercises = int(input("How many exercises did you do: ")) break except ValueError: continue grade_book = {9:1,10:2,11:3,12:4,13:5} if number_of_exercises < 9: print("You did not pass the course") elif number_of...
RED = "\033[31m" BLUE = "\033[34m" DEFAULT = "\033[0m" class Board: def __init__(self,rows,cols): self.col_num = cols self.row_num = rows self.board = [[0]*cols for row in range(rows)] def __getitem__(self,A): if isinstance(A,tuple): return self.board[A[0]][A[1]] ...
#I have the numbers saved in a .txt file. #I will read them in as strings, take the first 13 digits, #turn those into ints, and sum them. #Finally, I will read the first 10 digits of the result #by turning to a string to shorten nums = [] with open('p013_numbers.txt') as f: for line in f: nums.append([v fo...
import math PropDivSum = 0 #This method compiles a list of proper divisors, sums them, then returns the sum def PropDiv (n): divisors = [1] #by starting with 1, the list doesn't add n to it for i in range(2,math.floor(math.sqrt(n))+1): #check divison of numbers 2 thru sqrt(n) if n%i == 0: di...
#I am going to build an array of increasing factorials #Memoization is faster here than re-calculating each multiple up to 100 factorials = [1] summation = 0 for i in range(2,100): factorials.append(i*factorials[i-2]) for digits in str(factorials[len(factorials)-1]): summation += int(digits) print(summation)
import numpy as np from numpy import random import matplotlib.pyplot as plt from math import sqrt ##################################################### # 1. compute distance between every two cities # random example n = 20 # number of city city = random.randint(0, 1000, (n, 2)) # x,y, random generate n cities # tr...
# Import modules for creating file paths across operating systems and reading CSV files import os import csv # Map the path where the input csv file is located csvpath = os.path.join("Resources","budget_data.csv"); # Open the csv file with open(csvpath) as csvfile: # Specify the delimiter for the budget_data.csv...
from collections import Counter import csv import datetime months = { "January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12 } tau = 30 fileName ...
# -*- coding: utf-8 -*- import re import string def remove_punctuation(text): return re.sub(ur"\p{P}+", "", text) def remove_punctuation(to_translate, translate_to=u''): not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~' translate_table = dict((ord(char), translate_to) for char in not_letters_or_...
# ------------------------->Tuples<------------------------------ veg = ("onion", "potato", "tomato", "pepper", "carrot") Fruits = ("orange", "banana", "apples", "grapes") print(veg) print(type(veg)) print(len(veg)) print(veg[1]) print(veg[-2]) print(veg[2:4]) b = list(veg) b[2:4] = "pea", "cabbage" veg = tu...
def gcd(a,b): if a<b: a,b=b,a if b==0: return a return gcd(b,a%b) def plus(a,b): c=a[0]*b[1]+b[0]*a[1] d=a[1]*b[1] return [c/gcd(c,d),d/gcd(c,d)] n=100 def dfs(x): if x==n:return [1,0] if x==0: return plus([2,1],dfs(x+1)[::-1]) if x%3!=2: return plus([1,1],dfs(x+1)[...
import time import datetime t = time.time() print (t) #原始时间数据 print (int(t)) #秒级时间戳 print (int(round(t * 1000))) #毫秒级时间戳 nowTime = lambda:int(round(t * 1000)) print (nowTime()); #毫秒级时间戳,基于lambda print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) #日...
Nba_Players = {"Jordan Bell", 7, "Stephen Curry", 30, "Kevon Looney", 5, "Nico Mannion", 2, "Mycal", 15} def largestJerseyNumber(NBA_Players) : largestJerseyNumber = 0 print (Nba_Players ["Stephen Curry"]) print (largestJerseyNumber) # read in 1st Jersey Number, #compare to 2nd jersey Number ...
# findAll - return a list when there is zero or ONE groups # findAll - returns a list of tuples when there is two or more groups # [] - Custom character class # Use {} to specify occurrence in a patterns - {2} -> two vowels 'ao'in a row # ------------------------------ # Caret has two behaviours : when within character...
''' # Inheritance allows us to define a class that inherits all the methods and properties from another class. # Parent class is the class being inherited from, also called base class. # Child class is the class that inherits from another class, also called derived class. ''' class User(): def sign_in(self)...
''' # What is Polymorphism : The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types. ''' class User(): def sign_in(self): print('Logged In.') def attack(self): print('Do noth...
''' # Encapsulation in Python - The process of wrapping up variables and methods into a single entity is known as Encapsulation. It is one of the underlying concepts in object-oriented programming (OOP). It acts as a protective shield that puts restrictions on accessing variables and methods directly, and ca...
#Escreva um programa que leia uma string e imprima quantas vezes cada caractere aparece nessa string string = input('Digite uma string: ') count = {} for i in string: count[i] = count.get(i,0) + 1 for chave, valor in count.items(): print(f'{chave}: {valor}x') print()
#Write a function called is_abecedarian that returns True #if the letters in a word appear in alphabetical order (double letters are ok). #How many abecedarian words are there? def is_abecedarian(word): index = 0 while index < len(word) -1: if word[index] > word[index+1]: return Fal...