text
stringlengths
37
1.41M
from sys import argv from os.path import exists script, from_file, to_file = argv # commenting out next line to simplify the process # print "Copying from %s to %s" % (from_file, to_file) # this goes from opening the file to reading the file, all on one line. # # indata = open(from_file).read() # # we can bypa...
# Autor: Victor ivan koop Mendez # Matricula: Co6219 # Profesor: Christian Mendoza Gomez import math def metodo_punto_fijo(f, p, TOL): error = 1 iteraciones = 0 while error > TOL: try: p_nuevo = f(p) error = abs(p_nuevo - p) p = p_nuevo iteraciones ...
x=20 y=30 print("AND example: ", x==25 and y==30) print("OR example: ", x==25 or y==30) print("NOT example: ", not(x==25 or y==31))
dict = {1: "Paula", 2: "Mery"} print(dict) print(dict.keys()) print(dict.values()) print(dict.items()) for i in dict.keys(): print(i, dict[i]) del(dict[1]) print(dict)
#Integer type a = 12 b = 100 c = -66 print(a,b,c) print(type(a)) #Float type x = 33.3 y = -25.8 z = 205.0 print(x,y,z) print(type(x)) #Complex type d=3+5j print(d) print(type(d)) #Binary type e=0B1010 print(e) print(type(e)) #Hexadecimal f=0XFF print(f) print(type(f)) #Boolean g=True print(g) print(type(g)) #Conv...
# The hello function takes a name and it will return Hello under that name and then even create a decorator # function called howareyou that will take the result of the hello function and it will append a string # called "How are you" at the end # Hello (name) # howareyou() def howareyou(fun): def inner(n): ...
# Plus operator can concatenate numbers, strings or lists # Plus operator is overloaded and it is polymorphic, it does multiple things depending on what you give it x = 10 y = 20 print(x + y) s1 = "Hello" s2 = " Paula" print(s1 + s2) l1 = [1,2,3] l2 = [4,5,6] print (l1 + l2)
a,b,c = [int(x) for x in (input("Enter three integer numbers separated by comma: ").split(","))] average = (a+b+c) / 3 print("The average is: {}".format(average))
tpl = (40,50,60,70) print(tpl) print(tpl[2]) print(tpl*3) print(tpl.count(40)) print(tpl.index(40)) #List to tuple lst=[1,2,3,"abc"] print(type(list)) tpl1 = tuple(lst) print(type(tpl1))
import urllib.request # Request a web page and read its content try: url = urllib.request.urlopen("http://www.google.es/") content = url.read() url.close() except urllib.error.HTTPError: print("The web page is not found") exit() # Write the content in one file f = open('google.html', 'wb') f.write...
# If we don't specify buffer size, 4096 or 8092 will be used by Python VM f = open("filename", "mode", "buffer") # Do things and finally, close the file f.close() # MODES # W - WRITE MODE - # write on the file, if the file has content, # it will be deleted, new content is written from the beginning of the file # R ...
a=b=c=10 print(a,b,c) x,y=10,5 print(x,y) x+=y print(x)
#!/usr/bin/env python # coding: utf-8 # In[1]: #Exercise 8.2 #Reference Code from figure 8.7 word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count) # In[2]: #use string method count #write an invocation that counts the number of a's in 'banana' #want to "invoke...
######################################## #JUEGO TRIVIA DE PREGUNTAS Y RESPUESTAS# ######################################## #CREADOR: MATIAS MANUEL TONIOLO #VERSION: 1.0 #AÑO 2021 import random import csv with open('toniolo1.csv',encoding='utf-8') as mmm: data = mmm.readlines() dic = {}...
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils.exceptions import FileFormatError def read_conll_corpus(filename): """ Read a corpus file with a format used in CoNLL. """ data = list() data_string_list = list(open(filename)) element_size = 0 X = list() Y = list() for da...
# coding: utf-8 # # Intro to TensorFlow # In[1]: import math import numpy as np import tensorflow as tf from pprint import pprint from tensorflow.examples.tutorials.mnist import input_data from sklearn import preprocessing # ## HelloWorld # In[2]: class HelloWorld: def run(self): hello_con...
Student_Id = input('請輸入號碼: ') Chinese_Score = int(input('請輸入國文科目成绩: ')) Math_Score = int(input('請輸入數學科目成绩: ')) English_Score = int(input('請輸入英語科目成績: ')) All_Score = Chinese_Score + Math_Score + English_Score Average_Score = All_Score / 3 Chinese_Percent = Chinese_Score / All_Score *100 print('%s的平均成績為%.2f' %(St...
import sys #Box maker thingy Grid = [["_"]*3 for i in range (3)] #Makes the grid def initialise (Grid): for i in range (3): for j in range (3): print(Grid[i][j], end = '|') print ("") #Askes for input of x, o def Input (Grid): for i in range (9): ...
#Age guesser Input = input ("Pick a number from 1 - 9: ") num = int(Input) if num > 9: print("No, pick again by running the program again.") else: print ("Number Stored") print("Now the number will be multiplied by two: ") Multi = num * 2 print (Multi) print ("5 will be added to the nu...
# Fibonacci sequence a, b = 0, 1 for i in range(0, 10): print(a) a, b = b, a + b # Fibonacci generator def fib(num): a, b = 0, 1 for i in range(0, num): yield "{}: {}".format(i + 1, a) a, b = b, a + b for item in fib(10): print(item)
in_str = input("Please tell me your nickname!\n") #print(in_str.upper()+" in 10 seconds") input = 22 real_yooshink = "keroro" real_noah = "tamama" if in_str == real_yooshink: print("Hi Yooshin~") elif in_str == real_noah: # else if -> elif print("Hi Nonah~") else: print("who are you?")
count = 0 def hanoi_top(n, from_pos, to_pos, aux_pos): global count count = count + 1 if n == 1: print(from_pos," -> ",to_pos) return hanoi_top(n-1,from_pos,aux_pos,to_pos) print(from_pos," -> ",to_pos) hanoi_top(n-1,aux_pos,to_pos,from_pos) #---------------------...
number1 = int(input('First number: ')) number2 = int(input('Second number: ')) if 30 <= number1 <= 40 and 30 <= number2 <= 40: print('Both numbers are OK') elif number1 in [65, 72, 83, 90] and number2 in [65, 72, 83, 90]: print('Both numbers are OK') else: print('They are NOT OK') # use or in place of elif
total = number = int(input('Initial limit: ')) end = int(input('Final limit: ')) print('sum of numbers from', number, 'till', end) if number == end: print(number) while number != end: number += 1 total += number print('+', number, '-->', total)
kg = int(input('Your weight in kilograms: ')) length = int(input('Your length in centimeters: ')) bmi = (kg / length ** 2) * 10000 if bmi < 18: print(bmi) print('underweight') elif 18 <= bmi < 25: print(bmi) print('normal weight') elif 25 <= bmi < 27: print(bmi) print('slightly overweight') elif...
word = input('Enter a word: ') length = int(len(word)/2) print(word[length-1: length+2])
def convert(ex, euro): dol = ex * euro return dol # main exchange_rate = float(input('Current dollar rate (€ - > $): ')) amount = float(input('Your amount in Euro: ')) dollar = convert(exchange_rate, amount) print('€', amount, '= $', dollar)
def press_square(n, char): for i in range(n): print(char * n) # main character = input('Which character must be used to form the lines (enter = stop): ') times = int(input('Number of characters per line = numbers of lines = ')) while character != '': press_square(times, character) character = inpu...
colour = input('What is your favorite colour: ') print(colour[0], colour[2], sep='') print('This colour consists of', len(colour), 'letters') print() for i in colour: print(i, '=', ord(i)) print() x = 0 while x < len(colour): print('#' + colour[x] + '#') x += 1 print('**' + colour[x] + '**') x += 1
surname = input('Geef de achternaam: ') first_name = input('Geef de voornaam: ') street = input('Geef de straatnaam: ') number = input('Geef de huisnummer: ') zip_code = input('Geef de postcode: ') city = input('Geef de stad: ') print(first_name, surname) print(street, number) print(zip_code, city)
number1 = int(input('number 1 (0, 1 or 2): ')) number2 = int(input('number 2 (0, 1 or 2): ')) number3 = int(input('number 3 (0, 1 or 2): ')) if number1 == number2 and number2 == number3: if number1 == 2: print(10) else: print(5) elif number1 != number2 and number1 != number3: print(1) else: ...
number = int(input('Enter a number: ')) text = input('Enter a word') print(text * number)
numbers_1 = (1, 2, 3, 4, 5, 6, 7, 8, 9) numbers = (4, 2, 3, 9, 1, 4, 5) numbers_2 = (2, 3, 7, 5, 6, 1, 9) if 4 in numbers: i = numbers.index(4) new = numbers[i + 1:] while 4 in new: i = new.index(4) new = numbers[i + 1:] print(new) else: print('The number 4 does not appear in the tup...
def getMonthly(): anotherMonth = 'y' MIN_INVESTMENT = 100 MAX_INVESTMENT = 10000 while anotherMonth == 'y': try: monthly = float(input("Enter Monthly Investment:$ ")) if monthly < MIN_INVESTMENT: print("Monthly investment must be between $100 and $10,000."...
# Uendelig liste Melli oppgave >:) # Infinite list Melli task> :) # eternal list = [] evig_liste = [] # again = "yes" en_gang_til = "ja" # print ("Enter the desired number in the list:") print("Skriv inn ønsket tall i listen: ") # while again == "yes" or again == "Yes": def validate_input(inpu): try: ...
def pad_string(data, size, padding_character=' ', direction='left'): """This new function will determine if it will pad to the left or the right by using an if statement.""" if direction == 'left': data.rjust(size, padding_character) elif data == 'right': data.ljust(size, padding_character) ...
# OP's second attempt https://pastebin.com/fWUe8KGA name = input("Name: \n") games_played = int(input("Games: \n")) volleyball_times = 0 tennis_times = 0 badminton_times = 0 total_points = 0 volley_points = 0 tennis_points = 0 badminton_points = 0 volley = False tennis = False badminton = False for g in range(games_pla...
findMaxA(l): l.sort() return l[len(l) -1] findMaxB(l): m = l[0] for i in range(0, len(l), 1): if l[i] > m: m = l[i] return m l = [100,1,3,5,3,1234,423,5432,5423] print (max(l))
''' Description: Write a method called reverseWordA. The method takes a Strings and returns the string in reverse Name: reverseWordA Parameters: String s Returns: String Precondition: s is a valid string of any length. reverseWordA(“cat”) → “tac” ''' def reverseWordA(s): a = "" #empty string that I will bu...
file = open("DATA1.txt","r") #This will read the whole data in one go ''' content = file.read() print(content) ''' #This will read one line at a time for aline in file: print(aline)
''' This method takes two lists and returns a new list containing the common elements from both lists. ''' def commonElements(l1,l2): l3 = [] for i in range(0, len(l1),1): for j in range(0, len(l2),1): if l1[i] == l2[j]: l3.append(l1[i]) return l3 #Trace Table ''' l1 = ["monkey","cat","moose"] l2 = [...
#!/usr/bin/env python # coding: utf-8 # # Desafio 1 # # Para esse desafio, vamos trabalhar com o data set [Black Friday](https://www.kaggle.com/mehdidag/black-friday), que reúne dados sobre transações de compras em uma loja de varejo. # # Vamos utilizá-lo para praticar a exploração de data sets utilizando pandas. Vo...
def sorted_two(data, key = lambda x: -x): sort_data = [] for i in data: sort_data.append(sorted(i, key = key)) return sorted(sort_data, key = lambda i: i[-1]) data = [[6, 5, 4], [3, 2], [1]] key = lambda x: x print(sorted_two(data, key = key))
def transpose(table, n, m): table = [[table[i][j] for i in range(int(n))] for j in range(int(m))] for i in table: print(' '.join([str(j) for j in i])) n, m = input().split() transpose([[int(i) for i in input().split()] for j in range(int(n))], n, m)
def check(i): if i % 9 == 0: return 1 else: return 0 print(sum(map(lambda i: i**2, filter(check, range(10, 100))))) #обе работают print(sum(map(lambda i: i**2, filter(lambda i: i % 9 == 0, range(10, 100)))))
tuple1 = (1, 2, 3, 4, 5) tuple2 = ('a', 'b', 'c') tuple3 = (1, 'a', 'abc', [1, 2, 3, 4, 5], ['a', 'b', 'c']) #tuple1[0] = 6 def myfunc(): print('안녕하세요') tuple4 = (1, 2, myfunc) tuple4[2]() # ‘안녕하세요’ 가 출력됨
from zipfile import * import os def compressAll(zipname, folder): print('[%s] -> [%s] 압축...' %( folder, zipname)) with ZipFile(zipname, 'w') as ziph: for dirname, subdirs, files in os.walk(folder): for file in files: ziph.write(os.path.join(dirname, file)) folder = 'tmp' zi...
class Add: def add(self, n1, n2): return n1+n2 class Multiply: def multiply(self, n1, n2): return n1*n2 class Calculator(Add, Multiply): def sub(self, n1, n2): return n1-n2 obj = Calculator() print(obj.add(1, 2)) # 3이 출력됨 print(obj.multiply(3, 2)) # 6이 출력됨
#----------------------------------- # 기본 구문 #----------------------------------- # list, dictionary a = 200 msg = 'I love Python' list_data = ['a', 'b', 'c'] dict_data = {'a':97, 'b':98} #----------------------------------- print(a) print(msg) print(list_data) print(list_data[0])# 0, 1, 2 print(list_data[2]) print...
names = {'Mary':10999, 'Sams':2111, 'Aimy':9778, 'Tom':20245, 'Michale':27115, 'Bob':5887, 'Kelly':7855} ret1 = sorted(names) print(ret1) def f1(x): return x[0] def f2(x): return x[1] ret2 = sorted(names.items(), key=f1) print(ret2) ret3 = sorted(names.items(), key=f2) print(ret3) ret4 = sorted(names.items(...
listdata = list(range(5)) listdata.reverse() print(listdata) # [4, 3, 2, 1, 0]이 출력됨
names = {'Mary':10999, 'Sams':2111, 'Aimy':9778, 'Tom':20245, 'Michale':27115, 'Bob':5887, 'Kelly':7855} k = input('이름을 입력하세요: ') if k in names: print('이름이 <%s>인 출생아수는 <%d>명 입니다.' %(k, names[k])) else: print('자료에 <%s>인 이름이 존재하지 않습니다.' %k)
txt1 = '자바';txt2='파이썬' num1= 5; num2=10 print('나는 %s보다 %s에 더 익숙합니다.' %(txt1, txt2)) print('%s은 %s보다 %d배 더 쉽습니다.' %(txt2, txt1, num1)) print('%d + %d = %d' %(num1, num2, num1+num2)) print('작년 세계 경제 성장률은 전년에 비해 %d%% 포인트 증가했다.' %num1)
# Tools for grouping proteins into non-conflicting sets for # multiplexed screening of homologues import re from pychemy.peptides import mass_from_sequence import numpy as np import csv import os AA = re.compile('[ACDEFGHILMNPQSTVWY]+[RK]') AA_check = re.compile('[ACDEFGHILKMNPQRSTVWY]') def check_AA(test_string):...
emp=int(input("Enter number of Employees:")) count=0 rank=[] for i in range (emp): r=int(input("Enter rank of #%d employee :" %(i+1))) # print() rank.append(r) for i in range(emp-1) : for j in range(emp-i-1): if rank[j]<rank[j+1] : count+=1 else: ...
#"countinu" example : repeat printing "Too small" or "Input is..." according to input's lenth while True: s=raw_input('Enter something: ') if s == 'quit' : break if len(s) <3: print 'Too small' continue #continue : not exc...
# -*- coding: utf-8 -*- """ Created on Sun Nov 5 17:17:45 2017 @author: Aksharaa Sundarrajan """ #Importing the library import pandas as pd import numpy as np import matplotlib.pyplot as plt #Importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,:-1].values Y = dataset.iloc[:,1].values ...
print("1. Number Analyser") print() number = int(input("Give me a number: ")) total = 0 if number > total: print("Positive") elif number < total: print("Negative") elif number == total: print("Zero") else: print("Error") remainder = number % 2 if remainder == 0: print("Even") else: ...
"""Functions related to uploading to the ftp server are contained here""" from ftplib import FTP import re import os import datetime class FTPConnect: """This class defines easy methods for connecting to the server""" def __init__(self, server, username, password): self.server = server self.use...
class Deque(object): def __init__(self, front=[], back=[]): self._front = front self._back = back def shift(self): if len(self._back) == 0: self._flip() if len(self._back) == 0: raise ValueError("can't shift empty deque") return self._ba...
class Solution( object ): def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ list=[] for i in range(left,right+1): l=0 n1=len(str(i)) for j in range(n1): k=...
import math class Solution(object): def smallestGoodBase(self, n): """ :type n: str :rtype: str """ num = int(n) thisLen = int(math.log(num,2)) + 1 while thisLen > 2: # from equation [3], we havve thisBase = int(num ** (1.0/(thisLen - 1...
def czy_palindrom(wyraz): wyraz = wyraz.upper() if wyraz == wyraz[::-1]: return 1 return 0 wyraz = "palindrom" if czy_palindrom(wyraz) == 1: print(wyraz, "jest palindromem") else: print(wyraz, "nie jest palindromem") wyraz = "kajak" if czy_palindrom(wyraz) == 1: print(w...
n1 = int(input()) n2 = int(input()) n3 = int(input()) if n3 > n2: if n2 > n1: print("True") else: print('False') else: print("False")
# put your python code her number = input() n1 = int(number[0]) n2 = int(number[1]) n3 = int(number[2]) print(n1 + n2 + n3)
# -*- coding: utf-8 -*- """ Created on Thu Oct 10 00:27:49 2019 @author: Supi """ class Account: def __init__(self): self.amount = 200 def savings(self,amount): print("Savings amount : {}".format(amount)) def checking(self): print("checking Balance...
import random import math class Tree: """ # Param: # nodes = list of nodes e.g Nodes[] # Variables: # self.nodes will be the list that is edited (removed/added) # self.actualNodes is the actual list of node. This should not be changed. # self.distanceList is the list of distance...
####################################################### Level 1 def level1(path, y, x, h): '''Calculate the land area and its proportion of whole land area in given region that above a particular sea level height. Parameters: file name, mean vertical spacing (km), ...
#assignment 1 task 1 import sys while True: #input number try: num = input('Enter the desired goal cell number: ') except ValueError: print('Incorrect value, try again') try: num = int(num) if num <= 0: raise ValueError else: break exc...
from itertools import combinations class SudokuError(Exception): def __init__(self, message): self.message = message class Sudoku: def __init__(self, soduku_file): self.txt_name = soduku_file self.s_str = '' self.s_list = list(([None] * 9) for i in range(9)) self.b_l = ...
import sys import os #input try: string = input('Enter between 3 and 10 lowercase letters: ') except ValueError: print('Incorrect input, giving up...') sys.exit() try: lowercase = [] for c in string: if c.isspace(): pass elif c.islower(): lowercase.append(c)...
# matrix manipulations def Display(A,c): print("Matrix",c) for i in A: print(*i) def Addition(A, B): print("Addition :: ") Add = [] for i in range(r1): a = [] for j in range(c1): a.append(A[i][j] + B[i][j]) Add.append(a) for r in Add: print(*r) def...
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:summer_han #函数在内部调用自己,就叫递归函数 #1、要有明确的结束条件。 #2、每次进入更深一层递归时,问题的规模相比上次递归都应该有所减少。 #3、递归效率不高,层次过多容易栈溢出,栈内存大小不是无限的, 算法会详细介绍。 #递归最高999次,程序保护机制 def calc(n): print(n) if int(n/2) > 0: #一直到1/2 =0.5 int 之后为0,所以最后打印 --->:1 return calc(int(n/2)) print("--->:"...
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:summer_han ''' #server端 import socket socket.TCP/IP listen(0.0.0.0:port) waiting() recv() send #client端 import socket socket.TCP/IP connect(a,ip,a.port) socket.send(hello) socket.recv socket.close() http://www.cnblogs.com/alex3714/articles/5830365.html ''' # clien...
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:summer_han ''' class Person(object): # 构造方法 也叫 初始化方法 self 就等于实例化后的 实例 def __init__(self,name,food): # 下面 d=Person("jfsu") # 先实例化 相当于 Person(d,'jfsu'), # 将d 穿给self # ***如果 food 想被 say 调用,需要在此处声明,...
__author__ = 'sujunfeng' shopping_menu=[ ("Iphone X",8999), ("Mac pro",17999), ("Bike",999), ("Balance car",1999), ("Book",59), ("IWatch",3999) ] import sys with open("user_info_list.txt",'r') as f: info=f.read() user_info_dict = eval(info) def shopping_list(): # 打印商品列表 print('商品...
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:summer_han # 生成6位 有大写字母和数字随机组成的验证码 import random # 导入 随机模块 chkcode = '' # 初始化 验证码为空 for i in range(0,6): # 循环6次 # print(i) current = random.randint(0,6) # 定义一个值 # print(current) if current == i: # 定义的值 和循环到的值相等 chk_tmp = chr(random.rand...
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:summer_han ''' f = open("yesterday2",'r',encoding="utf-8") f_new = open("yesterday2.bak",'w',encoding="utf-8") #方法1: for line in f: if "雪绒花" in line: line = line.replace("雪绒花","小瀚宝") f_new.write(line) else: f_new.write(line) #方法2: fo...
import time # 高阶函数 + 嵌套函数 = 》 装饰器 def timer(func): # 嵌套函数 def decorator(*args,**kwargs): # 高阶函数 之前 func 是传递给 decorator的 start_time = time.time() func(*args,**kwargs) stop_time = time.time() print('run time is %s' % (stop_time - start_time)) return decorator @timer # 相当于...
def binary_exponent(base,pow1): ans=1 while(pow1!=1): if(pow1%2==0): ans*=base*base pow1=pow1//2 else: ans*=base pow1-=1 return ans base=int(input()) pow1=int(input()) ans=binary_exponent(base,pow1) print("binary_exponent=",ans) d...
import time import sys import os def is_number(s): try: float(s) return True except ValueError: return False #Test arguments count = sys.argv[1] if is_number(count): count = int(float(count)) print("STARTING Your Custom Counter\n") else: print("You did not enter a numb...
import numpy as np import cv2 import math def draw_border(img, border, col=255): """Draw a border on an image given the border coordinates.""" l, r, t, b = border cv2.line(img, (l, t), (l, b), col, 2) cv2.line(img, (l, t), (r, t), col, 2) cv2.line(img, (l, b), (r, b), col, 2) cv2.line(img, (r, ...
""" Simple graph implementation """ from util import Stack, Queue # These may come in handy class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex): self.vertices[vertex]=set() def ad...
# a = "Hello" # b = "world" # c = a + " " + b + "!" # "Hello world!" # print(a) # print(b) # print(c) # # print(c[1:7]) # print the 2nd through 7th characters (indicies 1-5) "ello w" # print(c[:5]) # print from the beginning of c to the 5th character (indicies 0-4) "Hello" # print(c[-6:]) # print from the 6th to la...
#!/usr/bin/python def displayPathtoPrincess(n,grid): rownum = 0 colnum = 0 bot = tuple()# (0,0) #initialize princess = tuple()# (0,1) #initialize for gp in grid: for gpr in gp: if(gpr == 'm'): bot = (rownum, colnum%n) if(gpr == 'p'): p...
""" This file contains both the Question and Quiz classes. The Question class holds the data on a question that has been taken from the database or imported, and the Quiz class holds the Question objects and handles saving and loading to and from the database, as well as importing and exporting quizzes into a non-datab...
def cat_dog(str): cat_n = 0 dog_n = 0 i = 0 while i < len(str) - 2: if str[i:i+3] == "cat": cat_n += 1 elif str[i:i+3] == "dog": dog_n += 1 i += 1 return dog_n == cat_n
def xyz_there(str): i = 0 while i < len(str) - 2: if str[i:i+3] == "xyz": if i - 1 < 0: return True elif i - 1 >= 0 and str[i-1:i] != ".": return True i += 1 return False
import requests from requests.exceptions import HTTPError def example_of_exception(): for url in ['https://api.github.com', 'https://api.github.com/invalid']: try: response = requests.get(url) # If the response was successful, no Exception will be raised response.raise...
# The purpose of this module is to provide the human interface for the snake game. import pygame import config class Draw(object): def __init__(self, grid): self.screen_size = (config.window_width, config.window_height) self.screen = pygame.display.set_mode(self.screen_size, 0, 32) self.gr...
class Team: """ Tournament object :param name: the team name foundation: the foundation's year of the team """ def __init__(self, name, *args, **kwargs): self.team_name = name self.foundation = kwargs.get('foundation') def __str__(self): retu...
str = "10101010" ​ def to_decimal(num_string, base): digit_list = list(num_string) digit_list.reverse() value = 0 for i in range(len(digit_list)): print(f"+({int(digit_list[i])} * {base ** i})") value += int(digit_list[i]) * (base ** i) return value ​ to_decimal(str, 2)
import sys sys.stdin = open("input.txt", "r") class Node: def __init__(self, element, next_address=None, before_address=None): self.element = element self.next_address = next_address self.before_address = before_address def insertion_node(index, origin_list_head, add_list_head): nod...
import sys sys.stdin = open("input.txt", "r") def bi_search(num,p): l = 1 r = p c = 0 ans = 0 if num == p or num == 1: return ans for i in range(15): c = (l + r)//2 if num == c: return (i+1) if num > c: l = c else: ...
# -*- coding: utf8 -*- import sys import re reload(sys) sys.setdefaultencoding("utf8") def baifenhao(str): while 1: mm = re.search("[\d\.]+%", str) if mm: mm = mm.group() str = str.replace(mm, "") # print str else: break ...
#coding=utf-8 # python http客户端 基于python的库 urllib import urllib import urllib2 import cookielib import json #发送跨域POST请求 def send_post_request(url,data,csrftoken,headers) : data = urllib.urlencode(data) opener = urllib2.build_opener() opener.addheaders.append(('Cookie', 'csrftoken=%s'%(csrftoken))) ope...
def ask_user(question): while True: question=input('Как дела? ') if question=='Хорошо': print ('Рад за тебя') return ask_user('question') # я потратил на это пол-дня!!все пропало/// писать в конце ask_user(ask_1)- не правильно, ...
#! /usr/bin/env python3 ''' Niema Moshiri 2021 Convert time from `time` command to seconds ''' import argparse from sys import stdin # parse arguments def parseArgs(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i', '--inp...
# exercise_1 # number = input('enter your number') # if number.isdigit(): # print('your number Even') if (abs(float(number)) % 2) == 0 else print('your number is Odd') # elif number[0] == '-' and number[1:].isdigit(): # print('Your number Even') if (abs(float(number)) % 2) == 0 else print('your number is Odd')...
year_list = ['зима', 'весна', 'лето', 'осень'] year_dict = {1 : 'зима', 2 : 'весна', 3 : 'лето', 4 : 'осень'} month_numb = int(input('введите номер месяца ')) if 3 <= month_numb == 12: print(year_list[0]) print(year_dict.get(1)) if 3 < month_numb <= 5: print(year_list[1]) print(year_dict.get(2)...