text
stringlengths
37
1.41M
""" Напишите программу, на вход которой подаётся список чисел одной строкой. Программа должна для каждого элемента этого списка вывести сумму двух его соседей. Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка. Например, если на вход подаётся...
#! /usr/bin/env python3 ''' This is our Stock class. It is designed to hold a single stock and the details around it ''' import time import logging import Finance class Stock: ''' This class will hold 1 stock from the config file ''' def __init__(self, symbol=None, name=None, purchase=None, share...
# -*- coding:utf-8 -*- # author:顾旭华 # date:2017/02/21 # description :对列表数据进行迭代:While循环 #先动态获取一个列表 data = [] while True: print 'Please Input data' a = raw_input('input data:') print 'a:'+a if a == 'q': break data.append(a) print data #while循环迭代列表数据 count = 0 while count<len(data): print...
# -*- coding:utf-8 -*- # author : 顾旭华 # date : 2017/02/22 # description : 引入一个模块,用来打印列表数据 # 初始化一个列表数据 Cast = ['Palin','Cleese','Idle','Jones','Gilliam','Chapman'] Movie = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91, ["Graham Chapman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle"...
class Student: __name = "" def __init__(self,name): self.__name__=name def getName(self): return self.__name if __name__ == "__main__": print 'Hello World' student=Student("guxh") print student.getName()
import math from math import * f = eval("lambda x:"+input("Ingrese la funcion: ")) xi = float(input("Ingrese xi: ")) xs = float(input("Ingrese xs: ")) tolerance = float(input("Ingrese la tolerancia: ")) niter = float(input("Ingrese el maximo de iteraccion: ")) print(""" Biseccion Tabla de resultados: |i| a ...
xs = eval(input("Ingrese los x: ")) ys = eval(input("Ingrese los y: ")) p = [] b = [] result = str(ys[0]) b.append(ys[0]) p.append(eval("lambda x: "+result)) b.append((ys[1]-b[0])/(xs[1]-xs[0])) result += f"+{b[1]}*(x-{xs[0]})" p.append(eval("lambda x: "+result)) for n in range(2,len(ys)): fun = p[n-1] den ...
#! /usr/bin/env/ python # -*- coding: utf-8 import tensorflow as tf import numpy as np def my_image_filter(input_images): conv1_weights = tf.Variable(tf.random_normal([5, 5, 32, 32]), name="conv1_weights") conv1_biases = tf.Variable(tf.zeros([32]), name="conv1_biases") conv1 = tf.nn.conv2d(input_...
#!/usr/bin/python def search_neighb(r, c, grid): if len(grid) < 1: return [] grid_r = len(grid) grid_c = len(grid[0]) nodes = [] if r - 1 > 0: u = grid[r-1][c] if u != '%': tup = (u, r-1, c) nodes.append(tup) if r + 1 < len(grid): u = grid[...
print('=' * 46) print('{:^46}'.format('ANÁLISE STR 2 DO VICENTÃO')) print('=' * 46) n = int(input('Digite um N° de até 4 dig: ')) nq = f'{n:04}' line = '\n' print( f'{line}', f'unidade: {nq[3]}{line}', f'dezena: {nq[2]}{line}', f'centena: {nq[1]}{line}', f'milhar: {nq[0]}{line}' ) # SÓ TA ACEITANDO ...
print('=' * 46) print('{:^46}'.format('CITY DO VICENTÃO')) print('=' * 46) c = str(input('Digite sua cidade: ')) l = c.lower(), c.split() print( 'Sua cidade começa com Santo?', #l[0].find('santo') 'santo' in l[0] )
import random print('=' * 46) print('{:^46}'.format('ROLETÃO DO VICENTÃO')) print('=' * 46) a1 = str(input('Aluno 1 = ')) a2 = str(input('Aluno 2 = ')) a3 = str(input('Aluno 3 = ')) a4 = str(input('Aluno 4 = ')) lista = [a1, a2, a3, a4] r = random.choice(lista) print('O fudido sorteado é : {}'.format(r)) # Tentei impor...
n1 = int(input('Digite um número: ')) a = n1 - 1 s = n1 + 1 print('O número {} tem antecessor {} e sucessor {}'.format(n1, a, s))
# -*- encoding: utf-8 -*- from sort.base import Sort """ 希尔排序的问题:相邻的希尔增量可能会存在公因子,导致不能进一步排序 当数组的个数为2 ** n,奇数列和偶数列的两个递增序列 且 奇数列的值小于偶数列的值 例子: 1, 5, 2, 6, 3, 7, 4, 8 step = 4 1 3 5 7 2 4 6 8 无变化 step = 2 1 2 3 4 5 6 7 8 无变化 step = 1 退化为 插入排序 改进 Hibbard 增量 2 ** k - 1 (1, 3, 7 ... ) """ class ShellSort(Sort): ...
# -*- encoding: utf-8 -*- def shortest_distances_with_weight(start_node_name): # 计算非负权重节点的最短距离 s_with_weight = Graph() s_with_weight.add_edge(node_name="V1", son_node_names=["V2", "V4"], weights=[2, 1]) s_with_weight.add_edge(node_name="V2", son_node_names=["V4", "V5"], weights=[3, 10]) s_with_wei...
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) sorted_list = sorted(arr, reverse=True) highest = sorted_list[0] second = highest i=1 while second == highest: if sorted_list[i] < highest: second=sorted_list[i] else: i+=1 print(second)
#!/usr/bin/env python3 """ Project 2 for CS 325 Section 401, Fall 2015 Group 1 members: David Rigert, Isaiah Perrotte-Fentress, Adam McDaniel CoinChangeTimer -- Determines the running time of the algorithms implemented in project2.py """ import time # Used for timing calculations import project2 ...
'''Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target =...
class Queue: def __init__(self): self.queue = [] def push(self, x): self.queue.append(x) def pop(self): self.queue.remove(self.queue[0]) def top(self): return self.queue[0] def checkQueue(self): print (self.queue) # Tests my_queue = Queue() my_queue.push(5) my_queue.push(2) my_queue.push(9) my_queue.pop...
from TestClass import MyStack ############################################ print "Using vector constructor..." stack = MyStack() stack.push(3.2) stack.push(3.1) stack.push(3) while not stack.empty(): print stack.pop() ########################################### ########################################### print...
""" The backend script for the book library frontend. connect(), insert(), delete(), search(), update(), view() """ import sqlite3 # Create a db / connection to db def connect(): conn = sqlite3.connect("books.db") cur = conn.cursor() cur.execute( "CREATE TABLE IF NOT EXISTS book" "(" ...
import tkinter as teek # Make our window window = teek.Tk() # Our conversion function def convert(): #a = "Hello World" #print("Hello World") # Get grams_value grams_value.delete('1.0', teek.END) grams = float(e1_value.get()) * 1000 grams_value.insert(teek.END, grams) # Get pounds_value ...
a = ['a','b','c'] b = [1,2,3] for letter, number in zip(a,b): print("{0} is {1}".format(letter,number))
n = 15 for i in range (1,n+1): print (' '*(n-i) + '* '*(2*i-1)) for i in range (1,n): print (' '*(i) + '* '*(2*(n-i)-1))
#import sys for stdout import sys #print a 2-dimensional grid def printGrid(grid): for i in range(len(grid)): for j in range(len(grid[i])): sys.stdout.write('|' + str(grid[i][j]) + '|') sys.stdout.write('\n') sys.stdout.flush() return def hit(row, col): matrix[row][col]...
# Your little brother is sad, because he can not play Rittileft. So you want to # help him. # # In Rittileft, there is a stright path made of N steps. Each step have two # numbers, one on the left and one on the right. # # You can collect the points by stepping on the number, but you cannot step on # a number that is d...
def GetApples(): print("The price of an Apple is 20 pesos.") ApplesFunction = int(input("How many would you like to buy? ")) return ApplesFunction def GetOranges(): print("The price of an Orange is 25 pesos.") OrangesFunction = int(input("How many would you like to buy? ")) return OrangesFuncti...
#Pídale al usuario que ingrese un número entre 10 y 20 (inclusive). Si ingresa un número dentro de #este rango, muestra el mensaje "Gracias"; de lo contrario, muestra el mensaje "Respuesta incorrecta" num = int(input("Ingresa un numero entre 10 y 20:")) if num >= 10 and num <= 20: print("Gracias!!") else: pri...
#Pregúntele al usuario si está lloviendo y convierta su respuesta a minúsculas para que no importa en #qué caso lo escriba. Si responde "sí", pregunte si hace viento. Si responden "sí" a esta segunda pregunta, #muestre la respuesta "Hace demasiado viento para un paraguas"; de lo contrario, muestre el mensaje "Tome un...
#Pide dos números. Si el primero es mayor que el segundo, muestre primero el #segundo número y luego el primer número; de lo contrario, muestre primero #el primer número y luego el segundo. num1 = int(input("Inserta un numero:")) num2 = int(input("Inserta otro numero:")) if num1 > num2: print(num2, num1) else:...
#Pregunte con cuántas porciones de pizza comenzó el usuario y pregunte cuántas #porciones se ha comido. Calcule cuántos cortes les quedan y muestre la respuesta en un formato fácil de usar. print("CALCULADORA DE PIZZA \n*******************************************") pedazosPizza = int(input("¿Cuantos pedazos tiene la p...
""" Домашнее задание №1 Цикл while: hello_user * Напишите функцию hello_user(), которая с помощью функции input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” """ def hello_user(): while True: user_say = input('Как дела? ') if user_say == 'Хорошо': print('Отл...
''' 面向对象高级编程 使用_slots—— 正常情况下,当我们定义一个class,创建了class实例后 可以给实例绑定任何属性和方法,这就是动态语言的灵活性 ''' class Student(object): pass #给实例绑定一个属性 s=Student() s.name='Michael'#动态给实例绑定一个属性 print(s.name) #还可以给实例绑定一个方法 def set_age(self,age): self.age=age from types import MethodType s.set_age=MethodType(set_age,s) #给实例绑定一个方法 s.set_age(...
''' 多重继承 继承时面向对象编程的一个重要的方式,通过继承,子类可以扩展父类的功能 回忆一下Animal类层次的设计,假如实现以下四种动物 Dog - 狗狗; Bat - 蝙蝠; Parrot - 鹦鹉; Ostrich - 鸵鸟。 按照哺乳类华和鸟类归类 按照能跑,能飞归类 把上面两种包含进来可以设计更多 哺乳类:能跑的哺乳类,能飞的哺乳类; 鸟类:能跑的鸟类,能飞的鸟类。 如果再增加,类的数量会呈指数增长,这样设计时不行的 ''' #正确的做法是采用多重继承,首先主要的类层次仍按照哺乳类和鸟类设计 class Aniaml(object): pass #大类 class Mammal(Aniaml): ...
''' 获取对象信息 当我们拿到一个对象的引用时,如何知道这个对象是什么类型 ''' #使用type() #我们来判断对象类型,使用type()函数 #基本类型都可以用type判断 print(type(123)) print(type('str')) print(type(None)) #如果一个变量指向函数或类也可以 print(type(abs)) #type()函数返回的是什么类型,返回的是class类型 #如果要在if语句中判断,就需要比较两个变量的type类型是否相同 print(type(123)==type(456)) #判断基本类型可以直接写int,str等,但如果要判断一个对象是否时函数怎么办? #可以使用...
''' 使用@property 在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单 但是没办法检查参数,导致可以把成绩随便改 ''' #s=Student() #s.score=9999 #显然不合逻辑,为了限制score的范围,可以通过一个set_score方法来设置成绩 #通过get_score方法来获取成绩,这样在方法中可以检查参数 class Student(object): def get_score(self): return self._score def set_score(self,value): if not isinstance(value,int): ...
import turtle def draw(): window = turtle.Screen() window.bgcolor("red") nate = turtle.Turtle() nate.shape("turtle") nate.color("white") for i in range(3): nate.forward(100) nate.left(120) window.exitonclick() draw()
#! -*- coding:utf-8 -*- # 裴波娜契数列优化算法 # 建立一个数组,使用一个for循环读取,比递归调用效率明显快很多 def fib(n): if n == 1: return 1 else: temp = [1] temp.append(1) for i in range(n): temp.append(temp[i] + temp[i + 1]) return temp[n] print fib(10000)
#カントールの対関数とその逆関数 def cantor(x,y): x = int(x) y = int(y) return (x+y)*(x+y+1)//2 + y def i_cantor(n): n = int(n) s = 0 i = 0 buf = 0 while buf<n: buf+=i+1 if buf<=n: i+=1 s=buf y = n-s x = i-y return x,y print("...
def is_member(value, alist): ''' (value, list) -> bool Defines a function is_member() that takes a value (i.e. a number, string, etc.) x and a list of values a, and returns True if x is a member of a, False otherwise. (Assuming there is no built-in in operator.) ''' for item in alist: if item == value: ret...
def bottles_of_beer(): ''' (str, int) -> str Defines bottles_of_beer() function, which prints all the lyrics to "99 Bottles of Beer." The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero. ''' bob = " bottles of beer" for i in range(99, 0, -1): ...
text = raw_input("Enter text: ") punctuation = " .,?!:;-—)(]['\"\\/" for x in punctuation: text = text.lower().replace(x, '') if text == text[::-1]: print "Yes, it is a palindrome" else: print "No, it is not a palindrome"
def generate_n_chars(n, c): ''' (int, str) -> str Defines a function generate_n_chars() that takes an integer n and a character c and returns a string, n characters long, consisting only of c's. For example, generate_n_chars(5,"x") should return the string "xxxxx". (Python is unusual in that 5 * "x" that will e...
from sys import argv script, filename = argv print "We're going to rewrite %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') # opens this file explicitly in "write" mode print "Truncating ...
#!/usr/bin/python """ iterate() produces a string of digital roots and sends it to compare() compare() compares the string to the sequence. if correct, it should call iterate again to try the next set of 24 fibonacci numbers the commented out if statement in compare gives the option of stopp...
"""Contains functions and constants for building game logic.""" import prompt ATTEMPT_COUNTS = 3 def play(game): """ Create boilerplate for game. Args: game: function with particular game. """ print('Welcome to the Brain Games!') print(game.DESCRIPTION) name = prompt.string(prom...
# coding:utf-8 import tkinter from tkinter import scrolledtext from tkinter import * import tkinter.messagebox from howdoi import howdoi from translate import Translator ytm = tkinter.Tk() # 创建Tk对象 ytm.title("Howdoi@马拉松程序员") # 设置窗口标题 ytm.geometry("600x400") # 设置窗口尺寸 menubar = Menu(ytm) fmenu1 = Menu(y...
class Solution: def __init__(self, problem): self.rides = dict() self.problem = problem def write(self, filepath): vehicles = sorted(self.rides.keys(), reversed=False) with open(filepath, 'w') as f: for vehicle in vehicles: f.write(str(vehicle)) ...
# -*- coding: utf-8 -*- """ Created on Sun Oct 18 10:59:41 2020 @author: Pranav Devarinti """ # In[] Comments """ This is a multiline comment """ # Another kind of comment # In[] Variable ba = 1 # Assign to number # In[] 1 # integer int("9") #integer call "Alpha" # String str(9) # Converts to String ["A","B"] #Li...
def num_calculate(str_number): even, ood = [], [] for i in str_number: if int(i) % 2 == 0: even.append(i) else: ood.append(i) str_list = "".join([str(len(even)), str(len(ood)), str(len(even) + len(ood))]) print("str_list == %s" % str_list) return str_list d...
""" 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] """ class Solution(object): def twoSum(self, nums, target): serial = list() for i in range(le...
# This class defines a table that is a 2D rectangle that is a play area. from tkinter import * class Table: #### constructor def __init__(self, window, colour="black", net_colour="white", width=600, height=400, vertical_net=False, horizontal_net=False): self.width = wid...
kmh = int(input("Enter KM/H:")) mph = 0.6214*kmh print("Speed:",kmh,"KM/H=",mph,"MPH")
import sys from math import sqrt from math import pow # verifica se as coordenadas de inicio e fim estão em um obstaculo ou acima da dimensão def verificaObstaculo(startEnds): for posicoes in startEnds: for tupla in posicoes: if (tupla[0] > len(matriz)-1 or tupla[1] > len(matriz[0])-1): ...
#This is to simulate a 3 cable driven ghost import math import matplotlib.pyplot as plt import numpy from numpy import sqrt, dot, cross from numpy.linalg import norm import yaml #To calculate the point of the ghost [xg,yg] we will use the other points known locations and the distance of the ...
# # 14.3 案例实战 - 电影智能推荐系统 # 1.读取数据 import pandas as pd movies = pd.read_excel('电影.xlsx') movies.head() score = pd.read_excel('评分.xlsx') score.head() df = pd.merge(movies, score, on='电影编号') df.head() df.to_excel('电影推荐系统.xlsx') print(df['评分'].value_counts()) # 查看各个评分的出现的次数 import matplotlib.pyplot as plt df['评分'].hi...
#Question4: import numpy as np array = np.random.randint(100, size = 10) for i in range(0,len(array)): if (i+1)%2 == 0: array[i] = -10 print(array)
from AES import AES_encryption import os user_name=input("please input user name: ") first_name=input("please input first name: ") last_name=input("please input last name: ") grade=input("please input grade: ") key=input("please input encryption key: ") encryption=AES_encryption(key) ciphertext=encryption.encrypt_st...
# 선형회귀 : Linear Regression # 실제 weight에 따른 cost값을 찾는 것 import tensorflow as tf import matplotlib.pyplot as plt X = [1, 2, 3] Y = [1, 2, 3] W = tf.placeholder(tf.float32) # placeholder의 전달 파라미터 # placeholder( 다른 텐서를 할당 # dtype=tf.float32, 데이터 타입을 의미하며 반드시 적어야 함 # shape=None, 입력 데이터의...
import json class Write(): """Writes objects to JSON files""" def write(data, file): with open(file, 'r') as f: keys = json.load(f) keys[list(data.keys())[0]] = list(data.values())[0] with open(file, 'w') as f: f.write(json.dumps(keys, indent=2))
"""Entity, Component, and System classes.""" from abc import ABCMeta, abstractmethod import six class Entity(object): __slots__ = ("_guid",) """Encapsulation of a GUID to use in the entity database.""" def __init__(self, guid): """:param guid: globally unique identifier :type guid: :clas...
# Write a Python script to generate and print a dictionary that contains # a number (between 1 and n) in the form (x, x*x). n=int(input("enter the number :- ")) d = dict() for x in range(1,n+1): d[x]=x*x print(d)
# Count the number of occurrence of each letter in word "MISSISSIPPI". # Store count of every letter with the letter in a dictionary. a="MISSISSIPPI" new={} for i in a: if i not in new: new[i]=1 else: new[i]+=1 print(new)
opened_brackets = '([{' closed_brackets = ')]}' stack = [] def brackets_equal(opened_bracket, closed_bracket): return opened_brackets.find(opened_bracket) == closed_brackets.find(closed_bracket) def validate(string): if len(string) == 1: return False for symbol in string: if symbol in ope...
# Write a function that accepts two arguments: a name and a subject. # The function should return a String with the name and subject interpolated in. # For example: # madlib("Jenn", "science") # "Jenn's favorite subject is science." madlib("Jeff", "history") # "Jeff's favorite subject is history." # Provide default ar...
# import datetime # year_born = int(input("Enter the year you were born: ")) # now = datetime.datetime.now() # current_year = now.year # print("You are " + str(current_year - year_born) + " years old!") # If over 100, say you're old # If under 10, say you're young # If over 100 and name is "Jackie", then say "Welc...
# Write a script that takes a word as its input, and returns a dictionary containing the tally of how many times each letter in the alphabet was used in the word. word = input("Input a word: ") dictionary = {} for i in set(word): # for characters in inputted word dictionary[i] = word.count(i) # use .count to ta...
# for letter in "Giraffe Acedemy": # print(letter) # abc = ["Jeff", "Queen", "Ximo", "King"] # for letter in abc: # print(letter) # for n in range(10): # print(n) # for n in range(3, 10): # print(n) # abc = ["Jeff", "Queen", "Ximo", "King"] # print(len(abc)) # for n in range(len(abc)): # print(...
# # split example # definition = input() # 'Coin of the realm is the legal money of the country' # print() # print(definition) # print(definition.split()) # # ['Coin', 'of', 'the', 'realm', 'is', 'the', 'legal', 'money', 'of', 'the', 'country'] # print(definition.split("legal")) # # ['Coin of the realm is the ', ' ...
# list comprehension # old_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] # new_list = [] #原始需用三行寫成的程式,可改用如下寫成一行 # for x in old_list: # new_list.append(x*2) # new_list = [x for x in old_list if x % 2 == 0] #[2, 8, 34] # new_list = [x for x in old_list if x >= 8] #[8, 13, 21, 34, 5...
from src.EACore.MethodClasses.HelperTemplate import BaseHelper from random import sample, random, shuffle class ParentSelectionHelper(BaseHelper): """ This class should be safe for all representations, as it mainly relies on integer or float representations of fitness, and manages the population on the wh...
import numpy as np L = [1, 2, 3] A = np.array([1, 2, 3]) for e in L: print(e) for e in A: print(e) # Works L.append(4) # Doesn't work try: A.append(4) except: print("Can't append to numpy array.") # Works L = L + [5, 6] # Dosn't work try: A = A + [4, 5, 6] except: print("Can't append list...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Time: 2020/4/1 11:30 # Author: Hou hailun # Numpy 进阶 # Numpy数据分析问题 # 1、导入Numpy作为np,并查看版本 import numpy as np print(np.__version__) # 2、创建一维数组,创建从0到9的一维数字数组 arr = np.arange(10) print(arr) # 3、创建一个布尔数组 # 创建一个numpy数组元素值全为True(真)的数组 bool_arr = np.full(shape=(3, 3), fill_val...
a = "abhijeet" b = "abhijeet" if a == b: print("yes") else: print("no") c =13 if c%2 ==0: print("yes") else: print("no")
for i in range(3): print("i= "+str(i)) # i must be a string, otherwise an exception will be thrown j=1 while(j<6): print("j= "+str(j)) j +=1
#! /usr/bin/env python3 words_to_letter = { "alpha" : "A", "bravo" : "B", "charlie" : "C", "delta" : "D", "echo" : "E", "foxtrot" : "F", "golf" : "G", "hotel" : "H", "india" : "I", "juliett" : "J", "kilo" : "K", "lima" : "L", "mike" : "M", "november" : "N", "oscar" : "O", "papa" : "P", "quebec" : "Q", "romeo" : "R", "...
def in_it(dict, y): x = dict.get(y) return x def transform(): dict = {} d = [ ('Hendrix' , '1942'), ('Allman' , '1946'), ('King' , '1925'), ('Clapton' , '1945'), ('Johnson' , '1911'), ('Berry' , '1926'), ('Vaughan' , '1954'), ('Cooder' , '...
#coding: utf-8 n = int(raw_input()) i = 0 while(i != 6): if n % 2 != 0 : print n i += 1 n += 1
print(1) print(3+1) print(10/3) print(5%2) print(2**3) print((1+2)*(10+3)) print(36**0.5) a = 1+1.5+4 print(type(a))
import csv print('---- How to read CSV file ----') data = open('example.csv') csv_data = csv.reader(data) data_lines = list(csv_data) print(data_lines) print(f'Number of Rows in csv file : {len(data_lines)}') email_list = [] for line in data_lines[1:]: email_list.append(line[3]) print(email_list) ...
class Cylinder(): pi = 3.14 def __init__(self, height=1, radius=1): print('Calculating Cylinder volume and surface area ') self.height = height self.radius = radius def volume(self): vol = self.pi * self.radius ** 2 * self.height print(f'Volu...
import math value = math.pi print(value) width = 1 while(True): precision = int(input('Enter the number of digit want after decimal : ')) print(precision) if precision>10: break else: print(f"result: {value:{width}.{precision}}") print('Done')
''' Created on Oct 9, 2020 @author: Asus ''' print("Welcome to python world") i = 1 for i in range(1, 10): if i <= 5 : print('Smaller or equal than 5.\n'), else: print('Larger than 5.\n'),
def vol(rad): return (4/3)*(22/7)*(rad**3) radius = 2 print(f'The volume of sphere with radius {radius} is {vol(radius):1.3f}') def ran_check(num,low,high): if(num>low and num<high): print(f'{num} is in the range between {low} to {high}') else: print(f'Out of range') ra...
# The function localize takes the following arguments: # # colors: # 2D list, each entry either 'R' (for red cell) or 'G' (for green cell) # # measurements: # list of measurements taken by the robot, each entry either 'R' or 'G' # # motions: # list of actions taken by the robot, each entry of the f...
# -*- coding: utf-8 -*- """ Created on Fri May 31 16:40:36 2019 @author: Tang """ ''' 题目描述 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 ''' def solution(node): if node==None: return None if node.right: cur=node.right while cur.left: cur=c...
# -*- coding: utf-8 -*- """ Created on Tue May 28 14:37:46 2019 @author: Tang """ ''' 题目描述 输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 (注意: 在返回值的list中,数组长度大的数组靠前) ''' def solution(root,n): def dfs(root,n,res,result): res.append(root) if root and root.left==None...
# -*- coding: utf-8 -*- """ Created on Tue Jul 9 18:31:44 2019 @author: Tang """ ''' 题目描述 有一堆箱子,每个箱子宽为wi,长为di,高为hi,现在需要将箱子都堆起来,而且为了使堆起来的箱子不倒,上面的箱子的宽度和长度必须小于下面的箱子。请实现一个方法,求出能堆出的最高的高度,这里的高度即堆起来的所有箱子的高度之和。 给定三个int数组w,l,h,分别表示每个箱子宽、长和高,同时给定箱子的数目n。请返回能堆成的最高的高度。保证n小于等于500。 测试样例: [1,1,1],[1,1,1],[1,1,1] 返回:1 ''' de...
# -*- coding: utf-8 -*- """ Created on Mon May 27 14:25:58 2019 @author: Tang """ ''' 题目描述 输入一个链表,反转链表后,输出新链表的表头。 ''' def solution(head): if head==None or head.next==None: return head p1=head p2=None while p1: p3=p1.next p1.next=p2 p2=p1 p1=p3 ...
# -*- coding: utf-8 -*- """ Created on Thu May 30 15:35:33 2019 @author: Tang """ ''' 题目描述 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它 ''' def solution(s,k): if k==0: return '' return s[k%len(s...
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 15:26:53 2019 @author: Tang """ ''' 题目描述 在n个顶点的多边形上有n只蚂蚁,这些蚂蚁同时开始沿着多边形的边爬行,请求出这些蚂蚁相撞的概率。 (这里的相撞是指存在任意两只蚂蚁会相撞) 给定一个int n(3<=n<=10000),代表n边形和n只蚂蚁,请返回一个double,为相撞的概率。 测试样例: 3 返回:0.75 思路:每个蚂蚁爬行的方向都有两个,即围绕多边形顺时针爬和逆时针爬,因此n个蚂蚁爬行的方法有2^n种。 只有当所有的蚂蚁按照同一个方向爬行才能保证所有的蚂蚁...
# -*- coding: utf-8 -*- """ Created on Sun Jun 2 16:23:55 2019 @author: Tang """ ''' 题目描述 请编写一个算法,若N阶方阵中某个元素为0,则将其所在的行与列清零。 给定一个N阶方阵int[][](C++中为vector<vector><int>>)mat和矩阵的阶数n, 请返回完成操作后的int[][]方阵(C++中为vector<vector><int>>),保证n小于等于300, 矩阵中的元素为int范围内。</int></vector></int></vector> 测试样例: [[1,2,3],[0,1,2],[0,0,1]]...
# -*- coding: utf-8 -*- """ Created on Thu May 30 16:23:17 2019 @author: Tang """ ''' 题目描述 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老, 自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m, 让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物, 并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友, 可以不用表演,并且拿到牛客...
# -*- coding: utf-8 -*- """ Created on Mon May 27 14:15:17 2019 @author: Tang """ ''' 题目描述 输入一个整数数组,实现一个函数来调整该数组中数字的顺序, 使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分, 并保证奇数和奇数,偶数和偶数之间的相对位置不变 ''' def solution(a): a1=[] a2=[] for i in a: if i%2==1: a1.append(i) else: a...
# -*- coding: utf-8 -*- """ Created on Mon Jun 3 17:09:48 2019 @author: Tang """ ''' 题目描述 实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。 给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。 ''' def solution(root): def depth(root): if root==None: return 0 return 1+max(depth(...
n = int(input()) star = "*" blank = " " if n > 1: for i in range(n): answer = "" answer += blank * i answer += star * ((n * 2 - 1) - (i * 2)) print(answer) for i in range(n-2, -1, -1): answer = "" answer += blank * i answer += star * ((n * 2 - 1) - (i * ...
board = [] length = [] answer = "" idx = 0 for i in range(5): board.append(str(input())) length.append(len(board[i])) for i in range(max(length)): for j in range(5): if idx >= len(board[j]): continue else: answer += board[j][i] idx += 1 print(answer)
n = int(input()) no = 0 yes = 0 for _ in range(n): answer = int(input()) if answer == 1: yes += 1 elif answer == 0: no += 1 if yes > no: print("Junhee is cute!") else: print("Junhee is not cute!")
year = str(input()) if year[-1] == "0" and year[-2] == "0": if int(year) % 400 == 0: print("1") else: print("0") else: if int(year) % 4 == 0: print("1") else: print("0")
number = int(input("")) print("Input","Output") print(number,end="") for x in range(number): print(1*"\t"," " * (number-x-1),"*" * (((x+1)*2)-1))