text
stringlengths
37
1.41M
# Даны четыре действительных числа: x1, y1, x2, y2. # Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2). # Считайте четыре действительных числа и выведите результат работы этой функции. x1 = float(input()) y1 = float(input()) x2 = float(input()) y2 = float(in...
class Matriz: pass def __init__(self, f, c): self.__fil = f self.__col = c self.__val = [] for i in range(f): fila = [] for j in range(c): fila.append(0) self.__val.append(fila) def valor(self, i, j, v): self.__val...
import pandas as pd import numpy as np ''' ========================================================================= Author (ported to python): George Milunovich Date: 5 November 2019 Based on Matlab code by: Michael W. McCracken and Serena Ng Date: 6/7/2017 Version: MATLAB 2014a Requi...
class BankAccount: def __init__(self, name, apellido, tasa_interes= 0.01, balance=0): # ¡No olvides agregar valores predeterminados para estos parámetros! # su código aquí! (recuerde, aquí es donde especificamos los atributos para nuestra clase) # no se preocupe por la información del usuario aqu...
# import modules used here -- sys is a very standard one import sys # Gather our code in a main() function def main(): f = int(sys.argv[1]) c = 5 * (f-32) / 9 print "Temp in Farenheit = (%d), equivelant in Celsius = (%d)" % (f,c) # Standard boilerplate to call the main() function to begin # the p...
#if statment example grade = int (raw_input("Enter precentage to calculate letter grade? ")) if grade >= 90 and grade <= 100: lettergrade = 'A' elif grade >= 80 and grade < 90: lettergrade = 'B' elif grade >= 70 and grade < 80: lettergrade = 'C' elif grade >= 60 and grade < 70: lettergrade = 'D' elif ...
from numpy import * a = array([1,2,7]) print a.mean() b = array([[1,2,7],[4,9,6],[1,2,7],[4,9,6]]) print b print b.mean() print b.mean(axis=0) # the mean of each of the 3 columns #array([ 2.5, 5.5, 6.5]) print b.mean(axis=1) # the mean of each of the 2 rows #array([ 3.33333333, 6.33333333]) print b.mean(axis=-1) print ...
""" For this solution, we'll do a for loop from the numbers 1 to n, whilst maintaining 2 counters. The first counter squares the current iteration number, and adds it to itself. The second counter just adds the number to itself Once the loop has finished, the 2nd counter will be squared, and the result that's output...
""" The easiest solution I can think of, would be to start with the number 1. Check if the number is divisible by every number between 1 to 20. Once we find a number that it's not divisible by, we add 20 to that number. And check again. We repeat this until we find a number that is divisible all of the numbers betwee...
def parse_data(file_name): with open(file_name, 'r') as file: interval = file.readline().split("-") return int(interval[0]), int(interval[1]) def find_valid_passwords(low, high): # TODO: use generating function instead of loop valid_passwords = [] for password in range(low, high + 1): ...
def parse_data(file_name): with open(file_name, 'r') as file: program = list(file.read().split(",")) return [int(position) for position in program] def int_code(program, input_code): index = 0 while index < len(program)-1: modes, opcode = read_instructions(index, program) ...
def difference(n): if n>=17: print((n-17)*2) else: print(17-n) #difference(n) for x in range(0,4,1): n=int(input("enter a number")) difference(n)
age=7 def a(): print("global variable 'age'",globals()['age']) globals()['age']=27 print("modified global variable 'age'",globals()['age']) age=12 print("local variable 'age'",age) return a() print("global variable is 'age' ",globals()['age'])
def insert(list): for start in range(len(list)): pos=start while pos>0 and list[pos]<list[pos-1]: (list[pos],list[pos-1])=(list[pos-1],list[pos]) pos=pos-1 #list=[2,4,1,3,5] list=list(range(-500,0,1)) insert(list) print(list)
x = (1,2,3,4) print(x) #Create an empty tuple with tuple() function built-in Python tuplex = tuple(x) print(tuplex)
n1=int(input("enter a number:")) n2=int(input("enter a number:")) n3=n1+n2 n4=n1-n2 if n1==n2: print("true") elif n3==5 or n4==5: print("true") else: print(n3,n4)
def dic(dic1): list=[] for x in dic1.keys(): list.append(x) l=len(list) print("length of list is",l) count=0 for y in dic1.items(): count=count+1 print(y) print("the count",count) if(count>l): return ("dic1 has duplicate keys") elif(count=...
string = input("Введите текст: ") length = len(string) let_s = let_b = 0 for i in string: if 'a'<=i<='z': let_s += 1 elif 'A'<=i<='Z': let_b += 1 print("%% Строчных букв: %.2f" % (let_s/length * 100)) print("%% Прописных букв: %.2f" % (let_b/length * 100))
import cs50 import csv from sys import argv, exit if len(argv) != 2: # check argument print("Usage: python ") exit(1) db = cs50.SQL("sqlite:///students.db") rows = db.execute("SELECT first,middle,last,birth FROM students WHERE house=? order by last, first", argv[1]) for row in rows: # to print and c...
# @author : Ibrahim Sma # @github_location: https://github.com/ibrahim-sma # @email: ibrahim.sma1990@gmail.com # @LinkedIn: www.linkedin.com/in/ibrahim-sma # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Problem 3 - Largest prime factor # The prime factors of 13195 are 5, 7, 13 and...
string = "Hello World" list = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] tuple = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd') print(string[0]) print(list[0]) print(tuple[0]) print(string[0:5]) print(list[0:5]) print(tuple[0:5]) for i in string: print(i) string1 = "Hello World" string2 = "...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 8 08:32:43 2021 @author: moep """ import sys import random import time import Spieler import names Alphabet = ['a','b','c','d','e','f'] Ablauf = ['Zeit','Ort','Person','Tat','Zeuge','Kommentar'] def Einstellungen(): print("Stell zunäc...
import json import os # TODO # need to write menu 2 # menu 1 works but need to assign real variables and return them to all files class Setting(object): def __init__(self, name, description, data_type: type = str, ending=""): self.name = name self.description = description ...
#!/usr/bin/python3 """ Creates connection with database and run SQL queries. """ import mysql.connector from mysql.connector import Error from utils import create_log def connect(): """ Creates mysql connection object :return: connection object """ try: conn = mysql.connector.connect(opti...
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...
''' Two friends ask the attendant a snack bar propose a challenge , so that whoever hit him more, would not pay the bill. Then the following is proposed : Given the following sum below report the result , with the same number of terms : S = 1 - 1 + 1 - 1 + 1 - 1 + 1 - 1 ... Write a program that , given a number of term...
import unittest import classes from main import generate_pieces class TestGameMethods(unittest.TestCase): def setUp(self): pieces = generate_pieces() self.pieces = pieces self.game = classes.Game() self.game.generate_board(pieces) self.game.create_piece_dictionary(pieces) ...
"""Panagram A panagram is a sentence which contains all letters of the alphabet. Write a function called panagram which takes a string s as input. It should return True if s is a panagram and False otherwise. """ import string def panagram(s): # applicable only for lowercase letters az=string.ascii_lowercase ...
"""Write a function called smallest_in which takes a list of numbers l and returns the smallest number in the list.""" def smallest_in(l): b = l[0] for i in l: if i < b: b = i print (b)
import turtle from turtle import* # new turtle Instance t = turtle.Turtle() speed(0) #fastest # Small Blue Circle t.color("navy") t.penup() t.goto(0, 160) t.pendown() # thick border of chakra t.width(4) t.circle(50) # 24 spokes of ashok chakra t.penup() t.goto(0, 210) t.pendown() t.pensize(2) for i in range(24): ...
import os # Path to directory to be cloned target = "" # Path to directory to be created clone = "" print("Cloning \"" + target + "\" to \"" + clone + "\"") os.mkdir(clone) for (root, dirs, files) in os.walk(target): for name in files: path = os.path.join(root, name); path = path.replace(target, clone, 1) f...
from socket import * import base64 # Mail content subject = "I love computer networks!" contenttype = "text/plain" msg = "I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailserver mailserver = "smtp.163.com" # Sender and reciever fromaddress = "******@16...
table = {} amicable_numbers = [] UPPER_BOUND = 10000 # given by the problem def sum_of_divisors(x): result = 0 for num in range (1,x): if x%num == 0: result += num return result def compute_sum_of_divisors(): # pre-computing, should make things more efficient for num in range(1,UPPER_BOUND): table[num] = s...
# -*- coding: utf-8 -*- from __future__ import division import requests, re from bs4 import BeautifulSoup from collections import namedtuple # Because there are only 3 budgets denoted in pounds, I'm hardcoding a dict of just those year's exchange rates. # Should there be a new one, a KeyError would be thrown. # Sourc...
class Employee: comp_name = "sathya" comp_cno = 9876543210 def display(self): print("Employee Class") print(Employee.comp_name) print(Employee.comp_cno) # e1 = Employee() # e1.display() # print("----------------") # e2 = Employee() # e2.display() print("----------------") print(E...
def divideBy2(decNumber): remstack = [] while (decNumber > 0): rem = decNumber % 2 remstack.append(rem) decNumber = decNumber // 2 binString = '' while len(remstack) > 0: binString = binString + str(remstack.pop()) return binString print divideBy2(42)
print "Test Program" import pandas as pd import collections import matplotlib.pyplot as plt ### for review #1 - lists are mutable and can change, use li=[]. #2 - tuples are immutable. tp = (). #3 - sets are like lists with only unique values data = '''Region, Alcohol, Tobacco North, 6.47, 4.03 Yorkshire, 6.13, 3.76 ...
import time class Requisitos: requisitos = [] def _init_(self, requisitos): self.requisitos = [1, 2, 3, 4, 5, 6] def Faserequisitos(self, tipo_requisitos): for requisito in self.requisitos: print('requisito:' + requisito) return def printaFase(self, faseRequistos...
#####Question##### # Given an array of integers, return a new array with each value doubled. # For example: # [1, 2, 3] --> [2, 4, 6] # For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know. ########################################################################...
# Student: Victoria Cadogan from dataclasses import dataclass, field @dataclass class Products: name: str unit_price: float type: str def __get_tax(state): if state.upper() == 'MA': return 0.0625 elif state.upper() == 'ME': return 0.055 else: return 0 def checkout(p...
def has_negatives(a): """ YOUR CODE HERE """ numbers = dict() negatives = [] for number in a: if number not in numbers and number < 0: numbers[abs(number)] = number for num in a: if num in numbers: negatives.append(num) return negatives ...
class ShoppingList(object): cart = {} # A dictionary to hold item_name:price as key:value balance = 0 budget_amount = 0 #one wouldn't want to shop for more than is available def __init__(self, budget_amount): self.budget_amount = budget_amount #a method to add items to the cart ...
#Oppgave 3: Problemløsning med beslutninger #Til å starte med ber vi brukeren legge inn to datoer. #Vi ber bruker om å legge inn med et format på 4 siffer slik at vi kan hente ut det vi trenger print("Tenk på en dato") dato0 = input("Vennligst skriv inn datoen du tenkte på: (ddmm) ") #De to følgende variablene tar de ...
class Node: def __init__(self, data): self.data = data self.next = None def reverse(head): dummy = Node(0) dummy.next = head prev, cur = dummy, head while cur: while cur and cur.data % 2 == 1: prev, cur = cur, cur.next p0 = prev c0 = cur ...
def merge_sort(lst, left, right): if right - left > 1: mid = (left + right) // 2 merge_sort(lst, left, mid) merge_sort(lst, mid, right) merge_list(lst, left, mid, right) def merge_list(lst, left, mid, right): left_list = lst[left:mid] right_list = lst[mid:right] k = left...
import collections def solution(word): count = collections.Counter(word) for idx, w in enumerate(word): if count[w] == 1: return idx return -1 print(solution('alphabet'))
#!/usr/bin/python3 #author:Hamid.19-07-2017 class APQHeap: """ Maintain an collection of items, popping by lowest key. This implementation maintains the collection using a binary heap. Keys and or values can be updated. Items can be arbitrarily removed. """ class Element: ...
def multiply(a,b): print('s= ',a,'*',b, '=', a*b) def printMax (x, y, z): if x>y and x>z : print("max x=",x) elif y>x and y>z : print("max y=",y) elif x==y and y==z : print("x=y=z") elif x==y : print("x=y") elif x==z : print("x=z") elif y==z : print("y=z") else: print("ma...
# https://www.w3schools.com/python/python_strings.asp a = "Hello" print(a) a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a) a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut ...
#################################################################################################### # # ECE 271C: Dynamic Programming MIDTERM 2017 # # Given a set of coin denominations and a desired change amount, find the most efficient # allocation of coins according to different measures of efficiency. # # ...
""" Robert Hamby December 5, 2019 Advent of Code Day 4 Part 1 https://adventofcode.com/2019/day/4/answer """ # Takes in a number, converts to a string and # compares each index's value. If the current # number is ever greater than the next, it returns # false. Otherwise, returns true def decrease_test(s): num = str(s...
import itertools a = [1, 2, 3, 4, 5] b = [1, 2, 3] print(list(zip(a, b)))
import tamil from tamil.utf8 import get_letters_length, get_words file=open("unique_sorted_words_in_all_words_20200604-133955.txt","r") read_word=file.read() word=get_words(read_word) x=int(input("enter the number of word ")) y=input("enter the starting word ") z=input("enter the ending word ") for each in word: ...
import collections import bisect import time from datetime import datetime """ Weighted Interval scheduling algorithm. Runtime complexity: O(n log n) """ class Interval(object): '''Date weighted interval''' def __init__(self, title, start, finish): self.title = title self.start = int(time.m...
# Returning unique list def Uniques(list): unique_list = [] for x in list: if x not in unique_list: unique_list.append(x) return unique_list print(Uniques([1,2,3,4,2,4,5,3,2,1,5,5]))
# Factors of a given number def factors(x): factor_lst = [] for i in range(1,x+1): if (x % i == 0 ): factor_lst.append(i) return factor_lst print(factors(21))
def move_zero(lst): """ Given a list of integers, moves all non-zero numbers to the beginning of the list and moves all zeros to the end of the list. This function returns nothing and changes the given list itself. For example: - After calling move_zero([0,1,0,2,0,3,0,4]), the given list should be...
number=int(input("Enter you luck number:-")) while number!=5: new_input=input("do want to continous:") option='yes' if option==new_input: number=int(input("enter number again:")) if option!=new_input: print("Good Bye") if number==5: print("congulation yo...
# # Competitive Programming # # @author Daniele Cappuccio # @link (https://github.com/daniele-cappuccio/UVa-online-judge) # @license MIT License (https://opensource.org/licenses/MIT) # from math import * def isprime(k): for i in range(2, k): if k%i == 0: return False return True N = int(...
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" while True: try: line = input() for char in line: if char not in letters: print(char, end="") else: if char in "ABC": print("2", end="") elif char in "DEF": ...
# name = input('Please enter your name') # message = "Hello {} Welcome to python scripting".format(name) # print(message) # one = input('Please enter number1\n') # two = input('Please enter number2\n') # result = int(one)+int(two) # message = 'Sum of {} and {} is {}'.format(one,two,result) # print(message) # x = 'Jav...
''' two_list_dictionary(['a', 'b', 'c', 'd'], [1, 2, 3]) # {'a': 1, 'b': 2, 'c': 3, 'd': None} two_list_dictionary(['a', 'b', 'c'] , [1, 2, 3, 4]) # {'a': 1, 'b': 2, 'c': 3} two_list_dictionary(['x', 'y', 'z'] , [1,2]) # {'x': 1, 'y': 2, 'z': None} ''' def two_list_dictionary(keys, values): collection = {} ...
''' reverse_vowels("Hello!") # "Holle!" reverse_vowels("Tomatoes") # "Temotaos" reverse_vowels("Reverse Vowels In A String") # "RivArsI Vewols en e Streng" reverse_vowels("aeiou") # "uoiea" reverse_vowels("why try, shy fly?") # "why try, shy fly?" ''' def reverse_vowels(s): vowels = "aeiou" string = list(s)...
temp = int(input("Enter the temperature :")) method = input("Enter C or F to convert into Celcius or Ferhenheit :") def convertIntoF(cTemp): return (cTemp * (9/5)) + 32 def convertIntoC(fTemp): return (fTemp -32) * 5/9 if method.upper() == "F": # convert into fahrenheit print("The ",temp, " ^C in Fa...
binary_number=[1,0,0,1,1,0,1,1] sum=0 b=1/2 i=(len(binary_number)-1) while i>=0: c= binary_number[i]*(2**(b)) print c sum=sum+c b=b+1 i=i-1 print "all decimal no sum=",sum
question_list = [ "1. How many continents are there?", # pehla question "2. What is the capital of India?", # doosra question "3. NG mei kaun se course padhaya jaata hai?" # teesra question ] options_list = [ #pehle question ke liye options ["(1) Four","(2) Nine","(3) Seven","(4)Eight"], #second question k...
#!/usr/bin/python3 ''' imports ''' import sqlite3 import matplotlib.pyplot as plt import numpy as np class PlotMonkey(): ''' Monkey to draw plots based on databases created by an UrlMonkey. ''' def __init__(self, db_name): self.db_name = db_name def packup_small_ratios(self, url_dict, min_ratio...
class LinearEquation(object): # initialization method def __init__(self, m=1, b=0): # defaults to 'y = x' if isinstance(m, (int, float)) and isinstance(b, (int, float)): self.m = m self.b = b else: ValueError('Values passed must be numbers!') # getters ...
class Inventory(): """docstring for Inventory""" def __init__(self,keys=2,weapons=5,moves=20,life_line=3,score=0): self.keys= keys self.weapons= weapons self.moves = moves self.life_line= life_line self.score = score def add(self, arg): if arg == "keys": self.keys=self.keys+1 return self.keys ...
pip install matplotlib salaries = [ ("Mark", 1000), ("John", 1500), ("Daniel", 2300), ("Greg", 5000) ] #%matplotlib inline import matplotlib.pyplot as plt X = [0,1,2,3] Y = [0,1,0,1] plt.plot(X, Y) salaries = [ ("Mark", 1000), ("John", 1500), ("Daniel", 2300), ("Greg", 5000) ] ...
# palindrom s="radar" def palindrom(s): if s==s[::-1]: print("yes") else: print("no") palindrom(s)
import re alphabet = open("Alphabet1.txt") alphabet1 = open("Alphabet2.txt") content = alphabet.read() content1 = alphabet1.read() result = [] def concat_alphabets(alphabet,alphabet1): caracters = re.findall(r"[\w']+", alphabet) caracters1 = re.findall(r"[\w']+", alphabet1) for i in range(1,len(caracters...
""" Cultural evolution simulation simulation creates an initial population of agent with zero-ed out systems and uses this to produce a data set of utterances. These utterances are used to train the population at the next time step. Different methods to update the population are included: chain - this implements a 't...
""" Oliphaunt creates an initial population of random agents with and evolves this population over a number of generations, printing total fitness at each generation. Fitness is calculated after a certain number of random interactions among the population and is determined by the proportion of successful 'sends' and s...
import re print("Without ignore case") print(re.findall(r"yes", "yes? Yes. YES!!")) print("With ignore case extension notation") print(re.findall(r"(?i)yes", "yes? Yes. YES!!")) print("With ignore case") print(re.findall(r"(?i)th\w+", "The quickest way is through this tunnel.")) print("With ignore case and multi li...
def strip_excel_data(filepath): """Output a _tuple representing an Excel workbook's value contents. Arguments: filepath | The path to the Excel workbook being captured. _tuple structure is ((sheet_name, sheet_data), (...), ...) sheet_name is the Worksheet.Name property of the COM interface. sheet_data is the out...
# File: hw5_part2.py # Author: Ujjwal Rehani # Date: 4/6/17 # Section: 21 # E-mail: urehani1@umbc.edu # Description: # Checks if a name give by a user is a common name based on its ending # isProperName() check if name is all lowercase, with an uppercase first letter # Input: name, a string that will be chec...
# File: proj2.py # Author: Ujjwal Rehani # Date: 4/13/2017 # Section: 21 # E-mail: urehani1@umbc.edu # Description: # This project simulates a vending machine SNACK_NAME = 0 #zero index is name SNACK_PRICE = 1 #first index is price SNACK_QUANTITY = 2 #second index is quantity SNACK_CODE = 3 #thi...
# Recursive Python program to check if a string is subsequence def isSubsequence(string1,string2,m,n): if m== 0 : return True if n==0 : return False #if last characters of two strings are matching if string1[m-1] == string2[n-1] : return isSubsequence(string1,string2,m-1,n-1) # if las...
from agent import Agent from random import random, sample from itertools import combinations from math import comb # from mission import Mission class Bayes3(Agent): ''' Maintains probabilities of all possible worlds. Calculates the probabilty of each player being a spy from set of worlds. Probabil...
""" Given an string in roman no format (s) your task is to convert it to. integer. Input: The first line of each test case contains the no of test cases T. Then T test cases follow. Each test case contains a string s denoting the Roman no. Output: For each test case in a new line print the integer representation of R...
"""Function taking left and right as arguments""" def binarySearch(arr, l, r, x): if r >= l: mid = (l + r) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binarySearch(arr, l, mid - 1, x) else: return binarySearch(arr, mid + 1, r, ...
class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return str(self.data) # Iterative approach def reverseList(head): prev_node = None current_node = head while current_node is not None: next_node = current_node.next current_node.next = prev_node prev_node = c...
def wrapping_presents(): # width, length, and height will have their respective values as an index # 2*l*w + 2*w*h + 2*h*l ----> 2*value[0]*value[1]*value[2] # Have a way to parse the first numbers before "x" and add calculate it in a list # Have a way to parse the second numbers before "x" and add calculate it in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 6 16:06:04 2017 @author: Jay - Create a script called webcounter.py - The script should define a function run() with 2 parameters: a link to webpage and a single word. - The function should return the number of times that the word appears on the...
#!/usr/bin/python3 """ count it! """ import requests def count_words(subreddit, word_list): """ prints a sorted count of given keywords """ headers = {"User-Agent": ""} url = 'https://www.reddit.com/r/{}/hot.json'.format(subreddit) data = requests.get(url, headers=headers, allow_redirects=False)....
#!/usr/bin/env python3 from json import loads from urllib.request import urlopen # Astronomy Picture of the Day API powered by NASA's Data Portal # More information in: https://data.nasa.gov/developer # main function # prints on the screen the APOD title, the title of the image, # the url of the image and, by end, a ...
# 2018-4-21 # Transpose a Matrix # for big Matrix, numpy array is at least 10^3 faster than python array from util.time import timedcall, timedcalls import numpy as np def transpose_1(A): ii, jj = len(A), len(A[0]) B = [[0]*ii]*jj for i in range(ii): for j in range(jj): B[j][i] = A[i][j] return B def...
""" 関数を定義してみる """ # まずはスタンダードに文字列だけ返す関数 def hoge(): return "defining-function!" print(hoge()) # 引数を渡せるようにする(この場合引数は必須) def hoge_age(n): return "n = %s" % (n) print(hoge_age(10)) print(hoge_age('ABC')) #print(hoge_age()) # 引数を渡していないと"TypeError" # 引数にデフォルト値を与える def hoge_age_default(m = 'default_value'): ...
import datetime class MoscowTime: hours: str minutes: str seconds: str def __init__( self, hours: str = "00", minutes: str = "00", seconds: str = "00" ): self.hours = hours self.minutes = minutes self.seconds = seconds @classmethod def from_datetime(cls, t...
import requests def single(): url=input("Enter the URL with HTTP : ") try: scan=requests.get(url) print(url," -------> ",scan.status_code) except: print(url," -------> URL Error") def bulk(): fileName=input("Enter The txt PATH : ") urList = open(fileName, 'r') url=(urList.readlines()) for i in range(len(ur...
import sys from collections import deque input = sys.stdin.readline def topology_sort(): #indegree가 0인 노드에 대해서 queue = deque() answer = [] for i in range(1, M+1): if indegree[i] == 0: queue.append(i) strahler[i] = 1 while queue: now = queue.popleft() ...
def operators(s1, s2, op): if op == '+': return s1+s2 elif op == '-': return s1-s2 else: return s1*s2 def solution(s, op): answer = [] for i in range(len(s)-1): answer.append(operators(int(s[:i+1]), int(s[i+1:]), op)) return answer
# 구현을 사용해서 풀었다 ,,, # -> 직접 list에 넣고 뺄지, ox로 마크만 할지 고민하다가 insert시 전부 뒤로 밀어야 된다는 점에서 비효율적일것 같아 마크함 # 아예 구현으로 접근해서 그런지 다른 풀이를 떠올리지 못했다 # linked list를 이용해서 풀면 될것같다고 생각했는데, 클래스 선언, 삽입삭제 등의 구현이 복잡할 것같아서 여기서 개선시키려고 노력했다 def solution(n, k, cmd): answer = ['O' for _ in range(n)] # 기존 file 목록에 대해 저장 -> O면 남아있고, X면 삭제된 파일 !...
#Health application: Compute BMI pounds = eval(input("Enter weight in pouds: ")) height = eval(input("Enter height in inches: ")) kilograms = 0.45359237 * pounds meters = 0.0254 * height BMI = kilograms / meters ** 2 print("BMI is", (round(BMI * 10000) / 10000))
#Convert feet into meters feet = eval(input("Enter a value for feet: ")) meters = 0.305 * feet print(feet, "feet is", meters, "meters")
#Conversion of celsius into fahrenheit #Prompt user for input for celsius celsius = eval(input("Enter a degree in Celsius: ")) #Compute fahrenheit fahrenheit = (9 /5 ) * celsius + 32 print(celsius , "Celsius is", fahrenheit, "fahrenheit")
a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) # 4 integer division, rounded down towards minus infinity print(a % b) # 0 modulo: the remainder after integer division print() print(a + b / 3 -4 * 12)
from room import Room from player import Player import random # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), ...
x = 6 print("condition is true") if x == 6 else print("condition is false") # conditon in single line