text
stringlengths
37
1.41M
from threading import Thread class InputReader(Thread): def run(self): self.line_of_text = input() print("Enter some text and press enter: ") thread = InputReader() thread.start() count = result = 1 while thread.is_alive(): result = count * count count += 1 print("calculated squares up to {0} * ...
import math def distance(p1, p2): return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2) def perimeter(polygon): perimeter = 0 points = polygon + [polygon[0]] for i in range(len(polygon)): perimeter += distance(points[i], points[i+1]) return perimeter
class EMail: def __init__(self, from_addr, to_addr, subject, message): self.from_addr = from_addr self.to_addr = to_addr self.subject = subject self.message = message email = EMail("a@example.com", "b@example.com", "You Have Mail!", "Here's some mail for you!") tem...
import math def merge_sort(arr: list) -> list: if len(arr) < 2: return arr length = len(arr) middle = math.floor(length / 2) left = arr[0:middle] right = arr[middle:] return merge(merge_sort(left), merge_sort(right)) # left and right will always be ordered! def merge(left: list, rig...
class Property: def __init__(self, square_feet='', beds='', baths='', **kwargs): super().__init__(**kwargs) self.square_feet = square_feet self.num_bedrooms = beds self.num_baths = baths def display(self): print("PROPERTY DETAILS") print("=======...
class CoffeeMachine: def __init__(self, water_amount, milk_amount, coffee_beans_amount, cups_amount, money): self.water = water_amount self.milk = milk_amount self.coffee = coffee_beans_amount self.cups = cups_amount self.money = money def __getitem__(self, item): ...
# Code Listing #2 """ Thumbnail converter using producer-consumer architecture: 1. Producers are a specialized class of workers (threads) producing the data. They may receive the data from a specific source(s), or generate the data themselves. 2. Producers add the data to a shared synchronized queue. In Python, this ...
def sum_two_smallest_numbers(numbers): min1 = 0 min2 = 0 min1 = min(array) array.remove(min1) min2 = min(array) numbers = min1 + min2 return (numbers)
class Solution: def numberOfSteps (self, num: int) -> int: step_count = 0 while(num > 0): #Check if number is even and divide by 2 if num%2 == 0: num = num//2 #Check if number is odd and subtract by 1 else: num = num - 1...
class Solution: def fizzBuzz(self, n: int): result_arr = [] for val in range(1, n + 1): if val%3 == 0 and val%5 == 0: result_arr.append('FizzBuzz') elif val%3 == 0: result_arr.append('Fizz') elif val%5 == 0: result_...
class Solution: def containsDuplicate(self, nums): charObj = {} for val in nums: if val in charObj: return True else: charObj[val] = 1 return False sol = Solution() print(sol.containsDuplicate([1,2,3,1]))
import unittest from index import sol class Testing(unittest.TestCase): #Check for input 'I speak Goat Latin' def test_toGoatLatin_input1(self): self.assertEqual(sol.toGoatLatin('I speak Goat Latin'), 'Imaa peaksmaaa oatGmaaaa atinLmaaaaa') #Check for input 'The quick brown fox jumped over th...
import numpy as np import scipy.stats as ss def add_noise(X, noise, seed = None): """Adds Gaussian noise to a point cloud.""" np.random.seed(seed = seed) X_noise = np.random.normal(scale = noise, size = X.shape) return X + X_noise # =============================================================== # -...
r=int(input("radius is")) pi=3.142 A=pi*r*r print("area of the circle",A)
########################################################## # Exposureness # # This function measures the exposureness of the images. # ########################################################## import cv2 import numpy as np ####################################################...
import openpyxl import win32com.client as win32 from NumberGenerator import NumberGenerator import datetime import time import sched import sys class Email: def __init__(self): self.book = 0 self.emails = "" # Generate the numbers and insert them into the numbers array in th...
""" Author : Sahil Ajmera Summer class """ from math import * from PriorityQueue import PQ class Summer: __slots__ = 'path_color' def __init__(self): self.path_color = (255, 0, 0) def getNeighbour(self, x, y, rows_max, columns_max, pixels): """ List of neighbors of a particular x...
#!/usr/bin/python import sys from classInflationCalc import * def get_value(myPrompt): while True: try: myValue = float(input(myPrompt)) except Exception: print "Please enter correct value or simple 0" continue else: break return myValue p...
#!/usr/bin/env python #coding=utf-8 ''' 功能: 删除多余的 jpg 或 xml 文件 ''' import os import sys # jpg_path = "JPEGImages" # xml_path = "Annotations" jpg_path = "jpg" xml_path = "xml" xmls = os.listdir(xml_path) jpgs = os.listdir(jpg_path) if len(xmls) < len(jpgs): print "jpgs is odd..." for...
customer_age = int(input("How old is the customer? ")) cost = 0 if customer_age <= 3: cost = 0 print("Your cost for a customer who is " + str(customer_age) + " years old") print("is $" + format(cost, ",.2f")) else: if 4 <= customer_age <= 11: cost = .99 * customer_age print("Your cost...
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 20:38:59 2020 @author: Dora """ name = ['Erina','Queenie','Hank','Sana','Yuna',] verb = ['玩','看','寫','摺','吃'] noun = ['Jacket','Computer','Tape','Horse','Sibling'] import random def random_list(list1): word = random.sample(list1,1)[0] return word ...
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 19:06:13 2020 @author: Dora """ import random answer = random.randint(1,10) times=0 while times < 5: guess = int(input("what number do you guess?")) times= times + 1 if guess < 1 or guess > 10: print("try again") else: ...
''' Created For Mega Projects Repository Problem: Pig Latin is a game of alterations played on the English language game. To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more...
#working with shapes #triangle print(" /|") print(" / |") print(" / |") print(" / |") print(" /____|") #square shape1 = "_" shape2 = "|" #rectangle print(shape1 * 4) for i in shape2: print(i + ' ' + i) print(i + ' ' + i) print(i + ' ' + i) print(i + ' ' + i) ...
from square import Square from piece import Piece import itertools import pygame as pg from move import Move from constants import WHITE, BLACK, SQUARES class Board: def __init__(self, xAxis, yAxis): self.xAxis = xAxis self.yAxis = yAxis self.width = len(xAxis) self.height = len(yAxis) self.squares = self...
class Runner: def __init__(self, program): self.program = program self.i = 0 def read(self): op = self.program[self.i] self.i += 1 return op def peek(self): return self.program[self.i] def run(self): while True: opcode = self.read() ...
import string import random #This function generated passwords that contain numbers, uppercase and lowercase letters, and other characters with a length between 4 and 16 characters. #The purpose is to have high level security passwords def generatePassword(): #characters variable will store letters, numbers and sp...
1.Question 1 Q1)When Python is running in the interactive mode and displaying the chevron prompt (>>>) - what question is Python asking you? 1)What is your favourite color? 2)What Python script would you like me to run? 3)What is the next machine language instruction to run? 4)What Python statement would...
"""The string defining the points of the quadrilateral has the next form: "#LB1:1#RB4:1#LT1:3#RT4:3" LB - Left Bottom point LT - Left Top point RT - Right Top point RB - Right Bottom point numbers after letters are the coordinates of a point. Write a function figure_perimetr() that calculates the perimeter of a qu...
"""Imagine you are creating an application that shows the data about all different types of vehicles present. It takes the data from APIs of different vehicle organizations in XML format and then displays the information. But suppose at some time you want to upgrade your application with a Machine Learning algorithms t...
"""'s3ooOOooDy' has exams. He wants to study hard this time. He has an array of studying hours per day for the previous exams. He wants to know the length of the maximum non-decreasing contiguous subarray of the studying days, to study as much before his current exams. Example: For a = [2,2,1,3,4,1] the answer is 3. ...
"""Write the function day_of_week(day) whose input parameter is a number or string representation of number. The function returns the corresponding day of the week if the input parameter is in the range of 1 to 7, namely · in the case when the input parameter is 5 the function should be displayed the message – "Frida...
"""In user.json file we have information about users in format [{“id”: 1, “name”: “userName”, “department_id”: 1}, ...], in file department.json are information about departments in format: [{“id”: 1, “name”: “departmentName”}, ...]. Function user_with_department(csv_file, user_json, department_json) should read from...
import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix def explore_data(data): data.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4, s=data["population"]/100, label="population", figsize=(10, 7), c="median_house_value", cmap=plt.get_cmap("jet"), colorbar...
""" 题目: 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 Longest Common Prefix """ class Solution: def longestCommonPrefix(self,strs): len0 = len(strs) if len0 == 0:#判断strs是否为空 return '' list_len = []#初始化存放每个子串的长度 # 找出最短的字符串长度min_len ...
''' 基于select方法的IO多路复用网络并发 重点代码!! ''' from select import select from socket import * HOST = "0.0.0.0" PORT = 2021 ADDR = (HOST, PORT) def main(): sock = socket() sock.bind(ADDR) sock.listen(5) print("listen the port %d" % PORT) sock.setblocking(False) rlist = [sock] wlist = [] x...
# 필요한 모듈 import import socket import random # multiply와 add에 따른 숫자를 계산하는 함수 def instruction(num, inst): i = random.randint(-1, 4) if inst == 'multiply': return num * i elif inst == 'add': return num + i TCP_IP = '10.0.2.15' TCP_PORT = 5001 # 3개의 client를 허용한다. sock = socket.socket(socket.A...
''' Faça um programa para calcular a situação de um aluno. O programa deve calcular a média das duas avaliações do aluno e apresentar: A média alcançada, arredondada para uma casa decimal (ex., "7.5") A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; A mensagem "Reprovado", se a média for menor do...
# Assumption : Array is sorted def binary_search(arr, item, start, end): mid = int((start + end) / 2) if start > end: return -1 elif arr[mid] == item: return mid elif arr[mid] > item: return binary_search(arr, item, start, mid - 1) else: return binary_search(arr, ite...
# Dutch National Flag problem : Segregate numbers 0, 1, 2 def segregate_numbers(arr): m = 0 j = len(arr) - 1 i = 0 while i <= j: if arr[i] == 0: swap(arr, i, m) i += 1 m += 1 elif arr[i] == 1: i += 1 else: while arr[j] =...
def find_next_greater_element(arr): print("Input Array : {}".format(arr)) stack = [] for i in arr: while len(stack) > 0 and stack[len(stack) - 1] < i: print("Next Greater element for {} is {} ".format(stack.pop(), i)) stack.append(i) while len(stack) != 0: print("Nex...
num=int(input("enter a number:")) print(num) if X > 0 and y > 0: print("quadrant:1") elif x > 0 and y < 0: print("quadrant 4") elif x > 0 and y < 0: print("quadrant 3") else: print("quadrant 2")
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
# импорт вебдрайвер и времени from selenium import webdriver #подключение библиотеки селект для выбора элементов из списка from selenium.webdriver.support.ui import Select import time import math #Создаем переменную с ссылкой на страницу link = "http://suninjuly.github.io/selects1.html" #Создаем переменную, в котором...
#!/usr/bin/python # -*- coding:utf-8 -*- import pygame from pygame.sprite import Sprite class Alien(Sprite): """表示单个外星人的类""" def __init__(self,ai_settings,screen): """初始化外星人并设置其起始位置""" super(Alien,self).__init__() #继承Sprite self.screen=screen self.ai_set...
def solve(heads,legs): error_msg="No solution" chicken_count=0 rabbit_count=0 #Start writing your code here # R + C = 35 --> heads # 4R + 2C = 94 --> legs #-- R = 12 AND C = 23 #Populate the variables: chicken_count and rabbit_count # Let's look at invalid condition if legs%2 ...
import numpy as np import matplotlib.pyplot as plt import machine_learning_algorithms as mla # 2d example data set from Coursera course Machine Learning # linear regression is used to estimate the prices of houses in dependence # on the size of the house in square feet and on the number of bedrooms data = np.loadtxt...
#!/usr/bin/env python # coding: utf-8 """ 求100w以内的素数 质数(Prime number),又称素数,指在大于1的自然数中,除了1和该数自身外,无法被其他自然数整除的数(也可定义为只有1与该数本身两个因数的数)。 简单来说就是,只能除以1和自身的数(需要大于1)就是质数。举个栗子,5这个数,从2开始一直到4,都不能被它整除,只有1和它本身(5)才能被5整除,所以5就是一个典型的质数。 """ p = [] max_num = 100 for i in range(2, max_num): for j in range(2, i): if i % j == 0...
#Binary Tree's Insertion and traversal class Node(): def __init__(self,data): self.left = None self.right = None self.data = data def preorder(self,i=0): print "Level::%s Value::%s"%(i,self.data) if self.left: self.left.preorder(i=i+1) if self.right...
''' print "hello" l = [10,20,30] try: import prasit x = int(raw_input("Enter 1st Number::")) y = int(raw_input("Enter 1st Number::")) s =x/y print s print l[0] except ValueError: print "GOT Value Error..." except ZeroDivisionError: print "GOT ZeroDivError..." except IndexError: prin...
import re ''' # Write a script to count numbers of words available in a given string pra = 'Prasit is a boy. He lives in Bangalore. He is from Kolkata' d ={} pra_list = pra.split(' ') #print pra_list for x in pra_list: print x,pra_list.count(x) # Write a script to count number of words which begins with Upper case...
import pandas as pd # Takes a dataframe, the column to groupby, and a list of columns # Normalizes them within each group def normalize_by_columns(df: pd.DataFrame, groupby: str, columns: list) -> pd.DataFrame: ids = df[groupby].unique() output_df = pd.DataFrame() for current_id in ids: current = ...
import random P = [] for i in range(0,13): P.append( [0]*13 ) CantCajones = int(input("ingrese la cantidad de cajones : ")) CantAgujeros = int(input("ingrese la cantidad de agujeros : ")) for cajon in range(1, CantCajones+1): print("ingrese cordenadas (fila, columna) de cajon", cajon) fila = int(i...
import os os.system('cls') import string from random import randint as azar #Benjajaja 2 sello #kenneth 1 sello """ Contraseña = PericoLosPalotes31* Numero al azar -> 5 Encriptacion Cesar -> UjwnhtQtxUfqtyjx31* Intercalacion de mayusculas -> UjWnHtQtXUFqTyJx31* Agregacion de numero al azar -> 5UjWnHtQtXUFqTyJx31* ...
# -*- coding: utf-8 -*- """ Created on Tue Aug 3 02:42:11 2021 @author: Omen 15 """ ''' Se pide realizar un programa en Python que lea dos Strings compuestos por palabras separadas por un espacio en blanco y ya ordenadas alfabéticamente, y que genere un tercer string (resultado) que contenga todas las palabras orden...
""" Given an integer,n, perform the following conditional actions: If n is odd, print Weird If n is even and in the inclusive range of 2 to 5, print Not Weird If n is even and in the inclusive range of 6 to 20 , print Weird If n is even and greater than 20 , print Not Weird """ N = int(input()) if N%2==0 : if N ...
import requests import pandas as pd import datetime import wbdata import plotly.express as px # Get all sources from the World Bank API sources = requests.get("http://api.worldbank.org/v2/sources?per_page=100&format=json") sourcesJSON = sources.json() # View the JSON response print("JSON Response: \n",sourcesJSON) ...
class Dog: def __init__(self, name, month, day, year, speakText): # Constructor of the class # self references the object itself self.name = name self.month = month self.day = day self. year = year self.speakText = speakText def __str__(self): # t...
class cal3 : def __init__(self,P,R,T): self.n1 =P self.n2 = R self.n3 = T def callinterest(self): self.interest =((self.n1*self.n2*self.n3/100)) def display(self): print("interest of given parameters:",self.interest) c=cal3(100,30,2) c.callinterest() ...
a =int(input('Enter first number : ')) b = int(input('Enter second number : ')) for num in range(a, b-3, -3): print (num)
n1= 100 n2 = int(input("enter a number")) if n1<n2 : print("n2 is greater than 100:") elif n1>n2: print("n2 is less than 100:") if n2 %2==0: print("it is even") else : print("it is odd")
# calculator in Python(v0.2) def div(num1, num2): return num1 / num2 # main res = div(5, 3) print(res)
import numpy as np import csv import random import time '''load csv file as data resource''' def loadCsv(filename): lines = csv.reader(open(filename, "rb")) dataset = list(lines) return dataset ''' clean the dataset delete the first row and first column, because the first colmun is id, the first r...
def CountingSort(alist, largest, key): #key - функція визначення розряду сортування c = [0] * (largest + 1) #заповнюємо нулями масив підрахунків for i in range(len(alist)): c[key(alist, i)] = c[key(alist, i)] + 1 # додавання індексів, пошук місця c[0] = c[0] - 1 # зменшуємо перший еоемент для...
#if (num %2 == 0): # print("numero exit() contador = 0 while contador <= 10: if contador % 2 == 0: print(contador) contador += 1 exit () num = 0 while true: if num == 5: break num += 1
''' Created on 2018年8月30日 @author: huowolf ''' #=============================================================================== # 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 # 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 #=============================================================================== class Solution: def twoSum(self, nums, ...
#买卖股票的最佳时机 II #=============================================================================== # 输入: [7,1,5,3,6,4] # 输出: 7 # 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 # 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。 #=================================================...
#Kim Hewson #18/09/14 #Stretch exercise one length=int(input("Enter length (m): ")) width=int(input("Enter width (m): ")) cost=((length-2)*(width-2))*10 print("The cost to turf your garden will be £{0}".format(cost))
import turtle import time pen = turtle.Turtle() class Star(object): def __init__(self, x=0, y=0, arm_length=2, color="red"): """creates a line starting from the coordinates given by beg to the coordinates given by end.""" self.pencolor = color self.x = x self.y =...
# def square_plus_one(a,b): # result = a * b + 1 # return result # # print(square_plus_one(2,3)) # def give_zhi_something(a,b): # return a + b # import math # # def quadratic(a,b,c): # x_1 = (-b + math.sqrt(math.pow(b,2)-(4*a*c)))/2*a # x_2 = (-b - math.sqrt(math.pow(b,2)-(4*a*c)))/2*a # re...
tekst = input("Podaj tekst: ") licznik = 0 pomiedzy_nawiasami = False for lit in tekst: if lit == '>': pomiedzy_nawiasami = False if pomiedzy_nawiasami: licznik += 1 if lit == '<': pomiedzy_nawiasami = True print(licznik)
def podwojenie(liczba): return liczba * 2 def pomniejszenie(liczba): return liczba / 2 def zwieksz(liczba, operacja): return operacja(liczba) + 1 # zwieksz_lambda = lambda liczba: liczba + 1 # print(zwieksz(1)) # print(zwieksz_lambda(2)) wynik = zwieksz(100, podwojenie) wynik2 = zwieksz(100, pomniejsze...
x = 0 while x < 100: print(x ** 2) x = x + 1 # można też zapisać x += 1 # po wyprintowaniu x^2 printujemy każdą następną x+1, aż x osiągnie 99
a=int(input()) b=int(input()) if a < 1 or b < 1: print("Exception") elif a%b==0: p=True else: p=False print(int(p))
from collections import deque predence = { '^' : 3, '*' : 2, '/' : 2, '+' : 1, '-' : 1 } for _ in range(int(input())): n = int(input()) infix = input().strip() stack = deque() postfix = "" for i in infix: if 'A' <= i <= 'Z': postfix += i elif i == '(': stack.append(i) ...
import xml.etree.ElementTree as ET contents = [] while True: line = input() if line == "</expr>": contents.append(line) break else: contents.append(line) contents = list(filter(None, contents)) s = ''.join(contents) root = ET.fromstring(s) # compute = s.find('sum|div|prod|sub') f...
n = int(input()) table = [0] * (n+1) table[0] = 1 print("3\n") for i in range(3, n+1): table[i] += table[i-3] print(table[i], table[i-3]) print("\n\n5\n") for i in range(5, n+1): table[i] += table[i-5] print(table[i], table[i-5]) print("\n\n10\n") for i in range(10, n+1): table[i] += table[i...
import string alpha = string.ascii_lowercase s = input() for i in s: print(alpha[int(i)],end="")
""" Responsible for producing the regular expression for a given R(i,j,k) Simplyfies the regular expression produced Returns a string """ class R_IJK: """ Initalize all constant variables """ def __init__(self): self.EMPTY_SET = '!' self.UNION_SYMBOL = 'U' self.EMPTY_STRING = 'e' self.IGNORE = True self...
#multiplicationTable(n) = [[1, 2, 3, 4, 5 ], # [2, 4, 6, 8, 10], # [3, 6, 9, 12, 15], # [4, 8, 12, 16, 20], # [5, 10, 15, 20, 25]] def table(n): collist=[] for j in range(1,n+1): rowlist=[] ...
#a e i o u def vowel_count(sting): count=0 for i in range(len(sting)): if sting[i].lower() in "aeiou": count+=1 return count a="i love potato" print(vowel_count(a))
quistion=input("Please enter the base at the square root : ") quistion2=input("Please enter an indeces from the square root : ") quistion3=quistion for i in range(1,int(quistion2)): quistion3=int(quistion3)*int(quistion) #print(quistion) print(quistion3)
def math1(num): result=1 if num<=0: return 0 for i in range(1,num+1): result=result*i return result print(math1(0)) #8!=40,320 # No.2=============================================================================================================================== def math2(num2): ...
def dagaghyoung(n): if 360%(180-n)==0: return "yes" else: return "no" n=int(input()) alist=[] for i in range(n): m=int(input()) alist.append(m) for i in alist: print(dagaghyoung(i))
#coding=cp949 def hello(n): word="hello" index=0 for i in range(len(n)): if index==5: return "Yes" if n[i]==word[index]: index+=1 if index<5: return "No" else: return "Yes" m=input() print(hello(m))
f=input() s=input() if sorted(f)==sorted(s): print("anagram") # sorted(f) else: print("not anagram")
#a,b,c : start a b end c divisor def divisor(a,b,c): dlist=[] for i in range(a,b+1): if i%c==0: dlist.append(i) return dlist[-1] print(divisor(1,100,13)) #lambda========================================= divisor2=lambda a,b,c:b-b%c print(divisor2(1,100,13))
# array a=array([]) # list a=[2,3,4] # tuple a=(2,3,4) # dictionary a={1:'a',2:'b'} a=[1,2,3,4] print(a) print(a[0]) print(a[2]) print(len(a)) a[2]=100 print(a) b=['Babo',2,1,9] print(b) b[0]='BIBI' print(b) print(b*3) print(b.index(9)) print(2 in b) print('Babo' in b) #=======================...
num=int(input("input your number : ")) if num<0: print("This is negative number.") elif num>0: print("This is positive number.") elif num==0: print("This is 0") else: print("Please input number!!!!!!!")
''' 功能:nonlocal的使用(必须在函数内层里面) ''' def foo(): b = 123 #内层函数 def bar(): nonlocal b#必须先定义 不能定义附值一起弄 b = 456 print("b=", b) #调用内层函数 bar() print("b=", b) #主函数 foo()
#Summary: This Program is meant to take the same gene sequence and put it through #three reading frames in order to figure out which is best for reading. #The input is a gene, the gene then goes through the reading frames and is transcribed #and then translated into protein, all within the program. #The output: In ...
from tkinter import * class About(Toplevel): def __init__(self): Toplevel.__init__(self) self.title("About") self.geometry("650x450+600+200") self.resizable(False, False) # frames self.top = Frame(self, height=100, bg='#a5b5c4') self.top.pack(fill=X) ...
# 문제 : 해달이는 1부터 100까지의 숫자를 분류하려 한다. # 리스트 "mul2"에는 2의 배수, 리스트 "mul3"에는 3의 배수, # 리스트 "mul6"에는 6의 배수를 넣고 # 나머지 수는 모두 더해서 출력하려고 한다. 해달이를 도와주자 # 사용할 개념 : 리스트 , for, range, if, %, append, += mul2 = [] mul3 = [] mul6 = [] result = 0 for i in range(1,101): if (i % 6 == 0): mul6.append(i) for i in range(1...
m=input("Enter number of rows: ") n=input("Enter number of columns: ") a=[[0 for x in range(n)] for y in range(m)] print "Enter the matrix elements:\n" for i in range(0,m): for j in range(0,n): a[i][j]=input() print "\nThe input matrix is:\n" for i in range(0,m): for j in range(0,n): print a[i][j], print "\n" ...
#!/usr/bin/python3 n=input("Enter number of list items required:") list1=set() for i in range(n): x=raw_input("Enter item:") list1.add(x) n=input("Enter number of list items required:") list2=set() for i in range(n): x=raw_input("Enter item:") list2.add(x) print("List1:", list1) print("List2:", list2)...
import itertools class NoFieldsError(Exception): pass class FormatError(Exception): pass def recursive_hierarchy(elements, fields): if not fields: return elements nodes = [] # Clone fields and remove first element fields = fields[:] field = fields.pop(0) # Sort elements b...
#!/usr/bin/env python """ Script to automatically add inline code comments Read in the code to be processed from a provided filename or from stdin. Read in the user’s GTP_API_KEY from an environment variable. Split out the preamble code before the first function definition, such as /^def / for python or /^\s*(public|...
"""main_a3.py """ import re import os import nltk from nltk.corpus import wordnet as wn from nltk.corpus import PlaintextCorpusReader # NLTK stoplist with 3136 words (multilingual) STOPLIST = set(nltk.corpus.stopwords.words()) # Vocabulary with 234,377 English words from NLTK ENGLISH_VOCABULARY = set(w.lower(...
# Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns # a boolean representing whether the BST is valid. # Each BST node has an integer value , a left child node, anda right child # node. A node is said to be a valid BST node if and only if it satisfies the BST property: # its valu...
# It's photo day at the local school, and you're the photographer assigned to take class # photos. The class that you'll be photographing has an even number of students, and all # these students are wearing red or blue shirts. In fact, exactly half of the class is wearing # red shirts, and the other half is wearing blu...