text
stringlengths
37
1.41M
'''module to add brick on board''' from make_brick import MakeBrick def brick(bricks): '''make all bricks''' brk = MakeBrick(30, 23, 1) bricks.append(brk) brk = MakeBrick(35, 23, -2) bricks.append(brk) brk = MakeBrick(40, 23, -2) bricks.append(brk) brk = MakeBrick(45, 23, -2) br...
'''class to make bricks''' class MakeBrick: '''class to make bricks''' def __init__(self, x, y, t): self.posx = x self.posy = y self.type = t def get_x(self): '''getter for x''' return self.posx def get_y(self): '''getter for y''' return self.posy
def print_sum(student_marks,query_name): total = 0 for key,value in student_marks.items(): if key == query_name: total = sum(value)/len(value) print(total) if __name__ == '__main__': #read number of students, followed by each student name along with their marks n = int(inp...
from random import shuffle def player_guess(): guess = '' while guess not in ['0','1','2']: guess = input('Please enter the guess 0,1 or 2: ') return int(guess) def shuffle_list(mylist): shuffle(mylist) return mylist def check_guess(mylist,guess): if mylist[guess] == 'O': prin...
new_list = [] if __name__ == '__main__': N = int(input()) operations = {} for _ in range(N): op,*line = input.split() item = list(map(int,line)) operations[op] = item for item in N: operation = input() if operation == 'print': funPrint() ...
# The rand7() API is already defined for you. from random import randint def rand7(): return randint(1, 7) class Solution: def rand10(self): """ :rtype: int """ r7_1 = rand7() r7_2 = rand7() idx = (r7_2-1) * 7 + r7_1 if idx > 40: return se...
# coding: utf-8 # Bubble Sort, Reverse = True則大至小(預設值);反之小至大 def bubble_sort_fun(x, reverse = 1): for i in range(0, len(x) - 1): for j in range(i + 1, len(x)): if reverse == 0: if x[i] > x[j]: x[i], x[j] = x[j], x[i] elif reverse == 1: ...
# -*- coding: utf-8 -*- """ Created on Sun Feb 04 03:02:59 2018 @author: pushkar """ import pygame import math import time from copy import deepcopy class BoxesGame(): def __init__(self): #initialize variables for the current state self.hColor=[[0 for x in range(6)] for y in range(7...
''' Analisis pseint Entradas: Nombre1, Nombre2 Salidas: ultima1,ultima2,primera1,primera2 si primera1 es igual a primera 2, escribir quer hay coincidencia, si ultima 1 es igual a ultima 2, hay coincidencia, sino escribir que no hay . pseudocodigo: Algoritmo p1 Escribir 'Ingresar primer nombre' leer n1 Escri...
def suma(a,b): total=a+b return total a=int(input("ingrese un numero: ")) b=int(input("ingrese otro numero: ")) resultado=suma(a,b) print("el resultado la suma de los numeros es:",resultado) input('Apretar enter para terminar')
#Descripcion: Eliminar todos los 0 de una lista definida #Entrada: No posee parametros de entrada #Salida: Lista sin cero lista = [0,5,1,0,3,5,4,8,9,0,2,1,0,6,0,0,1,6,8] while 0 in lista: lista.remove(0) print("La lista sin el numero cero es la siguiente:",lista) #[5, 1, 3, 5, 4, 8, 9, 2, 1, 6, 1, 6, 8]
''' Analisis Entrada: aleat, aleat2, aleat3 Salida: (aleat+aleat2+aleat3)/3 Proceso: def alear, aleat2, aleat3 <-(azar(7)), resultado<- (aleat+aleat2+aleat3)/3 Pseudocodigo: Algoritmo lab36 definir aleat,aleat2,aleat3 como real aleat <- (azar(7)) aleat2 <- (azar(7)) aleat3<- (azar(7)) Escribir alea...
## Descripcion: Une los dominios y los nombres en orden aleatorio ## Entradas: nombre, dominio ## Salidas: juntar(nombre,dominio) from random import randint nombre=["Nicolas","Andres","Ricardo","Exequiel","Catalina"] dominio=["@goqoez.com","@gmail.com","@outlook.cl","@educa.uct","@adretail.cl","@grange.cl","@out...
''' Analisis Entradas: ncandidato salidas: candidato_voto Pseudocodigo: Algoritmo votos Imprimir 'Los candidatos a las votaciones son: ' Imprimir '1.Emilia Hajimeru' Imprimir '2.Martin Completos' Imprimir '3.Armando Casas' Imprimir '4.Ignacio Montero' Imprimir '5.Ricardo Milos' Escribir 'Ingresar...
##descripion: mostrar por pantalla los primeros 15 numeros de la sucesion de fibonacci ##entrada: no posee parametro de entrada ##salida: muestra por pantalla la secuencia de fibonacci (primeros 15 numeros) def fibonacci(n): a=0 b=1 for i in range(n): c=a+b a=b b=c retu...
## Descripcion: Juntar dos cadenas de caracteres e imprimir ## Entradas: A,B ## Salidas: joint(A,B) a = ["Usted tiene 20 horas para vivir"," deme todos sus mangas"] b = [","] def joint(a,b): caracteres = a[0]+b[0]+a[1] return caracteres frase = joint(a,b) print(frase)
#importar libreria para graficos de visualizacion import matplotlib.pyplot as plt import numpy as np f, ax = plt.subplots() x = np.linspace(0, 2*np.pi) y = np.sin(x) ax.plot(x, np.sin(x), 'r', label='sin ruido') # añadimos algo de ruido xr = x + np.random.normal(scale=0.1, size=x.shape) yr = y + np.random.normal(scal...
from Tkinter import * root = Tk() #grid configures the widget in a tabular format label = Label(root,text="Name") label2 = Label(root,text="Password") entry_1 =Entry(root) #textbox entry_2 = Entry(root) label.grid(row=0,sticky=E) label2.grid(row=1,sticky=E) #sticky is used for alligning the labels in Eas...
from Tkinter import * #Creating the toolbar def ahi(): print("ahi") root = Tk() toolbar = Frame(root,bg="blue") button_1 = Button(toolbar,text="Insert Img",command=ahi) button_1.pack(side=LEFT,padx=2,pady=2) printbut = Button(toolbar,text="print ahi",command=ahi) printbut.pack(side=LEFT,padx=2,pady=2) toolbar.pac...
import base def bubblesort(arr): for i in range (len(arr)-1): for j in range (len(arr)-1 , i, -1): if arr[j] < arr[j-1]: arr[j], arr[j-1] = arr[j-1], arr[j] return arr if __name__ == '__main__': for i in range (10): arr = base.genlist () arr = bubblesor...
# _*_ coding:utf-8 _*_ # 函数的返回值可以是一个函数 def myabs(x): return abs(x) # 直接调用myabs 返回是abs的函数 print myabs(-1) #任务 #请编写一个函数calc_prod(lst),它接收一个list,返回一个函数,返回函数可以计算参数的乘积。 def calc_prod(lst): def calc(x,y): return x*y def delay_calc_prod(): return reduce(calc,lst) return delay_calc_prod f = calc_prod([1, 2, 3...
#-*- coding:utf-8 -*- # 定义一个无理数的加减乘除 class Rational(object): """docstring for Rational.""" #定义一个无理数,里面有分子和分母 def __init__(self, son,mother): self.son = son self.mother = mother self.__getSimperRational() # 分数的加法运算 def __add__(self,next): if self.mother == next.mother: ...
#-*- coding:utf-8 -*- # 类属性 class Person(object): count = 0 def __init__(self): Person.count += 1 p1 = Person() p2 = Person() p3 = Person() p4 = Person() p5 = Person() p6 = Person() print p2.count
# _*_ coding:utf-8 _*_ # sorted()也是一个高阶函数,它可以接收一个比较函数来实现自定义排序, #比较函数的定义是,传入两个待比较的元素 x, y, #如果 x 应该排在 y 的前面,返回 -1, #如果 x 应该排在 y 的后面,返回 1。 #如果 x 和 y 相等,返回 0。 L1 = [36, 5, 12, 9, 21] L2 = sorted(L1) print L2 def reversed_cmp(x,y): if x > y: return -1 elif x < y: return 1 else: return 0 L3 = sorted(L1,reverse...
# _*_ coding:utf-8 _*_ # list :python 内置的一种列表数据类型 特点:1.有序 2.可以随意删除和修改 3. 中括号表示(和js的数组类似) La = ['Micheal','Bob','Tracy'] Lb = ['Adam', 95.5, 'Lisa', 85, 'Bart', 59] print Lb #list 元素的访问,利用索引 从0开始 print Lb[0] #当然也可以倒序访问 默认最后一个元素的索引是-1, 利用len方法可以获取对象的长度 所以第一个元素就应该是 -len(L) print Lb[-len(Lb)] #添加新的元素 list # #第一种办法:ap...
# _*_ coding:utf-8 _*_ def testFileFunc(): ''' 用来测试文件打开的模式不同带来的结果 ''' # keywords = raw_input("请输入您要测试的模式:") # if keywords.lower() == 'r': # print '我是只读文件' # elif keywords.lower() == 'w': # print '我是可写文件' # else: # print '您的输入不正常' fp = open('hello.txt','a+') ...
# /usr/bin/env python # _*_ coding:utf-8 _*_ # author:eno2050 # email:117908549@qq.com # 2017-10-2 import re pattern = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!' # 正则的方法完成替换 print re.sub(pattern,r'\2 \1', s) # 函数的方法完成替换 def func(m): return m.group(1).title() + ' ' + m.group(2).title() print re.sub(patter...
""" Define a function `isPrime(number)` that returns `true` if `number` is prime. Otherwise, false. Assume `number` is a positive integer. Examples: isPrime(2); // => true isPrime(10); // => false isPrime(11); // => true isPrime(9); // => false isPrime(2017); // => true *************************************************...
#link for question #https://onlinecourses.nptel.ac.in/noc19_cs08/progassignment?name=102 def progression(l): i,j=0,1; n=len(l); if(n<=1): return True; d=l[0]-l[1]; while(j<n): if(l[i]-l[j]!=d): return False; i,j=i+1,j+1; return True; def primesquare(l): n=len(l); if(n<=1): ...
age = int(input('Please enter a persons age.')) if age >= 20: print 'The person is eligible to vote.' else print 'The person is not eligible to vote'
# # 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head): cur, prev = head, None # prev 是反转后的下一节点 # cur 是当前节点位置 # cur.next 当前的下一节点 while cur: next...
# 从一个线程向另一个线程发送数据最安全的方式可能就是使用 # queue 库中的队列了。创建一个被多个线程共享的 Queue 对象, # 这些线程通过使用 put() 和 get() 操作来向队列中添加或者删除元素。 例如: from queue import Queue from threading import Thread def producer(out_q): i =1 while True: ... out_q.put(i) i +=1 if i >100: break def consumer(in_q):...
# 将format()函数和字符串方法是使得一个对象能够支持自定义方法的格式化 # 自定义格式化输出 _formats = { 'ymd' : '{d.year}-{d.month}-{d.day}', 'mdy' : '{d.month}/{d.day}/{d.year}', 'dmy' : '{d.day}/{d.month}/{d.year}' } class Date: def __init__(self,year,month,day): self.year = year self.month = month self.day = day ...
# 输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值 # 要求时间复杂度为O(n)。 # 连续子数组:指在那个数组的连续的元素是连续截取出来的数组 # 动态规划 List = list class Solution: def maxSubArray(self, nums: list): max_list = [] for i in range(len(nums)): if len(max_list) == 0: z = nums[i] else: ...
# 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 # 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 # 输入:[2,0,2,1,1,0] # 输出:[0,0,1,1,2,2] class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ i, j, k = 0, le...
# 请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 # 输入:head = [4,5,1,9], node = 5 # 输出:[4,1,9] class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.nex...
# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 # 输入:babad # 输出:bab class Solution: def longestPalindrome(self, s: str) -> str: self.start = 0 self.max_len = 0 n = len(s) if n < 2: return s def helper(i,j): while i >= 0 and j < n and s[i] ==...
# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 # 有效字符串需满足: # 左括号必须用相同类型的右括号闭合。 # 左括号必须以正确的顺序闭合。 # 输入:"{[]}" # 输出:true class Solution: def isValid(self, s: str) -> bool: while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}','') s = s.replace('()','') s = s.rep...
import csv import pandas as pd import argparse def or_1(filename, output): df = pd.read_csv(filename) key_1 = input('First keyword : ') loc = df[df['message'].str.contains(key_1)] loc.to_csv(output, encoding='utf8') print("Finish!") def or_2(filename, output): df = pd.read_csv(filename) ...
def skal_proizv(a, b): if len(a) != len(b): raise Exception('Векторы имеют разную длину') res = 0 for i in range(len(a)): res += a[i]*b[i] #print('Скалярное произведение векторов =', res) return res def write_vec(): print('Введите координаты вектора в строку через пробел') r...
print "You enter a dark room with two doors. Do you go through door #1, door #2, or door #3?" door = raw_input("> ") if door == "1": print "There's a giant bear here eating a cheesecake. What do you do?" print "1. Take the cake." print "2. Scream at the bear." bear = raw_input("> ") if bear == "1": prin...
#http://ideone.com/DRnYj1 class AdoptionCenter: def __init__(self, name, species_type, location): self.name = name self.location = float(location[0]),float(location[1]) self.species_type = species_type def get_name(self): return self.name def get_location(self): retur...
#!/usr/bin/env python3 class Player(): def __init__(self, name_list:list=["X","Y","Z"]): """Takes two player names, or defaults to X and Y""" self.name_list = name_list self.index = 0 def switch(self): """Change current player""" self.index = (1+self.index) % len(self.name_list) def name(self): ""...
def e_impar(n): return n%2 == 0 n = int(input('digite um número:')) print(f'o número {n} é ímpar?', not e_impar(n))
sequence = 'Hello World' # expected output: # dlroW olleH for char in reversed(sequence): print(char, end='') print() # expected output: # dlroW olleH for idx in range(len(sequence)-1, -1, -1): char = sequence[idx] print(char, end='') print() # expected output: # dlroW olleH for char in sequence...
def should_react(current, previous): if current.lower() != previous.lower(): return False elif current == previous: return False elif current.upper() == previous or current == previous.upper(): return True if __name__ == '__main__': with open('input.txt', 'r') as f: stac...
#!/usr/bin/env python def isDivisibleByAll(number): for i in xrange(1,21): if number % i != 0: return False return True def problem5(): # note you can also set this number below to the lcm of # any of the prior in sequence, for example 1..10 = 2520 number = 20 # largest number amongst divisors while True...
# Question 1 def main(): # You don't need to modify this function. a = input('Enter one number') b = input('Enter another number') compare = which_number_is_larger(a, b) if compare == 'same': print('The two numbers are the same') else: print('The %s number is larger' % compa...
from collections import defaultdict, deque class Solution: def get_order(self, word1, word2): n, m = len(word1), len(word2) i = j = 0 while i < n and j < m and word1[i] == word2[j]: i += 1 j += 1 if i == n: return None, None return word1...
""" 314. Binary Tree Vertical Order Traversal Medium 1615 212 Add to List Share Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Example 1:...
""" 270. Closest Binary Search Tree Value Easy 1160 81 Add to List Share Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. Example 1: Input: root = [4,2,5,1,3], target = 3.714286 Output: 4 Example 2: Input: root = [1], target = 4.428571 Outpu...
#!/usr/bin/py """ Consider an array of integers, A, where all but one of the integers occur in pairs. In other words, every element in A occurs exactly twice except for one unique element. Find the unique element. Solution: Using bitwise xor on each integer, each integer pair will cancel each other out to return 0,...
# Caleb Manor # This is a Python comment # Create some dynamically typed variables and intitialize them an_integer = 55 a_string = "This is a Python program" a_bool = True a_float = 3.25 # Here is a calculation the_answer = an_integer * a_float + ord(a_string[0]) + int(a_bool) print(the_answer) # Write code that w...
#2. input a number. check if the number is 0 or 1, if so print '0 or 1 # otherwise check if the number is -1, if so print '-1' # otherwise print 'unknown number' a = int(input('input num to check a = ')) if a == 0 or a == 1: print('num is 0 or 1') else: if a == -1: print('num is -1') ...
# -*- encoding: utf-8 -*- """ 链表练习 @File : link_exercises.py @Time : 2020/04/13 23:05:41 @Author : Zhong Hao @Version : 1.0 @Contact : zh826256645@gmail.com @Desc : None """ from model import init_link, Link, Node def find_last_node(link, reverse_index: int): " 不使用 length 属性,查询倒数的节点 " f...
import tkinter class Store: def __init__(self): self.variable = tkinter.IntVar() def add(self, value): var = self.variable var.set(var.get() + value) return var.get() class Main(tkinter.Tk): def __init__(self, *args, **kwargs): tkinter.Tk.__init__(self, *args, **kw...
from instantiate import room from player import Player from room import Room from item import Item from functions import print_slow import sys # # Main # # Make a new player object that is currently in the 'entrance' room. player = Player() player.current_room = room['entrance'] # Write a loop that: # # * Prints th...
#meses = ["janeiro", "fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"] mes = str(input("insira o mes do nascimento de Jose Carlos: ")) dia = int(input("insira o dia do seu aniversario: ")) if mes == "abril": print("Estação do aniversario de José Carlos é outon...
import sys def fizz_buzz(): """ Classic fizz buzz """ test_cases = open( sys.argv[1], 'r' ) for test in test_cases: if len( test ) == 0: # ignore empty line continue else: ## read arguments ## args = test.split() x = int( args[0] ) ...
def distance(dna_strand_one, dna_strand_two): # Check if both have same size if len(dna_strand_one) != len(dna_strand_two): raise ValueError distance_count = 0 for nucleotide_one, nucleotide_two in zip(dna_strand_one, dna_strand_two): if not nucleotide_one == nucleotide_two: ...
""" 25. Em uma eleição presidencial existem 3 (três) candidatos. Os votos são informados através de códigos. Os dados utilizados para a contagem dos votos obedecem à seguinte codificação: · 1, 2, 3 = voto para os respectivos candidatos; · 9 = voto nulo; · 0 = voto em branco; Escreva um algoritmo que leia o código v...
'''07. Leia um número N, some todos os números inteiros entre 1 e N e escreva o resultado obtido.''' print('Questão 07.') numero = int(input('Informe um valor limite: ')) contador = 0 def total(contador, numero): for soma in range(1, numero+1): resultado = contador + soma contador += soma retu...
# -*- coding: utf-8 -*- """20. Leia uma temperatura em °C, calcule e escreva a equivalente em °F. (t°F = (9 * t°C + 160) / 5) """ temp_c = float(input('Digite a temperatura em ºC: ')) temp_f = (9* temp_c + 160)/5 print ('A temperatura %.1f ºC equivale a %.1f ºF.' % (temp_c, temp_f))
n = int(input("Enter a Number : ")) series_sum = [] for i in range(1,n+1): series_sum.append(i) if i==n: print(i, end='') else: print(i,end=' + ') print(' = ', sum(series_sum), sep='')
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] listt = [] for num in a: if num <5: listt.append(num) print(listt) # one liner print([aa for aa in a if aa < 5])
#python file to convert csv disease file to json import json csvfile = open("convertcsv.csv", 'r') json_list = list() disease_dict = dict() disease = ""; count_occurence = 0; symptoms = [] #disease_done = False for line in csvfile: if line.startswith(",,"): #disease_done = False symptoms.append(li...
from abc import ABC, abstractmethod class Pessoa: def __init__(self, nome, idade): self._nome = nome self._idade = idade @property def nome(self): return self._nome @property def idade(self): return self._idade class Conta(ABC): def __init_...
from termcolor import colored, cprint import random, math score = 0 pos = 0 global full full = 0 real = open('/usr/share/dict/words').read().split() #Added files to my computer fake = open('/usr/share/dict/fake').read().split() fake = sorted(set(fake)) def draw(): for k in range(0, 3): print '' def check(var): # pr...
username = input("输入角色") equipment = input("请输入拥有的装备") buy_equipent = input("请输入想购买的装备") payment_amount= input("请输入付款金额") print("{}购买了{}装备,花了{}钱".format(username,buy_equipent,payment_amount))
# 1234能组成多少个数字1.0 强算法 list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9,] list2= [] for i in list1: a = 100 * i # 百位 for x in list1: if x == i: continue else: b = 10 * x # 十位 for y in list1: if y == x: continue elif y == i: ...
a = input("请输入数字:") b = 0 for i in range(int(a)): b += i+1 print("从1到{}的和为{}.".format(a,b))
#4个数能组成多少种可能通 def func(a): ls=[] for i in range(1,5): for j in range(1,5): for k in range(1, 5): for n in range(1, 5): b="{}{}{}{}".format(i,j,k,n) ls.append(b) return ls a=func(4) print(len(a))
list1 = eval(input("输入一个列表:")) # 获得用户输入 num1 = eval(input("输入:")) #获得用户输入 list2 = [] # 定义一个空列表 for i in list1: # 遍历一遍用户输入 for y in list1: # 遍历一遍用户输入 if y == i: # 如果 y==i则跳出当次循环 continue else: # 不等于则 if i + y == num1: # 判断 i + y 是否等于 rargrt list2.append...
#身体bmi值 num1=eval(input("输入身高(米):")) num2=eval(input("输入体重(千克):")) bim=num2/pow(num1,2) print("身体的BMI值为:{:.2f}".format(bim)) a=""#国外 b=""#国内 if bim<18.5: a="偏瘦" b="偏瘦" elif 18.5<=bim<25: a="正常" elif 18.5<=bim<24: b="正常" elif 24<=bim<28: b="偏胖" elif bim>=28: b="肥胖" elif 25<=bim<30: a="偏胖" els...
# 工作人进步周末退步365天后 dayup = 1 dayx = 0.01 for i in range(365): if i % 7 in [0, 6]: dayup = dayup - dayx * dayup else: dayup = dayup + dayx * dayup print("365天后为:{:.2f}".format(dayup))
num1=input("输入:") num1=eval(num1) for i in range(1,num1+1): num1=i*num1 print(num1)
#靶盘 from turtle import * setup(900,900,0,0) pencolor("green") pensize(300) goto(-350,350) fd(700) for i in range(2): circle(-100,180) fd(700) circle(100,180) fd(700) goto(0,0) pensize(15) pencolor("red") circle(5) pensize(12) yanse=['white','black'] r=10 for i in range(100): pencolor(yanse[i%len...
#文本刷新 import time print("-----程序开始-----") num1=10 for i in range(num1+1): a="**"*i b="--"*(num1-i) c=(i/num1)*100 print("{:^3.0f}%[{}->{}]".format(c,a,b)) time.sleep(0.1) print("-----程序结束-----")
print('***************************') print('''欢迎光临小象奶茶馆! 您已进入小象奶茶自助点餐系统! 小象奶茶馆售卖宇宙无敌奶茶! 奶茶虽好,可不要贪杯哦! 1号. 原味冰奶茶 3元 2号. 香蕉冰奶茶 5元 3号. 草莓冰奶茶 5元 4号. 蒟蒻冰奶茶 7元 5号. 珍珠冰奶茶 7元 ''') print('***************************') milktea_name=int(input('请输入奶茶号:')) print('***************************') milktea_number=int(input('请输入要购买奶茶...
class MyClass: def __init__(self): self.public_attribute = "This is a public attribute" self.__private_attribute = "This is a private attribute" def public_method(self): print("This is a public method") def __private_method(self): print("This is a private method") my_obje...
''' NAME reverse-complement.py VERSION 1.0 AUTHOR Hely Salgado, Axel Zagal, Azaid Ordaz DESCRIPTION Make the reverse complement of DNA sequence CATEGORY Genomic Sequence USAGE % python reverse-complement.py -i example % python reverse-complement -i ''' import a...
""" 一个回合制游戏,游戏中有两个角色,每个角色都有HP、Power、Armor三种基本属性,主角属性有初始值 HP代表血量(初始值为100),Power代表攻击力(初始值为10),Armor代表护甲(初始值为10) 定义一个fight方法 final_HP = HP - enemy_Power + My_Armor enemy_final_HP = enemy_HP - my_Power + enemy_Armor 血量变为0的一方获胜 """ import random class game_characters: pro_hp: int pro_power: int pro...
from random import randint catalog = {1: 'Rock', 2: 'Paper', 3: 'Scissors'} player, comp = 0, 0 print("Game - \"Rock / Paper / Scissors\"") while player < 3 and comp < 3: print('Enter 1 for Rock, 2 for Paper, 3 for Scissors') com_choice = randint(1, 3) try: pl_choice = int(input('Your turn: ')) ...
from random import randint class Phone: def __init__(self): self.number = randint(10000000000, 99999999999) class Samsung(Phone): brand = "Samsung" os = "Android" class Apple(Phone): brand = "Apple" os = "IOS" new1 = Samsung() print(new1.brand, new1.os, new1.number)
first = int(input("Start: ")) second = int(input("End: ")) total = 0 for i in range(first, second + 1): if i % 13 == 0 or i % 4 > 0 and 99 < i < 1000: continue elif 999 < i < 10000 and i % 7000 == 0: break else: total += i print(f"Sum: {total}")
a = float(input("Для уравнения вида ax^2+bx+c=0\nУкажите коэфициент а ")) b = float(input("Укажите коэфициент b ")) c = float(input("Укажите коэфициент c ")) if a == 0: if b != 0: x = -c / b; print("x = ", x) else: c == 0; print("c = 0") elif b == 0: if c > 0: print("...
name=input("Please enter your name: \t") if(name=="Anu"): print("Hi I stay in cluster Y") elif(name=="Mahi"): print("Hi I stay in cluster U") else: print("I dont know where I stay")
# name="Aarav" # print("welcome",name) # print("i love coding") num1=13 num2=4 print("numbers",num1,num2) print("addition",num1+num2) print("subtraction",num1-num2) print("multiplication",num1*num2) print("division",num1/num2) print("quotient",num1//num2) print("remainder",num1%num2) print("repeated multiplication",num...
#!/usr/bin/env python3 """ Module of helper functions for dealing with patterns in entity regex. """ import re from itertools import chain import exrex def make_clean_input(pattern): """ Enforces that entities or words have parentheses around them and have trailing spaces >>> make_clean_input("@num{3}")...
#!/usr/bin/env python3 """ Freezes objects into immutable objects so they can hash Also contains wrapper for freezing arguments to lru_cache and unfreeze routine """ import collections import functools from immutables import Map def freeze_map(obj): """ freezes components of all mappables """ return ...
from collections import deque import numpy as np ''' OBJECTIVE LEGEND: 0 = looking for food 1 = count the available space 2 = check if we can see our tail (unused) ''' #breadth first search floodfill to find a goal def bfs(board, start, objective, tail): count = 1 queue = deque() queue.appen...
#! /user/bin/python # -*- coding: iso-8859-15 import os num = int(input("Positivo y Negativo: ")) if num > 0: print("El número introducido es positivo") elif num < 0: print("El número introducido es negativo") else: print("El número introducio es 0")
enum=int(input()) if enum>0: print("positive") elif enum<0: print("negative") elif enum==0: print("zero")
for _ in range(int(input())): n = int(input()) temp = (n - 1) // 26 temp2 = n % 26 ans = 2**temp if n == 0: print(1,0,0) elif temp2 > 0 and temp2 < 3: print(ans,0,0) elif temp2 > 2 and temp2 < 11: print(0,ans,0) else: print(0,0,ans)
''' Automate the Boring stuff First program in Python - prints to screen - prints user inputs to screen - prints user inputs through string calls ''' print('Hello world!') # Prints to screen print('What is your name?') # ask for their name myName = input() # Takes user input p...
# Sorting and creating set items # (i.e. removing redundant or repeated items from a list) List1 = [10,9,9,9,9,9,8,7,6,5,5,4,4,3,2,1,1,1,1,1,1] print("Your list is "), print(List1) print("Your list sorted is: ") List1.sort() print(List1) List3 = list(set(List1)) List3.sort() print("Your list as a set is: ")...
import csv import numpy as np from sklearn.svm import SVR import matplotlib.pyplot as plt dates = [] prices = [] def data(filename): with open(filename, 'r') as csvfile: csvFileReader = csv.reader(csvfile) # to skip column names next(csvFileReader) for row in csvFileReader: dates.append(i...
# 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: def getMinimumDifference(self, root: TreeNode) -> int: res = [] self.dfs(root, res) ...
import unittest # Using cyclic sort - O(n) time ; O(1) space def find_repeat(nums): # Find a number that appears more than once for i in range(len(nums)): while nums[i] != i + 1: j = nums[i] - 1 if nums[i] == nums[j]: return nums[i] nums[i], nums[j] ...
# 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: def isBalanced(self, root: TreeNode) -> bool: if not root: return True left = se...