text
stringlengths
37
1.41M
# coding:iso-8859-9 Trke # Python 3 - Multithreaded Programming # Yeni yntemle sicim yaratma: Thread altsnf, override __init__ ve run metodlar, # sicim tip nesneleri yaratma, start ile run' koturma, ve icabnda join ile sicimlerin # almas tamamlanmadan alttaki kodlamaya gememenin salanmas import threading impor...
# coding:iso-8859-9 Trke # 3: Python3 - Basic Operators # Python Identity Operators a=10; b=10 doru=True; yanl=doru print ("a=10 ve b=20") print ("a is b:", a is b) print ("doru is yanl:", doru is yanl) print ("a is not doru:", a is not doru)
# coding:iso-8859-9 Trke # p_10601.py: Python ilemcileriyle yaplan ilem ktlar rnei. print ("Toplama ve karma (10+/-3):", 10+3, 10-3) print ("arpma, blme ve kalan (27*/+7):", 27*7, 27/7, 27%7) print ("Ksratsz (-+//) zemin blme ve -+int(10/3) kesik blmesi:", 10//3, int (10/3), -10//3.0, int (-10/3) ) print ("ebirs...
# coding:iso-8859-9 # p_13706.py: Snf nesnesi metodlar, oklu tip deikenlerine deer atama ve okuma rnei. class Robot: def __init__ (self, ad = None, tarih = None): self.ad = ad self.imalat = tarih def selamlama (self): if self.ad: print ("\nMerhaba, benim adm " + self.ad + "!") ...
# coding:iso-8859-9 Trke # 4: Python3 - Decision Making say = 100 if ( say == 100 ) : print ("Deikenin deeri = 100") print ("Gle gle!\n") if (say == 90): print ("Deikenin deeri = 90") elif (say == 80): print ("Deikenin deeri 80 deildir!") print ("say=", say) else: print ("Deikenin deeri ...
# coding:iso-8859-9 Trke ondalk = int (input ("Bir ondalk tamsay girin: ")) print ("Binary/kili karl =", bin (ondalk)) print ("Octal/Sekizlik karl =", oct (ondalk)) print ("Hexal/Onaltlk karl =", hex (ondalk), "\n") k = input ("Herhangibir klavye karakteri girin: ") print ("[" + k + "]'nn ASCII kod k...
#coding:iso-8859-9 Trke from random import randint tesadfi = randint (0,100) kere=tahmin = alt = 0 st = 100 for i in range (10): if tahmin > alt: try: tahmin = eval (input ("Tahmininiz (" + str (tahmin - (st - alt)//2) + "): ")) if tahmin > st or tahmin < alt: ...
# coding:iso-8859-9 Trke # p_40808.py: Canvas tuvalinde eit aralkl yatay-dikey zgara hatlar izimi rnei. from tkinter import * from p_315 import Renk def zgaralama (t, aralk, en, boy): # Dikey/boy ve yatay/en izgiler aralk/px mesafeli olacak... renk = Renk.renk() for x in range (aralk, en, aralk): t.cr...
# coding:iso-8859-9 Trke # p_13206.py: reduce(lambda fonk, liste) ile liste elemanlarnn toplam, arpm min-max' rnei. from random import randint from functools import reduce print ("'reduce' ile liste elemanlarn toplama:", "\n", "-"*40, sep="") print ("[47,11,42,13] 4 adet liste elemanlar toplam:", reduce (lambd...
# coding:iso-8859-9 Trke # Python3 - Dictionary szlk1 = {'Ad': 'M.Nihat', 'soyad': 'Yava', 'Ya': 62, 'doum yeri': 'Yeilyurt'} szlk2 = {1: "Bir", 2:"ki", "":""} szlk3 = {} print ("szlk1['Ad']:", szlk1['Ad']) print ("szlk1['Ya']:", szlk1['Ya']) print ("szlk1['doum yeri']:", szlk1['doum yeri']) szlk1 ['Ya'] ...
#coding=utf-8 #两个列表相乘相加 def list_multi(ls1,ls2): sum=0 for i in range(len(ls1)): sum+=ls1[i]*ls2[i] return sum #两个列表的减法 def list_sub(big,small): ls=[] for i in range(len(big)): ls.append(big[i]-small[i]) return ls #列表叠加处理 def list_add(ls): def sum(lista): sum=0 ...
grupo1 = [ ] grupo2 = [ ] for i in range(6): aux = -1 while aux < 0: num = float(input(f'Informe a nota do {i+1}º aluno: ')) if(num > 10): print('Tente novamente!') elif(num < 0): print('Tente novamente!') else: grupo1.append(num) ...
import sqlite3 # from .config import db # .config means import from this directory # Get datetime info when the user gets a location. Store it in the user class. db_path = 'api.db' db = db_path class API: def __init__(self): with sqlite3.connect(db) as conn: conn.execute ('CREATE TABLE IF N...
#Find the bigger and smaller number in a list lista_numeros = [] #contador = 0 #maior_valor = 0 #menor_valor = 0 novo_valor = True while novo_valor: numero = int(input('Qual o valor? ')) lista_numeros.append(numero) flag = input('Continua (y/n)? ') if flag != 'y': novo_valor = False # for ind...
r"""Generate a bunch of empty demofiles with date in filename, random extension. >>> python filenameWithDate 50 t a = filesWithDateName(howMany=50, pad=True, format_='American') => will create <50> random empty files with <padded American format date> in filename. Nguyen Thanh Hung - hungnt89@gmail.com hungntgrb""" ...
# Simple tetris program! v0.2 # D. Crandall, Sept 2016 ''' For this problem we have implemented an AI for winning the Tetris game. The main idea behind this code is as follows: - for a given piece, create a search tree with all the possible boards considering all the possible locations and rotations for that piece. ...
numero = int(input("Ingrese el número a calcular el factorial: ")) factorial = 1 while numero != 0: factorial*=numero numero-=1 print(factorial)
lista1 = [1,2,3,4,5,6,11] #Lista 1 en cuestión lista2= [4,5,6,7,8,9,11,13,14] #Lista 2 en cuestión listaIguales = list() #Creamos lista para almacenar datos iguales listaDistintos = list() #Creamos lista para almacenar datos distintos for i in lista1: #Entramos a lista1 para comenzar a comparar datos for ...
from itertools import permutations import sys import time in_word = sys.argv[1] already_seen = [] #already seen is already found de jumbled word if len(sys.argv) > 2: already_seen = sys.argv[2:] #read from english word dictionary eng_dict = open("english3.txt", "r").read().split("\n") #generator for eng...
from tkinter import * import tkinter as tk from tkinter import filedialog from PIL import Image, ImageDraw, ImageFont, ImageTk BACKGROUND_COLOR = "#F7F7FF" BUTTON_COLOR = "#279AF1" EXIT_COLOR = "#C14953" def exit_program(): window.destroy() def watermark_text(): filename = filedialog.askopenfilename(initia...
# # Mazecraft: 2D and 3D Maze Generation for Minecraft # # (c) 2011 Lee Supe (lain_proliant) # Released for the GNU General Public License # import random def pathFlagsFromDiffCoords (diffCoords): """ Computes forward and backward path flags for the given difference between coordinates. """ path...
def main(): def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 if __name__ == '__main__': main() print("this part isn't meant to show")
#!/usr/bin/python import unittest def near_one_or_two_hundred(number_to_check): """ Given an int number_to_check, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number. """ pass class TestNear(unittest.TestCase): def test_89(self): sel...
import pygame import random import math """ ScreenSaver with following features: 1. multi polylines, configure each separately (selected polyline is marked by yellow points, others - white points) 2. add a new polyline. support two classes: Polyline(pure base)/Knot 3. different polylines can have a different classes a...
def fib(n): a,b=1,1 for i in range (n-1): a,b = b,a+b return a print fib(10)
# 实现一个 @timer 装饰器,记录函数的运行时间, # 注意需要考虑函数可能会接收不定长参数。 import time from functools import wraps def timer(func): @wraps(func) def decorated(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() running_time = end - start print(f"{func.__name__} ...
#!/bin/python3 import math import os import random import re import sys # Complete the jumpingOnClouds function below. def jumpingOnClouds(c): jump=0 a=0 for i in range(1,len(c)): if a==1: a=0 continue if(c[i]==0): jump+=1 else:...
number1 = input("Enter an integer: ") n_list = list(number1) n_list.reverse() number2 = "".join(n_list) print('"Inverse" number: ', number2)
def max_local(text, max_loc=0, counter=0, max_lenght_words_pos=0): for x in text: if max_loc < len(x): max_loc = len(x) max_lenght_words_pos = counter counter += 1 return max_lenght_words_pos def min_local(text, counter=0, min_lenght_words_pos=0): min_local = len(te...
def arithmetic_arranger(problems, ok=False): # check problem list first = '' second = '' sum_x = '' lines = '' # check if there are more than 5 problems if len(problems) > 5: return 'Error: Too many problems.' # split problems to single problem for i in problems: a = ...
value = input("Please Enter the number: ") print("Your Entered number is " +value) if int(value) in range (1, 100): print ("Positive Number") else: print ("Negative number")
person = input ("Please Enter your name :") print("Hello " +person)
import time import Suspect def intro(): print("A game of guesses") introText() def introText(): # Suspect.set_difficulty() #skipIntro = input("Want to skip intro?") #if skipIntro == "yes": # gameplayStart() #else: time.sleep(3) print("You are a detective in the 10th century.\n...
import json from grid import * class GridDisplay: def __init__(self, grid): self.grid = grid def __str__(self): out = [] for row in range(self.grid.height): out2 = [] for col in range(self.grid.width): out2.append("{" + str(self....
# -*- coding:utf-8 -*- import json import argparse import os def importingargs(): """ importing args """ parser = argparse.ArgumentParser( description="Reverse the file by DESC by col3") parser.add_argument( "--inputfilepath", help="This is the filepath of input file") parser....
import argparse import os def importingargs(): """ importing args """ parser = argparse.ArgumentParser( description="Searching the different first literals") parser.add_argument( "--inputfilepath", help="This is the filepath of input file") parser.add_argument("--linesnum",help=...
from sys import argv def average_word_length(file_name): with open(file_name, 'r') as file: contents = file.read() split = contents.split(' ') return sum([len(word) for word in split]) / float(len(split)) if __name__ == '__main__': filename = argv[1] avg_word_length = average_word_lengt...
# https://www.hackerrank.com/challenges/python-division/problem n1 = int (input()) n2 = int (input()) print(n1 // n2) print (n1 /n2)
# https://www.hackerrank.com/challenges/merge-the-tools/problem from collections import OrderedDict z= input() k = int(input()) a = int(len(z)/k) store = [] for i in range(a): temp = z[i * k : (i+1) * k ] store.append(temp) for items in store: print("".join(OrderedDict.fromkeys(items)))
#Print a hashtag pyramid from cs50 import get_int #Get user input for pyramid height while True: height = get_int("height: ") width = height if height >= 0 and height < 24: break #Iterate through layers of pyramid for i in range(1, height + 1): hashes = i spaces = width - hashes print...
#!/usr/bin/env python # coding: utf-8 # In[3]: # Imports import math import numpy as np import pandas as pd import scipy.stats get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt plt.style.use('ggplot') import seaborn as sns # In[4]: housingdf = pd.read_csv('AmesHousing.csv') ...
""" Osbert Lee, Yui Suzuki, Yukito Shida CSE 163 Section AA This file serves to produce quantifiable values that the user can interpret. Specifically, the probabilities file should be able to produce the results of a machine learning prediction and also a confidence interval to test the 911 dials between season...
#!/usr/bin/env python # -*- coding: utf-8 -*- import random def main(): print "Welcome to the Lottery numbers generator" st_stevilk = int(raw_input("Please enter how many random numbers would you like to have:")) loto = [] while True: if len(loto) == st_stevilk: break else...
from os.path import isfile, exists import os import shutil def makeFolders(): foldersNeeded = ['Documents', 'Pictures'] # Just add whatever folders are required here for folder in foldersNeeded: if(not exists(folder)): os.mkdir(folder) def sortFiles(): files = [f for f in os.listdir(...
from .Algorithm import Algorithm class CreateLoop(Algorithm): def __init__(self,start,end,step,inner_code): self.start=start self.end=end self.step=step self.inner_code=inner_code def python3(self): return f'for i in range({self.start},{self.end},{self.step}){self.inne...
import math class Distribution: def __init__(self): self.quantity = 0 self.percentage = 0 self.range = [0, 0] self.totalBits = 0 self.flowerNumber = 0 def add(self): self.quantity += 1 #Setter def setQuantity(self, total): self.quantity = total ...
def calc(x, y, op): res = 0 if op == '+': res = x + y elif op == '-': res = x - y elif op == '*': res = x * y elif op == '/': res = x / y return res while True: data = input('Type formula like \'x + y\' or \'quite\' to exit: ') if data == 'quit': ...
# Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() fruit = ["яблоко", "ба...
""" This module illustrates how to use Matplolib subplots routine. This recipe is useful when there is necessary to plot multiple related plots within the same figure, side by side. """ import numpy as np import matplotlib.pyplot as plt def generate_newton_iters(x0, number): """ This function represents a Newt...
""" Linear regression is a tool for modeling the dependence between two sets of data so that we can eventually use this model to make predictions. The name comes from the fact that we form a linear model (straight line) of one set of data based on a second. In the literature, the variable that we wish to model is frequ...
""" This module provides examples of Numpy's universal functions (ufunc), which are routines that can operate efficiently on Numpy array types. """ import numpy as np arr_a = np.array([1, 2, 3, 4]) arr_b = np.array([1, 0, -3, 1]) arr_a + arr_b # array([2, 2, 0, 5]) arr_a - arr_b # array([0, 2, 6, 3]) arr_a * arr_b # ...
""" Correctly keeping track of units in calculations can be very difficult, particularly if there are places where different units can be used. For example, it is very easy to forget to convert between different units – feet/inches into meters – or metric prefixes – converting 1 km into 1,000 m, for instance. This mod...
""" Networks are also useful in scheduling problems, where you need to arrange ctivities into different slots so that there are no conflicts. For example, we could use networks to schedule classes to make sure that students who are taking different options do not have to be in two classes at once. In this scenario, th...
""" This module contains code that creates n-dimensional arrays """ import numpy as np mat = np.array([[1, 2], [3, 4]]) vec = np.array([1, 2]) mat.shape # (2, 2) vec.shape # (2,) mat.reshape(4,) # array([1, 2, 3, 4]) mat1 = [[1, 2], [3, 4]] mat2 = [[5, 6], [7, 8]] mat3 = [[9, 10], [11, 12]] arr_3d = np.array([mat1...
""" This module illustrates how to solve a simple system of differential equations. Consider the following, classic, Prey-Predator example: dP/dt = 5*P - 0.1*W*P dW/dt = 0.1*W*P - 6*W where P is the prey specie and W, the predators. Note that this system is a compete predator-prey example. """ import numpy as...
def welcome(msg="welcome to python"): print(msg) welcome("Nice to have you here") def not_welcome(msg="welcome to python"): print(msg) not_welcome() #CLASS means classification/ a group of methods are placed in CLASS print('--------------------- Class -------------------------') ...
""" init variable while condition: Statements ... """ #alternative of For loop #while loop i=1 while i<=5: print(i,end='\t') i = i+1 print("\n") print(40*"_") j=10 while j<=20: print(j,end="\t") j = j+1 print("\n") print(50*"_") z=10 while z<=20: print(z,end="...
from collections import deque graph = {} graph["Sherif"] = ["Toqa", "Amr", "Zakaria"] graph["Amr"] = ["Zizo", "Selim"] graph["Toqa"] = ["Sherif", "Dodo", "Mohamed"] graph["Zakaria"] = [] graph["Dodo"] = [] graph["Mohamed"] = [] graph["Zizo"] = [] graph["Selim"] = [] def search(name): search_queue = deque() ...
"""Coin guess and math game!""" __author__ = "730449914" from random import randint points: int = 1 player: str NAMED_CONSTANT: str = '\U0001F600' NAMED_CONSTANT_1: str = '\U0001F62A' def greet() -> None: """Welcome message!""" print(f"Welcome stranger! You have now entered the game {NAMED_CONSTANT}.") ...
"""Repeating a beat in a loop.""" __author__ = " 730449914" Counter: int = 0 beat: str = str(input("What beat do you want to repeat? ")) frequence: int = int(input("How many times do you want to repeat it? ")) if frequence > 0: while Counter < frequence: if Counter < frequence - 1: print(beat...
class Node(object): ''' Node object. This object corresponds to an orginal node: a single metabolite or reaction. Initialization -------------- node_id: string. Node name. e.g. 'glu__D_e', 'ATPM' node_type: int, 0 or 1. Node type. type = 0, metabolites. type...
import csv import argparse def remove_uncategorized_products(file_input): try: with open(file_input, newline='') as csvfile: reader = csv.DictReader(csvfile) return [row for row in reader if row["Categories"]] except FileNotFoundError: err = f"{file_input} does not exis...
''' An integer d is a divisor of an integer n if the remainder of n % d = 0. Given an integer, for each digit that makes up the integer determine whether it is a divisor. Count the number of divisors occurring within the integer. Note: Each digit is considered to be unique, so each occurrence of the same digit should...
'''Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty. The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the t...
""" You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest. Example candles = [4, 4, 1, 3] The maximum height candles are 4 units high. Ther...
""" Staircase detail This is a staircase of size : # ## ### #### Its base and height are both equal to . It is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size . Function Description Complete the staircase function in the editor be...
numero=15 while numero>0: print(numero) numero=numero-1 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 a=2 while numero>0: print(numero) numero=numero-a while numero>0: print(numero) numero=numero-2 numero=14 a=2 while numero>0: print(numero) numero=numero-a 14 12 10 8...
numero=1 if (numero==1): print('número é igual a 1') if (numero==2): print('numero é igual a 2') numero=2 if (numero==1): print ('numero é igual a 1') else: print('numero não é 1') nome=input('insira o nome:') if ('t'in nome): print('o nome tem um t') elif ('l' in nome): print('o nome tem um l...
numero=int(input()) #para inverter, um meio é transformar o int em str numero=str(numero) #fazendo: print('datatype',type(numero)) #tenho confirmação: datatype <class 'str'> oremun=''.join(reversed(numero)) print(oremun) #é algo como ".join reversed faz a reversão como itens de lista, e join serve pra juntar ela...
var = "hello world!" var1 = 5 var2 = 5.0 var3 = True print(type(var)) print(type(var1)) print(type(var2)) print(type(var3)) reverse_var = var[::-1] splitted = var.split(" ") var = "agam" if var.islower() == True: print("string with lower chars") elif var.isupper() == True: print("string with upper chars") else...
x = set() num_set = {0,1,2,3,4,5} num_list = [0,1,2,3,4,5] for n in num_list: print(n)
formula = str(input("Please enter a formula:\n")) formula_list = formula.split() #1 + 1 print(formula_list) formula_list[0] = number1 formula_list[1] = operator formula_list[2] = number2
lst1 = [10, 20, 30] #global variable def changeme(lst1): lst1 = [1, 2, 3, 4] # local variable print("the values inside lst1 are:", lst1) changeme(lst1) print("the values outside of the function are:", lst1)
from random import randint import time /Users/BOF/Desktop/Education/algorithms/bubble_sort/bubble_sort.py def bubble(array): for i in range(N-1): for j in range(N-i-1): if array[j] > array[j+1]: buff = array[j] array[j] = array[j+1] array[j+1] = bu...
# #!/usr/bin/env python3 # -- coding: utf-8 -- # --------------------------------------------------------------------------------- # Copyright (c) 2019. Oraldo Jacinto Simon # #---------------------------------------------------------------------------------- # All rights reserved. # # # This is free software; ...
def get(dict1: dict, string: str) -> str: if string in dict1: return str(dict1[string]) return "" commands = [] def get_dict(_dict: dict) -> str: """ helper function - get dict in format printable :type _dict: dict """ result = "" for key, value in _dict.items(): if ...
#Cosmeticos ventas={} precioF=0 respuestaW=1 respuesta=1 yellow = '\033[33m' white = '\033[37m' green = '\033[32m' while respuesta==1: print(green) print("||| Bienvendio al Menú |||") print(white) print("¿Que accion vas a realizar?") print("1-Registrar ventas") print("2-Consultar ventas") p...
import webbrowser import pyautogui from time import sleep def open_website(): """ Opens Henry Ford Hospital MyChart Scheduling link. :return: n/a """ webbrowser.open('https://mychart.hfhs.org/MyChart/Scheduling') sleep(4) def click_button(button_image, delay=1): """ :param button_im...
class Point(tuple): def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) @property def x(self): return self.__getitem__(0) @property def y(self): return self.__getitem__(1) def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def...
''' 12. Write a Python program to extract all the text from a given web page. ''' import requests from bs4 import BeautifulSoup url = 'https://www.python.org/' html = requests.get(url).text soup = BeautifulSoup(html,"html.parser") print(soup.get_text().strip())
''' 35. Write a Python program to wrap an element in the specified tag and create the new wrapper. ''' from bs4 import BeautifulSoup soup = BeautifulSoup("<p>Python exercises.</p>", "lxml") print("Original Markup:") print(soup.p.string.wrap(soup.new_tag("i"))) print("\nNew Markup:") print(soup.p.wrap(soup.new_tag("...
''' 32. Write a Python program to extract a tag or string from a given tree of html document. ''' from bs4 import BeautifulSoup html_content = '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>' soup = BeautifulSoup(html_content, "lxml") print("Original Markup:") print(soup.a) i_tag = soup.i.ext...
from dataclasses import dataclass from exceptions import EmployeeDictError fields = { "employee_id": "Employee ID", "name": "Employee Name", "department": "Department", "designation": "Designation", "salary": "Salary", "sales": "Sales" } @dataclass(order=True) class Employee: employee_id...
""" 본 연습문제에서는 m^n을 구하는 프로그램을 작성합니다. 입력으로는 m, nm,n이 차례대로 입력됩니다. 만약 getPower 함수의 반환 값이 1,000,000,007 보다 클 경우, 반환 값을 1,000,000,007로 나눈 나머지 값을 반환하세요. 입력 예시 3 4 출력 예시 81 """ LIMIT_NUMBER = 1000000007 def getPower(m, n): ''' m^n 을 LIMIT_NUMBER로 나눈 나머지를 반환하는 함수를 작성하세요. ''' return 1 def main(): ''' ...
""" 정수들의 리스트가 입력으로 들어옵니다. 이 정수들의 리스트를 일부분만 잘라내어 모두 더했을 때의 값을 부분합이라 부릅니다. 이때 가장 큰 부분합을 구해봅시다. 예를 들어, [-10, -7, 5, -7, 10, 5, -2, 17, -25, 1]이 입력으로 들어왔다면 [10, 5, -2, 17]을 모두 더한 30이 정답이 됩니다. """ import numpy as np def maxSubArray(nums): arr = [] for i in range(len(nums)): subArray = np.cumsum(nums[i:]) ...
""" 입력으로 n개의 수가 주어지면, quick sort를 구현하는 프로그램을 작성하세요. 입력 예시 10 2 3 4 5 6 9 7 8 1 출력 예시 1 2 3 4 5 6 7 8 9 10 """ def quickSort(array): ''' 퀵정렬을 통해 오름차순으로 정렬된 array를반환하는 함수를 작성하세요. ''' if len(array) <= 1: return array pivot = array[0] left = getSmall(array[1:], pivot) right = getLa...
""" try: 실행할 명령 except 예외 as 변수: 오류 처리문 else: 예외가 발생하지 않을 때의 처리 """ str = "89점" try: score = int(str) print(score) except: # 모든 예외에 대해 print("예외가 발생했습니다.") print("작업완료") print() str = "89" try: score = int(str) a = str[5] except ValueError: print("점수의 형식이 잘못되었습니다.") except Index...
""" 프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다. 전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요. """ def solution(phone_number): answer = "" length = len(phone_number) - 4 for i in range(length): answer = answer + "*" answer = answer ...
array = [1,3,5,6,9] sum = 0 for x in array: sum += x print("sum: ",sum)
""" 자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다. """ def solution(n): answer = [] s = str(n) l = len(s) - 1 for i in range(l,-1,-1): answer.append(int(s[i])) return answer a = solution(12345) print(a)
stack = [None,None,None,None,None] top = -1 # push top += 1 stack[top] = 'A' top += 1 stack[top] = 'B' top += 1 stack[top] = 'C' print(stack) # pop data = stack[top] print(data) stack[top] = None top -= 1 print(stack)
""" 문자열 s는 한 개 이상의 단어로 구성되어 있습니다. 각 단어는 하나 이상의 공백문자로 구분되어 있습니다. 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을 리턴하는 함수, solution을 완성하세요. 문자열 전체의 짝/홀수 인덱스가 아니라, 단어(공백을 기준)별로 짝/홀수 인덱스를 판단해야합니다. 첫 번째 글자는 0번째 인덱스로 보아 짝수번째 알파벳으로 처리해야 합니다. """ def solution(s): answer = '' i = 0 for n in s: if n == " ": ...
import sys def getSlope(a, b): return abs((b[1] - a[1]) / (b[0] - a[0])) def maxSlope(points): points.sort() result = 0 for i in range(len(points) - 1): result = max(result, getSlope(points[i], points[i + 1])) return result def main(): n = int(input()) points = [] for i ...
#Here are the excercises listed in the 'Try It Yourself' section at the end of Chapter 2: #See Python Crash Course (pages 28-29) for more details on each exercise. #Written By: Kaila Stevenson #Last Edited: 04/27/2019 #2-3. Personal Message first_name = "Kaila" print("Hello, " + first_name + ", would you like to learn...
#3-1. Names: names = ['Ami', 'Christina', 'Tim', 'Elena', 'Bradley', 'Zon', 'Joshua'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4]) print(names[5]) print(names[6]) print("________________________\n") #3-2. Greetings: names = ['Ami', 'Christina', 'Tim', 'Elena', 'Bradley', 'Zon', 'Josh...
#!/usr/bin/env python def is_vowel(s): length = 0 vowel = ["a", "e", "i" ,"o", "u"] for itm in s: length +=1 if length == 1: if itm in vowel: print "yes it is vowel " else: print "no this is not a vowel" else: print " Entered input is not a single character "...
# ###1: # def info(name, hometown, skill): # print("This is ", name, " of ", howetown, " undefeated in ", skill, "!") # # ###2: # def p_suggest(p_old): # if p_old > 100: # p = p_old*1.05 # else: # p = p_old*1.1 # print("The total price is suggested to be", p, " when the price is ", p_old...
""" Write a function that recursively walks through a directory, printing its contents. Indent with spaces based on recursion depth. (max 10 lines) """ from pathlib import Path def show_path(path, level=0): if not path.is_dir(): return for p in path.iterdir(): print("{}{}".format(" " * level...
import pygame from mazeSolver import * class MazeSolverRecursive(MazeSolver): def __init__(self, maze): super().__init__(maze) self.current = self.start print(self.current, self.end) # set the state self.state = [[0 for y in range(self.height)] for x in range(self.width)] ...
#this program says hello and asks to print my age print ('Hello World') print ('what is your name?') myName = input() print ('nice to have you here ' + myName) print ('the length of your name is ') print (len(myName)) print ('what is your age?') myAge = input() myAge = int(myAge) + 1 myAge = str(myAge) print ('you wil...