text
stringlengths
37
1.41M
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def compare(a, b): if a is None and b is None: return True if a.val != b.val: return False if a is not None and b is not None: return com...
import pandas as pd fixed_df = pd.read_table('telrecords.csv', ";") base_of_numbers = list(fixed_df.loc[:, 'caller']) base_of_innumbers = list(fixed_df.loc[:, 'caller']) accepted = [] def inline_calls(number): for i in base_of_numbers: right = base_of_numbers[base_of_numbers['caller'] == number]['c...
## IMPORTS GO HERE from math import pi ## END OF IMPORTS #### YOUR CODE FOR get_area GOES HERE #### def get_area(radius): r=radius area=pi*pow(radius,2) return area #### End OF MARKER #### YOUR CODE FOR output_parameter GOES HERE #### def output_parameter(radius): r=radius parameter=2*pi*radius print 'Th...
def checkPalindrome(inputString): return inputString == inputString[::-1] ''' Alternative Solution''' ''' length = len(inputString) for i in range((length+1) // 2): if inputString[i] != inputString[length-1-i]: return False return True '''
__author__ = 'BHS-programing' def findAverage(cost, items): average = cost/items print("Average item cost is $ "+ str(average)) def costDisplay(cost): print("Total cost of items is $" + str(cost)) numItemsPurchased = int(input("How many items? ")) totalCostItems = 0 for numItemsPurchased in range(numIt...
""" Machine Learning(기계 학습) -> Deep Learning(심층 학습) training data set(학습 세트) / test data set(검증 세트) 신경망 층을 지나갈 때 사용되는 가중치(weight) 행렬, 편항(bias) 행렬을 찾는 게 목적 오차를 최소화하는 가중치 행렬을 찾아야 한다 손실(loss) 함수 / 비용(cost) 함수의 값을 최소화하는 가중치 행렬 찾기 손실 함수: - 평균 제곱 오차(MSE: Mean Squared Error) - 교차 엔트로피(Cross-Entropy) """ import numpy a...
import numpy as np import matplotlib.pyplot as plt def numerical_diff(fn, x): """함수 fn과 점 x가 주어졌을 때 x에서의 함수 fn의 미분(도함수) 값""" h = 1e-4 # 0.0001 return (fn(x + h) - fn(x - h)) / (2 * h) def f1(x): return 0.001 * x**2 + 0.01 * x def f1_prime(x): """근사값을 사용하지 않은 함수 f1의 도함수""" return 0.002 * x...
x=2 y=3 for i in range(100000): n=y/x if int(n)==n: y=y+1 x=2 elif int(n)!=n: x=x+1 if x==y: print(y) #while x <= y or int(n)==n: # n=y/x # # if int(n)==n: # print("Ist keine Primenzahl") # elif int(n)!=n: # x=x+1 #if x==y: # print(y...
# Task 1 - while loop that repeats forever - comment this task later so you don't run into infinite loop later number = 1 while True: print(number) number += 1 # Task 2 - print only the first 10 integers and calculate the sum of these numbers number_2 = 1 sum = 0 while number_2 < 11: print(number_2) su...
input_date = input("Give me today's date with this format: e.g. 2021-02-24:\n") date = input("Give me your birth date with the same format:\n") days = 0 daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # Spliting the text to list element for i in date: born = date.split('-') for j in input_date: ...
''' Dictionaries Create a function that takes 2 dictionaries and 1 list as inputs. The output of the function should be a dictionary with one key for each value in the input list where the corresponding value is a list of key pairs that indicate where the input dictionaries match for that particular value. See exampl...
# Вывести последнюю букву в слове word = 'Архангельск' print(word[-1]) # Вывести количество букв "а" в слове counter = 0 word = 'Архангельск' for letter in word: if letter.lower() == 'а': counter += 1 print(f'Word {word} has {counter} \'a\' char(s) \n') # Вывести количество гласных букв в слове word = ...
# from typing import Number from numbers import Number def sign(val: float) -> int: """Return 1 or -1 to represent the sign of the given value""" return -1 if val < 0 else 1
# codding utf-8 import turtle #import tkSimpleDialog # 2.x python import random import math def gotoxy(x, y): turtle.penup() turtle.goto(x, y) turtle.pendown() def draw_circle(rad, color): turtle.fillcolor(color) turtle.begin_fill() turtle.circle(rad) turtle.end_fill() turtle.speed(0) ...
import sys def checkAnagrams(strA, strB): if len(strA) != len(strB): # trivial case return 'no' else: if sorted(strA) == sorted(strB): return 'yes' else: return 'no' print('enter strings and find out if they are anagrams') print('exit with ctrl-c\n') wh...
#task01 """ 0. Дан список чисел, заменить каждое число на квадрат этого числа. [1, 2, 3, 4] -> [1, 4, 9, 16] """ spis_OK = [1, 2, 3, 4] def f(spis_OK): for i in range(len(spis_OK)): spis_OK[i] = spis_OK[i] ** 2 return spis_OK print(f(spis_OK))
# Task03 """ Дан список, содержащий положительные и отрицательные числа. Заменить все элементы списка на противоположные по знаку. Например, задан список [1, -5, 0, 3, -4]. После преобразования должно получиться [-1, 5, 0, -3, 4].""" # a = [-4, -2, -3, 4, -6, 4, 343] def reverse_values(a): for i in range(len(a)): ...
#task 05 """ Напишите программу, запрашивающую имя, фамилия, отчество и номер группы студента и выводящую введённые данные в следующем виде: ************************************ *Лабораторная работа № 1 * *Выполнил(а): ст. гр. ЗИ-123 * *Иванов Андрей Петрович * ************************************ """ # a = ...
# Task 15 """ 15. Программа переводчик на соленый язык. Правило: после каждой гласной вставляем с + сама гласная. Привет -> Приcивеcет Сальса -> саcальсаcа """ vowels = ['а', 'о', 'и', 'е', 'ё', 'э', 'ы', 'у', 'ю', 'я'] a = [i for i in input('Введите фразу по-русски:')] b = [] s = 'с' c = '' for i in range(len(a))...
#task04 """ Вывести на экран 10 первых простых чисел используя функцию задания 1 Подсказка: >>if is_prime(num): print(num) """ a = int(input('Введите кол-во простых\n>')) list = [2] j = 3 def is_prime(b): for i in range (2, b): if b % i is not 0: i += 1 else: return b return 0...
#Task 02 """ Создать класс Автосалон содержащий информацию: адрес, имя, список доступных машин. Реализовать методы для отображения всех доступных машин, добавления новых машин, покупки машин (после покупки машина удаляется из списка) + проверки на наличие такой машины в салоне Пример >> car1 = Car(‘Audi’, ‘Red’, ‘1999...
x=int(input("enter a 3 digit number")) print(x%10) x=x//10 print(x%10) x=x//10 print(x%10)
__all__ = ['date_range', 'get_past_date', 'parse_date'] import datetime def date_range(since=datetime.date.today(), until=datetime.date.today()): """Get date range from `since` until `until`. :type since: datetime.date :param since: Earliest date of the range. :type until: datetime.date :param ...
import pandas def moving_average(series, n): #calculate moving average #the outputing numpy ndarray is the output outcome=pandas.Series(series).rolling(window=n).mean().iloc[n-1:].values return print(outcome) #testing array x = [87, 56, 16, 97, 45, 75, 41, 863, 90.2, 4] #testing the function with window...
import copy from typing import List, Tuple from environment import Environment class Board(object): """board for the game /* * ///////////////////////////////////////////////// * // //////////////////////// 棋盘表示, 坐标, 一维坐标, 字母 * // Y * // ^ * // S 18 | * // R 17 | ...
class Heap: def __init__(self): self.storage = [] def insert(self, value): # add the value to the end of the array self.storage.append(value) # bubble it up self._bubble_up(len(self.storage) - 1) def delete(self): # store reference to first heap element max_val = self.storage[0] ...
# full_name = "Amanda" # birth_year = input ("Qual ano voce nasceu?") # year = 2019 # print(year - int(birth_year)) # lbs = input ("Quantas lbs voce quer converter? => ") # kg = int (lbs) * 0.45 # print (int(kg)) # ---------------------------------------------------------------- # name = "Ana Julia" # print(name[1:5]) ...
# Given an integer array nums, find the contiguous subarray (containing at least one number) # which has the largest sum and return its sum. # # Example: # Input: [-2,1,-3,4,-1,2,1,-5,4], # Output: 6 # Explanation: [4,-1,2,1] has the largest sum = 6. # # Follow up: # If you have figured out the O(n) solution, try codin...
# Description: # Given a reference of a node in a connected undirected graph. # Return a deep copy (clone) of the graph. # Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. # Constraints: # 1 <= Node.val <= 100 # Node.val is unique for each node. # Number of Nodes will not exceed 100...
# Description: Given a singly linked list, determine if it is a palindrome. class Solution: def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if head == None: return True def revLL(head): if head == None: return None ...
# purpose: merge two sorted lists of ints # e.g., [1,2,4,10] and [3,4,5,8] -> [1,2,3,4,4,5,8,10] from typing import List class Solution: def mergeSortedLists(self, list1: List[int], list2: List[int]) -> List[int]: len1 = len(list1) len2 = len(list2) index1 = 0 # pointer for index in list1 index2 = 0 # pointe...
# Purpose: Given an array arr of N integers. Find the contiguous sub-array with maximum sum. import sys def maximizeSum(inputArray): # check for bad inputs length = len(inputArray) if (length == 0): raise Exception("The array cannot be empty") for i in inputArray: if (type(i) is not int): raise Exception("T...
# Purpose: Given an unsorted array A of size N of non-negative integers, # find a continuous sub-array which adds to a given number S. import random import sys def findSubArray(fullArray, sum): size = len(fullArray) runningSum = 0 # input checks / error handling if (size == 0): raise Exception("The array is e...
# purpose: Given n non-negative integers a1, a2, ..., an , where each represents a point # at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i # is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, # such that the container contains the most water. ...
# purpose: Given an unsorted array of integers, find the length of longest increasing # subsequence. from typing import List class Solution: def lengthOfLIS(self, nums: List[int]) -> int: listLen = len(nums) # corner case if(listLen <= 1): return listLen # otherwise, proceed to main code longest = [1] ...
Print("Report card using if elif else statements") Marks = 90 if Marks >= 90: print("Your Grand is A+"); elif Marks< 90 and Marks >= 80: print("Your Grand is A"); elif Marks< 80 and Marks >= 70: print("Your Grand is B+"); elif Marks< 70 and Marks >= 60: pri...
# Given an array of strictly the characters 'R', 'G', and 'B', segregate the values of the array so that all the Rs # come first, the Gs come second, and the Bs come last. You can only swap elements of the array. Do this in linear # time and in-place. For example, # given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], ...
# Find the maximum number in an array of numbers def find_max(array): return max(array) my_array = [-27, 0, 34, -3] print(find_max(my_array))
arr = [1, 2, 3, 4, 5]; n = 1 print("Original array: ",arr); m = len(arr) for i in range(0, n): first = arr[0]; for j in range(0, m-1): arr[j] = arr[j + 1]; arr[m - 1] = first; print(); print("Array after left rotation: "); for i in range(0, m): print(arr[i])
num=int(input("enter number: ")) sum=0 while num>0: remainder=num%10 sum=sum + remainder num=num//10 print(sum)
array=[3,6,12,14] n=len(array) sum=0 for i in range (0,n): sum=sum+array[i] average=sum/n print(average)
arr = [1, 2, 3, 4, 5] n = 1; m=len(arr) print("Original array: ",arr); for i in range(0, n): last = arr[m - 1]; for j in range(m - 1, -1, -1): arr[j] = arr[j - 1]; arr[0] = last; print(); print("Array after right rotation: "); for i in range(0, m): print(arr[i])
array = [2,3,-1,5,7,9,10,15,95] sum = 0 N=len(array) for i in range(N): sum = sum + array[i] print("Sum : ",sum)
arr = [1,2,3,4]; print("original array: ",arr) arr2 =[] m = len(arr) print("reversed array: ") for i in range (m-1,-1,-1): print(arr[i])
name = input('enter user name') password = input('enter password') if(name == "asfina" and password == "1234"): print('Login success') else: print('invalid login')
# a=input('enter a string') # l=len(a) # status=0 # for x in range(int(l/2)): # if(a[x]!=a[l-1-x]): # status=1 # break # if(status==0): # print('palindrome') # else: # print('not palindrome') # fibnoccii # limit=int(input('enter limit')) # f1=0 # f2=1 # print(f1,f2,' ',end="") # i=0 # wh...
# s=input('enter the string') # ch=input('enter the letter to be removed') # n=len(s) # str='' # for x in s: # # print(x) # if(x!=ch): # str+=x # print(str) # find the occurance of a character s=input('enter the string') ch=input('enter the letter') count=0 for x in s: if(x==ch): count+=1 ...
''' Leetcode - 187. Repeated DNA Sequences Time complexity - O(N) space complexity - O(1) Approach - 1) I traverse through the entire string with length 10 2) if that substring is in ptn set, then we append to the res set. 3) finally we convert set to list ''' class Solution: def...
# dataset.py import torch import numpy as np from PIL import Image from PIL import ImageFile # sometimes, you will have images without an ending bit # this takes care of those kind of (corrupt) images ImageFile.LOAD_TRUNCATED_IMAGES = True class ClassificationDataset: """ A general classification dataset cl...
'''A simple program to create an html file froma given string, and call the default web browser to display the file.''' contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>Hello</title> ...
age = 12 if (age < 4): print("Your admission cost is $0.") elif (age < 18): print("Your admission cost is $5.") else: print("Your admission cost is $10.") if (age < 4): price = 0 elif (age < 18): price = 5 else: price = 10 print("Your admission cost is $" + str(price) + ".")
''' def shortest_line(list): Min = list[4] - list[0] for n in range(3): if list[n+2] - list[n] < Min: Min = list[n+2] -list[n] return Min spots = [1,3,7,20,26] print("입력된 점 :", spots) print("최소 선분 길이 :", shortest_line(spots)) temp = 0 for i in range(len(spots)): for j in range(le...
# A CircularQueue is Queue, implemented with Python's built in list, with max capacity of 5000 class CircularQueue: def __init__(self): self.queue_contents = [None] * 5000 self.queue_len = 0 self.front = -1 self.back = 0 def __eq__(self, other): return type(other) == Cir...
import unittest # * Section 1 (Lists) # * dd: NumList Data Definition # A Head is a number representing a value in a List # A Tail is a NumList # A NumList is one of: # - "mt" # - a Pair(Head, Tail) class Pair: def __init__(self, head, tail): self.head = head # a Head self.tail = tail # a Tail...
import unittest from list_queue import * class TestQueue(unittest.TestCase): def test_class(self): test_queue = empty_queue() test_queue = enqueue(test_queue, "Test") test_queue = enqueue(test_queue, "foo") test_queue2 = empty_queue() test_queue2 = enqueue(test_queue2, "Te...
# TODO: 3 (all), 4 (all) # from array_list import * from linked_list import * import sys # None -> None # function loads a given file name, and throws exceptions if not found, or if no file name is given # Handles IOError if file not found, and IndexError if no command-line argument given def main(): try: ...
""" Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example: Given nums = [1,1,2], Your function should return length ...
""" 326. Power of Three Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? """ Max3PowerInt = 1162261467 # 3^19, 3^20 = 3486784401 > MaxInt32 MaxInt32 = 2147483647 # 2^31 - 1 def isPowerOfThree(n): """ :type n: int ...
def valid_placement_exists(team1, team2): for i, j in zip(sorted(team1), sorted(team2)): print(i, j) if i > j: return False return True team1 = [1, 2, 3, 4, 5] team2 = [4, 3, 3, 1, 6] print(valid_placement_exists(team1, team2))
def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ # Base case: # Initialize first row and col with value r, c. # No of steps to convert a string to an empty string is equal to the size of the string. # Formula: # if word[i] == word[j]:...
def intersection(A, B): A = A + B A.sort(key=lambda x: x[0]) n = len(A) result = [] for i in range(1, n): if A[i - 1][1] >= A[i][0]: result.append([A[i][0], min(A[i - 1][1], A[i][1])]) A[i][1] = max(A[i - 1][1], A[i][1]) return result def intersection2(A, B): n,...
# Enter your code here. Read input from STDIN. Print output to STDOUT # N {digits} * M {digits}= # N "12345" M "425" ''' 425 (M) 12345 ------ ''' def get_multiplication(N, M): nlen, mlen = len(N), len(M) if nlen == 0 or mlen == 0: return "0" res = [0] * (nlen+mlen) carry = 0 ...
import threading import time import random def executeThread(i): print(f"Thread {i} started\n") sleepTime = random.randint(1,10) time.sleep(sleepTime) print(f"Thread {i} finished executing\n") thread = {} #start 10 threads for i in range(10): thread[i] = threading.Thread(target=executeThread, arg...
def is_num_prime(num, ndict): if num in ndict: return ndict[num] if num < 2: ndict[num] = False else: ndict[num] = True i = 2 while i * i <= num: if num % i == 0: ndict[num] = False break i += 1 return ndict...
import threading import time import random readers = 0 resource_lock = threading.Lock() readers_lock = threading.Lock() item = 0 def write_lock(): resource_lock.acquire() def write_unlock(): resource_lock.release() def read_lock(): global readers readers_lock.acquire() try: readers +=...
''' file = open("testfile.txt", "w+") file.write("Hello World\n") file.write("This is our new text file\n") file.write("and this is another line.\n") file.write("Why? Because we can.\n") file.close() file = open("testfile.txt", "r") print(file.read()) print(file.name) file.close() ''' # context manager with open("tes...
""" What is this pattern about? The Facade pattern is a way to provide a simpler unified interface to a more complex system. It provides an easier way to access functions of the underlying system by providing a single entry point. This kind of abstraction is seen in many real life situations. For example, we can turn o...
''' 70. Climbing Stairs Formula: dp[0] = 1 dp[n] = dp[n-1] + dp[n-2] ''' def climb_stairs(n): dp = [0] * (n + 1) dp[0] = 1 for i in range(n + 1): for step in [1, 2]: if i - step >= 0: dp[i] = dp[i] + dp[i - step] return dp[-1] # print (climb_stairs(15)) ##########...
def get_max_sum_brute_force(lst, k): l = len(lst) max_sum = 0 for i in range(l - k + 1): current_sum = 0 for j in range(i, i + k): current_sum += lst[j] max_sum = max(max_sum, current_sum) return (max_sum) def get_max_sum_sliding_window(lst, k): l = len(lst) max...
def alternatve_pos_neg(nums): pos_count, neg_count = 0, 0 pos, neg = [], [] for num in nums: if num < 0: neg_count += 1 neg.append(num) else: pos_count += 1 pos.append(num) if not pos_count or not neg_count: return nums nums = ...
""" 6. ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string...
class Vertex: def __init__(self, label): self.neighbors = [] self.label = label class Graph: def __init__(self): self.vertex_list = [] def add_edge(self, u, v): u.neighbors.append(v) self.vertex_list.append(u) def explore_bfs(cur, seen, component): seen.add(c...
class Node: def __init__(self, val): self.data = val self.prev = None self.next = None def get_data(self): return self.data class DList: def __init__(self): self.head = None self.tail = None def push(self, val): new_node = Node(val) if s...
""" Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] E...
class Solution: def check_valid(self, col_placement, row1, col1): for row2 in range(row1): col2 = col_placement[row2] if col1 == col2: return False if abs(col2 - col1) == abs(row2 - row1): return False return True def helper(se...
def shortestDistance(words, word1, word2): """ :type words: List[str] :type word1: str :type word2: str :rtype: int """ l = len(words) idx1 = -1 idx2 = -1 ans = l for i in range(0, l): if words[i] == word1: idx1 = i elif words[i] == word2: ...
#python3 ~/lang/python/lang/functools.py import functools #functools.reduce (function, iterable[, initializer]) print ("functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) -> ((((1+2)+3)+4)+5)") print (functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])) print ("functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 100...
'''A multi-producer, multi-consumer queue. https://github.com/python/cpython/blob/3.7/Lib/queue.py ''' import threading from collections import deque from heapq import heappush, heappop from time import monotonic as time class Full(Exception): 'Exception raised by Queue.put(block=0)/put_nowait().' pass class...
""" Given a array of 'n' elements with numbers in the range of 1-n There is exactly 1 number missing that we need to find """ arr = [1, 2, 3, 4, 5, 7] # Method 1: Get the sum using n * (n+1)/ 2 and subtract the sum of the array n = len(arr) + 1 range_sum = n * (n + 1) // 2 sum = 0 for i in arr: sum = sum + i pr...
""" Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ def singleNumber(nums): final = nums[0] for i in range(1, len(nums)): final = final ^...
""" Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not ...
""" Implement a UNIX TAIL command """ def tail(file_name, n): f = open(file_name, 'rb') f.seek(0, 2) file_size = f.tell() newline_cnt = 0 print ("file size: ", file_size, " # of line:", n) last_n_lines = "" for i in range(1,file_size): f.seek(-i, 2) c = f.read(1).decode('utf-8...
import threading import queue import time import random queue = queue.Queue() def producer(): """ Producer: Add the item in the Queue """ for i in range(10): item = random.randint(0, 256) queue.put(item) print (f'producer notify: item {item} is added to queue') time.sleep(1) def consumer(thread_...
def is_palindrome(n): nstr = str(n) l = len(nstr) for i in range(l // 2): if nstr[i] != nstr[l - 1 - i]: return False return True def is_prime(n): i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True n = 1 i = n while 1: ...
import pandas as pd import numpy as np import sklearn from sklearn import linear_model from sklearn.utils import shuffle data = pd.read_csv("student-mat.csv", sep=";") # print(data.head()) #prints out all the data data = data[["G1", "G2", "G3", "studytime", "failures", "absences"]] # print(data.head()) #prints out on...
class Solution: def Met(n): i=2; st='1'; if n == 1: print(st); else: while i<=n: st=st+" "+str(i)+" "+st i+=1; print(st) if __name__ == "__main__": Solution.Met(3); print(); Solution.Met(2);...
""" Unicode Transformation Format – 8-bit As the name suggests UTF-8 was designed to encode data in a stream of bytes. It works by splitting the bits up in multiples of eight. This is achieved by inserting headers to mark in how many bytes the bits were split. If the bits need to be split in two, the header 110 is ad...
""" In mathematics, the symbols Δ and d are often used to denote the difference between two values. Similarly, differentiation takes the ratio of changes (ie. dy/dx) for a linear relationship. This method can be applied multiple times to create multiple 'levels' of rates of change. (A common example is x (position) ->...
""" How many times we create a python class and in the init method we just write: self.name1 = name1 self.name2 = name2 ..... for all arguments..... How boring!!!! Your task here is to implement a metaclass that let this instantiation be done automatically. But let's see an example: class Person(metaclass=LazyIni...
#-----------------OS model---------------------------- #The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s # standard utility modules. This module provides a portable way of using operating system-dependent # functionality. The *os* and *os.path* modules incl...
#Build a list,check the name on the list, check against another list and get the index of the particular list name=input('What is your name? \n') allowedUsers=['Rossi','James','Sandra'] allowedPassword=['passwordRossi','passwordJames','passwordSandra'] if name in allowedUsers: password=input('Your password? \n') ...
#A way to receive input from the user is by using input() function #To star from the next line use \n name=input('What is your name? \n') allowedUers=['Rossi','Toria','Ada'] #List of allowed users AllowedPassword='Password'#Password is static for ni if name in allowedUers: password=input('Your password? \n') ...
#Object oriented deep dive class class Animal: # Class attribute animal_type='insects' # instance(object) attribute def __init__ (self,name,number_of_legs): self.name=name self.number_of_legs=number_of_legs #This a method (an instance method) def can_run(self): print(f'An...
num1, num2, num3 = map(int,input("정수 3개를 입력해주세요:").split()) if num1>num2 and num1>num3 : #첫 번째 수 num1이 가장 커야함 print("True") else : print("False") if num1==num2==num3 : #세 수가 모두 같아야함 print("True") else : print("False")
# 두 개의 정수를 입력받아 두 정수 사이(두 정수를 포함)에 3의 배수이거나 5의 배수인 수들의 합과 평균을 출력하는 프로그램을 작성하시오. # 평균은 반올림하여 소수 첫째자리까지 출력한다. # 입력 예: 10 15 # 출력 예: sum : 37 avg : 12.3 num1, num2 = map(int, input("두개 정수 입력:").split()) sum = 0 count = 0 temp =0 if num1 > num2: # num2 가 더 큰수로 치환 temp = num1 num1 = num2 n...
# "FizzBuzz"문제 # 1에서 100까지의 숫자를 출력하되, # 만약 해당 숫자가 '3'으로 나누어지면 숫자 대신에 "Fizz"를 출력하고, # 만약 해당 숫자가 '5'로 나누어지면 숫자 대신에 "Buzz"를 출력하며, # 만약 해당 숫자가 '3'과 '5'로 모두 나누어지면 숫자 대신에 "FizzBuzz"를 출력 # 입력 예1: 5 # 출력 예1: "Buzz" # 입력 예2: 3 # 출력 예2: "Fizz" # 입력 예3: 15 # 출력 예3: "FizzBuzz" num = int(input("1~100까지의 숫자를 ...
# 아래와 같은 모양으로 출력하는 프로그램을 작성하시오. # 사용자에게 숫자를 입력받아 입력 받은 높이 만큼의 삼각형을 출력하시오. # 입력 예: 5 # ***** # **** # *** # ** # * num = int(input("정수를 입력하시오:")) for line in range(num,0,-1): print(" "*(num-line) + "*"*line)
# 공백을 포함한 문자열을 입력받아 각 단어로 분리하여 문자열 배열에 저장한 후 입력순서의 반대 순서로 출력하는 프로그램을 작성하시오. 문자열의 길이는 100자 이하이다. # 입력 예: C++ Programing jjang!! # 출력 예: # jjang!! # Programing # C++ str_list = input("100자 이하 문자열을 입력해주세요:").split() str_list_len = len(str_list) #리스트 각각의 인덱스에 저장된 값 합치고 길이가 100이하인지 확인 if len(' '.join(str_list))...
# 정수를 입력받아서 3의 배수가 아닌 경우에는 아무 작업도 하지 않고, 3의 배수인 경우에는 3으로 나눈몫을 출력하는 작업을 반복하다가 -1이 입력되면 종료하는 프로그램을 작성하시오. # 예시: # 5 # 12 # 4 # 21 # 7 # 100 # -1 num=1 while num!=-1: num = int(input("정수 입력:")) if num % 3 ==0: num=num/3 print(int(num))
class Employee: def __init__(self, irum, nai): self.irum = irum self.nai = nai def pay(self): pass def data_print(self): pass def irumnai_print(self): pass class Regular(Employee): def __init__(self,irum, nai, salary): super().__init__(irum, na...