text
stringlengths
37
1.41M
#Initial Password Input def passwordsetup(): from getpass import getpass as gp passmatch = False passcount = 0 passfinal = "" while not passmatch and passcount < 3: password_try1 = gp() password_try2 = gp() if password_try1 == password_try2: print "Your password has been set" passf...
#!/usr/bin/env python #-*- coding:utf-8 -*- name = "I\'m {0},age {1}" print name.format("alex",28) """ result = 'I an %s,age %s' % ('rain',27) print result """
#!/usr/bin/env python #-*- coding:utf-8 -*- #Description:This program is mainly practicing the bob sort method(冒泡算法) #实际上是一个排列组合 li = [13,22,18,33,99,15] for n in range(1,len(li)): for m in range(len(li)-n): #获取m个值 num1 = li[m] #获取m+1个值 num2 = li[m+1] if num1 > num2: #将较大的值放在右侧 temp = li[m] li[m]...
#The code was run on PYCHARM IDE on WINDOWS python version 3.x ''' Steps to recreate: 1)Open PYCHARM 2)Create a new project 3) Add a new python file and paste the code 4) Run the code ''' print("Only one test data was added 8int.txt") text=input("enter the file name excluding '.txt' extension as 8int:\n") text=text+"....
# -*- coding: utf-8 -*- # Name: Naga Venkata V Vinnakota # Netid: nvv13 # Ran on Pycharm #Submitted date: 04/17/2020 import math import random random.seed(0) # Sigmoid activation and deactivation functions def sigmoid(x): return 1.0 / (1.0 + math.exp(-x)) def desigmoid(x): return x * (1 - x) # Random ...
import time count=0 count1=0 class Node: def __init__(self): self.children = {} self.endOfWord = False def insertWord(root, word): ''' Loop through characters in a word and keep adding them at a new node, linking them together If char already in node, pass Increment the current t...
# importing the socket and datagram modules from socket import socket, AF_INET, SOCK_DGRAM # creation of socket module s = socket(AF_INET, SOCK_DGRAM) # binding it to the local host s.bind(('127.0.0.1', 8888)) # Keeps the server in listening mode forever while True: print('Waiting for the client') # saves t...
"""Module which contains shape area computation functions.""" def square_area(a): """Method which returns the area of a square.""" return a*a def rectangle_area(a, b): """Method which returns the area of a rectangle.""" return a*b def triangle_area(a, b, c): """Method which returns the area of...
"""Module which holds the Army class.""" import random class Army: """Class which holds Army methods.""" def __init__(self, name, fighters): """Initialises the name and fighter list for the army.""" self.name = name self.fighters = fighters def __str__(self): """Returns ...
def check_divisible(): """Stores in a list the elements from 1000 to 2000 which are divisible by 7 but not by 5.""" result = [] for i in range(1000, 2000): if i % 7 == 0 and i % 5 != 0: result.append(i) print("result: {}".format(result)) check_divisible()
""" Module which contains the Car thread. """ from threading import Thread import random class CarThread(Thread): """ Class which handles the baby car race. """ def __init__(self, name, target, args): """ Constructor of the CarThread class. :param name: Name of the car ...
def to_fahrenheit(): """Gets the celsius degrees from the command line, transforms it into fahrenheit and prints.""" celsius = int(input("give the temperature...")) fahrenheit = (9/5) * celsius + 32 print(fahrenheit) to_fahrenheit()
def is_leap_year(): """Takes an year given from command line and checks whether it is leap or not.""" year = int(input("give the year...")) if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): print("true") else: print("false") is_leap_year()
""" Module for cone thingy. """ from math import pi class Cone: """ Class which handles cone thingy. """ def __init__(self, radius, height): """ Constructor of the Cylinder class. :param radius: Radius of the cone. :param height: Height of the cone. """ ...
frase = input('Digite seu nome completo: ') print(len(frase[0])) num = input('Digite um número entre 0 e 9999: ') m = num[0] c = num[1] d = num[2] u = num[3] print("""Unidade: {} Dezena: {} Centena: {} Milhar: {}""".format(u, d, c, m))
pri = int(input('Primeiro termo da PA? ')) raz = int(input('Qual a razão da PA? ')) termo = pri cont = 1 total = 0 mais = 10 while mais != 0: total += mais while cont <= total: print('{} -> '.format(termo), end='') termo += raz cont += 1 print('PAUSA') mais = int(in...
geral = list() dados = list() while True: dados.append(str(input('Nome: '))) dados.append(float(input('Nota 1: '))) dados.append(float(input('Nota 2: '))) geral.append(dados[:]) dados.clear() op = str(input('Quer adicionar mais um aluno?[S/N] ')).upper() if op in 'SN': if ...
jogador = dict() partidas = list() jogador['nome'] = str(input('Nome do jogador: ')) tot = int(input(f'Quantas partidas o jogador {jogador["nome"]} jogou? ')) print('=-='*15) for c in range(tot): partidas.append(f'>>>>Quantos gols na partida {c}? ') jogador['gols'] = partidas[:] jogador['total'] = sum(parti...
maior = 0 media = 0 soma = 0 mulher = 0 for i in range(4): nome = input('Qual é o seu nome? ') idade = int(input('Qual é a sua idade? ')) sexo = input('Qual é o seu sexo?(M/F) ') soma += idade media = soma / 4 if sexo == 'M': if idade > maior: maior = idade ...
num = float(input('Digite um número: ')) print('Parte inteira do número: ',math.trunc(num))
from random import randrange jogos = list() qtdjogos = int(input('Quantos jogos serão? ')) for _ in range(qtdjogos): jogo = [randrange(1,60),randrange(1,60),randrange(1,60),randrange(1,60),randrange(1,60),randrange(1,60)] jogos.append(jogo) print('Seus jogos serão:') for num, element in enumerate(jogos):...
# Bug Collector Project # 20170625 # CTI-110 M4T1 - Bug Collector # Loraine Armenta # # Total amount of days 5 days = 5 # Total number of bugs collected in five days number_of_bugs = 0 # How many bugs were collected for todate in range(1, days + 1): bugs_collected = int (input ('How many bugs were collec...
# ft to in' # 20170704 # CTI-110 M5T2_FeetToInches # Loraine Armenta # INCHES_PER_FOOT = 12 def main (): feet = int (input ( 'Enter a number of feet: ' )) print (feet, 'equals' , feet_to_inches (feet), 'inches.') def feet_to_inches (feet): return feet * INCHES_PER_FOOT main ()
a = input('enter the name of a doctor or specialization: ') b = a.lower() import csv with open ('dr.csv','r') as csvfile: reader = csv.DictReader(csvfile) for i in reader: if b in i.values(): d = i.get('name') e = i.get('Eduction') f = i.get('Experience') h = i.get('specialist') g = i.get('fees') ...
from datetime import datetime print(datetime(1993,9,21).isocalendar()[1]-datetime(1993,9,25).isocalendar()[1]) print(datetime(1993,9,21).isocalendar()[2]-datetime(1993,9,25).isocalendar()[2]+2) def lc_calc(start='1993-09-21', date): start = datetime(start) date = datetime(date) timediff = datetime.timedelt...
# Display window # - Create main display window # - moving tiles into their own class # - create time/date bar? # - add scroll bars if not full screen # - get data from file to set up many tiles import tkinter from tiles import tile from tiles import event_tile # Display Window class Disp_Dialog: ...
import threading import Queue; import time; def test_lol(num1, num2): while(1): print(num1+num2) def sleep_func(sleep_time, name): print('Hi, I am {}. Going to sleep for {} seconds\n'.format(name, sleep_time)); print(time.localtime()); time.sleep(sleep_time); print(time.localtime()); print('{} has woken up ...
# coding:utf-8 # kaggle Jane Street Market Prediction代码 # 《深度学习入门:基于python的理论与实现》 # 第五章 误差反向传播法 import numpy as np import matplotlib.pyplot as plt import run import pandas as pd from PIL import Image import random import pickle from collections import OrderedDict # 乘法层的实现 class MulLayer: def __init__(self): ...
# coding:utf-8 # kaggle Jane Street Market Prediction代码 # 《深度学习入门:基于python的理论与实现》 # 第四章 神经网络的学习 import numpy as np import matplotlib.pyplot as plt import run import pandas as pd from PIL import Image import random import pickle # 阶跃函数 def step_function(x): """ if x > 0: return 1 else: re...
from .keywords import * from decimal import * # imported functions and constants functions = ("d", "root", "factorial", "log10", "log2", "sin", "cos", "tan", "rad", "deg") constants = ("pi", "e") # global variables for evaluation purposes variables = {} getcontext().prec = 6 def to_expr(_string): """ ret...
import pandas as pd def getURLs(): ''' Function to create a list of urls for the flightsfrom.com site for each airport. Returns: url_list -- list of urls in the form of 'flightsfrom.com/<iata code>/destinations' ''' df = pd.read_csv('airport_data.csv') iata_list = list(df['Unnamed: 0'...
""" __title__ = '' __author__ = 'Thompson' __mtime__ = '2019/1/14' # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ☃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻ ┃ ┗━┓ ┏━...
import unittest def letterCasePermutation(S): """ :type S: str :rtype: List[str] """ out = [] m = len([e for e in S if e.isalpha()]) for i in range(2 ** m): new_str = '' j = 0 for e in S: if e.isalpha(): if 2 ** j & i: ...
import unittest def findTheDifference(s, t): """ :type s: str :type t: str :rtype: str """ def letter_counts(string): d = {} for e in string: try: d[e] += 1 except: d[e] = 1 return d s_counts = letter_counts(s)...
from turtle import Turtle import random class Food(Turtle): def __init__(self): super().__init__() self.color("red") self.shape("circle") self.shapesize(stretch_wid=0.5, stretch_len=0.5) self.penup() self.speed("fastest") self.new_position() def new_pos...
#!/usr/bin/python primes = [int(prime) for prime in open("primes").readlines()] primedict = dict([(int(prime), True) for prime in primes]) nprimes = len(primes) maxprime = 0 for i in range(nprimes): sum = 0 nums = [] for j in range(i, nprimes): sum += primes[j] nums.append(primes[j]) ...
#!/usr/bin/python def factorial(n): if n <= 1: return n else: return n * factorial(n - 1) def nth_permutation(init, n): nelts = len(init) if nelts == 1: return init div = 0 nperms = factorial(nelts - 1) rem = n if nperms < n: div = n / nperms re...
#!/usr/bin/python n = 1 sum = 0 while n < 1000: if n % 3 == 0: sum += n elif n % 5 == 0: sum += n n+=1 print sum
from findBestSequence import FindBestSequence import random import sys sys.path.append("/Users/juliuside/Desktop/BWINF_Runde2/Aufgabe2") import HelperMethods as hm class Breeding: def __init__(self, a, b, num_of_seq): """ a has the better fitness """ self.a = a self....
from collections import namedtuple class Knapsack: def __init__(self, triangles, capacity): self.triangles = list(triangles) self.w = [t[0] for t in triangles] self.v = [t[1] for t in triangles] self.capacity = capacity def main(self): w = self.w v = self.v ...
import numpy as np from collections import namedtuple Triangle = namedtuple("Triangle", "smallest_angle, largest_edge, edges") class PolygonesToAngle: def __init__(self, polygones): self.polygones = polygones self.main() def main(self): """ output: the output is a ...
class FindBestSequence: def __init__(self, triangles): """ input: - triangles = list of [smallest_angle, lengths] """ self.vertex = [] self.triangles = list(triangles) self.len = len(triangles) @property def finalSequence(self): LIMIT = 180 ...
text = input("Enter your comment\n") if("make a lot of money"in text): spam = True elif("buy this"in text): spam = True elif("subscribe this"in text): spam = True if("click this"in text): spam = True else: spam = False if(spam): print("This comment is a spam") else: print("This comment is ...
a = input("Enter the number :") a = int(a) b = a*a print("The square of the number is ", b)
__author__ = 'Liam' from random import randrange from room import * class Player: """The Player object, with associated variables and methods. This is you! """ def __init__(self, location): """When initialising the character, we'll later give the player the choice of a name and spirit an...
# -*- coding: utf-8 -*- """ Created on Fri Mar 6 19:41:44 2020 @author: baotr """ class Graph(object): def __init__(self, graph_dict=None): if graph_dict == None: graph_dict={} self.graph_dict=graph_dict def neighbors(self, node): return self.graph_dict[...
""" 使用列表推导式写下面这个算法题 给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。 • 示例 1: 输入:[-4,-1,0,3,10] 输出:[0,1,9,16,100] • 示例 2: 输入:[-7,-3,2,3,11] 输出:[4,9,9,49,121] • 提示: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A 已按非递减顺序排序。 """ # 列表推导式,sorted()表示对列表推导出来的结果进行排序 list_a = [-7, -3, 2, 3, 11, -4, -1, 0, 3, 10, -10000, 10000]...
from pilas import Stack def suma_lista_rec(lista): if len(lista)==1: return lista[0] else: return lista.pop()+suma_lista_rec(lista) def cuenta_regresiva(n): if n ==0: return n else : print(n) print("----") return cuenta_regresiva(n-1) def eliminar_medio(p...
# https://leetcode.com/contest/weekly-contest-183/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/ # If the current number is even, you have to divide it by 2. # If the current number is odd, you have to add 1 to it. s = "1101" # to convert into decimal dec,cnt = int(s,2),0 whil...
# It is a tree-like structure where each node represents a single character of a given string. # And unlike binary trees, a node may have more than two children. class Trienode(object): def __init__(self, char): self.char = char self.children=[] # Is it the last character of the word...
from collections import deque class Node: def __init__(self, data): self.data = data self.left = None self.right = None def levelorder(root): # Create a empty queue for level order traversal queue = deque() queue.append(root) while queue: # Get the first data fr...
#The distance value is defined as the number of elements arr1[i] # such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d. # https://leetcode.com/contest/biweekly-contest-22/problems/find-the-distance-value-between-two-arrays/ # Complexity : n^2 # Difficulty : Easy # Naive Approach (two loops) arr1...
# Spanning tree: That connect all vertices together # MST: That connect all vertices with minimum weight # If there are V -> vertices in graph # Than there are V-1 edges in MST """ Algorithm 1. Sort all edges according to their weight 2. Pick smallest weight edge check if it form cycle 2.1 If cycle then discard ...
# @Date: 2020-05-02T16:43:47+05:30 # @Last modified time: 2020-05-02T16:47:26+05:30 # The goal in this problem is to count the number of inversions of a given sequence def merge(a, b, left, mid, right): # Let i is used for indexing the left sublist and j for the right sublist. # At any step in the merge pr...
class Node: def __init__ (self, data): self.head = None self.data = data class Linkedlist: def __init__(self): self.head = None def push(self, data): newnode = Node(data) newnode.next = self.head self.head = newnode def printlist(self): ...
# Approach # (i) We use a counter to count the occurance of letters in our given word # (ii) We get the run the loop times len(text)-len(word) # (iii) We match the counter of words from this loop and match with previous counter from collections import Counter p = int(input()) while p: t = input() w = input(...
# Task : Return no. as sum of two prime numbers # Approach : (i)To find all position of prime numbers in whole range using sieve of eratos # (ii) Rup loop to half of numbers and get those numbers whole sum is 2 in prev stored array arr = [1]*10001 for i in range(2,len(arr)): if arr[i]==1: f...
for _ in range(int(input())): s = list(input()) flag = 0 # to keep track of opening brackets stack = [] # Hashmap for keeping track of mappings mappings = {"]":"[", "}":"{", ")":"("} for char in s: # if character is closing bracket if char in mapping...
arr = ["cat", "dog", "tac", "god", "act"] def all_ana(arr): words = [''.join(sorted(i)) for i in arr] dct = {} for n, i in enumerate(words): if i in dct: dct[i].append(n) else: dct[i] = [n] print([[arr[i] for i in lst] for lst in dct.values()]) all_ana(arr) ...
# @Date: 2020-04-30T17:20:23+05:30 # @Last modified time: 2020-04-30T17:29:52+05:30 # https://leetcode.com/problems/largest-number/ # Given a list of non negative integers, arrange them such that they form the largest number. # Approach (Libarary Fuction) from functools import cmp_to_key as cmp nums = [3,30,34,5,9...
# Given an array of positive integers. Your task is to find the leaders in the array. # Note: An element of array is leader if it is greater than or equal to all the elements to its right side. # Also, the rightmost element is always a leader. for i in range(int(input())): n = int(input()) lst = list(ma...
# Check that the same number is not present in the current row, current column and current 3X3 subgrid # After checking for safety, assign the number, and recursively check whether this assignment leads to a solution or not # If the assignment doesn’t lead to a solution, then try the next number for the current empty c...
# Problem is to find prime numbers that are in arrays pf numbers t = int(input()) arr = list(map(int,input().split())) for j in arr: d,primes=[],[] for i in range(2,j+1): if i not in d: primes.append(i) for i in range(i*i,j-1,2): d.append(i) print(list(set(p...
# The idea is to use a queue to store only the left child of current node. # After printing the data of current node make the current node to its right child, if present. # A delimiter NULL is used to mark the starting of next diagonal. from collections import deque class Node: def __init__(self, data): ...
# <left subtree> <root> <right subtree> # Create an empty stack s # Initialize current node as root # Push current node to S and set curr=curr->left # If curr is NULL and stack is not empty # (i) Pop the top and print # (ii) Set curr = popped->right # If curr is NULL and stack is empty class Node: def __init...
# Leftmost Column with at Least a One # https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/530/week-3/3306/ binaryMatrix = [[0,0],[0,1]] #n, m = len(binaryMatrix), len(binaryMatrix[0]) n, m = binaryMatrix.dimensions() row = 0 col = m-1 # last column where we found 1, default case is -1 l...
# @Date: 2020-04-04T13:30:44+05:30 # @Last modified time: 2020-04-30T17:10:42+05:30 # Maximum subarray (Dp Problem) # https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3285/ # Given an integer array nums, find the contiguous subarray # which has the largest sum and return its sum. ...
Pick_a_number = input("pick a number: ") def character_name(): char_name = input("Please enter your name: ") print(f"Hello {char_name}. Welocme to the game.") if(Pick_a_number == "5"): character_name() else: print("You did not pick the right number.") character_name() ...
""" Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. ...
""" This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it? Design a class which receives a list of words in the constructor, and implements a method that takes t...
""" Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. Credits: Special thanks to @jianchao.li.fighter for adding this problem and creatin...
""" The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the fil...
# # @lc app=leetcode id=20 lang=python3 # # [20] Valid Parentheses # # https://leetcode.com/problems/valid-parentheses/description/ # # algorithms # Easy (38.24%) # Likes: 4571 # Dislikes: 207 # Total Accepted: 936.3K # Total Submissions: 2.4M # Testcase Example: '"()"' # # Given a string containing just the cha...
# Generates a list of prime numbers value = int(input("Enter a value: ")) values = list(range(2, value + 1)) print(f"Input: {values}") for i in values: for j in values: if j > i and j % i == 0: values.remove(j) print(f"Result: {values}")
year_str = input('あなたの生まれの年を西暦で入力してください: ') # タプル型・変更できない eto_tuple = ("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥") year = int(year_str) num_of_eto = (year + 8) % 12 # print('あなたの干支は', eto_tuple[num_of_eto], 'です。', sep='===') eto_name = eto_tuple[num_of_eto] print('あなたの干支は{}です。'.format(eto_name))
import random #importing random to allow random gneration of word from list. HANGMANPICS = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | ...
import copy class const: SHEEP_DEFENSE = 1000 SHEEP_MANA = 1000 BOAR_DEFENSE = 2000 BOAR_MANA = 500 SEAL_DEFENSE = 1500 SEAL_MANA = 750 class BeastPrototype: _defense = None _mana = None def clone(self): pass def getDefense(self): return self._defense def getMana(self): return self._mana cla...
#!/usr/bin/python3 """Amenity Model Unit tests""" import unittest import datetime from models.base_model import BaseModel from models.amenity import Amenity class TestAmenity(unittest.TestCase): """Test normal base instantiation""" def test_Amenity(self): # Tests values after creating Base Model ...
#3장 1번 ##chi=2 ##pig=4 ##cow=3 ##leg=(chi*2)+(pig*4)+(cow*4) ##print("닭의 수: " ,chi) ##print("돼지의 수: " ,pig) ##print("소의 수: " ,cow) ##print("전체 다리의 수 :",leg) #3장 2번 ##x1=int(input("x1:")) ##y1=int(input("y1:")) ##x2=int(input("x2:")) ##y2=int(input("y2:")) ##result=(((x2-x1)**2)+((y2-y1)**2))**0....
# ch07 추가 연습문제 2번 import random values=[] for i in range(5): values.append(random.randint(1,20)) print(values) for j in range(5): print(str(values[j])+"\t\t"+'*'*int(values[j]))
print("hello world") message = "hellow world python" message = message + "nihao" print(message) name = 'wang "shuai"' address = "shanxi" print(name.title()) print(name.upper()) print("\n"+name + "\t"+address) trim = " polunzi " print(trim + name) print(trim.rstrip() + name) print(trim + name) print(3*0.1) ...
wangshuai = {'age': 20, 'city':"beijing"} print(wangshuai['age']) wangshuai['sex']= 'male' print(wangshuai) wangshuai['age'] = 25 print(wangshuai) #del wangshuai['age'] #print(wangshuai) for k,v in wangshuai.items() : print(k + "=======>" + str(v) + "\n") users = { 'wangshuai': {'age': 25, 'sex': 'male', 'la...
import pygame from pygame.sprite import Sprite class Ship(Sprite): #init a ship to the screen def __init__(self, screen, setting): super().__init__() self.screen = screen self.image = pygame.image.load("images/alien.jpg") # rect == Rectangle (chang fang xing) self.rect = self.image.get_rect() self.screen...
arr = [1,2,3,4,5] for num in arr: print(num) nums = [] for value in range(1, 5): print(value) nums.append(value * value) print(nums) # form 1(default 0) to 20 (required)increase 3(default 1) everytime for value in range(1, 20, 3): print(value) test_list = list(range(1,10)) print(test_list) print(max(test_list)...
#!usr/bin/env python3 # -*- coding: utf-8 -*- ' Queue Reconstruction by Height - Medium ' __author__ = 'Roger Cui' ''' Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'Complex Number Multiplication - medium' __author__ = 'Roger Cui' ''' Given two strings representing two complex numbers. You need to return a string representing their multiplication. Note i2 = -1 according to the definition. Example 1: Input: "1+1i", "1+1i" Output: "...
#!usr/bin/env python3 # -*- coding: utf-8 -*- ' Maximum Depth of Binary Tree - easy ' __author__ = 'Roger Cui' ''' Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Results: Run time: 59ms, beats 48.11%...
#!usr/bin/env python3 # -*- coding: utf-8 -*- ' Maximum Binary Tree - Medium ' __author__ = 'Roger Cui' ''' Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left ...
#EXAMPLE 1 """ a=23 b=23 if a > b: print("A is Greater than B") elif a==b: #---Otherwise print("A is Equal to B") else: print("A is Less than B") """ # EXAMPLE 2: x=39 if x==23: print("X is 23") elif x==36: print("X is 36") else: print("X is not 36")...
# 参数默认值 def f1(a, b=5, c=10): return a + b * 2 + c * 3 print(f1(1, 2, 3)) print(f1(100, 200)) print(f1(100)) print(f1(c=2, b=3, a=1)) # 可变参数 def f2(*args): sum = 0 for num in args: sum += num return sum print(f2(1, 2, 3)) print(f2(1, 2, 3, 4, 5)) print(f2()) # 关键字...
#!/usr/bin/env python from __future__ import print_function import argparse import sys if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('input_file', type=argparse.FileType()) parser.add_argument('output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout) ...
#!/usr/bin/env python """Calculate scores for Heinz. This script transform a p-value into a score: 1. Use alpha and lambda to calculate a threshold P-value. 2. Calculate a score based on each P-value by alpha and the threshold. For more details, please refer to the paper doi:10.1093/bioinformatics/btn161 Inp...
# -*- coding: utf-8 -*- """ Simple Span Beam Design Author: Margaret Wang This program is developed to design a beam for the geometry and loading provided by a user. Design uses LRFD factors in calculating capacity and loading requirements. The shape database used is limited to W shapes. For this design, gravity loa...
# Standard widget used to input and/or output a single line of text # To enter multiple lines, use the Text widget from tkinter import * master = Tk() e = Entry(master) e.pack() # To add text, use insert, but first use a delete to replace current text # e.delete(0, END) e.insert(0, 'a default value') # To fetch the ...
# Labels are used to display text and images # Uses double buffering, so it can be updated at any time without pesky flickering # To display data for users to manipulate, one may wish to consider Canvas widgets # # To use a label, just specify what to display in it (text, bitmap, or image) from tkinter import * from PI...
# Creates an entry widget, and a button that prints the current contents from tkinter import * master = Tk() e = Entry(master) e.pack() e.focus_set() # This sets the cursor to start here? def callback(): print(e.get()) b = Button(master, text='get', width=10, command=callback) b.pack() mainloop() e = Ent...
print("Введите 3 целых числа: ") a = int(input ("А: ")) b = int(input ("Б: ")) c = int(input ("B: ")) while a<b: print((a), "Пока что нет") a=int(a + c) if a>b: print("Дождались",(a))
print("Загадай два числа") a=int(input ("a= ")) b=int(input ("b= ")) if a==b: print (int(a)) elif a>b: print("Разница чисел =",int(a-b)) else: print("Сумма чисел =", int(a+b))
import json import string #get the food_name_dataset from Vasily #food_name_dataset is the food name #do the demo data for a popular restaurant nearby here with a lot of review on yelp def remove_punctuation(word = " "): "Remove punctuation from a word if there is punctuation at the end" punct = set(st...
#!/usr/bin/env python # START STUDENT CODE HW32CFREQMAPPER import re import sys # input here is p32c_results.txt # read from standard input for line in sys.stdin: line = line.strip().lower() words = line.split() for word in words: if word[0]< "f": print '%s\t%s\t%s' % ("A",word, 1) ...