text
stringlengths
37
1.41M
# Name: David Espinola #Date: March, 20, 2019 #Description: Question 1 import math for i in range(30,41):#iterate over numbers 30 through 40 inclusive print("Number is "+str(i)+" square root is = "+str(math.sqrt(i)))#print number and its square root # Name: David Espinola #Date: March, 20, 2019 #Description: Ques...
# Name: David Espinola #Date: April 21, 2019 #Description: Challenge 2- You are given a feature class called parcels.shp located in the Exercise12 folder that contains the following fields: #FID, Shape, Landuse and Value. Modify the parceltax.py script so that it determines the property tax for each parcel and stores t...
#Class exercise 1 ##a=[1,4,8,12] ##b=20 ##for i in range(len(a)): ## if b-a[i] in a: ## print "here is i",i,"here is b",b,"difference will be",b-a[i] ## ## ## ##for i in range(1,29): ## if math.sqrt(i)%1==0: ## print "this is i {0} and this is sqrt {1}".format(i,math.sqrt(i)) ###Class exe...
day = "monday" temp = 20 raining = False if day == "monday" and temp > 10 and not raining: print("Take a trip") else: print("Sit home and learn 'Python'") if 0: # this will always execute the false value print("True") else: print("False") name = input("Enter your name") #if you enter...
i = 0 while i < 10: print("New Value of i is{}".format(i)) i = i+1 print(i) for i in range(0, 100, 7): print(i) if i>0 and i% 11 == 0: break
#ex1 # name = input("What is your name? \n") # print("Hello, %s" % name) #ex2 # name = input("What is your name? \n") # length = len(name) # print("Hello, %s" % name.upper()) # print("Your name has " + str(length) + " letters in it! Awesome!") #ex3 # print("Please fill in the blanks below:") # name = input("Enter a n...
anakin_mc_count = 20421 yoda_mc_count = 19632 c3po_mc_count = 0 print(anakin_mc_count > 20000) print(anakin_mc_count < yoda_mc_count) print(anakin_mc_count >= 1000) # greater than, less than, or greater/less than equal to print(0 == c3po_mc_count) # order does not matter - so 0 or c3po_mc_count can flip flop print...
from random import randint class StackOfPlates: def __init__(self,size=10): self.size = size self.stack = [[0] * self.size] self.top_index = -1 def push(self,item): self.top_index += 1 if (self.top_index + 1) > (len(self.stack) * self.size): self.stack.a...
from collections import defaultdict class Graph: def __init__(self,vertices): self.v = vertices self.graph = defaultdict(list) def add_edge(self,a,b): self.graph[a].append(b) def is_reachable(self,a,b): visited = [a] next_nodes = [a] while(len(next...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
import random def create_card(suit, val): card = (suit, val) return card def create_deck(): deck = [] for suit in range(1, 3): for val in range(1, 14): deck.append(create_card(suit, val)) deck.append(("A", "J")) deck.append(("B", "J")) return deck def insert_card(car...
from functools import total_ordering from datetime import datetime @total_ordering class User(): ''' This is a class. Every class has to have a __init__ method that instantiates the object. ''' ''' The 'self' is required to be in every method a class has. 'self' has to do with referencing this object. ...
country = str(input('請問您的國家是?')) if country == '台灣' or country == 'Taiwan' : age = int(input('輸入年齡')) if age >= 18: print('你可以考駕照') else: print('你還不能考駕照') print('還差' , 18-age,'歲') elif country == '美國' or country =='USA': age = int(input('輸入年齡')) if age >= 16: prin...
#1write a programme to find maximum between five number a=int(input("enter number a:")); b=int(input("enter number b:")); c=int(input("enter number c:")); d=int(input("enter number d:")); e=int(input("enter number e:")); if a>b and a>c and a>d and a>e: print("the maximum number is",a); elif b>a and b>c and b>d and...
import sys from linked_list import * #import array_list # A Song consists of: # - title is a str # - artist is a str # - album is a str class Song: def __init__(self,number,title,artist,album): self.number = number self.title = title self.artist = artist self.album = album def __repr__(...
#ingresamos los 3 numeros y los ponemos en una lista print ("Vamos a encontrar el mayor de los numeros ingresados") ListadoNumeros=[] for x in range (3): Numero=int(input("Ingrese un número:")) ListadoNumeros.append(Numero) #imprimimos el mayor del listado print(f'El numero mayor es {max(ListadoN...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: def merge2(l1: ListNode, l2: ListNode) -> ListNode: start = ListNode(No...
class Solution: def isHappy(self, n: int) -> bool: def squarify(n: int): digits = map(int, str(n)) squared = [d**2 for d in digits] return sum(squared) results = set([n]) # Cache the attractor state results.update([2, 4, 16, 37, 58, 89, 145, 42, 2...
"""3- Ingresar una oración que pueden tener letras tanto en mayúsculas como minúsculas. Contar la cantidad de vocales. """ oracion = input("Ingrese una oracion: ") vocales = "aeiouAEIOU" contador = 0 for i
""" 4- Crear dos lista paralelas y almacenar los nombres de n países y su población. Ordenar de mayor a menor por cantidad de habitantes la lista e imprimirla. """ cantidad = int(input("Ingrese cantidad de paises: ")) x = 0 paises = [] poblaciones = [] for x in range(cantidad): pais = input("Ingrese país: ") ...
#!/usr/bin/env python #title :Monty Hall with Monte Carlo #description :This script uses Monte Carlo simulation on Monty Hall problem # to determine the answer to the Monty Hall problem #author : Samir Madhavan #website : https://www.samirmadhavan.com #date :201...
# Write a function that returns the sum of multiples of 3 and 5 # between 0 and limit (parameter). For example, if limit is 20, # it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20. def sum_of_multiples(limit): sum = 0 sum_str = "" for number in range(limit + 1): if number % 3 == 0 or numb...
import random for i in range(3): print(random.random()) print(random.randint(10, 30)) members = ["Pradeep", "Sandeep", "Swetha"] leader = random.choice(members) print(leader)
# Range is a complex type and # which is iterable used in for loops # Strings can also be iterable print(type(5)) print(type(range(5))) # String Iterable for letter in "Python": print(letter) # List Iterables for number in [1, 2, 3, 4]: print(number) # Custom Objects
# numbers = [5, 2, 5, 2, 2] # xxxxxx # xx # xxxxxx # xx # xx # print L numbers = [5, 2, 5, 2, 2] for x in numbers: output = '' for y in range(x): output += 'x' print(output)
def square(number): return number * number result = square(3) print(result) print(square(3)) # By default all functions in Python returns None # We can change that by using return statement def qube(numbers): print(numbers * numbers * numbers) print(qube(3))
numbers = [1, 5, 3, 8, 2, 7, 2] max = 0 for number in numbers: if number >= max: max = number print(f'Max number : {max}')
course = 'Python for Beginners' print(len(course)) # len() - built in function for calculating number of characters in string
temparature = 15 if temparature > 30: print("It's warm") print("Drink Water") elif temparature > 20: print("It's nice") else: print("It's cold") print("Done") age = 22 # if age >= 18: # print("Eligible") # else: # print("Not Eligible") message = "Eligible" if age >= 18 else "Not Eligible" # T...
# Two - Dimensional list is a list where each item in that list is another list matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix) # to get the first item from the matrix print(matrix[0][0]) # 1 # to get second row second element print(matrix[1][1]) # 5 # We can also assign a new value to it ma...
high_income = False good_credit = True student = False # AND Operator if high_income and good_credit: print("Eligible") else: print("Not Eligible") # OR Operator if high_income or good_credit: print("Eligible") else: print("Not Eligible") # NOT Operator if not student: print("Eligible") else: ...
# Formatted strings are useful in situation where we want to dynamically generate some text with variables first_name = 'Sandeep' last_name = 'Varma' # message = first_name + ' [' + last_name + '] is a coder' - hard to visualize the output message = f'{first_name} [{last_name}] is a coder' print(message) # Formatted ...
message = input("> ") words = message.split(' ') print(words) emoji_map = { ':)': '🌝', ':(': '😟', ':|': '😑' } # using string.replace method # for emoji in emoji_map: # message = message.replace(emoji, emoji_map.get(emoji)) # print(message) output = '' for word in words: output += emoji_map....
personas = int(input( "personas: ")) #Aqui verificamos que la cantidad sea mayor a 0 si no, no tiene sentido pedir nada while personas > 0: #Le pedimos el nombre y lo guardamos en un input n = input("Su nombre por favor: ") e = int(input("Su edad en años por favor: ")) #como la altura es en...
import random class Card(object): """this class represents a set Card""" def __init__( self, color, number, shape, fill ): self.color = color self.number = number self.shape = shape self.fill = fill def __repr__(self): return "<" + self.color + str(self.number) + self.shape + str(self.fill) + ">" pass ...
# -*- coding: utf-8 -*- """ Created on Tue Jan 15 15:49:18 2019 @author: Student mct """ number = 0 while number < 5: print('Yo Yo') number = number + 1
""" @author: Wei Wei wei0496@bu.edu BUID:U85731466 """ import numpy as np import matplotlib.pyplot as plt class NeuralNet: """ This class implements a simple 3 layer neural network. """ def __init__(self, input_dim, output_dim, epsilon): """ Initializes the parameters of the neura...
import sys import math max_speed=0 light_count = 0 lights=[] def get_input(): global max_speed global light_count global lights max_speed = int(input()) light_count = int(input()) for i in range(light_count): distance, duration = [int(j) for j in input().split()] lights.appen...
""" Find the diagonal diff in a matrix https://www.hackerrank.com/challenges/diagonal-difference """ #!/bin/python3 import sys n = int(input().strip()) a = [] for a_i in range(n): a_t = [int(a_temp) for a_temp in input().strip().split(' ')] a.append(a_t) leftSum = 0 rightSum = 0 for i, list in enumerate(a): ...
stack = [] postfix = "" lastItem = "" def pref(char): if char in ["+", "-"]: return 1 elif char in ["*", "/"]: return 2 elif char == "^": return 3 else: return -1 def infix_to_postfix(equation): """ Covert infix equation to postfix equation :param equation...
#Score #this code will lead to an error score_total = 0 score = input("Enter your score: ") #here we are trying to add an integer and a string #the error is: #TypeError: unsupported operand type(s) for +=: 'int' and 'str' score_total += score
# ****************************************************************** # * * # * * # * Example Python program that receives data from an Arduino * # * ...
# -*- coding: utf-8 -*- ''' 题目: 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? ''' import math num = 1 while True: sqrt_100 = math.sqrt(num + 100) sqrt_268 = math.sqrt(num + 268) a = sqrt_100 - int(sqrt_100) b = sqrt_268 - int(sqrt_268) if a == 0 and b == 0: print(num) break el...
# -*- coding: utf-8 -*- ''' 题目: 对于一个整数X,定义操作rev(X)为将X按数位翻转过来,并且去除掉前导0。例如: 如果 X = 123,则rev(X) = 321; 如果 X = 100,则rev(X) = 1. 现在给出整数x和y,要求rev(rev(x) + rev(y))为多少? ''' def rev_str(str): return str[::-1] def rev_str2(str): if str == '': return str else: return rev_str2(str[1:]) + str[0] d...
from new_users_class import * from functions import * open_print('names.txt') choose_user = int(input('Which user to you want to use')) - 1 user_list[choose_user].user_info() # while True: # # option = input('What would you like to do?\n 1.Print Text File \n 2.Create new user file\n') # if option == '1'...
# Python 3.x import re # PART 1 def Input(day): "Open this day's input file." filename = './input_files/input{}.txt'.format(day) return open(filename) def is_passphrase(words): """do these words are a valid passphrase ? (no duplicate words)""" return len(words) == len(set(words)) assert is_p...
import re def Input(day): "Open this day's input file." filename = './input_files/input{}.txt'.format(day) return open(filename) def parse_words(text): "All the words in text" return re.findall(r'\w+', text) def parse_numbers(text): "All the numbers in text" return [int(x) for x in re....
#! /usr/bin/env python3 import re #Getting all the countries. #Starts with an A = ^A #Followed by any characters = .+ #Ends with an a = a$ print(re.search(r"^A.+a$", "Alemania")) print(re.search(r"^A.+a$", "Azerbaijan")) print(re.search(r"^A.+a$", "Australia")) pattern = r"^[a-zA-Z_][a-zA-Z0-9_]*$" print(re.search(...
#!/usr/bin/env python3 import os #In Linux and MacOS, the portions of a file are split using a forward slash (/) #On Windows, they're splt using a backslash (\) dir = "First_week" for name in os.listdir(dir): fullname = os.path.join(dir, name) if os.path.isdir(fullname): print("{} is a directory".form...
#Print a 5x5 square of * characters #setup side = 5 y = 0 #Code to make it work while(y < side): x = 0 while(x < side): x = x + 1 print('*', end = ' ') y = y + 1 print('') #end
#the purpose of this program is to help me find trouble spots in my writing class SecondDrafting: def __init__(self, text): self._text = text def check_repetition(self, text): word_list = [] common_word_list = ['and', 'the', 'or', 'is', 'of', 'was', 'if', 'her', 'hers', 'she', ...
stuff = raw_input("do you want the flag? ") if stuff.strip() == "yes": with open("flag", "rb") as f: flag = f.read() print "here you go:", flag else: print "ok, bye"
''' Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24hr digital clock? The program should print two numbers: the number of hours(between0 and 23) and the number of minutes(between 0 and 59). For example, if N = 150, then 150 minutes have ...
""" File: reflection.py ---------------- Take an image. Generate a new image with twice the height. The top half of the image is the same as the original. The bottom half is the mirror reflection of the top half. """ # The line below imports SimpleImage for use here # Its depends on the Pillow package being installed...
from simpleimage import SimpleImage from images import stop def main(pic): image = SimpleImage(pic) bordered_img = add_border(image, 10) bordered_img.show() def add_border(original_img, border_size): """ This function returns a new SimpleImage which is the same as original image except with a...
from simpleimage import SimpleImage from images import beach BRIGHT_PIXEL_THRESHOLD = 153 def main(pic): image = SimpleImage(pic) for pixel in image: pixel_average = get_pixel_average(pixel) if pixel_average > BRIGHT_PIXEL_THRESHOLD: convert_to_grayscale(pixel, pixel_average) #...
''' Determine if a string is a palindrome ''' def isPalindrome(str): left = 0 right = len(str) - 1 while left < right: while not str[left].isalpha(): left += 1 while not str[right].isalpha(): right -= 1 if str[left].lower() != str[right].lower(): return False left += 1 right -= 1 return T...
import random ''' random.randint(min, max) #random INTEGER inclusive random.random() # Random FLOAT between 0 and 1 random.uniform(min, max) # Random FLOAT between min and max random.seed(x) # Sets seed of generator to X ''' NUM_SIDES = 6 def main(): die1 = random.randint(1,NUM_SIDES) die2 = random.randint(1,NU...
import math """ math.pi math.e math.sqrt math.exp => e ^ x math.log => log_e (x) """ print(math.pi) def main(): print("This program returns the square root of a num") num = float( input('Enter a number:')) root = math.sqrt(num) print('The square root of', num, 'is', root) main()
# https://www.hackerrank.com/challenges/python-string-split-and-join/problem # The answer wants a split and then join with characters, but replace() is much # easier to read answer. def spaces_to_dashes(string): return string.replace(" ", "-")
# https://www.hackerrank.com/challenges/whats-your-name/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen # Used string concatenation since it is inline and allows for more natural # reading. There are other instances formatting would be a better solution # a is the first name, b is the last name def prin...
""" This file contains the implementation of the Newton-Cotes rules """ import numpy as np def rectangle(x, f): """ Compute a 1D definite integral using the rectangle (midpoint) rule Parameters ---------- f : function User defined function. x : numpy array Integration domain. ...
color = input("Enter a color: ") plural_noun = input("Enter a plural noun: ") celebrity = input("Enter a celebrity: ") print("Flower are " + color) print(plural_noun + "are cute") print("I love celebrity " + celebrity)
n=int(input()) if n>=0: tot=sum(range(0,n+1)) avg=(n+1)/2 print('total: %d \n average: %f'%(tot,avg)) else: print('try again')
# The script is parsing the "output.xml"-file and printing out the ports mode. # I.e whether they are input or output. # # N.B! At startup all ports are by default declared as input. If the user does not # declare the port as input this will not show up in the list. # Now, reading and understanding the inner details o...
#print max and min element of a set Set = {1, 2, 6, 4, 9, 12, 25} #max element in set print("MAX: "+str(max(Set))) #min element in set print("MIN: "+str(min(Set)))
#print the repeated element in tuple #entered numbers are 1, 2, 3, 4, 5, 6, 7, 8 and 1 3 5 are the repeated element Tuple = (1,3,5,7,2,4,3,5,8,6,5,3,1) for i in Tuple: if Tuple.count(i) > 1: print('REPEATED %d' %i)
string = input() print("normal string") print(string) splitstr = string.split(" ") #this will split the string where it find space in string print("after splitting result string:") print(splitstr) joinstr = "-".join(splitstr) # this will join the splitted string splitstr joining by - symbol print("after joining the ...
score = raw_input("Enter Score: ") score=float(score) if score > 1.0: print "Error, score must be between 0 and 1.0" elif score >= 0.9: print "A" elif score >= 0.8: print "B" elif score >= 0.7: print "C" elif score >= 0.6: print "D" elif score >= 0.0: print "F" elif score < 0.0: print "Error, score m...
#!/usr/bin/env python # coding: utf-8 # In[2]: import pandas as pd from pandas import DataFrame Data = pd.read_csv('Data\Health.csv') df = DataFrame(Data,columns=['country','year','status','life_expectancy','alcohol','percentage_expenditure','measles','bmi','polio','total_expenditure','gdp','population','schooli...
import os import sys import argparse import numpy as np import matplotlib.pyplot as plt from neural_nets.models import FNN class FeedbackAlignment(FNN): """ Lillicrap, Timothy P., et al. Random synaptic feedback weights support error backpropagation for deep learning. Nature communications 7 (2016): 13276."...
v=1 p=0 k="yes" n="no" o=input("Enter your name: \t") print("\n\nHi !",o,"welcome to kishore's calculator") def addition(): print("addition") print("\n\nenter number [0] to stop addtion") b=int(input("\n\nenter a first number to add : \t")) c=int(input("\n\nenter a second numbe...
from entidades_auxiliares import * import math """ Modulo responsavel por agrupar as classes que representam entidades eletrizadas """ class CargaPontual(object): """ Classe representando uma carga pontual """ def __init__(self, carga, posicao): """ Metodo construtor da classe. Assume que o param...
import pygame class GameText(): def __init__(self): """ Initialize a new text instance. This handles any global game text, game scores, as well as menu text. """ # Game surface self.surface = pygame.display.get_surface() # Sprites self.msg_start ...
''' Health Management System ''' def getdate(): import datetime return datetime.datetime.now() getdate() CLient_1, CLient_2, CLient_3 = "Harry", "Rahul" , "Hammad" print("Hello") print("Enter CLient name YOu want to access") print(CLient_1, CLient_2, CLient_3) print("Press 1 for Harry\nPress 2 for Rahul\nPress ...
dict = {"Jordan" : 1, "Michael" : 2} print "Student id of Jordan is: " , dict['Jordan'] print "Student id of Michael is: ", dict["Michael"]
""" Name: Karlee Gibson Date: 28/08/16 Brief program details: Shopping List 2.0 Create a Graphical User Interface (GUI) version of the program made in assignment 1, using Python 3 and the Kivy toolkit. The program will help build skills on using classe...
#Faça um programa em PYTHON que receba um conjunto de valores numéricose que calcule e mostre o #maior e o menor valor do conjunto. Considere quepara encerrar a entrada de dados deve ser digitado o valor zero Lista_valores = [] cond = True while cond == True: valor = float(input('Digite um valor: ')) i...
# -------------------------------------------------------------------------- # Biblioteca contendo as funções para geração e impressão # das cartelas de bingo # -------------------------------------------------------------------------- import random # -----------------------------------------------------------...
# The Role of this file is to add a well-named section to the webpage. #The basic structure is: #1. The user invokes this python script #2. The script asks the about the name of the section #3. The script asks the user about where the section will be added #4. Script creates a well formed section #5. Script inserts th...
#2. import numpy numbers=input().split() lis=list(map(int,numbers)) array=numpy.array(lis) print (numpy.reshape(array,(3,3))) #3. import numpy as np N,M=map(int,input().split()) array=np.array([input().split() for i in range(N)],dtype=int) #List Comprehension to Create a Numpy Array print (array.transpose()) print (...
class Node: def __init__(self, car, number, left=None, right=None): self.car = car self.num = number self.left = left self.right = right self.code = '' def Right(self, right=None): if(right is not None): self.right = right return self.right ...
vetor = [] for i in range(1, 8): num = int(input(f'Digite o {i}º número: ')) vetor.append(num) print(f'{max(vetor)}-{min(vetor)}')
import string UPPERASCII = 65 LOWERASCII = 97 alphaL = string.ascii_lowercase alphaU = string.ascii_uppercase alpha = string.ascii_letters def alphabet_position(letter): if letter in alphaU: # num = alphaU[ord(letter)-65] num = ord(letter)-UPPERASCII return num if letter in alphaL: ...
### 다리를 지나가는 트럭 def solution(bridge_length, weight, truck_weight): bridge=[0]*bridge_length answer=0 while True: if sum(truck_weight) == 0 and sum(bridge) ==0: break answer+=1 del bridge[0] next=0 if truck_weight: if sum(bridge) + truck_...
## 전화번호 목록 def solution(phone): answer=True phone.sort() for i in range(len(phone)-1): if phone[i+1].startswith(phone[i]): answer=False return answer phone=["119", "97674223", "1195524421"] answer=solution(phone) print(answer)
#문자열 내림차순 정렬 #처음 풀이 def solution(s): up=[] low=[] for i in s: if i.isupper(): up.append(i) else: low.append(i) up.sort(reverse=True) low.sort(reverse=True) answer=''.join(low+up) return answer #간결한 풀이 def solution(s): answer=''.j...
##수찾기 import sys input = sys.stdin.readline def binary_search(array, target, start, end): if start > end : print(0) return None mid = (start+end) // 2 if array[mid] == target: print(1) return mid elif array[mid] < target: return binary_search(array, target, mi...
import sys import os import mysql.connector import mysql_user_config # Creates the data base if it does not exist, then it creates the table if it does not already exist def create_databse(): # Connects to MYSQL server db = mysql.connector.connect(user=mysql_user_config.user, password=mysql_user_config.passwor...
import unittest from base import BaseTest class ProtocolTest(BaseTest): def test_basic_set_and_get(self): """ simple set and get test """ self.SET('A', 100) resp = self.GET('A') assert resp == '100', 'expected 100 got %s' % resp def test_get_inexistent(self):...
import pygame import Label class Button(pygame.Rect): def __init__(self, position, sizes, text, action): pygame.Rect.__init__(self, position, sizes) self.color = pygame.Color(41, 45, 54) self.action = action self.label = Label.Label(position = [pos + size / 2 for pos, size in zip(position, sizes)], text = tex...
''' 백준 16935 배열돌리기3 arr[::-1] : 배열 역순 list(zip(*arr)) : 행열 치환 ''' ''' #배열 상하 반전 def reverse_up_down(): global arr arr = arr[::-1] #배열 좌우 반전 def reverse_left_right(): global arr for i in range(N): arr[i] = arr[i][::-1] #배열 오른쪽으로 90도 회전 def rotate_right(): global arr, N, M temp = M ...
''' 백준 2661번 좋은수열 1. 뒤에서 첫번째 숫자와 두번째 숫자는 달라야한다 2. 뒤에서 첫번째, 두번째 숫자는 세번째, 네번째 숫자와 달라야한다 ''' def isok(string): length = len(string) tempLength = range(2,length+1,2) #원래 문자열을 뒤집음 string = ''.join(reversed(string)) for temp in tempLength: if string[:temp//2] == string[temp//2:temp//2 * 2]: ...
def solution(priorities, location): answer = 0 p = [(v,i) for i,v in enumerate(priorities)] m = max(priorities) #print("max: ", m) while True: #print(p) pi = p.pop(0) #print(pi) #print(pi[0]) #최대값과 같으면 프린트 출력! if m == pi[0]: #출력하므로 answe...
#!/usr/bin/python # -*- coding: utf-8 -*- """Renames identifiers in-place in files specified on the command-line.""" import re import sys def ReadRenames(filename): """Returns a dictionary mapping old identifiers to new.""" renames = {} line_number = 0 for line in open(filename): line_number += 1 if ...
from math import * from basic_functions import * from hexclass import * from cornerclass import * from roadclass import * #uses the 3 .txt files import cTurtle import os INF=float("inf") class Board(object): #creates objects for each hex, corner, and road #reads files which tell objects what they are next to ...
''' 문자열 관련 내용들 ''' # escape 문자 greet = 'Hello' * 4 + '\n' end = '\tGood \'Bye\' !!' end2 = "\t Good 'Morning' ??" print(greet + end + end2) # bool 타입과 str 타입 is_flag = False my_str = 'False' print(type(is_flag), type(my_str)) if not is_flag: print(my_str) # 문자열 인덱스(오프셋) # 012345678910 greeting = 'hello ...
import guardar_en_diccionarios def pedir_etiqueta_a_eliminar(): """"Le pide al usuario que ingrese el nombre de la etiqueta que desea eliminar. La elimina""" #Pedir el nombre de la etiqueta diccionario = guardar_en_diccionarios.guardar_en_diccionarios() etiqueta = input("Ingrese el nombre de la not...
import math # A = i +(b/2) -1, Picks Theorem def findNumBoundaryPoints(a,b,c,d): gcdab = findGCD(b,a) gcdbc = findGCD(b,c) gcdcd = findGCD(c,d) gcdda = findGCD(d,a) return gcdab+gcdbc+gcdcd+gcdda def findGCD(x, y): x,y = abs(x), abs(y) gcdxy = math.gcd(x, y) return gcdxy def is_squar...
fw= open('sample.txt', 'w') fw.write('My dear fellow citizens,The whole world is currently passing through a period of very serious crisis. Normally, when a natural crisis strikes, it is limited to a few countries or states. However, this time the calamityis such that it has it has put all of mankind in crisis. World ...