text
stringlengths
37
1.41M
def quick_sort(a,b,e): if b < e: q = do_partition(a,b,e) quick_sort(a,b,q) quick_sort(a,q+1,e) def do_partition(a,b,e): # efficient when all values are equal # more efficient than Lomuto’s partition scheme # because it does three times fewer swaps on average # find a p...
from math import sqrt def distanciaDisparo(x, y): distancia = round(sqrt(x**2 + y**2)) return distancia def mejorDisparo(dis1, dis2, dis3): mejor = dis1 if dis2 < mejor: mejor = dis2 if dis3 < mejor: mejor = dis3 return mejor def promedioDisparo(disparo1, disparo2, disparo3): ...
#!/bin/python from dateutil import parser import datetime DEBUG=True class battery: def __init__(self,name,capacity,charge_power,output_power): """ Arguments name - String capacity - Usable storage in Wh charge_power - maximum power draw to charge in Wh output_power - maxi...
from collections import OrderedDict class LRUCache(OrderedDict): def __init__(self, capacity): self.capacity = capacity def get(self, key): if key not in self: return - 1 # move_to_end(key, last=True) moved to the right, if last is true (default) or to the start if last i...
from typing import List """ x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y. bin() Return the binary representation of an integer. >>> bin(2796202) '0b1010101010101010101010' x | y Does a "bitwise or". Ea...
def check_pwd(password): countUpper = 0 countLower = 0 countDigit = 0 countSymbol = 0 symbols = '~`!@#$%^&*()_+-=' if len(password) < 8 or len(password) > 20: return False for i in password: if i.isupper(): countUpper += 1 if countUpper == 0: return F...
import random def test_print(): print("hello") def test_get_array(): A = [] for i in range(100): A.append(int(random.random()*100)) return A def test_get_sorted_array(): A = [] for i in range(100): A.append(int(random.random()*100)) return insertion_sort2(A) def test_get_sorted_array_unique(): A = [] f...
''' 45 - Jokenpô criar lista com Pedra, Papel e Tesoura para randomizar a escolha do computador ''' import random lista = ['Pedra', 'Papel', 'Tesoura'] print(' [1] Pedra \n [2] Papel \n [3] Tesoura') escolha = random.choice(lista) jogador = int(input('Escolha sua arma: ')) if jogador == 1 and escolha == 'P...
''' 36- Programa aprova empréstimo para compra de casa Pergunta: 1 - valor da casa 2 - salário 3 - quantos anos vai pagar Calcular valor da prestação mensal sabendo que não pode exceder 30% do salário ou então o empréstimo será negado dica: Pega o valor da casa, divide o valor dos anos que ele colocou e verifica o val...
# Desafio 9: Programa que le um número inteiro e mostre na tela a tabuada # Desafio 10: programa que le quanto dinheiro a pessoa tem e mostra quantos dolares ela pode comprar. 1 dolar igual a 3,27 n = int(input('Número: ')) print(f'TABUADA \n {n} x 1 = {n*1} \n {n} x 2 = {n*2} \n {n} x 3 {n*3} \n {n} x 4 {n*4} \n {...
''' 59) programa que pede dois valores e mostra um menu na tela: [1] somar 2 multiplicar 3 maior 4 novos números 5 sair do programa ''' n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) menu = 0 while menu != 5: menu = int(input( ''' O que deseja fazer? [1] SOMAR [2] MULT...
# 54 - pergunta ano de nascimento de 7 pessoas (logo 7x) e mostra quantas ainda não atingiram a maioridade e quantas ja sao maiores from datetime import date ano = date.today().year s = 0 u = 0 for c in range(1, 8): nasc = int(input(f'Qual o ano de nascimento da {c}º pessoa? ')) idade = ano - nasc if idade...
n1 = int(input('Um valor: ')) n2 = int(input('Outro valor: ')) di = n1 / n2 print(f'A soma \n vale {n1+n2}! ', end='') print(f'Já a divisão vale {di:.3f}') # dica só é bom colocar a soma em variável quando você sabe que precisará usar a soma depois # da para colocar espaçamentos: < > seta pra cima deixa centralizado ...
#encoding: UTF-8 # Autor: Adrián E. Téllez López # Sacar el porcentaje de hombres y mujeres en una clase # A partir de aqui escribe tu programa hombres = int(input("Cuantos hombres hay inscritos en la clase")) mujeres = int(input("Cuantas mujeres hay inscritos en la clase")) total = hombres + mujeres Porcentajeh = (...
class Version: def __init__(self, major:int, minor:int, bug:int): """Object for version recording. Uses the major.minor.bug notation. Parameters ---------- major: int The major number for the version number. minor: int The minor number for th...
import src.utils as utils from src.cols import Cols from src.row import Row class Data: """Data class processes takes the file to be processed as input , opens it and performs respective operations line by line. If it the line happens to have Column information then it is handled by cols class and ...
from sorting.test_sorting_algos import TestSorting def shell_sort(arr): gap = len(arr) // 2 while gap: for i in range(gap): gap_insertion_sort(arr, i, gap) gap = gap // 2 return arr def gap_insertion_sort(arr, index, gap): for i in range(index + gap, len(arr), gap): position = i while position >= ga...
class BinaryHeap: def __init__(self): self.heap_list = [0] self.currentsize = 0 def insert(self, object): self.heap_list.append(object) self.currentsize += 1 self.percolation(self.currentsize) def delete_min(self): if self.currentsize < 1: retur...
from Node import Node def nth_to_last_node(n, head): last_node = head for i in range(n-1): if not last_node.nextnode: raise LookupError("Error: n is larger then the linked list") last_node = last_node.nextnode n_minus_last_node = head while last_node.nextnode: last_n...
#! /usr/bin/python class Player_Game(): def __init__(self, player1, player2,board_class): self.myboard=board_class self.player1=player1 self.player2=player2 self.turn=0 #White=0 def new_game(self): self.myboard.layout_pieces(self) color=['White'...
# Booleans and If Statements # Question 1 # moths_in_house = True # moths_in_house = False # print(moths_in_house) # print(not moths_in_house) # moths_in_house = True # moths_in_house = False # # print(moths_in_house or not moths_in_house) # if moths_in_house: # print("Get the moths!") # else not moths_in_h...
#The program finds the standard deviation of a list of numbers given by the user, without using the 2 smallest and the 2 largest numbers given by the user. #It is made in a way to provide a quite foolproof and interactive user experience. #Variable initialization. nums=[] #Creates a list that the numbers given by th...
import turtle screen = turtle.Screen() t = turtle.Turtle() t.color("red") t.shape("turtle") t.pensize(2) turtle.bgcolor("grey") t2 = turtle.Turtle() t.color("green") t.shape("arrow") t.pensize(3) t3 = turtle.Turtle() t.color("blue") t.shape("turtle") t.pensize(3) def square2(): for i in range(4): t.forward(...
def fact(n): if(n<=1):return 1; return n * fact(n-1) d={} for i in range(0,10): d[str(i)]=fact(i) n = (input("enter a number:")) sum=0 for i in range(len(n)): sum=sum+d[n[i]] if(sum==int(n)): print("strong number") else: print("not strong number") #Copyright @Amol Paliwal
def inner(a,b,c):return a+b+c def outer(a,b,c):return inner(a,b,c)+5 print(outer(2,3,4)) #Copyright @Amol Paliwal
def area(l,b):return l*b def call(l,b): return area(l,b) + area(l+1,b-1) + area(l,b+1) print(call(2,2)) #Copyright @Amol Paliwal
print('Snap') print('Crackle') print("'Nay,' said the nyasayer.") print('The rare double quote in captivity; ".') print('A two by four" is actually 1 1/2" x 3 1/2".') print("'There's the man that shot my paw!' cried the limping hound.") print('''Boom!''') print("""Eek!""") poem = '''There was a Young Lady of Norway,...
todos = 'get gloves,get mask,give cat vitamins, call ambulance' print(todos.split(',')) print(todos.split()) print() poem = '''All that doth flow we cannot liquid name Or else would fire and water be the same; But that is liquid whitch is moist and wet Fire that property can never get. Then 'tis no cold that doth the ...
from collections import defaultdict food_counter = defaultdict(int) for food in ['spam', 'spam', 'eggs', 'spam']: food_counter[food] += 1 for food, count in food_counter.items(): print(food, count)
#START = 'cqjxjnds' START = 'cqjxxyzz' ALPHABET = 'abcdefghjkmnpqrstuvwxyz' def increment(string): r = [] for i,c in enumerate(string[::-1]): if c != ALPHABET[-1]: r.append(ALPHABET[ALPHABET.index(c)+1]) r.append(string[:len(string)-i-1]) break else: ...
__author__ = 'Erick' class Background: """ Class Background is the container for all elements in the background of the game. This class utilizes two lists, one for stars, and one for trees. Each list is then traversed through by the function move_bg in order to create the illusion of movement. """...
#!/usr/bin/env python3.8 message = input("Enter a message: ") count = input("Enter a number of times to repeat the message: ") if count: count = int(count) else: count = 1 def repeat_message(message, count): while count > 0: print(message) count -= 1 repeat_message(message, count)
name='' while name!='your name': print('your name is wrong please enter right name below') name=input() print('thank you')
import random def getAnswer(answer): if answer==1: return 'it is certain' elif answer==2: return 'it is decidedly so' elif answer==3: return 'yes' r=random.randint(1,3) fortune=getAnswer(r) print(fortune)
while True: print('enter your name') name=input() if name!='cool': continue print('enter the password') password=input() if password=='badboy': print('access granted') break
import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1, 1, 100) y0 = x + 1 y1 = x ** 2 plt.figure() plt.plot(x, y0) plt.plot(x, y1) # 修改坐标轴长度 plt.xlim((-1, 6)) # x坐标轴长度(-1,1) plt.ylim((-1, 2)) # y坐标轴长度(-1,2) # 修改刻度 # 如果x坐标轴,刻度为:-1, -0.6, -0.2, 0.2, 0.6, 1, # 可用这个方法 new_ticks = np.linspace(-1, 1, 6) p...
import numpy as np if __name__ == '__main__': i = 0 while(i<6): if(i<3): np.random.seed(0) # 执行生成随机数前,都令random seed为0,可看到生成的3个随机数全部相同 print('result',np.random.randn(1, 5)) else: print('result0',np.random.randn(1, 5)) pass i += ...
# sorting an array/list of numbers/int by Insertion sort method num=list(map(int,input("\n Enter numbers :").split())) l=len(num) for i in range(1,l): key=num[i] j=i-1 while j>=0 and num[j]>key: num[j+1]=num[j] j-=1 num[j+1]=key print(num)
from random import random, randint, choice import time import sys slow_time = False def time_01(): if show_time: time.sleep(0.1) def time_025(): if show_time: time.sleep(0.25) def time_050(): if show_time: time.sleep(0.50) def time_1(): if show_time: time.sleep(1) # ch...
import ciphers from ciphers import caesar_cipher def main(): cypher = caesar_cipher.Caesar() message = "... hello this is a TEST with punctuation; : and with capitals!?#$" cypher.print_translations(message) if __name__=="__main__": main()
#Great Circle import math x1 = float(raw_input("Enter latitude (in degrees) of first point: ")) y1 = float(raw_input("Enter longitude (in degrees) of first point: ")) x2 = float(raw_input("Enter latitude (in degrees) of second point: ")) y2 = float(raw_input("Enter longitude (in degrees) of second point: ")) x1 = math...
##take 3 positive integers and check whether they are lengths of triangle len1 = int(raw_input("Enter first number: ")) len2 = int(raw_input("Enter second number: ")) len3 = int(raw_input("Enter third number: ")) if ((len1 == len2 + len3) or (len2 == len1 + len3) or (len3 == len1 + len2)): print "True" else: p...
#take three input names and print out on console person1 = raw_input("Enter first name: ") person2 = raw_input("Enter first name: ") person3 = raw_input("Enter first name: ") print "Hi " + person1 + ", " + person2 + ", " + person3 + "."
#Day of week #get 3 inputs from commandline then write the day of week on which that date falls m = int(raw_input("Enter month: ")) d = int(raw_input("Enter day: ")) y = int(raw_input("Enter year: ")) y0 = y - (14 - m)/12 x = y0 + y0/4 -y0/100 + y0/400 m0 = m + 12*((14-m)/12)-2 d0 = (d+x+(31*m0)/12) % 7 if (d0 == 0)...
#compute the euclidean distance of two vectors import math def Euclidean(a,b): if len(a) == len(b): s = 0.0 for i in range(0,len(a)): s += (a[i] - b[i])**2 return math.sqrt(s) else: print "Error. Two Vector are not alligned" a = [1,2,3] b = [2,3,4] print Euclide...
# Accept integers n and trialCount as command-line arguments. Do # trialCount random self-avoiding walks in an n-by-n lattice. # Write to standard output the percentage of dead ends encountered. import random n = int(raw_input("Enter the size of matrix: ")) trials = int(raw_input("Enter the number of trials: ")) ...
import random import datetime import csv import math class Reactor: """ The reactor object creates a simulation of a bioreactor and records the data into a csv file similar to how an Eppendorf Dasgip would record the data. Process Set Points Temperature - 32.0 °C pH - 7.20 Air...
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: OBSTACLE = "*" ROCK = "#" EMPTY = "." ## This is matrix transpose, not 90-degree clockwise rotation. #def rotate(array2D): # m, n = len(array2D), len(array2D[0]) # res = [["...
qualified = {1, 3, 4, 9} class Solution: def checkPowersOfThree(self, n: int) -> bool: if n in qualified: return True remainder = n % 3 if remainder == 2: return False #elif remainder == 1: # reduced = (n-1) // 3 # if checkPowersOfThree(r...
#class Solution: # def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: def getMaximumXor(nums, maximumBit): n = len(nums) answer = [0 for _ in range(n)] # N.B. Nobody says maximumBit > 0 if maximumBit <= 0: return answer # From now on, we are assured maximumB...
class Solution: def sortSentence(self, s: str) -> str: D = {} for word_i in s.split(): i = int(word_i[-1]) word = word_i[:-1] D[i-1] = word sentence = "" for i in range(len(D)): sentence += f"{D[i]} " return sentence.rstrip() d...
""" The 3rd and final phase of my program """ # troll-warrior paladin,hunter,rogue,shaman,mage,warlock,monk,druid, # death knight,priest def troll_Classes(): """ This is were the Troll class will be decided """ wowClass = ['Warrior', 'Hunter', 'Paladin', 'Mage', 'Shaman', 'Monk...
""" The 3rd and final phase of my program """ # worgen-warrior,hunter,rogue,shaman,mage,warlock,death knight,priest def worgen_Classes(): """ This is were the Worgen class will be decided """ wowClass = ['Warrior', 'Hunter', 'Rogue', 'Mage', 'Shaman', 'Warlock', 'Priest', 'Death...
 input_1 = input() input_2 = input() num = int(input_1.split(' ')[0]) max_num = int(input_1.split(' ')[1]) num_list = input_2.split(' ') # 모든 리스트 요소를 숫자로 만들기 for i in range(num): num_list[i] = int(num_list[i]) guess_num = 0 for i in range(num-2): for a in range(i+1,num-1): for b in range(a+1,num): ...
def binarySerach(target, l, left, right): while left<=right: mid = (left+right)//2 if l[mid]>target: right=mid-1 elif l[mid]<target: left = mid+1 elif l[mid] == target: return 1 return 0 N = int(input()) Nlist = [int(x) for x in input()....
def solve(num, arr): global res arr.append(str(num)) if num == N: temp = arr.copy() while " " in temp: temp.remove(" ") temp = "".join(temp) if eval(temp) == 0: temp = "".join(arr) res.append(temp) return cache = arr.copy() ...
# 쿼드트리 import sys def search(x, y, k): if(k == 1): return str(matrix[x][y]) result = [] for i in range(x, x + k): # 0 ~ 8 for j in range(y, y + k): # 0 ~ 8 if(matrix[i][j] != matrix[x][y]): result.append('(') result.extend(search(x, y, k//2)) ...
# 문제 # 문자열 N개가 주어진다. 이때, 문자열에 포함되어 있는 소문자, 대문자, 숫자, 공백의 개수를 구하는 프로그램을 작성하시오. # 각 문자열은 알파벳 소문자, 대문자, 숫자, 공백으로만 이루어져 있다. # 입력 # 첫째 줄부터 N번째 줄까지 문자열이 주어진다. (1 ≤ N ≤ 100) 문자열의 길이는 100을 넘지 않는다. # 출력 # 첫째 줄부터 N번째 줄까지 각각의 문자열에 대해서 소문자, 대문자, 숫자, 공백의 개수를 공백으로 구분해 출력한다. import sys for i in range(100): x = sys.stdin.readl...
for i in range(int(input())): result = "YES" stack = [] str = input() strL= list(str) for j in strL: if j=="(": stack.append("(") elif j==")": if stack == []: result="NO" break stack.pop() if stack!=[]: r...
S = input() Slist = [] for i in range(len(S)): Slist.append(S[i:]) Slist.sort() for i in Slist: print(i)
# https://www.acmicpc.net/problem/2920 from sys import stdin input = stdin.readline for i, v in enumerate(["a","b","c"]): print(f'index = {i},value={v}') # # solution 1 # input_list = list(map(int, input().split())) # is_ascending = True # is_descending = True # for i in range(1,8): # if input_list[i-1] < input_l...
# https://www.acmicpc.net/problem/10815 from sys import stdin input = stdin.readline # 정렬해서 찾기 def binarySearch(c): l = 0 r = n - 1 while l <= r : t = (r+l)//2 if cards[t] == c : return 1 elif cards[t] > c : r = t - 1 else : l = t + 1 return 0 n = int(input()) cards = list(map(int, input().spli...
from tkinter import * import time class StopWatch(Frame): msec = 50 def __init__(self, parent=None, **kw): Frame.__init__(self, parent, kw) self._start = 0.0 self._elapsedtime = 0.0 self._running = False self.timestr = StringVar() self.makeWidgets() self...
# question url: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: def bisect(is_left): # variant of array bisection algorithm # where we keep on searching the valu...
###### reverse a string user_string=input('Enter a String : ') print('Input string : '+user_string) def reverse_string(): return (user_string[::-1]) print('Reversed string : '+reverse_string())
########## swape first two character of two string a,b=input("Enter two string separated by space : ").split() print("Output : '{}'" .format((b[:2]+a[2:])+' '+(a[:2]+b[2:])))
###### Add a number with random number import random def add(a): unknown_num=int(random.random()*100) print('The sum between {} and {}(unknown_num) : {}'.format(a,unknown_num,(a+unknown_num))) a=int(input('Enter a number : ')) add(a)
####### concating string to each element of the list num_list=input('Enter list of numbers separated by space : ').split() prefix=input('Enter a string that you want to in prefix : ') def concat_list(): for i in range(len(num_list)): num_list[i]=prefix+num_list[i] return num_list print('Output : '+str(...
####### Largest number in the list a =input('Enter list of numbers separated by space : ').split() x=[int(i) for i in a] def max_list(): return max(x) print("Output : "+str(max_list()))
############## remove a character of given index a=input('Enter a String : ') if(len(a)!=0): b=int(input('Which index character you want to remove : ')) a=list(a) a.remove(a[b]) print("Output : "+''.join(a)) else: print('Warning!!!, you must enter String')
############### adding ing and ly to string a=input('Enter a String : ') if len(a)>2: if a[(len(a)-3):]!='ing': a+='ing' else: a+='ly' print('Output : '+a)
######### Multiplication of numbers of the list a =input('Enter list of numbers separated by space : ').split() def list_mul(): x=1 for i in a: x*=int(i) return x print('Output : '+str(list_mul()))
from __future__ import print_function import sys from time import sleep from random import randint, seed, choice from argparse import ArgumentParser import pygame # Account for lack of xrange in py3 if sys.version_info[0] == 3: xrange = range def gen_board(size, random=False): """Returns a blank or random bo...
count = 0 position = 0 pace = 1 target = int(input()) if target<0: count = 1 target = -1 * target while position<target: position=position+pace*2 count = count+1 print(count)
def ada(): s, w1, w2, w3 = list(map(int, input().split())) if s >= w1+w2+w3: print("1") elif s >= w1+w2 or s >= w2+w3: print("2") else: print("3") test = int(input()) for _ in range(0,test): ada()
#!/usr/bin/env python #! -*- coding: utf-8 -8- class BackTrack: def generateBoard(self, width, height): board = [] for i in range(width): for j in range(height): board.append([i, j]) return board def getAvailables(self, pos): availables = [] for i in self.moves: tmp = [i[0] + pos[0], i[1] + pos[...
import sys from time import * sa = sys.argv length_sa = len(sys.argv) if length_sa != 3: print("\nInvalid arguments!") print("USAGE: python file_name.py mins_value secs_value") print("Example: python alarm_clock.py 10 35") print("Use a value of 0 minutes 0 seconds for testing the alarm immed...
# http://api.openweathermap.org/data/2.5/weather?q=London&appid=fed9597b3ac268198e76e038dc48c748 """ Getting started with a 'click' package """ import requests import click SAMPLE_API_KEY = 'fed9597b3ac268198e76e038dc48c748' @click.group() def cli(): pass def current_weather(location, api_key): url = 'http...
import numpy as np import matplotlib.pyplot as plt np.random.seed(1) def sigmoid(x): return 1 / (1 + np.exp(-x)) def softmax(A): expA = np.exp(A) return expA / expA.sum(axis=1, keepdims=True) # a 3 x 4 x 3 network example s = 5 # five samples n = 3 # three features per sample d = 4 # four...
"""Defines a generic submarine""" from commands import PingCommand, MoveCommand, FireCommand from util import Coordinate class Submarine(): """Generic submarine""" location = Coordinate(0, 0) dead = False active = True max_sonar_charge = False max_torpedo_charge = False size = 100 shiel...
def hiddenBadWords(sentence): #List of badWords that you want control. You can use a data-set of Bad Words to in csv format too. badWords = ["asshole"] #The sentence is splitted into words lst = sentence.split() separatore = "" sentence = " " + sentence + " " try: #For each word in the sentence... ...
#!/usr/bin/env python3 import sys x = 0 for line in sys.stdin: line = [int(v) for v in line.split()] found = False for i in range(len(line)): for j in range(len(line)): if i == j: continue if line[i] % line[j] == 0 and not found: x += line[i] / line[j] found = True print(x...
#!/usr/bin/env python3 import sys for line in sys.stdin: line = line.strip() n = len(line) x = 0 line += line for i in range(n): if line[i + int(n/2)] == line[i]: x += int(line[i]) print(x)
# 用来计算复利 def interst(): rate = 0.15 sum = 0 money = 12000 for i in range(5): print(i) sum = (sum+money)*(1+rate) print(sum) # 主函数 if __name__ == "__main__": interst()
""" 内置类属性 """ class InnerCls: '姓名' name = "" def __init__(self, name): self.name = name print("InnerCls.__doc__:", InnerCls.__doc__) print("InnerCls.__name__:", InnerCls.__name__) print("InnerCls.__module__:", InnerCls.__module__) print("InnerCls.__bases__:", Inn...
# list 是一种有序的集合。可以随时添加和删除里面的元素 # list 是一个可变的 def test(): list1 = [1, 2, 3, 4] # len() 统计元素的个数 print(len(list1)) # 索引从 0 开始 print(list1[0]) # 删除末尾的元素可以使用 pop() print(list1.pop()) # 添加元素到 list 的末尾 list1.append(22) print(list1) # 插入元素到具体的位置 list1.insert(1, 44) prin...
"""私有变量和方法""" class JustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 def count(self): self.__plus() print(self.__secretCount) def count2(self): return self.__secretCount # 私有方法 def __plus(self): self.__secretCount += 1 self.publicCount...
def factorial(): n=int(input("Enter the input:")) fact=1 if(n==0): print(0); else: for i in range (1,n+1): fact=fact*i print(fact) factorial()
"""f = open("shubham.txt", "rt") content =f.read(12345) print("01",content,end=" ") content =f.read(1234) print("\n02",content,end=" ") f.close()""" #1)))) print charater by character program using for """f=open("shubham.txt") content=f.read( ) for line in content: print(line) f.close() """ #2)))print all line in...
class Friends: no_of_friends = 8 def __init__(self, aproffesion, agraduate, aage): self.proffession = aproffesion self.graduate = agraduate self.age = aage def func(self): return f"{self.proffession},{self.graduate},{self.age}" @classmethod def bbhua(cls, param): ...
# Script Name : batch_file_rename.py # Author : Craig Richards # Created : 6th August 2012 # Last Modified : # Version : 1.0 # Modifications : # Description : This will batch rename a group of files in a given directory, once you pass the current and new extensions import os # Load the library...
import matplotlib.pyplot as plt import numpy as np import os #Tugas Praktikum Konsep Teknologi #author: Anastasyarez #fungsi input nilai def inputnilai(): lagi = "y" while (lagi=="y"): print("ISI DATA NILAI") nis = input("NIS: ") nama = input("NAMA: ") test1 = f...
#!/usr/bin/env python #Author by : Stack Cong count = 0 #while True: # print("count:",count) # count = count +1 ''' for i in range(0,10): if i<5: print("This is:",i) else: continue print("HeHe.....") ''' for i in range(10): print("++++++++++++++",i) for j in range(10): print(j) if j>5: break
#!/usr/bin/env python #教学视频第24集 product_list = [ ('iPhone',5800), ('Mac Pro',9800), ('Bike',800), ('Watch',10600), ('Coffee',31), ('Alex Python',120) ] shopping_list = [] salary = input("Please input your salary:") if salary.isdigit(): salary = int(salary) while True: for inde...
# -*-coding:Utf-8 -* """Ce fichier contient le code du container de robot. amélioration possible rendre la classe itérable """ class Robots: """ classe qui contient tous les robots qui sont entrain de jouer """ def __init__(self): self.robots = {} def ajouter_robot(self, robot): """ ajou...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSymmetric(self, root): stack1=[] stack2=[] if root==None: return True if root.left==None and root.right==None: ret...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param A : head node of linked list # @return the head node in the linked list def printList(self,A): temp=A while temp!=None: print temp.val, temp=temp.next ...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree(self,A,B): if A==None and B==None: return True temp1=A temp2=B if (temp1==None and temp2!=None) or (temp1!=None and t...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param A : root node of tree # @return an integer def isSubtreeLesser(self,root,value): if root==None: return 1 if root.val<=value and self.isSubt...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param A : root node of tree # @param B : integer # @return the root node in the tree def getSuccessor(self, A, B): curr=A while curr!=None: i...