text
stringlengths
37
1.41M
ele=input() for i in ele: if i=="1" or i=="0": f=1 else: print("no") break if(f==1): print("yes")
#!/usr/bin/env python import socket import struct def read_string(source): s = "" c = '' while c != '\n': c = source.recv(1) s += c return s[:-1] if __name__ == '__main__': try: server = socket.create_connection(('localhost', 5555)) except socket.error as se: print("Error: " + se.strerror) exit(-1) ...
#!/usr/bin/env python import socket from threading import Thread from SocketServer import * # multithreaded python server : TCP server socket thread pool class ClientThread(Thread): def __init__(self, ip, port): Thread.__init__(self) self.ip = ip self.port = port print("[+] New server socket thread started ...
#-*- coding: UTF-8 -*- input = '地址是北京市朝阳区太阳宫二街1号院太阳公元二期3号楼1602' sheng = ['江苏省'] zhiXiaShi = {1: '北京市', 2: '天津市', 3: '上海市', 4: '重庆市'} for (key, shi) in zhiXiaShi.items(): print shi[:-3] if input.find(shi) > 0 or input.find(shi[:-3]) > 0: print str(key) + ', ok' # 找到这个市下面的区; qu = ''
######################################################################################################## # The open() function takes two parameters; filename, and mode. # "r" - Read/"a" - Append/"w" - Write/"x" - Create # you can specify handling mode - "t" - Text/"b" - Binary ##########################################...
''' Remove & Pop in List - For remove, mention element. - Pop() mention Index , if none mentioned removes last element. ''' lst = [10,20,30,40,50,60,70,80,90] lst.remove(30) print(lst) # [10, 20, 40, 50, 60, 70, 80, 90] lst = [20,30,20,40] lst.remove(20) print(f'Duplicates in list {lst}') # doesn't concern about d...
########################################################################## # store multiple values as key:value pairs. # ordered*(from 3.7), changeable, duplicates. # If duplicate keys, values will overwrite with latest/recent values ########################################################################## dict = {'n...
class rajiv_gandhi: def __init__(self, fname, lname): self.fname = fname self.lname = lname def nativePlace(self): print('Delhi') def role(self): print('Ex Prime Minister') def parents(self): print('Foriz & Indhira') class human: def __init__(self,gender...
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 ...
import csv from datetime import datetime open_file = open("death_valley_2018_simple.csv","r") csv_file = csv.reader(open_file,delimiter=",") header_row = next(csv_file) print(type(header_row)) for index, column_header in enumerate(header_row): print(index,column_header) #------------------------------- ...
# ====================================================================== # There are 5 questions in this exam with increasing difficulty from 1-5. # Please note that the weight of the grade for the question is relative # to its difficulty. So your Category 1 question will score significantly # less than your Catego...
"""Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False.""" def is_leap(year): leap = False if year % 100 == 0 and year % 400 == 0: leap = True if year % 4 == 0 and year % 100 != 0: leap = True return leap if __name_...
"""Sum all values in a 2D array.""" def arr_sum(arr): result = 0 for row in arr: for column in row: result += column return result if __name__ == '__main__': array = [ [-1,2,1], [2,-1], [1,2,-1], [0] ] print(arr_sum(array))
"""https://www.hackerrank.com/challenges/merge-the-tools/problem Consider the following: A string, s , of length n where s = c0c1c2c2....cn. An integer,k , where k is a factor of n. We can split s into n/k substrings where each substring,ti , consists of a contiguous block of k characters in s. Then, use each ti to cr...
''' Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","nat","b...
def solve(s): lst = s.split(' ') res = [] for word in lst: if word[0].isalpha(): res.append(word.capitalize()) else: res.append(word) return ' '.join(res) # Test s = '12dsg' print(s.split(' ')) print(s.capitalize())
x = input("Introduce primul item din lista ") y = input("introduce al doilea item din lista: ") z = input("introduce al treilea item din lista: ") lista = [x,y,z] for r in lista: print(r)
#!/usr/bin/env python # -*- coding: utf-8 -*- class Movie(object): """ Stores movie information. title (str): title of the movie poster_image_url (str): url of the image trailer_youtube_url (str): url of the trailer on youtube imdb_url (str): ulr of the movied details on imdb """ def __i...
#!/usr/bin/env python """ Create random pasword with: + least one lowercase + least one uppercase + least one digit + least one punctuation + length = 16 """ import random import string def gen_passwd(passwd_length=16): """ Create password with default length = 1...
#!/usr/bin/python3 "python3 path" import time import sys import os from playsound import playsound def main(concentration: int = 25, short_break: int = 5, concentrations_before_long_break: int = 4, long_break: int = 30, total_cycles: int = 2): ''' The main function of the app ''' f...
# -*- coding: utf-8 -*- """ Created on Tue Dec 15 19:14:35 2020 @author: Kunal """ import time #Recursion def traversal_grid(n,m): s=0 if n==0 or m==0: return 0 if n==1 and m==1: return 1 s+=traversal_grid(n-1, m) s+=traversal_grid(n, m-1) return s #DP di={} def traversal_grid...
a = int(input("Enter the A number... ")) b = int(input("Enter the B number... ")) n = int(input("Enter the N number... ")) counter = 0 for i in range(a,b): if i%n == 0: counter += 1 else: continue print(f'The number of devisions are {counter} without reminder')
# coding: cp949 print("I eat %d apples." %3) # Ʈ ٷ print str = "In addition, I eat %d bananas" %2 # Ʈ ڿ Ȯϴ ̽ print(str) number = 4 print("Further more, I eat %d mangoes" %number) number = "five" print("Moreover, I eat %s tangerine" %number) number = 0.25 print("At the end, I eat %s melon" %number) # $s ⺻ ڿ ...
def input_ingredient(): ingredient_list = [] while True: ingredient = str(input("안녕하세요. 원하시는 재료를 입력하세요(종료입력시 종료): ")) if ingredient == "종료": return ingredient_list else: ingredient_list.append(ingredient) def make_sandwiches(ingredient_list): print("\n샌드위치를 만...
class Restaurant: def __init__(self, name, type): self.restauran_name = name self.cuisine_type = type def describe_restaurant(self): print("저희레스토랑 명칭은 %s 이고 %s 전문점입니다" % (self.restauran_name, self.cuisine_type)) def open_restaurant(self): print("저희 %s 레스토랑 오픈했습니다. 어서오세요" %s...
class Restaurant: def __init__(self, name, type): self.restauran_name = name self.cuisine_type = type def describe_restaurant(self): print("저희레스토랑 명칭은 %s 이고 %s 전문점입니다" % (self.restauran_name, self.cuisine_type)) def open_restaurant(self): print("저희 %s 레스토랑 오픈했습니다. 어서오세요" %s...
import re original_text = 'life is too short' p = re.compile('[a-z]+') m = p.search(original_text) print(m) # 검색결과는 매칭된 문자열들을 리스트로 반환한다. match_list = p.findall(original_text) for match_element in match_list: print(match_element)
from xml.etree.ElementTree import Element,dump, SubElement, ElementTree, parse import xml.etree.ElementTree as ET def summary_data(): tree = parse("n.xml") note = tree.getroot() men = women = major_com = program_experi = master_level = python_exp = twenties = thirties = forties = 0 twenties_dic = {} ...
while True: print("1~10000사이에서 숫자 두개의 공배수를 구합니다") num_x = int(input("첫번째 숫자 입력: ")) num_y = int(input("두번째 숫자 입력: ")) if num_y == 0 or num_x == 0: print("0이 입력되었습니다 프로그램을 종료합니다") break p =[i for i in range(1,10001) if i % num_x == 0 and i% num_y == 0] print(p)
# 비휘발성 데이터 베이스 생성 # 외부 데이터로부터 초기 DB table 값 생성 import csv import sys import sqlite3 input_file = sys.argv[1] # supplier_data.csv # SQLite의 경우 DB명이 파일로 1:1 매칭이 된다. con = sqlite3.connect('Suppliers.db') c = con.cursor() create_table = '''CREATE TABLE IF NOT EXISTS Suppliers (Supplier_Name VARCHAR(20), InVoice_Nu...
#coding: cp949 # print("⺻ if") # if, for, while ܵ indentation Ұ money = True #money = False # if Ͽ ݵ 1 ̻ statement ־ Ѵ. #if money: #print("ýø Ÿ ") # indentation , Ѵ. #if money: # print("ýø Ÿ ") # indentation , Ѵ. # indentation statement statement block Ѵ. #if money: # print(" ִ Ȯ Ǿϴ") # print("ýø ...
#!/usr/bin/env python3 import random """ p0nushiK_a Hangman game. This game is more complicated than our previous games but also more fun. Because the game is advanced, we’ll first carefully plan it out by creating a flowchart in this chapter. In Chapter 8, we’ll actually write the code for H...
'''Вам дана последовательность строк. В каждой строке замените все вхождения подстроки "human" на подстроку "computer" и выведите полученные строки''' import re pattern = r"human" repl = r"computer" line = input() out_line = "" while line: out_line += re.sub(pattern, repl, line) +"\n" line = input() print(out...
'''Вам дано описание наследования классов в формате JSON. Описание представляет из себя массив JSON-объектов, которые соответствуют классам. У каждого JSON-объекта есть поле name, которое содержит имя класса, и поле parents, которое содержит список имен прямых предков. Пример: [{"name": "A", "parents": []}, {"name": "...
import re pattern = r"cat" line = input() out_line = "" while line: if len(re.findall(pattern, line)) > 1: out_line += line+"\n" line = input() print(out_line)
# -*- coding: utf-8 -*- # Problem 003 Largest prime factor # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? # No need to check for prime, we are getting smalled factor that is different from 1. and that is always a prime number. import time start = ...
# -*- coding: utf-8 -*- # Problem 001 # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. somme = 0 for i in range(1,1000) : if i%3 == 0 or i%5 == 0: somme ...
#Saving the last session in a text file #And continue from where we left import time try: #Reading text file read_url = "text.txt" f = open(read_url, "r") lines = f.readlines() #print(lines[0]) for i in range(int(lines[0]) , 60): print(str(i)+...
ASSIGNMENT3 1. >>> li=[] >>> num=input("Enter the value added in List") Enter the value added in List 20 >>> li.append(num) >>> print(li) [' 20'] ----------------------------------------------------------------- 2. >>> l=[] >>> num=input("E...
# write a Program to Copy or Clone a list class listCopyOrClone: def aCopyOrClone(self,List): copyList=List print("copy List : ",copyList) def cloneList(self,List): cloneLst=List[:] print("cloneList : ", cloneLst) List=(1,2,3,4,5,6,7,8,9,10) copyList=listCopyOrClone() print("Orig...
# Write a Python program to generate all permutations of a list in Python. class generatePermutation: def permutationList(self,List): for i in range(len(List)): for j in range(len(List)): for k in range(len(List)): if (List[i] != List[j] != List[k]): ...
# Write a Python program to sort three integers without using conditional statements and loops class sortThreeIntegeger: def sortValues(self,numb1,numb2,num3): min1=min(numb1,numb2,num3) max1=max(numb1,numb2,num3) mid1=numb1+numb2+num3-min1-max1 print("Sorted Values are : ", min1,mid...
# Write a Python program to concatenate all elements in a list into a string and return it. class concatenateListString: def conListString(self,List): result = '' for element in List: result += str(element) print(result) List=[1,2,3,4,5,6] concat=concatenateListString() concat.c...
# Write a Python program to iteration over sets. class iterationSet: def iterations(self,Set): for iter in Set: print(iter,end="") value=set("Bhcratd") ite=iterationSet() ite.iterations(value)
# Write a Python program to get the smallest number from a list. class smallestNumber: def minimumNumber(self,list): for num in range(len(list)-1): for sort in range(len(list)-num-1): if(list[sort]>list[sort+1]): list[sort],list[sort+1]=list[sort+1],list[sort...
# Write a Python program to split a list based on first character of word. class splitList: def firstCharacter(self,listWord): character = listWord.split(" ") for word in character: print(word[0],end=" ") list1="Hi! are you going to college, if. Please see My Bench" words=splitList() w...
#Write a Python program to create a set. class setCreating: def set(self,set1,set2): setx=set1&set2 sety=set1|set2 setz=set1-set2 print(setx,sety,setz) set1=set(['Bharath','Harika']) set2=set(['Bharath','Aishwerya']) setCreate=setCreating() setCreate.set(set1,set2)
# Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. #--------------Sample List : ['abc', 'xyz', 'aba', '1221'] #--------------Expected Result : 2 class countFirstLast: def sameStartEndWord(self,list): ...
# Write a Python program to count the number occurrence of a specific character in a string. class countSpecificCharacter: def characterSpecial(self,string): print("count of ! : ",string.count('!')) string='i like to learn! live hadoop in mumbai!, i is a word!' odj=countSpecificCharacter() odj.characterSpec...
# Write a Python program to calculate number of days between two dates. # Sample dates : (2014, 7, 2), (2014, 7, 11) # Expected output : 9 days from datetime import date class daysBetweenDates: def days(self): f_date = date(2014,7,2) l_date = date(2014,7,11) delta = l_date - f_date ...
# write a Program to remove Item from Tuple class removeItemTuple: def itemTupleRemo(self,Tup): val=list(Tup) val.remove(4) print(tuple(val)) Tup=(1,2,3,4,5,6,7) tupleset=removeItemTuple() tupleset.itemTupleRemo(Tup)
from datetime import date if __name__ == '__main__': actual = list(map(int, input().split())) expected = list(map(int, input().split())) actual = date(day =actual[0], month= actual[1], year=actual[2]) expected = date(day=expected[0],month= expected[1], year=expected[2]) fine = 0 if actual > ex...
#!/usr/bin/env python3 """ Encrypting passwords """ import bcrypt def hash_password(password: str) -> bytes: """ Returns a salted, hashed password, which is a byte string """ encoded = password.encode() hashed = bcrypt.hashpw(encoded, bcrypt.gensalt()) return hashed def is_valid(hashed_password: by...
import itertools from functools import reduce list2 = [20, 10, 20, 1, 100] print(min(list2)) #############################find N largest elements from a list li = [81, 52, 45, 10, 3, 2, 96] n=3 li.sort() print(li[-3:]) ###############################program to print even numbers in a list li = [81, 52, 45, 10, 3, 2...
import turtle def draw_square(some_turtle): #Creating a Square for vertices in range (0,4): some_turtle.forward(100) some_turtle.right(90) def draw_circle(): # Creating a second turtle josercleia = turtle.Turtle() josercleia.shape("turtle") josercleia.color("#EF767A") joser...
# -*- coding: utf-8 -*- """ Created on Sun Jan 1 22:49:57 2017 @author: priyansh """ from math import sqrt plot1 = [1,3] plot2 = [2,5] euclidean_distance = sqrt((plot1[0]-plot2[0])**2 + (plot1[1]-plot2[1])**2) print(euclidean_distance)
''' Given a 32-bit signed integer, reverse digits of an integer. ''' def reverse(x): """ :type x: int :rtype: int """ ma = 2 ** 31 if x == 0: return x if x < 0: x = -x flag = -1 else: flag = 1 out = '' while x > 0: out = out + str(x % 10...
import traceback def findVcs(str): count=0 lst=str.split() for i in lst: if i=="vcs": count+=1 return count try: mycount=0 with open("fiple_io.txt") as f: for l in f: mycount+=findVcs(l) except IOError as e: print e traceback.print_exc() print myco...
# File has binary numbers # Find out the line with largest binary number import os.path def findOne(ln): count =0 for i in ln: if i=='1': count+=1 return count #print findOne([1,1,1,1,1,1,0,0]) list1=[] if os.path.exists("bin.txt"): with open("bin.txt","r") as f: for ln in ...
""" The following code will explain the supper and inhenritance """ class A(object): def __init__(self): print "initiate class A" def sub(self): print "This is Class A sub" class B(A): def __init__(self): A.__init__(self) print "override class A inside class B" # A._...
""" Generator explained """ import traceback class ygen: def __init__(self,n): self.n=n self.i=0 def ygen_f(self): while self.i < self.n: i=self.i yield i self.i+=1 try: obj=ygen(10) print (type(obj.ygen_f())) g=obj.ygen_f() pr...
#convert celcius to farenhit import re st = "print only the words that start with s in this sentence" l=re.split(" ",st) L=[] for i in l: match=re.search(r'^s[\w]',i) if match: L.append(i) print L
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Author : Rohit Maurya """ # This program takes more time than expected.I Will code sometime later. from math import sqrt from timeit import default_timer as timer start = timer() def isprime(n): """Returns True if n is prime.""" if n == 2: return ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 12 12:16:31 2017 @author: fun """ from timeit import default_timer as timer start = timer() def isprime(n): """Returns True if n is prime.""" if n == 2: return True if n == 3: return True if n % 2 == 0: retur...
''' ProjectEuler#46 auther: Rohit Maurya ''' # Solved using https://zach.se/project-euler-solutions/46/ from itertools import product def isprime(n): """Returns True if n is prime.""" if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: ...
import sys if len(sys.argv) > 1: if not sys.argv[1].isnumeric() or len(sys.argv) != 2: print("ERROR") elif int(sys.argv[1]) == 0: print("I'm Zero.") elif int(sys.argv[1]) % 2 == 0: print("I'm Even.") elif int(sys.argv[1]) % 2 != 0: print("I'm Odd.")
import categories import page import classify import pickle """ This method generates prior probabilities for a list of category link suffixes. ***INPUT*** catsLinks: list of strings where each string is a valid categories suffix link depth: positive integer to represent how far we want to recurse from the root categ...
# -*- coding: utf-8 -*- # The character we are playing as # Provides functions for the actions we can perform class Character: def __init__(self, location, items): self.Location = location self.Items = items def Inventory(self): print map(str,self.Items) def Look(self): pr...
# es una coleccion que es desordenada, por ende no tiene un indice # los son utilizados para definir una coleccion que no tiene indice colors = {'red', 'green', 'blue'} #print(type(colors)) #tipo de dato 'set' # tambien se puede comprobar # si hay un dato dentro de los tipos de datos en el set # usando 'in' print('r...
# bucles o alteradores. (nos permiten hacer una tarea tipica que va # relacionada con una lista de datos) # 'for' 'while' # puedes usar 'break' para romper con la lista y se pare donde el # usuario puso el comando # puedes hacer lo inverso pero con 'continue' # rompen y continuan el ciclo de un bucle foods = {'apple...
from foods import * food_order = ' ' user_choice = ' ' food_list = [] order_counter = 1 while True: user_choice = input('Choose 1 to exit or Choose 2 to create a food order or Choose 3 to print an order:') if user_choice == '1': print('Exit') break elif user_choice == '2': food_o...
<<<<<<< HEAD # Hej, jag kom inte på något sätt att köra bara en del av koden så jag använde mig av "#" för att få det att fungera #Omvandling Kelvin -> C K = float(input("ange temperaturen i Kelvin")) C = K-273.15 print(f"{K}Kelvin = {C}C") #Omvandling C -> Kelvin #C = float(input("ange temperaturen i C")) #K = C+273...
a = 'I love my dad' print(a) I love my dad b = 'I wanna learn Python' c = 'but i gotta show for it' d = a +' and '+" "+b +' '+ c print(d)
import string CHAR_SET = string.printable[:-5] SUB_CHARS = CHAR_SET[-3:]+CHAR_SET[:-3] ENCRYPT_dict = {} DECRYPT_dict = {} for i,k in enumerate(CHAR_SET): v = SUB_CHARS[i] ENCRYPT_dict[k] = v DECRYPT_dict[v] = k for c in string.printable[-5:]: ENCRYPT_dict[c] = c DECRYPT_dict[c] = c #encrypt ...
def h_line(num = 1, width = 82): if num == 1: line = '-' if num == 2: line = '=' full_line ='' for count in range(width): full_line += line return full_line
import sys import time import numpy # MATH IS MAGIC # simple script to generate diagonally dominant matrix # if matrix is diagonally dominant => we have solution with any right side # https://en.wikipedia.org/wiki/Diagonally_dominant_matrix # usage: # python data_generator.py <number_of_variables> # generate output fi...
from phonebook import PhoneBook from contact import Contact from student import Student from teacher import Teacher def main(): phonebook = PhoneBook("Examples/Classes/contacts.csv") person1 = Contact("Maija", "Meikäläinen", "123456789", 1990) person2 = Contact("Matti", "Meikäläinen", "987654321", 1991) perso...
# *-operaattoria käyttäen voidaan määrittää funktio, joka hyväksyy määrittämättömän määrän # paramerteja [0..*]. Funktiossa parametrit on tallennettu tupleen. Kutsuttaessa parametrit # erotetaan toisistaan pilkulla def sum(*numbers): result = 0 for number in numbers: result += number return result sum1 = su...
''' Seuraavaa tehtävää on käytetty yleisesti työhaastatteluissa ennakkotehtävänä: Kirjoita funktio, joka ottaa parametrinaan numeron ja palauttaa joko "Fizz", "Buzz" tai "FizzBuzz" seuraavien ehtojen perusteella: - Jos numero on jaollinen kolmella, funktio palauttaa "Fizz" - Jos numero on jaollinen viidellä, funktio ...
# Harjoitus # Kirjoita ohjelma, joka kysyy käyttäjän nimeä. Ohjelma tulostaa esim. tekstin # "Mikä sinun nimesi on?" nimeä kysyttäessä. # Jos nimi on kirjoitettu pienellä alkukirjaimella, ohjelma muuttaa nimen alkukirjaimen # isolla kirjoitetuksi. Lopuksi ohjelma tulostaa "Sinun nimesi on <Nimi>" name = input("What is ...
from userstories.sprint04_us.userStory27 import us27_individual_ages import unittest class UserStory27Test(unittest.TestCase): def test_us27(self): error_list = us27_individual_ages("gedfilestest/sprint04_ged/us27testdata.ged") print(error_list) self.assertEqual(error_list,["US27: The list o...
from ParserModule import parse_main from utils import checkDiffInDays from print_main import printTables from datetime import datetime #Get Age def getAgeAt(born, given): born = datetime.strptime(born, "%Y-%m-%d") given = datetime.strptime(given, "%Y-%m-%d") return given.year - born.year - ((given.month, ...
txt = "Мы изучаем " "Python" print(txt) print("Всего", len(txt), "букв") print("Индекс\tБуква") for i in range(len(txt)): print(str(i) + ": \t" + txt[i]) print(txt[11:]) print(txt[::-1]) word = "Java" txt = txt[:3] + "не" + txt[2:11] + word print(txt)
class Fibs: def __init__(self, n): self.start() self.n = n def start(self): self.count = 1 self.a = 1 self.b = 1 def __iter__(self): return self def __next__(self): if self.count > self.n: self.start() raise StopIteration...
from math import sqrt class LinearEquationWarning(Warning): def __init__(self, b, c): try: self.x = -c / b except ZeroDivisionError: if c == 0: self.x = "любое число" else: self.x = "решений нет" def __str__(self): tx...
def show_me(*args): i = 0 print("Аргумент(ы) функции:") for s in args: i += 1 print(str(i) + "-й аргумент:", s) print("Выполнение функции завершено.") show_me() show_me(100) nums = [10, 55, 2 + 3j, 0.123] show_me(*nums) show_me("Python", "Java")
A = {1, 2, 3, 4} print("Множество A:", A) B = {3, 4, 5, 6} print("Множество B:", B) C = A - B print("Множество C = A - B:", C) print("Множество A.difference(B):", A.difference(B)) print("Множество B.difference(A):", B.difference(A)) A.difference_update(B) print("Множество A:", A) B = B - {4, 6, 8, 10} print("Множество ...
res = input("Введите что-нибудь: ") resType = type(res) if resType == int: print("Это целое число!") elif resType == float: print("Это действительное число!") else: print("Наверное, это текст!") print("Работа завершена!")
''' class Calculator: def __init__(self,first,second): self.first=first self.second=second def add(self): result=self.first+self.second return result def sub(self): result=self.first-self.second return result def mul(self): result=self....
#math 모듈 pi ''' r=float(input('원의 반지름:')) import math l=2*r*math.pi m=math.pi*r**2 print('반지름 %f인 원의 둘레는 %f'%(r,l)) print('반지름 %f인 원의 넓이는 %f'%(r,m)) ''' #math 모듈 삼각함수 '''from math import raidans, tan''' #radians, tan를 바로 사용가능 ''' d=int(input('거리:')) g=float(input('각도:')) import math #import하...
def Add(a,b): r=int(a)+int(b) print('%s+%s=%d'%(a,b,int(r))) def Sub(a,b): r=int(a)-int(b) print('%s-%s=%d'%(a,b,int(r))) def Mul(a,b): r=int(a)*int(b) print('%s*%s=%d'%(a,b,int(r))) def Div(a,b): r=int(a)/int(b) print('%s/%s=%d'%(a,b,int(r))) def Calculator(num...
#! /usr/bin/python """ [SERVER] Unsupervised Parkinson's Disease Assessment Date: Tuesday June 12th, 2018 Author: Alexander Adranly Console class """ from server import * """ [CLASS] Command Defines a new command a user can install into the console class """ class Command(object): def __init__(se...
# http://www.pythonlearn.com/code/BeautifulSoup.py # Into the same folder as this program import urllib from BeautifulSoup import * url = raw_input('Enter - ') html = urllib.urlopen(url).read() soup = BeautifulSoup(html) count = raw_input('Enter count:') count = int(count) position = raw_input('Enter position:') po...
############################################################################################### ## Learn Python The Hard Way ## ## Exercise #2 : Comments and Pound Characters ## ## http://learnpythonthehar...
# STRING OPERATIONS IN PYTHON PART 01 str = 'hello world' print('string: ', str) print('Length: ', len(str)) print('Str[1]: ', str[1]) # character in 1st position gets printed print('str[0:4]', str[0:4]) # 0th index included but 4th index is excluded # which means characters in 0,1,2,3 get printed print('str[4...
# FILE HANDLING IN PYTHON PART 01 file = open('try.txt') print(file) # can give a opening mode like open('try.txt', 'r') # r - read only linecount = 0 for line in file: #line refers to a single line in a code print(line) linecount = linecount + 1 print(linecount)
# Given the participants' score sheet for your University Sports Day, #you are required to find the runner-up score. #You are given scores. Store them in a list and find the score of the runner-up. # Input Format. The first line contains n. The second line contains an array of 'n' scores if __name__ == '__ma...
num = [3, 12, 9, 41, 15, 74] maxnum = -1 # assume maximum number as -1 for n in num: if n >= maxnum: maxnum = n print('Maximum number = ', maxnum) # this will print the maximum number among the numbers in the 'num' list # however the negative side of this is if any number is a negative number, ...
# List comprehensions---------------------------------- # You are given three integers x,y,z representing the # dimensions of a cuboid along with an integer n. # Print a list of all possible coordinates given by # (i,j,k) on a 3D grid where the sum of i,j,k is not equal to n. # Here, 0<=i<=x, 0<=j<=y, 0<=k<=z....
# from asyncio import Queue import numbers class EmptyQueueException(Exception): pass class BaseQ(): def __init__(self): self.l = list() def enqueue(self, x): assert isinstance(x, numbers.Number) self.l.append(x) def dequeue(self): return self.l.pop(0) def peek_f...