text
stringlengths
37
1.41M
#1 Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". #Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5] def big(list): newlist = [] for x in range(0,len(list)): if list[x] > 0: newlist.append("big") e...
class Product: def __init__(self, name, price, category): self.name = name self.price = price self.category = category self.store = Store(name) def update_price(self, percent_change, is_increased): if is_increased == True: self.price += self.price * percent_change if is_increased == False: self.pric...
#1 Update Values in Dictionaries and Lists x = [ [5,2,3], [10,8,9] ] students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] ...
class BankAccount: def __init__(self, name): self.name = name self.balance = 0 self.interest_rate = 0.05 def deposit(self, balance): self.balance += balance return self def withdraw(self, balance): if (self.balance - balance) < 0: print('Insufficient funds: Charging a $5 fee') self.balance -= 5 e...
# 3.写函数,参数为int,在屏幕上输出其: 10 进制,2进制、8进制、16 进制形式 a = int(input("请输入想要转换的数字:")) def transform(num): print("10进制形式:"+"\t"+str(int(num))) print("2进制形式:"+"\t"+str(bin(num))) print("8进制形式:"+"\t"+str(oct(num))) print("16进制形式:"+"\t"+str(hex(num))) transform(a)
class Solution: # @param {string} s # @return {string} def longestPalindrome(self, s): def isPalindrome(s): #s = "".join(map(lambda c: c.lower(), filter(lambda c: c.isalnum(), s))) L = len(s) mid = int(L/2) if L % 2 == 0: r...
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 2: Which telephone number spent the ...
print("Hello. This program converts kilometers into miles.") repeat = None while True: km = int(input("Enter number of kilometers: ")) mi = km * 0.621371 print(mi) repeat = str(input('Do you want to do another conversion? Type "yes" or "no": ')) if repeat != "yes": print(...
wrd = input("Enter a word: ") if wrd == wrd[::-1]: print(wrd, "is a pallindrome") else: print(wrd, "is not a pallindrome") input("Press Enter key to exit")
from sqlalchemy import MetaData, Table, Column, String, Integer, ForeignKey, create_engine from sqlalchemy.sql import select engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String(100), nul...
from define_create_table import users, addresses from create_query import conn from sqlalchemy.sql import select, func stmt = select([users.c.name]).order_by(users.c.name) print(conn.execute(stmt).fetchall()) print() """ Ascending or descending can be controlled using the ColumnElement.asc() and ColumnElement.desc() ...
""" The Union type allows a model attribute to accept different types, e.g.: """ from pydantic import BaseModel from uuid import UUID from typing import Union class User(BaseModel): id: Union[int, str, UUID] name: str user_01 = User(id=123, name='John Doe') print(user_01) # > id=123 name='John Doe' print(use...
class seat(): def __init__(self , x, y): self.x = x self.y = y def is_seat_valid(self): if self.x < 9 and self.x > 0 and self.y < 9 and self.y > 0: return True else: return False def get_x(self): return self.x def get_y(self): re...
a = 2 b = 2 c = "txt" d = "txt" print("a = " + str(a)) # ตัวแปรต่างชนิดกัน print("b = " + str(b)) print(a+b) print("c + d = " + c + d) # string + string คือ ข้อความต่อกัน a = b = 2 # การกำหนดแบบลูกโซ่ c = d = "txt" print("a = " + str(a)) print("b = " + str(b)) print(a+b) print("c + d = " + c + d)
# This solution belongs to user https://www.codingame.com/profile/8fe6daf329d120f0e3014777bebfec313384001 # User Ryba published it over 1 year ago import sys import math surface_n = int(raw_input()) # the number of points used to draw the surface of Mars. x1 = x2 = yr = 0 f = False for i in xrange(surface_n): lan...
''' This file is not an actual blockchain. It's hardcoded Python that I used to prepare the design of the actual app which could be found in /py-blockchain/app.py You can run this in your terminal to play around with it as well. ''' # create users class class Users: def __init__(self, address, key, id, wallet_id...
from molmass import Formula RawData = input("Gas Formula, to second Gas, ratio, x for unknown: ") while(RawData != "quit"): SplitData = RawData.split(" ") F0 = SplitData[0] F = Formula(F0) R = float(SplitData[1]) print("Results: x = ", F.mass/(R**2)) RawData = input("Gas Formula, Mass, Temp(C), ...
import numpy as np import matplotlib.pyplot as plt x = np.arange(-3,3,0.01) y = (x**4)-(2*(x**2))+(11*x)-6.1 fx = lambda x : (x**4)-(2*(x**2))+(11*x)-6.1 # x0=float(input("Masukkan x0: ")) # x1=float(input("Masukkan x1: ")) Es = 0.0001 Er = 100.0 x1 = 2.75 x0 = 1 i = 0 if(x0!=0): print("Iterasi\t Xn-1\t\t Xn \t\t Xn...
import tkinter as tk root = tk.Tk() root.title('Find and Replace') tk.Label(root, text="Find: ").grid(row=0, column=0, sticky=tk.E) tk.Entry(root, width=60).grid(row=0, column=1, padx=2, pady=2, sticky=tk.W + tk.E, columnspan=9) tk.Label(root, text="Replace: ").grid(row=1, column=0, sticky=tk.E) tk.Entry(root, width...
#!/usr/bin/env python from Word_Counter import * def test_word_counter(): """ >>> wc = Word_Counter() >>> sent = "Once upon a midnight dreary while I pondered weak and weary " >>> sent += "over many a quaint and curious volume of forgotten lore" >>> for word in sent.split(): wc.count(word) >>> wc.get_coun...
# -*- coding: utf-8 -*- # 20200213 by sangkny # y2img : convert y image to normal format # y2img(in_y_file, out_imgfile, img_height=40, img_width=32, debug_general = True) # binary file i/o example import os import numpy as np import cv2 def y2img(in_y_file, out_imgfile, img_height=40, img_width=32, debug_general = ...
#Author: Jiang Wei #装饰器:本质是函数,(装饰其他函数)就是为其它函数添加附加功能 '''原则:不能修改被装饰函数的源代码,不能修改被装饰函数的调用方式''' ''' def foo(): print("in the foo") bar() def bar(): print("in the bar") 这一段代码可以正常运行,因为调用foo之前foo跟bar都已经声明并且已经在内存中存好 foo() ''' ''' def foo(): print("in the foo") bar() foo() def bar(): print("in the...
class hospital (object): def __init__(self,name,capacity,*patients): self.patients = list(patients) self.name = name self.capacity = capacity - len(self.patients) def info(self): print self.name names = "" for x in range(0,len(self.patients)): names +...
def draw_stars(x): for i in range(0,len(x)): string = "" isInt = isinstance(x[i],int) isStr = isinstance(x[i],str) if isInt == True: for j in range(1,x[i]+1): string += "*" elif isStr == True: for j in range(0,len(x[i])): ...
# function input my_dict = [ {"Speros": "(555) 555-5555"}, {"Michael": "(999) 999-9999"}, {"Jay": "(777) 777-7777"} ] # function output # [("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")] def dictTup (my_dict): my_tuple = [] for x in range(0,len(my_dict)): ...
#//-------------------------------------------------------------------------------------------- #// set_methods #//-------------------------------------------------------------------------------------------- ''' set={"app","telsuko","learning"} set.add("phone") print(set) ''' ''' set={"app","telsuko","learning"} set1...
import pandas as pd rep=0 fields=['Name','Admission number','Roll number','Class','Science marks','Maths marks','Sst marks','English marks'] def menu(): print('1. Add new student data : ') print('2.Display marksheet : ') print('3.Compute ranks : ') print('4.Merit students : ') print('5.Exit ...
import arcade from . import constants class Background: """ A class representing a window background.""" def __init__(self, texture=None, color=None): # To avoid error with loading a texture with None as parameter self.texture = None if texture is None else arcade.load_texture(texture) ...
#!/usr/bin/env python # Author: Epihaius # Date: 2019-10-06 # Last revision: 2020-10-08 # # This is a basic example of how to use the sizer-based GUI system. # It specifically showcases the growth of a Sizer in two directions. # Cells are always added in a specific "primary" direction, which is # either horizontal or ...
from typing import List import numpy as np class Generator: """Class that generates new training examples""" def __init__(self): self.best_x = 0 self.best_y = np.inf self.width = 2 def partial_fit(self, x: np.ndarray, y: float): """Add another entry""" if y < se...
a= int(input("Inrese un numero")) b= int(input("Inrese un numero")) for i in range (a,b): if i%3 == 0 and i%5 == 0: print ("FizzBuzz") elif i%5 == 0: print ("Buzz") elif i%3 == 0: print("Fizz") else: print(i)
from func.info import Info from func.purchase import Purchase username = input("Please enter your username: ") password = input("Please enter your password: ") purchasing = input("Are we purchasing stock today? Y/N: ") p = Purchase() buyStock = Purchase.purchaseQuestion(p, purchasing) # Build portfolio for program t...
def remove_names(names): ''' Remove a name from a list. ''' removed_name = names.pop() print('Goodbye ' + removed_name.title() + '.') return names friends = ['john', 'jack', 'jill', 'james'] print(friends) new_friends = remove_names(friends.copy()) print(friends) print(new_friends) # def add_two(num): # ...
# for loops : running a set number of times # while loops : running until a certain condition is met for i in range(1, 11): print(i) current_num = 1 while current_num <= 10: print(current_num) current_num += 1 current_num = 1 while True: print(current_num) current_num += 1 choice = input("Press enter to...
class House(): ''' a class to model a house that is for sale. ''' def __init__(self, style, sq_foot, year_built, price): ''' initialize attributes. ''' self.style = style self.sq_foot = sq_foot self.year_built = year_built self.price = price self.sold = False self.weeks_on_m...
print('5') print(5) print(4 + 2) print(4 - 2) print(4 * 2) print(4 / 2) print(4 ** 2) y = 4.15 print(y) y = y + 2 print(y) y += 2 print(y) y = y - 1 print(y) y -= 1 print(y)
def times_ten(x): ''' Multiply a number by 10 ''' print('Current value: ' + str(x)) x *= 10 print('Updated value: ' + str(x)) return x def char_replace(word): ''' replace specific characters in a string with other characters. ''' while 'a' in word: word = word.replace('a', '@') while 'e' in...
name = 'Mike' age = 33 money = 9.75 # print using concatination print(name + ' is ' + str(age) + ' and has $' + str(money) + ' dollars.') # print using the .format() method for strings print("{0} is {1} and has ${2} dollars.".format(name, age, money)) # print using f-strings print(f'{name} is {age} and has ${money} ...
import random print('Welcome to the Thesaurus App!') print('\nChoose a word from the thesaurus and I will give you a synonym.') thesaurus = { 'hot': ['balmy', 'summary', 'tropical', 'boiling', 'scorching'], 'cold': ['chilly', 'cool', 'freezing', 'frigid', 'polar'], 'happy': ['content', 'cheery', 'merry', 'jovia...
num = int(input("enter mobile no")) #6612312645 max=0 for i in range(1,11): a=num%10 num=num//10 if max<a: max=a print("max digit is "+str(max))
try: a=int(input("enter first number")) b=int(input("enter second number")) c=a/b print(c) except ZeroDivisionError: print("Denominator can not be zero") except ValueError: print("Enter Only Numeric Value") else: print("No Error Found") finally: print("Division Program")
f = int(input("enter the temprature in farenhite to convert on celsious")) #120 c = (5*f-160)/9 #print(c) print("Temprature in celsious is ",c)
class A: def fun1(self): print("A") class B: #B inherited by A class def fun2(self): print("B") class C(A,B): #C Multiple def fun3(self): print("C") class D(C): def fun4(self): print("D") obj = B() #obj.fun1() obj.fun2() obj1 = C() obj1.fun1...
num = int(input("Enter Number To Check Prime")) i=1 c=0 while i<=num: if num%i==0: c=c+1 break i=i+1 if c==0: print("prime") else: print("not prime")
num = int(input("enter number")) #78923 a = num%10 #5 num=num//10 #1234 b = num%10 #4 num=num//10 #123 c = num%10 #3 num=num//10 #12 d = num%10 #2 e= num//10 #1 num1 = e*10000+b*1000+c*100+d*10+a*1 print(num1)
num= int(input("enter number")) i=num f=1 s="" while(i>=1): f=f*i if i>1: s=s+ str(i) +"*" else: s=s+str(i) i=i-1 print(s+"="+str(f))
# Assessment 2 @ Noroff University College _author_ = "Thomas Thaulow" copyright = "Thomas Thaulow" _email_ = "thaulow@thaulow.co" import random ###################################### #======== 6x6 Sudoku Boards =========# ###################################### board1 = [[0, 6, 0, 0, 0, 0], # Row 0 [0, 0,...
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from flask import request, redirect, flash from system.core.controller import * c...
# Square wheel import turtle jack = turtle.Turtle() jack.color("green") jack.speed(0) def draw_square(distanse): for side in range(4): jack.forward(distanse) jack.right(90) for square in range(72): draw_square(150) jack.forward(5) jack.left(5) jack.hideturtle() turtle.done()
import random '''Class containing all the process for the processing of the music; transform the concept of the emotion into musical parts''' class Music: '''Match the musical modes with diffent modes and storages the notes in them emotion_to_modes: this variable matchs every emotion with differnet m...
""" Newton-Raphson for square root Fix x such that x**2 - 24 is within epsilon of 0 Add some code to the implementation of Newton-Raphson that keeps track of the number of iterations used to find the root. Use that code as part of a program that compares the efficiency of Newton-Raphson and bisection search. (You shou...
def add(x, y): return x * y def main(): print(add(5, 2)) # 10 if __name__ == '__main__': exit(main())
#libraries from datetime import date import datetime #global constans viriable userList = []#This initialise userlist to nothing. passList = []#this initialise passlist to nothing #define function def reg_user(): newusername = input("Enter New username: ")#This will input the username when user want to log in,it...
''' This is a python script to read CDF V3 files without needing to install the CDF NASA library. You will need Python version 3, as well as the Numpy library to use this module. To install, open up your terminal/command prompt, and type:: pip install cdflib ########## CDF Class ########## To begin accessi...
def max_list_iter(int_list): # must use iteration not recursion """finds the max of a list of numbers and returns the value (not the index) If int_list is empty, returns None. If list is None, raises ValueError""" if int_list == []: return None elif int_list is None: raise ValueError ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import json def phone_num_count(phone_nums): ''' Returns the count of phone numbers in the column. If it is missing return 0 count instead of np.nan Args: ---- phone_nums(str) - phone number in the string form '...
import random __author__ = 'Dmitry Panfilov' # Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользов...
import time start_time = time.time() answer = int(input("What is 2+2?\n")) if time.time() - start_time > 10: print("Too slow! You did it in:", round(time.time() - start_time,2), "seconds.") else: if answer == 4: print("Correct! You did it in:", round(time.time() - start_time,2), "seconds.") else: ...
import tkinter as tk from PIL import Image, ImageTk from tkinter import font as tkFont from tictactoeGUI import ticTacToe as tttGame import configFile as cf import random import time # Initializes main window root = tk.Tk() root.geometry("720x600") root.title("RPG - Bence Redmond") # Creates fonts helv10 = tkFont.Fon...
import os import random import colorama from colorama import Fore, Back, Style, init init() def cls(): return os.system('cls') cls() name = input("Type your name here: ") print(f"You have {len(name)} letters in your name ") print("The letters of your name are:") for x in range(len(name)): if x % 2 == 0: p...
import random import os from colorama import init from colorama import Fore, Back, Style, init init() def cls(): return os.system('cls') cls() def printRed(s): print(f"{Fore.RED}{s}{Style.RESET_ALL}") def printYellow(s): print(f"{Fore.YELLOW}{s}{Style.RESET_ALL}", end="") def inputBlue(s): return ...
class Boardposs : def __init__(self,player1 = 'X', player2 = 'O'): self.size = {'c' : 7, 'r': 6} # 7 columns x 6 rows self.grid = [] self.first_player = True # True - player 1 on the move, False - player 2 on the move self.players = {True : player1, False : player2} # Anything except ? (question mark) AND 1 ...
""" Print the sum of digits in 100! This is a very easy question , I choose to learn python functional programming features from this I have used reduce(x, y, z) x is a binary operator that returns a value y is an iterable object (list, generator .... ) z is the starting value. ...
#Andreu Pomar Cabot #Ejercicio 7.4 - Cambiar espacios de un str por * def estrella(): final = frase.replace(" ","*") return final frase = str(input("Introduzca una frase con espacios: ")) final = estrella() print (final)
#Andreu Pomar Cabot #Práctica 3 - Programa que calcula el precio de una compra con iva print ("Este programa calcula el IVA de un producto \n") producto = str(input("¿Qué producto ha adquirido? \n")) IVA = int(input("¿Cuál es el tipo de IVA del producto? \n")) bimponible = float(input ("¿Cuál es la base imponible del p...
#Andreu Pomar Cabot #Práctica 5 - Determinadora de primos num = int (input ("Introduzca un número: ")) primo = True for i in range(2,num): if num%i==0: primo = False if primo == True: print ("Es primo") else: print ("No es primo")
#Andreu Pomar Cabot #Práctica 3 - Programa que calcula la media print ("Este programa calcula la media de tres notas \n") n1, n2, n3 = list(map(float, input ("Introduzca las tres notas cuya media quiera calcular (separadas por un espacio) \n").split())) media = (n1+n2+n3)/3 print ("La media de ",n1," ",n2," y ",n3," es...
#Andreu Pomar Cabot #Ejercicio 6 - Hacer un programa que pide números incrementales y los guarda en una lista print("Este programa pide números incrementales y los guarda en una lista") entrada = int (input ("Escriba un numero: ")) ultimo = entrada-1 lista = [] while entrada > ultimo: lista.append (entrada) ...
import time import matplotlib.pyplot as plt import numpy as np import random def ChangeMaking(d, S, coins, used): for s in range(S + 1): count = s newCoin = 1 for j in [c for c in d if c <= s]: if coins[s-j] + 1 < count: count = coins[s-j] + 1 newCoin = j coins[s] = count used[s] = ne...
acceleration = 9.8 on = True def distance_traveled(distance): if(distance > 100): print("distance traveled = ", distance, "\nGood going") elif(distance < 50): print("distance traveled = ", distance, "\nPathetic") else: print("distance traveled = ", distance, "\nnot bad") while(on)...
"""Plotting functions.""" import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import cm from scipy.optimize import OptimizeResult def plot_convergence(*args, **kwargs): """Plot one or several convergence traces. Parameters ---------- * `args[i]` [`OptimizeResult`, list of `Op...
from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: answer = 0 if root is None : return answer ...
# -*- coding:utf-8 -*- import math numbers = list(map(float, input().split(" "))) numbers.sort(reverse=True) a,b,c = numbers if a >= (b + c): print('NAO FORMA TRIANGULO') else: if (a ** 2) == (b ** 2) + (c ** 2): print('TRIANGULO RETANGULO') if (a ** 2) > (b ** 2) + (c ** 2): print('TRIAN...
# -*- coding: utf-8 -*- valorSegundos = int(input()) hours = int(valorSegundos / 3600) minutes = int((valorSegundos % 3600) / 60) seconds = int((valorSegundos % 3600) % 60) print('%d:%d:%d' % (hours, minutes, seconds))
# -*- coding: utf-8 -*- originalNumbers = list(map(int, input().split(" "))) newNumbers = originalNumbers.copy() newNumbers.sort() for x in newNumbers: print(x) print() for x in originalNumbers: print(x)
# -*- coding:utf-8 -*- ddds = { 61:'Brasilia', 71:'Salvador', 11:'Sao Paulo', 21:'Rio de Janeiro', 32:'Juiz de Fora', 19:'Campinas', 27:'Vitoria', 31:'Belo Horizonte' } value = int(input()) if value in ddds: print(ddds[value]) else: print('DDD nao cadastrado')
print('1. feladat:') # keszits programot ami egy neveket tartalmazó listában # megmondja hogy van e benne Pista es kiirja azt is hogy hanyadik elem # a listában a Pista x = ['Eszti', 'Patrik', 'Tamás', 'Brigi', 'Pista', 'Anna', 'Márk'] print('Pista' in x) print('A listában a Pista a {}. név.'.format(x.index('Pista'))) ...
print("Olá! para calcular seu IMC, insira os seguintes dados abaixo") peso = input("Digite seu peso: ") altura = input("Digite sua altura: ") IMC = float(peso) / float(altura) ** 2 print("O seu IMC é de:" ,IMC)
class Atm(object): def __init__(self,cardNumber, pinNumber, balanceAmount): self.cardNumber=cardNumber self.pinNumber=pinNumber self.balanceAmount=balanceAmount def CashWithdrawl(self, amount): self.amount=amount print(amount, "has been withdrawn from y...
# -*- coding: utf-8 -*- """ Created on Tue Jul 9 18:29:53 2019 @author: user """ #258. Add Digits class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ #input: 1~9 -> only one digit #output: 1~9 #input 10~.... ...
# Project Euler Problem 25 # Problem Brief: # Determine which term in Fibonacci sequence is # the first to have 1000 digits # Source: # Brian Puthuff # 2015.04.01 # function to get next fibonacci number def next_fib(a = [], f_one = [], f_two = []): carry, sum = 0, 0 for i in range(999, -1, -1): sum = f...
class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if not A: return [[]] aRow = len(A) aCol = len(A[0]) bCol = len(B[0]) res = [[0 for _ in ran...
class PowerSet: def __init__(self): self.line = 20000 self.step = 3 self.slots = [None] * self.line # создает массив с size количеством слотов def size(self): count = 0 for i in self.slots: if i != None: count += 1 return...
class Node: def __init__(self, v, d=None): self.value = v self.next = d class LinkedList: def __init__(self): self.head = None self.tail = None def add_in_tail(self, item): if self.head == None: self.head = item else: ...
class Queue: def __init__(self): self.queue_1 = [] self.queue_2 = [] def enqueue(self, item): return self.queue_1.append(item) def copy(self): self.queue_2.append(self.queue_1[-1]) self.queue_1.pop() def dequeue(self): if self.size_1() ...
class BSTNode: def __init__(self, key, val, parent): self.NodeKey = key self.NodeValue = val self.Parent = parent self.LeftChild = None self.RightChild = None class BSTFind: def __init__(self): self.Node = None # None если # в дереве вообще ...
class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class OrderedList: def __init__(self, asc): self.head = None self.tail = None self.__ascending = asc def compare(self, v1, v2): if v1 < v2: ...
def calc_volume(temp): if(temp.isnumeric()==False): raise ValueError("The length must be a positive integer") num = int(temp) return num*num*num #print(calc_volume("4"));
my_set = {1, 5, 7, 3, 8, 2} print(my_set) my_bitch = set ([1, 4, 6]) print(my_bitch) my_set.add(4) print(my_set) my_set.update([6, 9]) print(my_set) my_set.discard(3) print(my_set) my_set.remove(7) print(my_set) my_set.discard(7) print(my_set) returned_value = my_set.pop() print(my_set) print(returned_v...
"""# Outer enclosing function def print_msg(msg): # This is a nested function def printer(): print(msg) #calling printer() from inside print_msg() printer() print_msg("HELlo") #Define a closure # Outer enclosing function def print_msg(msg): ...
class Polygon: def _init_(self, no_of_sides): self.n = no_of_sides self.sides = [] for i in range(no_of_sides): self.sides.append(0) def input_sides(self): for i in range(self.n): self.side[i] = float(input("Enter side"+str(i+1)+" : "...
class Number: def add(self, a, b): return a+b def multiply(self, a, b): return a*b #instantiate an object n1 = Number() sum = n1.add(2, 5) print(sum) product = n1.multiply(2, 5) print(product)
#파이썬 자료구조 #리스트:sequence 자료구조를 사용 #sequence:순서가 있는 데이터 구조를 의미 #리스트,튜플,레인지,문자열등이 sequence 구조 사용 #리스트는 []을 이용해서 각 요소에 접근할 수 있다 msg = 'Hello,World!' #파이썬에서는 자료구조를 의미하는 접미사를 #변수명에 사용하기도 한다 list1_list = [] #빈 리스트 list2_list = [1,2,3,4,5] #숫자 list3_list = ['a','b','c'] #문자 list4_list = ['a','b','c',1,2,3,True] #혼합 print(l...
import tkinter as tk import time root = tk.Tk() root.geometry('400x400') root.title('canvasの使い方') #図形を壁画するキャンバスをウインド上に作成 canvas=tk.Canvas(root,width=300,height=300,bg="white") canvas.pack() #図形の壁画 dx=20 dy=20 square=canvas.create_rectangle(5,5,5+dx,5+dy,fill='red')#四角 x=150#四角の初期x座標 y=150#四角の初期y座標 while True: ...
import difflib # Rentrer le non des deux fichiers newFile = input("Enter the new filename: ") oldFile = input("Enter the old filename: ") # Print confirmation print("-----------------------------------") print("Comapraison des fichiers ", " > " + newFile, " < " +oldFile, sep = '\n') print("--------------------------...
class Description(): """Given a list of non negative integers, arrange them in such a manner that they form the largest number possible. The result is going to be very large, hence return the result in the form of a string. Input: The first line of input consists n...
income = float(input("Enter the annual income: ")) if income <= 556.02/.18: tax = 0 elif income <= 85528: tax = (income *.18) - 556.02 else: tax = 14839.02 + .32*(income-85528) tax = round(tax, 0) print("The tax is:", tax, "thalers")
from util import Stack, Queue from graph import Graph import random class User: def __init__(self, name): self.name = name class SocialGraph: def __init__(self): self.last_id = 0 self.users = {} self.friendships = {} def add_friendship(self, user_id, friend_id): ...
""" iterative binary search """ def binary_search(array, target): start = 0 end = len(array) while start <= end: mid = (start + end) // 2 if array[mid] == target: return mid if array[mid] > target: end = mid - 1 else: start = mid + 1 return None if __name__ == "__main__": ta...
def rec(d, n): if d == n: print("_" * 4 * d, end='') print("\"재귀함수가 뭔가요?\"") print("_" * 4 * d, end='') print("\"재귀함수는 자기 자신을 호출하는 함수라네\"") print("_" * 4 * d, end='') print("라고 답변하였지.") return print("_" * 4 * d, end='') print("\"재귀함수가 뭔가요?\"") print("_" * 4 * d, end='') print("\"잘 들어보게. 옛날옛날 한 산 꼭대기에...