text stringlengths 37 1.41M |
|---|
import math
def solution(n):
if int(math.sqrt(n)) == math.sqrt(n):
return int((math.sqrt(n) + 1) ** 2)
else:
return -1
print(solution(121))
|
def solution(n):
base3 = ""
while n:
base3 = str(n % 3) + base3
n = n // 3
ans = 0
for i in range(len(base3)):
ans += int(base3[i]) * (3 ** i)
return ans
print(solution(45))
|
'''
리스트 및 문자열
'''
#여러 줄 한번에 쓰기
multiline="""
TEST ECHO
1 2 3
"""
print(multiline)
testStr = "Life is Good"
print(testStr[0:4])
'''
ERROR CASE1
testStr2 = "ABCD"
testStr2[0] = 'B'
'''
print("ERROR IS %d"%98)
testStr3 = "i eat {0} applies"
print(testStr3.format(10))
testStr4 = "i eat {number} applies"
print(testStr4... |
from typing import List
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h:
h[num] = i... |
import itertools
from collections import *
original = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
rotated = list(zip(*reversed(original)))
# print(rotated)
# 구조체 테스트
class TEST():
def __init__(self, L):
# x, y : 좌표
self.x = L[0]
self.y = L[1]
# a : 0은 구조물 설치, 1은 ... |
'''
def solution(board):
for i in range(len(board)):
for j in range(len(board[0])):
if i == 0 or j == 0:
continue
if board[i][j] != 0:
board[i][j] = min(board[i - 1][j - 1], board[i - 1][j], board[i][j - 1]) + 1
ret = []
for i in range(len(boa... |
def solution(record):
answer = []
data = {}
for s in record:
s = s.split(" ")
if s[0] == "Leave":
pass
else:
data[s[1]] = s[2]
for s in record:
s = s.split(" ")
if s[0] == "Enter":
answer.append(f"{data[s[1]]}님이 들어왔습니다.")
... |
#NOT GATE implementation using Single Layered Perceptron
import numpy as np
import random
# function to predict output value
# if calculated value is less than 0, predict 0
# if calculated value is greater than or equal to 0, predict 1
def predict(X, w, b):
p = np.sign(X*w + b)
if p == -1:
p = 0
else:
... |
import unittest
from .models import news
News = news.News
class NewsTest(unittest.TestCase):
'''
Test class to test the behaviour of the News class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_news = News('By Ciaran Barnes','Huronr... |
class Solution:
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 1:
return True
data = bin(num)[2:]
return data.startswith("100") and (data[3:].count("0") % 2 == 0 and data[3:].count("1") == 0)
|
# Items to sort has to be of fixed length
# For fixed set of distinct values
# here chars sorting can be done in order of n
# space complexity of n
# stable sort
import unittest
import string
import random
class LSDRedix:
def __init__(self, items):
self.aux = [None]*len(items)
self.a = items
... |
# Heap sort
# No extra space
# O(nlogn) run time compexity
def sink(items, idx, last_index):
while idx*2+1 <= last_index:
mx_idx = idx*2+1
if idx*2+2 <= last_index and items[idx*2+2] > items[idx*2+1]:
mx_idx = idx*2+2
if items[mx_idx] > items[idx]:
items[mx_idx], it... |
'''
S08Q03
Ask the user to enter a number.
- If the user enters a number as 5, then
generate the following string :
- 00001111222233334444
- If the user enters the number as 3, then
generate the following string :
- 001122
'''
x = int(input("Enter a num:"))
for i in range(x):
a = str(i)*(x-1)
print(a,end = '... |
'''
Write a program that generates a HTML file.
Prompt the user for webpage title and webpage body contents.
The webpage body should contain
one main header,
one sub header, and
at least 2 paragraphs.
A sample output is shown below
'''
fh = open('html_file.txt','w')
fh.write('\n')
fh.write('\n')
f... |
'''
S17Q03 - Phonebook Search Program
Write a Python program that takes a file name as its argument.
This file contains names of people and their corresponding contact numbers.
- Prompt the user to enter a few characters to search for.
- Print all the names that contain this sequence of characters
in the ascen... |
'''
S04Q01
- A Chemical plant has a tank for storing ethanol.
- When the tank is more than 80% full, it
should raise an alarm to close the valve.
- When the tank is less than 20% full, it
should send an SMS to buy more liquid.
- The total tank ... |
'''
S05Q03
- Take a number as input from the user.
Print all the squares of numbers from 1 to any large number.
The numbers printed should be less than
the number given as input by the user
'''
def user_input():
x = int(input("Enter the user number:"))
return x... |
'''
S13Q01
Ask the user to enter a 3 digit number, till he enters 0.
Discard all numbers that are not 3 digit numbers.
From all the 3 digit numbers entered by the user,
find and print the prime numbers in descending order.
'''
def user_input():
x = int(input("enter the num:"))
return x
a = 1
numbers... |
# Advanced Scientific Programming in Python, autumn school, Trento, 2010
# Day 1, Exercise 1 (unit testing and coverage)
# Author: Pietro Berkes <berkes _at_ brandeis _dot_ edu>
def find_maxima(x):
"""Find local maxima of x.
Example:
>>> x = [1, 2, 3, 2, 4, 3]
>>> find_maxima(x)
[2, 4]
Input... |
# Uses python3
import sys
import random
def partition3(a, l, r):
"""
a => list of numbers being sorted
l => starting index of the list
r => the last index of the list
Checks the list from index (l + 1) to r for values that are less than or
equal to a[l]. If the value is equal to or less than ... |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
import pandas as pd #importing pandas in order to read csv file
# In[5]:
data=pd.read_csv("C:/Users/Acer/Downloads/iris.csv")# storing the csv file components in data variable
# In[6]:
print(data) #checking the data optional
# In[7]:
x=data[["Id","SepalLengt... |
from collections import OrderedDict
import string
import sys
LetterList = [chr(x) for x in range(65, 91)]
LetterList.insert(0, 0)
LetterNumDic={'A':1}
#print(LetterList)
def CalculateNumber():
'''calculates number corresponding to each character based on series
A=1
B=A*2+2
C=B*2+3
...
and save... |
# -*- coding: utf-8 -*-
"""
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
Monthly interest rate = (Annual interest rate) / 12.0
Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
Updated balance each month = (Monthly unpaid... |
# -*- coding: utf-8 -*-
"""
1. balance - the outstanding balance on the credit card
2. annualInterestRate - annual interest rate as a decimal
3. monthlyPaymentRate - minimum monthly payment rate as a decimal
Monthly interest rate= (Annual interest rate) / 12.0
Minimum monthly payment = (Minimum monthly payment ... |
from Node import Node
from SingleLinkedList import LinkedList
"""
<Circular linked List class>
Example :
1->2->3->1
This linked list does not have a null ending pointer. the node before last is
next to the head node
Here 1 is the head node and 3 is the node before last and it is curularly next to the head
... |
import math
def solution(n):
answer = 0
if n == 2:
return 1
elif n == 3:
return 2
for i in range(4, n+1):
if i % 2 == 0 or i % 3 == 0:
continue
if prime(i):
answer = answer + 1
return answer + 2
def prime(n):
for i in range(2, int(math.... |
def solution(arr1, arr2):
answer = [[0 for col in range(len(arr2[0]))] for row in range(len(arr1))]
for i in range(len(arr1)):
for j, k in enumerate(arr1[i]):
for m, n in enumerate(arr2[j]):
answer[i][m] += k * n
return answer
print(solution([[1, 4], [3, 2]... |
def solution(s):
answer = []
s=s[:-2]
s= s.replace("{","")
s= s.split("},")
mTuple = []
for i in s:
mTuple.append(i.split(','))
for i in range(len(mTuple)):
head = min(mTuple, key=len)
for j in head:
if int(j) not in answer:
answer.append... |
def solution(n, arr1, arr2):
answer = []
for i in range(n):
temp = bin(arr1[i] | arr2[i])[2:]
if len(temp) < n:
temp = ('0'*(n-len(temp)))+temp
strtemp = ''
for j in temp:
if j == "1":
strtemp = strtemp + '#'
elif j == "0":
... |
# 우선순위 큐가 생각남
import queue
def solution(arr, divisor):
answer = []
myQueue = queue.PriorityQueue()
for i in arr:
if i % divisor == 0:
myQueue.put(i)
if myQueue.qsize() == 0:
answer.append(-1)
else:
for i in range(myQueue.qsize()):
answer.append(myQue... |
# -*- coding: utf-8 -*-
from typing import List
def search_in_rotated_sorted_array(nums: List[int], target: int) -> int:
l = 0
r = len(nums) - 1
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return m
if target > nums[m]:
if target > nums[r] >= nums[... |
# -*- coding: utf-8 -*-
import os
import sys
from typing import List
file_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(file_dir, "../"))
from graphs import Graph
def topsort(G: Graph) -> List[str]:
"""
Topologically sort the graph
"""
i = 0
visited = set()
ft... |
# -*- coding: utf-8 -*-
from collections import Counter
from itertools import combinations_with_replacement
from typing import List
def three_sum(nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
nums = Counter(nums)
zero_sums = set()
for a, b in combinations_with_replacement(... |
class Animal(object):
def run(self):
print('animal is running!')
class Dog(Animal):
# pass
def run(self):
print('Dog is running')
class Cat(Animal):
# pass
def run(self):
print('Cat is running')
dog = Dog()
cat = Cat()
# dog.run()
# cat.run()
a = list()
b = Dog()
c = Ca... |
classmates = ['Micheal','Bob','Tracy']
print(classmates)
print(len(classmates))
print(classmates[0],classmates[1],classmates[2])
print(classmates[-1])
classmates.append('bubby')
print(classmates)
classmates.insert(1,'steven')
print(classmates)
classmates.pop()
print(classmates)
classmates.pop(-2)
print(classmates)
clas... |
def capitalize(string):
return string[:1].upper() + string[1:]
def capitalize(s):
return s.capitalize() |
#rock beats scissor
#scissor beats paper
#paper beats rock
print("Rock ... Paper ... Scissors...")
player_one_choice=input("Player 1, make your move: ")
player_two_choice=input("Player 2, make your move: ")
if player_one_choice and player_two_choice:
if player_one_choice == player_two_choice:
print("Clash, its a ... |
def intersection(l1, l2):
return [val for val in l1 if val in l2]
def intersection(list1, list2):
return [val for val in set(list1) & set(list2)]
|
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import datetime
from datetime import date
to_date = date.today()
#Number of top countries to be reported
topCountryNum = 23
#Graph size matters
desired_width=360
pd.set_option('display.width', desired_width)
pd.set_option('display.max_columns'... |
#!/bin/python3
import sys
def catAndMouse(x, y, z):
' Case for Cats and Mouse '
x_diff = abs(x - z)
y_diff = abs(y - z)
if x_diff == y_diff:
return "Mouse C"
elif x_diff < y_diff:
return "Cat A"
elif x_diff > y_diff:
return "Cat B"
if __name__ == "__main__":
q = ... |
#!/bin/python3
import sys
def beautifulTriplets(d, arr):
ret_val = 0
for mem in arr:
ret_val += 1 if arr.__contains__(mem + d) and arr.__contains__(mem + 2 * d) else 0
return ret_val
if __name__ == "__main__":
n, d = input().strip().split(' ')
n, d = [int(n), int(d)]
arr = list(map(... |
'''https://www.hackerrank.com/challenges/merge-the-tools/problem'''
import collections
def merge_the_tools(string, k):
t = []
unique_word = []
for i in range(0, len(string), k):
t.append(string[i:i + k])
for word in t:
word = "".join(collections.OrderedDict.fromkeys(word))
prin... |
class bounds(object):
def __init__(self, minimum = None, maximum = None):
self.minimum = minimum
self.maximum = maximum
def __call__(self, val):
if isinstance(val, str):
val = len(val)
if self.minimum is not None and val < self.minimum:
return Fa... |
# Bruce Maxwell
# Spring 2015
# CS 251 Project 8
#
# Modified from KNN class test
#
import sys
import data
import classifiers
import numpy as np
def main(argv):
'''Reads in a training set and a test set and builds two KNN
classifiers. One uses all of the data, one uses 10
exemplars. Then it classifies the test da... |
import math
import pandas as pd
def return_pixel(row):
"""Takes in a latitude and longitude coord and returns a pixel location"""
lat = row['location-lat']
lon = row['location-long']
assert(isinstance(lat, float))
assert(isinstance(lon, float))
map_width = 360
map_height = 540
map_lo... |
i=2
while(i<100):
j=2
while(j<=i/j):
if not(i%j):break
j=j+1
if(j>i/j):print (i,"是素数")
i=i+1
print("good bye!") |
var=10
while var>0:
print('当前变量值:',var)
var=var-1
if var==5:
break
print("good bye!") |
is_started = False
while True:
command = input('> ').lower()
if command == "start":
if is_started:
print("Car is already started")
else:
print("Car started")
is_started = True
elif command == "stop":
if not is_started:
print("Car is alr... |
# https://www.practicepython.org/exercise/2014/04/30/13-fibonacci.html
def fib(num):
if num == 1:
return 1
elif num == 0:
return 0
return fib(num - 1) + fib(num - 2)
print(fib(1))
print(fib(10))
|
# https://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 25, 57, 36]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
common_without_duplicates = [item for item in set(a) & set(b)]
# One way not able to remove duplicates.
# common_item_list = [item for item ... |
is_hot = False
is_cold = False
if is_hot:
print("Coffee is hot")
elif is_cold:
print("Coffee is cold")
print("I love cold coffee")
else:
print("Chocolate coffee yum! nor hot nor cold")
print("Enjoy your coffee")
# Exercise
house_price = 10**6
has_good_credit = True
if has_good_credit:
down_paymen... |
# Tuples are like list but these are immutable
numbers = (1, 2, 3) # For tuples we use parentheses
print(numbers)
# Unpacking (You can do the same with list as well)
coordinates = (14, 2, 3)
# x = coordinates[0]
# y = coordinates[1]
# z = coordinates[2]
# Above all lines can be written as below.
x, y, z = coordinat... |
import numpy as np
import src.niave_bayes as nb
import random
import pandas as pd
def classify_zero_r(training_class_obs, num_to_classify):
""" Classifies according to the most common class in the training data.
Args:
training_class_obs: the observations of class in the training data
... |
a=input()
b=a[::-1] #String is reversed and stored in b
if (a==b): # If a and b both are equal string is Palindrome
print("String is Palindrome")
else:
print("String is not Palindrome")
|
fact=int(input("input any number"))
# input any number
factorial = 1
#predefined factorial of 0
if fact < 0:
print("factorial is not possible")
elif fact == 0:
print("factorial of "+str(fact) +" is "+str(factorial))
else:
fact1=fact
while(fact>2):
fact-=1
fact1=fact1*(fact)
print("fa... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 12 21:01:31 2021
@author: I'am the best
"""
#1-匿名函数的定义
def sqr(x):
return x ** 2
print(sqr)
# <function sqr at 0x000000BABD3A4400>
y = [sqr(x) for x in range(10)]
print(y)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
lbd_sqr = lambda x: x ** 2
print... |
import numpy as np
def create_df(data_path):
# input: the path of the csv file
# output: data frame
df = []
return df
def nan_columns(df):
# input: data frame
# output: a list of names of columns that contain nan values in the data frame
nancolumns = []
return nancolumns
def categoric... |
#!/usr/bin/env python
from random import randint
DESCRIPTION = 'Find the greatest common divisor of given numbers.'
def gcd(number_1, number_2):
while number_1 != 0 and number_2 != 0:
if number_1 > number_2:
number_1 %= number_2
else:
number_2 %= number_1
return number... |
#Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count o... |
counts = dict()
str = raw_input("Enter: ")
for i in str:
counts[i] = counts.get(i,0) + 1
print counts
for name,occurrence in counts.items():
if occurrence>1:
print name, occurrence |
#to control the mouse
#from pynput.mouse import controller
#def controlmouse():
#mouse = controller()
#mouse.position=(420,96) -->the cursor will move to that pixel position(x,y)
#controlmouse() -->the moment ill call this function, the cursor will move to that position
#to control keyboard
#from pynput.keyboard im... |
#webbrowser模块的open() 可以打开新的浏览器 打开指定的url
from selenium import webdriver
b= webdriver.firebox()
b.get('http://mail.sina.com.cn//')
l = b.find_elemnet_by_link_text('Read It Online')
l.click() |
#!/usr/bin/env python3
# Chapter 9 Project Backup to Zip
# Copies a folder recursively into a zip file and names it incrementally.
import os
import zipfile
#如果不修改工作目录 就默认去这个类里面的的同级文件夹里面
#这样调整到e盘
#os.chdir('e:\\')
def backupToZip(folder):
folder = os.path.abspath(folder)
#os.path.abspath(path) #返回绝对路径
number ... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
def main():
"""Em python a tipagem é dinâmica
- O python identifica o objeto associado com letras e a partir dai
disponibiliza os métodos
- Tipagem forte, não converte de forma implícita
- Com python também é possível fazer sobrecarga de operadores.
... |
#import modules
import os
import csv
#create variables for calculations
candidates = []
totalvotes = 0
votecounter = []
dataset = ["data"]
#looping through dataset
for data in dataset:
#setting up csv
with open("C:\\Users\\ericl/Desktop/Course/python-challenge/PyPoll/Resources/election_data.csv... |
print("Enter any number: ")
number = int(input())
temp = int(number)
Sum = 0
while(temp != 0):
rem = temp % 10
Sum = Sum + (rem * rem * rem)
temp = temp // 10
if(number == Sum):
print ("Armstrong Number")
else:
print ("Not an Armstrong Number")
|
class X:
def m1(self):
print("in m1 of x")
class Y(X):
def m2(self):
print("in m2 of Y")
y1 = Y()
print(X.__bases__)
print(Y.__bases__)
y1.m1()
y1.m2()
|
def myfunc(a, b):
print("hello")
c = a + b
print(c)
return c
print(myfunc)
c = myfunc(1, 2)
print(c + 8) # using the return in the another variable
var = myfunc # accessing address of the my func to variable
var(4, 5)
print(var)
|
# python3
def fibonacci_number_again_naive(n, m):
assert 0 <= n <= 10 ** 18 and 2 <= m <= 10 ** 3
if n <= 1:
return n
previous, current = 0, 1
for _ in range(n - 1):
previous, current = current, (previous + current) % m
return current
def pisanoPeriod(m):
previous, current... |
def pow(n,m):
if(m < 0):
raise("m must be greater than or equal to 0")
elif(m == 0):
return 1
elif(m % 2 == 0):
# this is an optimization to reduce the number of calls
x = pow(n, m/2)
return (x * x)
else:
return n * pow(n, m - 1)
print(pow(2,3))
print(pow(4,3))
print(pow... |
def binary_search(my_list, target):
return helper(my_list, target, 0, len(my_list) - 1)
def helper(my_list, target, start, end):
if(start <= end):
mid = int(start + (end - start) / 2)
if(my_list[mid] == target):
return mid
elif(target < my_list[mid]):
return helper(my_list, target,... |
class Word:
def __init__(self, word):
self.raw_word = word
self.characters = list(word)
def to_string(self):
return self.raw_word
# TODO: Has to be moved to Painter
def display_masked_word(self, selected_letters = []):
display_string = ""
for letter in self.char... |
'''https://www.hackerrank.com/challenges/python-print/problem'''
from __future__ import print_function
n = int(input())
for i in range(1,n+1):
print(i, end='')
|
print "Kalispera"
n=input("Give Fibonacci Sequence Term ")
terms=[1,1]
for i in range (1,n-1):
p=terms[-1]+terms[-2]
terms.append(p)
p=terms[-1]
print p
import random
prwtos=1
for i in range (20):
a=random.randint(1,1000000)
print a%p
print a**p
if a**p == a%p:
print "ka... |
"""
Tests tokenize_by_lines function
"""
import unittest
from lab_2.main import tokenize_by_lines
class TokenizeByLinesTest(unittest.TestCase):
"""
Checks for tokenize_bby_lines function
"""
def test_tokenize_by_lines_ideal(self):
"""
Tests that tokenize_by_lines function
... |
import fileinput
def swap(array, index1, index2):
"""
Función para realizar el intercambio de valores dentro de un arreglo.
Tomamos los índices donde se encuentran los valores que deseamos
intercambiar, y el arreglo correspondiente, y realizamos el intercambio.
Args:
array: Arreglo del que... |
def average():
#print("first average called")
sum = 0.0
cnt = 0
while 1:
print("average before yield")
age = yield
if age is None:
break;
sum += age
cnt += 1
return sum / cnt
def average_group(results, key):
while 1:
print('before a... |
# atbs - timed multiplication quiz
import random, time, pyinputplus as ip
noQs = 10
correctAnswers = 0
difficulty = ip.inputMenu(['easy','medium','hard']) # provide options to user
if difficulty == 'easy':
t = 10 # t will represent the time allocated for each guess
elif difficulty == 'medium':
t ... |
"""
Author: Gabriele Pompa
Identification Number: ABCXYZ [substitute with your Unisi Identification Number]
Date: 30-Mar-2020
File name: Ex_Sheet_4_Num_1.py
Description: This script filters rows of a given DataFrame based on value and
smaller-or-equal condition applied to the first column.
... |
"""
Author: Gabriele Pompa
Identification Number: ABCXYZ [substitute with your Unisi Identification Number]
Date: 15-Mar-2020
File name: Ex_Sheet_1_Num_4.py
Description: This computes the product of elements in a list.
"""
def listMul(l):
"""
Function listMul(l) computes and returns the product of elements i... |
salario = float (input())
if (salario <= 400.00):
reajuste = salario * 0.15
novo_salario = salario + reajuste
percentual = 15%
print ("Novo salario: {:.2f}" .format(novo_salario))
print ("Reajuste ganho: {:.2f}" .format(reajuste))
print ("Em percentual: {}" .format(percentual))
elif (salario >=... |
num = float (input ())
if (num >= 0 and num <= 25):
print ('Intervalo [0,25]')
elif (num > 25 and num <= 50):
print ('Intervalo (25,50]')
elif (num > 50 and num <= 75):
print ('Intervalo (50,75]')
elif (num > 75 and num <= 100):
print ('Intervalo (75,100]')
else:
print ('Fora de intervalo') |
"""Decodes messages."""
import encoder
import filler
def _decrypt_message(encrypted_message, shift):
"""
Decrypt encrypted message using the given shift.
:param encrypted_message: Message which was encrypted by _encrypt_message.
:param shift: The amount of letters needed to shift forward.
:return... |
"""Simulation."""
def simulate(wmap: list, moves: list) -> list:
"""
Simulate a robotic lawn mower.
:param wmap: A list of strings indicating rows that make up the map.
The map is always rectangular and the minimum given size is 1x1.
Cut grass is indicated by the symbol ... |
"""Timekeeping."""
def seconds(time_string, from_seconds_in_minute):
"""
Amount seconds in time_string.
:param time_string: current time as a time_string
:param from_seconds_in_minute: current amount of seconds in one minute
:return:amount seconds
"""
a = from_seconds_in_minute
m, s =... |
"""Generate list of princesses."""
from base64 import b64decode
def read(read_file) -> list:
"""
Read, decrypt and save information from the given file.
:param file: the file we read from
:exception: Exception
:return: lines
"""
try:
f = open(read_file)
except FileNotFoundErr... |
def list_filling(): # Ввод значений через пробел, а затем изменение типа элементов списка
print("Введите произвольное количество чисел через пробел")
temp = input().split(' ')
temp = [float(x) for x in temp]
return temp
def list_changing(local_list): # Умножение всех значений списка на 0.13 и... |
from exeptions import MaxPizzaAmount, Discount
class Order:
order = []
finalCost = 0
status = False
def add(self, pizza):
try:
if len(self.order) == 15:
raise MaxPizzaAmount(len(self.order))
else:
self.order.append(pizza)
... |
# 생성
d = {'basketball': 5, 'soccer': 11, 'baseball': 9}
print(d, type(d))
# 인덱싱 대신 키 객체로 검색
print(d['basketball'])
# 없는 키 객체면 당연히 에러
# print(d['volleyball'])
# mutable
d['volleyball'] = 6
print(d)
# 길이
print(len(d))
# 확인
print('soccer' in d)
print('volleyball' not in d)
# 다양한 사전 생성
d = dict()
print(d)
d = dict(on... |
# 숨겨진 카드의 수를 맞추는 게임입니다. 1-100까지의 임의의 수를 가진 카드를 한 장 숨기고 이 카드의 수를 맞추는
# 게임입니다.
# 아래의 화면과 같이 카드 속의 수가 57인 경우를 보면 수를 맞추는 사람이 40이라고 입력하면 "더 높게",
# 다시 75이라고 입력하면 "더 낮게" 라는 식으로 범위를 좁혀가며 수를 맞추고 있습니다.
# 게임을 반복하기 위해 y/n이라고 묻고 n인 경우 종료됩니다.
import random
n = random.randrange(100) + 1
print(n)
print('수를 결정하였습니다. 맞추어 보세요')
print(... |
# 한 줄 문자열 정의
s = ''
str1 = 'Hello World'
print(type(s), type(str1))
# 여러줄 문자열 정의
# '"'가 3개 있으면 여러 줄 string을 지원하나, 주석으로도 사용 가능하다
str2 = """ABCDEFG
abcdefg
가나다라마바사
123456789
"""
print(str2)
# escape
print('Hello\nWorld\nI Say "hello World"')
print("Hello\nWorld\nI Say \"hello World\"")
#
# sequence 타입이 가지는 공통적 연산
#
... |
# class Point
# class 내에 변수를 만들지 않는데, 그 이유는 클래스 인스턴스가 class Point와 다른 공간을 사용하기 때문
# p = Point()라고 할 때, p가 가지는 공간과 class Point의 공간이 다름.
# 따라서 Point안에 x라는 변수가 있을 때 p.x를 하면 파이썬 룰에 따라 p에 없으면 Point에서 x를 찾으나
# 실제로 p안에 x가 없어 여러 개의 Point 인스턴스가 생성될 시 문제될 수 있음
# class instance method에 parameter로 self가 들어오면 self는 클래스 인스턴스변수를 지칭한... |
class BuildProducts(object):
'''A class to help keep track of build products in the build.
Really this is just a wrapper around a dict stored at the key
'BUILD_TOOL' in an environment. This class doesn't worry about
what stored in that dict, though it's generally things like
SharedLib configurators... |
number_list = [6, 2, 1, 9, 4, 7]
print(number_list)
# 인덱스 번호로 리스트에 들어있는 값을 가져올 수 있어요.
print(number_list[0])
print(number_list[3])
# 인덱스 번호로 해당 인덱스의 값을 변경 할 수 있어요.
number_list[2] = 4
print(number_list[2])
# append함수로 리스트에 값을 추가할 수 있어요.
number_list.append(99)
print(number_list)
# pop함수로 리스트의 마지막 값을 반환 받고 리스트에서는 삭제 할... |
print("+----------------------------------------------------------+")
print("| 숫자 야구 게임 |")
print("+----------------------------------------------------------+")
print("| 수비수가 고른 세자릿수를 맞춰보세요. |")
print("| 0에서 9까지 서로 다른 숫자이다. (같은 숫자 사용 금지) |")
print("| 스트... |
#this program calculates the average height of students in a list
import itertools #this import itertools is used to print more than one list using one for loop
for i in range(0,1000):
suma=0
studentName = []
studentHeight = []
Size=int(input("Enter the number of students in the list\n"))
print("\n")
for j in ran... |
number_list = []
n = int(input("Enter the list size "))
print("\n")
for i in range(0, n):
print("Enter number at index", i, )
item = int(input())
number_list.append(item)
print("User list is ", number_list) |
#calculate the number of cans required to paint the area of wall
#user should enter the height and width of the wall in meters
#calculate the area and then calculate the number of cans required
#formula for calculating the number of cans = 1 can = 5 meters square area of wall
# height = 2 width = 4 -> no of cans = (2X4... |
#terminal calculator
for i in range(0,999999999):
#function for addition
def addition(a,b):
return a + b
#function for subtraction
def subtraction(a,b):
return a-b
#function for multiplication
def multiplication(a,b):
return a*b
#function for division
def divisi... |
# Computer Architecture Lab 8 - 05-03-2018
# Assignment: Write a program to simulate Scoreboard Technique.
# Module : Decode Instructions for Scoreboard Simulator from assembly code in the SCB.asm file
# -- Eshita Arza (COE15B013)
# -- Akshay Kumar (CED15I031)
# -- Aditya Prakash (CED15I025)
import re # imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.