content
stringlengths
7
1.05M
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2016 Dean Jackson <deanishe@deanishe.net> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2016-12-17 # """CLI program sub-commands."""
n = int(input()) for i in range(1, 10): if n % i != 0: continue for j in range(1, 10): if n % j != 0: continue for k in range(1, 10): if n % k != 0: continue for m in range(1, 10): if n % m != 0: continue for o in range(1, 10): if n % o != 0: continue for p in range(1, 10): if n % i != 0: continue if (i * j * k * m * o * p == n): print("{0}{1}{2}{3}{4}{5}".format(i, j, k, m, o, p), end=' ')
''' Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit. ''' temperatura = float(input('Digite a temperatura em graus Celsius: ')) fahrenheit = temperatura * 9 / 5 + 32 print('{:.1f} graus Celsius equivale a {:.1f} graus Fahrenheit!'.format(temperatura, fahrenheit))
def clean_path(path): """ Removes illegal characters from path (Windows only) """ return ''.join(i for i in path if i not in '<>:"/\|?*')
reserv_list = set() party_list = set() command = input() while command != 'PARTY': reserv_list.add(command) command = input() if command == 'PARTY': command = input() while command != 'END': party_list.add(command) command = input() diff = abs(len(reserv_list) - len(party_list)) print(diff) losers = (reserv_list-party_list) sort = sorted(losers) for el in sort: print(el)
# Author Atticus # -*- coding =utf-8 -*- # 中文翻译# # -----------# ### 操作符 ### # -----------# info = ( (("*", "An elegant way to set up your scene"), ((), ()), ("zh_CN", "一种优雅的设置场景的方式", (False, ())), ), (("*", "3D View > Object mode > Shortcut 'F' / Side Menu > Edit"), ((), ()), ("zh_CN", "3d视窗 > 物体模式 > 快捷键 F 或者 侧边栏菜单 > 编辑 ", (False, ())), ), ) ops = ( (("*", "Add View Cam"), ((), ()), ("zh_CN", "添加视角相机", (False, ())), ), (("*", "Pick Mat"), ((), ()), ("zh_CN", "材质拾取", (False, ())), ), (("*", "Smart Scene Manager"), ((), ()), ("zh_CN", "快速场景管理", (False, ())), ), (("Operator", "Enable Side Menu"), ((), ()), ("zh_CN", "启用侧边栏菜单", (False, ())), ), (("Operator", "D2F"), ((), ()), ("zh_CN", "对齐地面", (False, ())), ), (("Operator", "Track"), ((), ()), ("zh_CN", "朝向", (False, ())), ), (("Operator", "TransPSR"), ((), ()), ("zh_CN", "位置转移", (False, ())), ), (("Operator", "Translate"), ((), ()), ("zh_CN", "一键翻译", (False, ())), ), (("Operator", "export_obj"), ((), ()), ("zh_CN", "导出obj", (False, ())), ), (("Operator", "LightCheck"), ((), ()), ("zh_CN", "灯光检查", (False, ())), ), (("Operator", "PP"), ((), ()), ("zh_CN", "透明度", (False, ())), ), (("Operator", "Switch 2"), ((), ()), ("zh_CN", "跳转到", (False, ())), ), (("Operator", "Select a camera to enter"), ((), ()), ("zh_CN", "选择将要进入的相机", (False, ())), ), (("Operator", "Switch"), ((), ()), ("zh_CN", "跳转", (False, ())), ), (("Operator", "Flip"), ((), ()), ("zh_CN", "翻转", (False, ())), ), (("Operator", "Flip"), ((), ()), ("zh_CN", "翻转", (False, ())), ), (("Operator", "Add Cam"), ((), ()), ("zh_CN", "添加相机", (False, ())), ), (("Operator", "ViewCam"), ((), ()), ("zh_CN", "场景相机", (False, ())), ), (("Operator", "Cam2V"), ((), ()), ("zh_CN", "相机到视角", (False, ())), ), (("Operator", "Lock Cam to view"), ((), ()), ("zh_CN", "锁定相机到视角", (False, ())), ), ) # -------------# ### 属性 ### # -------------# prop = ( (("*", "Length(mm)"), ((), ()), ("zh_CN", "焦距(mm)", (False, ())), ), (("*", "Enable Cam Name"), ((), ()), ("zh_CN", "相机名字", (False, ())), ), (("*", "Ortho camera"), ((), ()), ("zh_CN", "正交相机", (False, ())), ), (("*", "Ortho_scale"), ((), ()), ("zh_CN", "正交比例", (False, ())), ), ) # ------------# ### 工具提示 ### # ------------# tooltips = ( (("*", "Ctrl: reset scene EV while not in camera view"), ((), ()), ("zh_CN", "Ctrl 点击:当不在相机视角时,重设场景曝光", (False, ())), ), (("*", "Check the tooltips that show on the left"), ((), ()), ("zh_CN", "使用时查看左边的提示", (False, ())), ), (("*", "move your mouse left or right to set cam passepartout"), ((), ()), ("zh_CN", "左右滑动以控制摄像机背景透明度", (False, ())), ), (("*", "add view cam\nctrl: add ortho cam\nshift: inherit the last camera's setting"), ((), ()), ("zh_CN", "添加视角相机\nctrl:添加正交相机\nshift:继承上一个相机的属性", (False, ())), ), (("*", "Flip SceneCam\nPress x,y,z or 1,2,3 to flip camera\nleft click: confirm"), ((), ()), ("zh_CN", "翻转场景相机\n按x,y,z或者1,2,3来翻转\n左键:确认翻转", (False, ())), ), (("*", "pick focus, left click to confirm\nconfirm with shift: generate empty target"), ((), ()), ("zh_CN", "拾取焦点,左键点击确认\n按住shift键来确认:在对焦点生成空物体并对焦", (False, ())), ), (("*", "enter select cam"), ((), ()), ("zh_CN", "跳转到所选相机", (False, ())), ), (("*", "enter select cam\nshift : popup camera list"), ((), ()), ("zh_CN", "跳转到所选相机\nshift:弹出摄像机列表", (False, ())), ), (("*", "select objects look at active object\nshift: add look-at constrains"), ((), ()), ("zh_CN", "选择物体朝向激活物体(可作用于灯光)\nshift:添加朝向约束", (False, ())), ), (("*", "Transform selected object(s) to active"), ((), ()), ("zh_CN", "转移所选物体位置到激活物体", (False, ())), ), (("*", " select objects look at active object\nshift: add look-at constrains"), ((), ()), ("zh_CN", "选择物体朝向激活物体(可作用于灯光)\nshift:添加朝向约束", (False, ())), ), (("*", "If not English,translate interface between English and your language"), ((), ()), ("zh_CN", "点一下就可以翻译了", (False, ())), ), (("*", "export select obj to blend file dir\nctrl: export as fbx"), ((), ()), ("zh_CN", "导出选中物体到blend文件目录\nctrl:导出为fbx(未完善)", (False, ())), ), (("*", "Check your lights !"), ((), ()), ("zh_CN", "检查你的灯光 !", (False, ())), ), (("*", "wheel up and down to change contrast looks"), ((), ()), ("zh_CN", "使用滚轮上下滚动切换对比度", (False, ())), ), (("*", "ctrl: change to false color"), ((), ()), ("zh_CN", "ctrl:切换到热度图(曝光)", (False, ())), ), (("*", "drop all 2 floor\nctrl : drop each 2 floor\nshift : drop 2 active"), ((), ()), ("zh_CN", "对齐所选到地面\nctrl:每一个都对齐到地面\nshift:对齐到激活物体顶部", (False, ())), ), ) # ------------# ### 报错提示 ### # ------------# report = ( (("*", "No scene camera"), ((), ()), ("zh_CN", "没有场景摄像机", (False, ())), ), (("*", "No camera select, now popup cam list."), ((), ()), ("zh_CN", "没有选中摄像机,请使用跳转菜单", (False, ())), ), (("*", "Confirm Flip"), ((), ()), ("zh_CN", "确认翻转", (False, ())), ), (("*", "Focus Distance"), ((), ()), ("zh_CN", "对焦距离", (False, ())), ), (("*", "Focus On Object"), ((), ()), ("zh_CN", "对焦物体", (False, ())), ), (("*", "Active space must be a View3d"), ((), ()), ("zh_CN", "需要在3d视窗下激活", (False, ())), ), (("*", "select 2 more objects"), ((), ()), ("zh_CN", "至少选择两个物体", (False, ())), ), (("*", "finish! export obj to"), ((), ()), ("zh_CN", "完成!已经导出obj至", (False, ())), ), (("*", "no select object"), ((), ()), ("zh_CN", "没有选中物体", (False, ())), ), (("*", "Contrast"), ((), ()), ("zh_CN", "对比度", (False, ())), ), (("*", "Very"), ((), ()), ("zh_CN", "非常", (False, ())), ), (("*", "Low"), ((), ()), ("zh_CN", "低", (False, ())), ), (("*", "Medium"), ((), ()), ("zh_CN", "中等", (False, ())), ), (("*", "High"), ((), ()), ("zh_CN", "高", (False, ())), ), ) translations_tuple = ops + prop + tooltips + report + info translations_dict = {} for msg in translations_tuple: key = msg[0] for lang, trans, (is_fuzzy, comments) in msg[2:]: if trans and not is_fuzzy: translations_dict.setdefault(lang, {})[key] = trans
class Player(object): TEAM_GREEN = 0 TEAM_RED = 1 TEAM_BLUE = 2 def __init__(self, id, front_grey, front_red, front_blue, deck_grey, deck_red, deck_blue): self.id = id self.front_grey = front_grey self.front_red = front_red self.front_blue = front_blue self.deck_grey = deck_grey self.deck_red = deck_red self.deck_blue = deck_blue
# Advent of code 2021 : Day 1 | Part 2 # Source : https://adventofcode.com/2020/day/1 infile = "aoc/2020/Day 1/input.txt" inputs = list(map(int, open(infile).read().splitlines())) print([i*j*_ for i in inputs for j in inputs for _ in inputs if i + j + _ == 2020][0]) # Answer : 165080960
#!/usr/bin/python class JustCounter: __secret_count = 0 def count(self): self.__secret_count += 1 print(self.__secret_count) counter = JustCounter() counter.count() counter.count() # can't access print(counter.__secret_count)
N = int(input()) A = [int(n) for n in input().split()] ans = [0] + [0]*N for i in range(N-1): ans[A[i]] += 1 for i in range(1, N+1): print(ans[i])
# -*- encoding: utf-8 -*- """ Created by Ênio Viana at 20/06/2021 at 15:07:27 Project: py_dss_interface [jun, 2021] """
def solve_part1(numbers, boards): marked = {}.fromkeys(list(boards.keys())) for key in marked: # idx // 5 idx % 5 # row column marked[key] = ([0,0,0,0,0],[0,0,0,0,0]) for number in numbers: for board_idx in boards: try: idx = boards[board_idx].index(number) # Update rows e.g: (marked[idx] [0] [1]) represents row 1 of board idx marked[board_idx] [0] [idx // 5] += 1 # Update columns e.g: (marked[idx] [1] [2]) represents column 2 of board idx marked[board_idx] [1] [idx % 5] += 1 # Full marked row or column (when there is a 5 in any row or column) if 5 in marked[board_idx] [0] or 5 in marked[board_idx] [1]: # This return means: sum each number in the board that is not in the numbers that have been drawn up until now res = sum([n for n in boards[board_idx] if n not in numbers[0: numbers.index(number) + 1]]) # Here i return the solution and some parameters that will be useful in part2 # Solution, current number return res * number, numbers, number, marked, boards, board_idx except: # Number not in board pass def solve_part2(numbers,number,marked,boards, board_idx): # Here we finish what is left of the last iteration from solve_part1() completed_boards_list = [0] * len(boards) completed_boards_list [board_idx] = 1 completed_boards = 1 for board_idx in range(board_idx + 1, len(boards)): try: idx = boards[board_idx].index(number) # Update rows e.g: (marked[idx] [0] [1]) represents row 1 of board idx marked[board_idx] [0] [idx // 5] += 1 # Update columns e.g: (marked[idx] [1] [2]) represents column 2 of board idx marked[board_idx] [1] [idx % 5] += 1 if (5 in marked[board_idx] [0] or 5 in marked[board_idx] [1]) and completed_boards_list[board_idx] == 0: completed_boards_list [board_idx] = 1 completed_boards += 1 if completed_boards == len(boards) - 1: last = completed_boards_list.index(0) elif completed_boards == len(boards): return sum([n for n in boards[last] if n not in numbers[0: numbers.index(number) + 1]]) * number except: # Number not in board pass for number in numbers[numbers.index(number) + 1:]: for board_idx in boards: try: idx = boards[board_idx].index(number) # Update rows e.g: (marked[idx] [0] [1]) represents row 1 of board idx marked[board_idx] [0] [idx // 5] += 1 # Update columns e.g: (marked[idx] [1] [2]) represents column 2 of board idx marked[board_idx] [1] [idx % 5] += 1 if (5 in marked[board_idx] [0] or 5 in marked[board_idx] [1]) and completed_boards_list[board_idx] == 0: completed_boards_list [board_idx] = 1 completed_boards += 1 # If there's only 1 left to win if completed_boards == len(boards) - 1: last = completed_boards_list.index(0) elif completed_boards == len(boards): return sum([n for n in boards[last] if n not in numbers[0: numbers.index(number) + 1]]) * number except: # Number not in board pass """ Coder's note: Sometimes is harder to prepare the input than solving the problem... """ # Get input for part 1 input_file = open('Day4_input.txt','r') # Numbers for bingo numbers = input_file.readline().split(',') # Last number has a "\n" character attached to it, we eliminate it numbers[-1] = numbers[-1][:-1] numbers = [int(num) for num in numbers] # Skip next "\n" in file input_file.readline() boards = {} board_idx = 0 aux = input_file.read().split("\n") # Split leaves '' characters, we must filter them aux = [elem for elem in aux if elem != ''] for i in range(len(aux)//5): boards[board_idx] = aux[5*i] + " " + aux[5*i+1] + " " + aux[5*i + 2] + " " + aux[5*i + 3] + " " + aux[5*i + 4] boards[board_idx] = boards[board_idx].split() boards[board_idx] = [int(num) for num in boards[board_idx]] board_idx +=1 del aux, board_idx # We return this many variable to take advantage of what we have already calculated part1_sol, numbers, number, marked, boards, board_idx = solve_part1(numbers, boards) print("Part 1 solution:",part1_sol) part2_sol = solve_part2(numbers,number,marked,boards, board_idx) print("Part 2 solution:",part2_sol)
metros = int(input('Digite o valor em metros: ')) conv_cm = metros * 100 conv_milimetros = metros * 1000 conv_km = metros * 1000 conv_deca = metros / 10 conv_deci = metros * 10 conv_hect = metros / 100 print(f'Segue abaixo a conversão de metros para os valores solicitados (Km, Hect, Decametros, Decimetros, Centimetros e Milimetros)') print(f'De metros para Hect: {conv_hect}') print(f'De metros para Decametros: {conv_deca}') print(f'De metros para Decimetros: {conv_deci}') print(f'De metros para Centímetros: {conv_cm}') print(f'De metros para Km: {conv_km} ') print(f'De metros para Milimetros: {conv_milimetros}')
def count(start, end=None, step=None): if step == 0: raise IndexError if hasattr(step, "__iter__"): raise TypeError if (hasattr(start, "__iter__") or hasattr(end, "__iter__")): return __iter_count(start, end, step) else: return __num_count(start, end, step) def __iter_count(start,end=None, step=None): items = None if hasattr(start, "__iter__"): if step is not None: raise IndexError items = start count = 0 step = end if hasattr(end, "__iter__"): count = start items = end if step is None: step = 1 for item in items: yield count, item count += step def __num_count(start, end=None, step=None): if end is None: end = start start = 0 count = start if step is None: step = 1 if start > end: if step > 0: step *= -1 while count >= end: yield count count += step else: if step < 0: step *= -1 while count <= end: yield count count += step
#!python2.7 # -*- coding: utf-8 -*- """ Created by kun on 2016/10/10. """ __author__ = 'kun'
def prime(n): i=2 while i<=n//2: if n%i==0: return 0 i=i+1 return 1 n=2 sum=0 while n<=2000000: if prime(n): sum=sum+n n=n+1
# Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. # For example, # Given n = 3, # You should return the following matrix: # [ # [ 1, 2, 3 ], # [ 8, 9, 4 ], # [ 7, 6, 5 ] # ] class Solution: # @param {integer} n # @return {integer[][]} def generateMatrix(self, n): matrix = [[0 for x in range(n)] for x in range(n)] boundaries = [n-1, n-1, 0, 1] #r, d, l, u bi = 0 directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] #r, d, l, u di = 0 e = [0, 0] ei = 1 for i in xrange(n*n): matrix[e[0]][e[1]] = i+1 if e[ei] == boundaries[bi]: boundaries[bi] -= directions[di][ei] bi = (bi+1)%4 di = (di+1)%4 ei = (ei+1)%2 e[0] += directions[di][0] e[1] += directions[di][1] return matrix
# # This file contains the Python code from Program 4.20 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm04_20.txt # class LinkedList(object): class Element(object): def insertAfter(self, item): self._next = LinkedList.Element( self._list, item, self._next) if self._list._tail is self: self._list._tail = self._next def insertBefore(self, item): tmp = LinkedList.Element(self._list, item, self) if self is self._list._head: self._list._head = tmp else: prevPtr = self._list._head while prevPtr is not None \ and prevPtr._next is not self: prevPtr = prevPtr._next prevPtr._next = tmp # ...
#file = open("data.csv", "r") #for line in file: # print(line) with open("output.csv", "a") as fileout: fileout.write("Hello World") fileout.close()
# -*- coding: utf-8 -*- __title__ = 'atomos' __version_info__ = ('0', '3', '1') __version__ = '.'.join(__version_info__) __author__ = 'Max Countryman' __license__ = 'BSD' __copyright__ = 'Copyright 2014 Max Countryman'
# Copyright (C) 2019 Intel Corporation # # SPDX-License-Identifier: MIT class Converter: def __init__(self, cmdline_args=None): pass def __call__(self, extractor, save_dir): raise NotImplementedError() def _parse_cmdline(self, cmdline): parser = self.build_cmdline_parser() if len(cmdline) != 0 and cmdline[0] == '--': cmdline = cmdline[1:] args = parser.parse_args(cmdline) return vars(args)
class Credential : """ Class that generates new instances of credentials """ credential_list = [] def __init__ (self,account_name,email,password): """ __init__ method that helps us define properties for our objects. """ """ Args: accountname : New name of the account. email : New contact email address. password : New password of the user. """ self.account_name = account_name self.email = email self.password = password def delete_user(self): """ delete_user method deletes user objects from our user_list """ Credential.credential_list.remove(self) @classmethod def find_by_accountname(cls,accountname): """ Method that takes in an account name and returns an account that matches that account name Args: account name: Account name to search for Returns : Account of user that matches the account name. """ for user in cls.credential_list: if user.accountname == accountname: return user @classmethod def user_exist(cls,email): """ Method that checks if a user exists Args: email: Email to search if it exists Returns : Boolean: True or false depending if the contact exists """ for user in cls.credential_list: if user.email == email: return True return False @classmethod def display_users(cls): """ method that returns the user list """ return cls.credential_list
primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 ] # len(primes) = 54 # symbol_size = 3 # for prime in primes: # column_size = prime * symbol_size # if 1048576 % (column_size) == 1 or \ # 1048576 % (column_size) == (column_size - 1): # print('1048576 % column_size(={}, 3 * prime={}) = {}'. # format(column_size, prime, 1048576 % column_size)) divisions = (17, 32, 41) symbol_size = 3 target_size = 1048576 for d in divisions: column_size = symbol_size * d remainder = target_size % column_size if remainder == 0: padding_size = 0 else: padding_size = column_size - remainder rate = (1048576 + padding_size) / d print('(1048576 + {:3d}) / {} = {}, column_size = {:3d}, division = {}'. format(padding_size, d, rate, column_size, d)) # (1048576 + 35) / 17 = 61683.0, column_size = 51, division = 17 # (1048576 + 32) / 32 = 32769.0, column_size = 96, division = 32 # (1048576 + 122) / 41 = 25578.0, column_size = 123, division = 41 # 1048576 % prime=17 = 16 # 1048576 % prime=32 = 0 # 1048576 % prime=41 = 1 # (1048576 + 1) / 17 = 61681.0 # (1048576 + 0) / 16 = 65536.0 # (1048576 + 40) / 41 = 25576.0 # 1048576 % column_size(= 15, 3 * prime= 5) = 1 # 1048576 % column_size(= 33, 3 * prime=11) = 1 # 1048576 % column_size(= 93, 3 * prime=31) = 1 # 1048576 % column_size(=123, 3 * prime=41) = 1
# -*- coding: utf-8 -*- RADIX = 3 BYTE_RADIX = 256 MAX_TRIT_VALUE = (RADIX - 1) // 2 MIN_TRIT_VALUE = -MAX_TRIT_VALUE NUMBER_OF_TRITS_IN_A_BYTE = 5 NUMBER_OF_TRITS_IN_A_TRYTE = 3 HASH_LENGTH = 243 BYTE_TO_TRITS_MAPPINGS = [[]] * HASH_LENGTH TRYTE_TO_TRITS_MAPPINGS = [[]] * 27 HIGH_INTEGER_BITS = 0xFFFFFFFF HIGH_LONG_BITS = 0xFFFFFFFFFFFFFFFF TRYTE_ALPHABET = '9ABCDEFGHIJKLMNOPQRSTUVWXYZ' MIN_TRYTE_VALUE = -13 MAX_TRYTE_VALUE = 13 def increment(trits, length): for i in range(length): trits[i] += 1 if trits[i] > MAX_TRIT_VALUE: trits[i] = MIN_TRIT_VALUE else: break def init_converter(): global BYTE_TO_TRITS_MAPPINGS, TRYTE_TO_TRITS_MAPPINGS trits = [0] * NUMBER_OF_TRITS_IN_A_BYTE for i in range(HASH_LENGTH): BYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_BYTE] increment(trits, NUMBER_OF_TRITS_IN_A_BYTE) for i in range(27): TRYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_TRYTE] increment(trits, NUMBER_OF_TRITS_IN_A_TRYTE) def from_trits_to_binary(trits, offset=0, size=HASH_LENGTH): b = bytearray(b' ' * int((size + NUMBER_OF_TRITS_IN_A_BYTE - 1) / NUMBER_OF_TRITS_IN_A_BYTE)) for i in range(len(b)): value = 0 for j in range(size - i * NUMBER_OF_TRITS_IN_A_BYTE - 1 if (size - i * NUMBER_OF_TRITS_IN_A_BYTE) < NUMBER_OF_TRITS_IN_A_BYTE else 4, -1, -1): value = value * RADIX + trits[offset + i * NUMBER_OF_TRITS_IN_A_BYTE + j] b[i] = value % 256 return bytes(b) def from_binary_to_trits(bs, length): offset = 0 trits = [0] * length for i in range(min(len(bs), length)): # We must convert the binary data # because java using different range with Python index = bs[i] if bs[i] < 127 else bs[i] - 256 + HASH_LENGTH copy_len = length - offset if length - offset < NUMBER_OF_TRITS_IN_A_BYTE else NUMBER_OF_TRITS_IN_A_BYTE trits[offset: offset + copy_len] = BYTE_TO_TRITS_MAPPINGS[index][:copy_len] offset += NUMBER_OF_TRITS_IN_A_BYTE return trits init_converter()
i=int(input("Değer giriniz:")) #Sayi kaça kadar sıralanacak. x=0 y=int(input("Atlanacak sayi")) #Hangi sayi atlansın. for x in range(i): #Döngü x i'ye gelene kadar dönsün. x+=1 # X her defasında 1 arttırılsın. if x==y: #Eğer x y'ye denk gelirse; continue #Bu sayıyı atla ve döngüye devam et. print(x) # x i'ye eşit olduğu zaman x in değerini bastır.
""" `adafruit_hid` ==================================================== This driver simulates USB HID devices. Currently keyboard and mouse are implemented. * Author(s): Scott Shawcroft, Dan Halbert """
class AttributeDict(dict): __slots__ = () __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ def __init__(self, dictionary: dict = {}): super().__init__() self.update(dictionary) _defaults = AttributeDict({ "master": "master", "develop": "develop", "features": "feature", "fixes": "bugfix", "releases": "release", "hotfixes": "hotfix", "others": ["spike"], }) class Gitflow(AttributeDict): """ Contains all settings related to branches from YAML file. It extends :class:`AttributeDict <AttributeDict>`, so settings may be accessed like properties: ``gitflow.features`` It will contain custom settings if you add them in YAML file as a child of ``branches`` node. """ def __init__(self, settings: dict): defaults = _defaults.copy() if settings and settings.get('branches', None): defaults.update(settings['branches']) super().__init__(dictionary=defaults) class RulesContainer: def __init__(self, rules: dict): if not rules or not rules.get('rules', None): raise KeyError('Yaml file does not contain rules') self._rules = rules['rules'] @property def rules(self): return self._rules.keys() def args_for(self, rule) -> dict: return self._rules.get(rule, {}) def consume(self, rule: str): del self._rules[rule]
#encoding:utf-8 subreddit = 'HQDesi' t_channel = '@r_HqDesi' def send_post(submission, r2t): return r2t.send_simple(submission)
class OrderElement: def __init__(self, product, quantity): self.product = product self.quantity = quantity def calculate_price(self): return self.product.unit_price * self.quantity def __str__(self): return f"{self.product} x {self.quantity}"
#!/usr/bin/env python3 class Parser: def __init__(self): self.token = None self.remained_token = None '''from regex string to NFA class''' def parse(self, regex_str): if len(regex_str) == 0: print("The compiled content is empty. Stop parsing.") return None regex_str_list = [i for i in regex_str] + [None] self.token = regex_str_list[0] self.remained_token = regex_str_list[1:] result = self.re() return result def advance(self): self.token = self.remained_token[0] self.remained_token = self.remained_token[1:] '''<RE> ::= (<simple-RE> "|" RE>) | <simple-RE>''' def re(self): result = self.simple_re() while self.token == "|": result_head = self.token self.advance() rhs = self.simple_re() result = [result_head, result, rhs] rhs = result return result '''<simple-RE> ::= <basic-RE>+''' def simple_re(self): result = self.basic_re() # self.token != ")" and self.token != "|" is used to fix the bug while self.token != None and self.token != ")" and self.token != "|": result_head = "CONC" # concat rhs = self.basic_re() result = [result_head, result, rhs] rhs = result return result '''<basic-RE> ::= <elementary-RE> "*" | <elementary-RE> "?" | elementary-RE> "+" | <elementary-RE>''' def basic_re(self): result = self.elementary_re() if self.token == "*": self.advance() result = ["STAR", result] elif self.token == "?": self.advance() result = ["QUESTION", result] elif self.token == "+": self.advance() result = ["PLUS", result] return result '''<elementary-RE> ::= <group> | <any> | <char> | <char-set>''' '''<group> ::= "(" <RE> ")"''' def elementary_re(self): # <group> ::= "(" <RE> ")" if self.token == "(": self.advance() result = self.re() if self.token != ")": raise("Except \")\", found %s", self.token) self.advance() result = [result] elif self.token == ".": self.advance() result = "ANY" elif self.token == "[": result = self.char_set() else: result = self.char() return result '''<char> ::= any non metacharacter | "\" metacharacter''' '''metacharacter = set{ \ * + . \ [ ] ( ) | }''' def char(self): meta_char_list = ["*", "+", ".", "\\", "[", "]", "(", ")", "|", "?"] # \ + metacharacter if self.token == "\\": self.advance() if self.token in meta_char_list: result = self.token self.advance() return result else: # exception description exception_desc = "Expect" + ", ".join(meta_char_list) + " , found \"%s\"" % self.token raise(exception_desc) else: if self.token in meta_char_list: print("Caution: \"%s\" is not recommended to be singly used." % self.token) result = self.token self.advance() return result '''<char-set> ::= <positive-set> | <negative-set>''' def char_set(self): # token [ is checked in elementary_re. so advance() self.advance() '''<negative-set> ::= "[^" <set-items> "]"''' if self.token == "^": result_rhs = self.set_items() result = ["NOT", result_rhs] else: result = self.set_items() return result def set_items(self): result = ["SET"] if self.token != "]": result.append(self.set_item()) return result '''<set-item> ::= <range> | <char> <range> ::= <char> "-" <char>''' def set_item(self): result = self.char() # range = <char> "-" <char> if self.token == "-": result_lhs = result self.advance() result_rhs = self.char() result = ["RANGE", result_lhs, result_rhs] return result regex_parser = Parser() print(regex_parser.parse("(abc)")) print(regex_parser.parse("(a|bc)")) print(regex_parser.parse("a*bc")) print(regex_parser.parse("(a*|b)c")) print(regex_parser.parse("a+bc")) print(regex_parser.parse("(a+|b)c")) print(regex_parser.parse("a*+bc")) print(regex_parser.parse("a*+bc"))
def isgreaterthan20(number1,number2): print(number1) print(number2) num=20 num1=10 isgreaterthan20(num,num1)
class Solution: def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ memo={} for i,v in enumerate(nums): if memo.get(v) is None: memo[v]=1 else: memo[v]+=1 result=[] for i in memo: if memo[i]==2: result.append(i) return result if __name__=='__main__': solution = Solution() t1=[4,3,2,7,8,2,3,1] print(solution.findDuplicates(t1))
# -*- coding:utf-8 -*- """ Description: Transaction Type in AntShares Usage: from AntShares.Core.TransactionType import TransactionType """ class TransactionType(object): MinerTransaction = 0x00 IssueTransaction = 0x01 ClaimTransaction = 0x02 EnrollmentTransaction = 0x20 VotingTransaction = 0x24 RegisterTransaction = 0x40 ContractTransaction = 0x80 AgencyTransaction = 0xb0
class InvalidIdError(RuntimeError): def __init__(self, id_value): super(InvalidIdError, self).__init__() self.id = id_value
sku = [{"name": "id", "type": "varchar(256)"}, {"name": "object", "type": "varchar(256)"}, {"name": "active", "type": "boolean"}, {"name": "attributes", "type": "varchar(max)"}, {"name": "created", "type": "timestamp"}, {"name": "currency", "type": "varchar(256)"}, {"name": "image", "type": "varchar(256)"}, {"name": "inventory", "type": "varchar(512)"}, {"name": "livemode", "type": "boolean"}, {"name": "metadata", "type": "varchar(max)"}, {"name": "package_dimensions", "type": "varchar(512)"}, {"name": "price", "type": "integer"}, {"name": "product", "type": "varchar(256)"}, {"name": "updated", "type": "timestamp"}]
def import_code_query(path, project_name=None, language=None): if not path: raise Exception('An importCode query requires a project path') if project_name and language: fmt_str = u"""importCode(inputPath=\"%s\", projectName=\"%s\", language=\"%s\")""" return fmt_str % (path, project_name, language) if project_name and (language is None): fmt_str = u"""importCode(inputPath=\"%s\", projectName=\"%s\")""" return fmt_str % (path, project_name) return u"importCode(\"%s\")" % (path) def workspace_query(): return "workspace"
#no refactoring class hash_test: participant = ["leo","kiki","eden"] completion = ["leo","kiki"] p = 31 m = 0xfffff x = 0 hash_table = list([0 for i in range(m)]) unfinished = list() # polynomial rolling hash function. for i in participant: print(i) mod_value=0 for j in i: mod_value = mod_value + ord(j)*pow(p,x) x+=1 hash_table[mod_value % m] = 1 #hash for completion for k in completion: print(k) mod_value=0 for j in i: mod_value = mod_value + ord(j)*pow(p,x) x+=1 if hash_table[mod_value % m] != 1: unfinished.append(i) print("unfinished="+i)
# -*- coding: utf-8 - # # This file is part of tproxy released under the MIT license. # See the NOTICE for more information. version_info = (0, 5, 4) __version__ = ".".join(map(str, version_info))
"""Errors raised by mailmerge.""" class MailmergeError(Exception): """Top level exception raised by mailmerge functions."""
def eh_primo(x): if (x==3) or (x==2): return True if (x<2) or (x%2==0): return False for i in range(3, int(x**0.5)+1, 2): if x%i==0: return False return True def sup_primo(num): while num >= 10: sup = num % 10 num = int(num / 10) if not eh_primo(sup): return 0 if((num == 2) or (num == 3) or (num == 5) or (num == 7)): return True else: return False while(True): try: # (Entrada) n = input() if len(n)==0: break else: n = int(n) if not eh_primo(n): print("Nada") else: if sup_primo(n): print("Super") else: print("Primo") except EOFError: break
""" 深圳航空订单采集 createby swm 2018/06/11 """
# -*- coding: iso-8859-1 -*- """ MoinMoin - Widget base class @copyright: 2002 Juergen Hermann <jh@web.de> @license: GNU GPL, see COPYING for details. """ class Widget: def __init__(self, request, **kw): self.request = request def render(self): raise NotImplementedError
#listing #representacion de grafos a,b,c,d,e,f,g,h = range(8) N = [{b:2,c:1,d:3,e:9,f:4}, #a {c:4,e:3}, #b {d:8}, #c {e:7}, #d {f:5}, #e {c:2,g:2,h:2}, #f {f:1,h:6}, #g {f:9,g:8}] #h print(b in N[a]) #neighborhood membership/es vecino b de a?? print(len(N[f])) #degree of f print(N[a][b]) #edge weight for (a,b) input() #matrix for graphs #matriz de adyacencia # a b c d e f g h M = [[0,1,1,1,1,1,0,0], #a [0,0,1,0,1,0,0,0], #b [0,0,0,1,0,0,0,0], #c [0,0,0,0,1,0,0,0], #d [0,0,0,0,0,1,0,0], #e [0,0,0,1,0,0,1,1], #f [0,0,0,0,0,1,0,1], #g [0,0,0,0,0,1,1,0]] #h print(sum(M[a])) input() #representacionde nodos con infinito a traves de matrices: #a weight matrix with infinite weighr for missing edges print("------------------------------") a,b,c,d,e,f,g,h = range(8) _ = float('inf') # a b c d e f g h G = [[0,2,1,3,9,4,_,_], #a [_,0,4,_,3,_,_,_], #b [_,_,0,8,_,_,_,_], #c [_,_,_,0,7,_,_,_], #d [_,_,_,_,0,5,_,_], #e [_,_,2,_,_,0,2,2], #f [_,_,_,_,_,1,0,6], #g [_,_,_,_,_,9,8,0]] #h print(G[a][b] < _) print(G[c][e] < _) print(sum(1 for g in G[a] if g < _)-1) #degree #note: 1 is substracted from G[a] because we dont want the o from the diagonal input()
class Config(object): _instance = None def __new__(self): if not self._instance: self._instance = super(Config, self).__new__(self) return self._instance def setConfig(self, config): self.config = config def get(self, key): return self.config[key] def getAll(self): return self.config
#nanan=input("nafn:") #arg=float(input("hæð 1 metrum:")) #print(arg) #if arg == 2: # print("þú ert 2 metra há 200cm") #elif arg >= 2: # print("þú ert",arg-2,"metrum hæri og",(arg*100)-200,"cm ifir") #elif arg <= 2: # print("þú ert",arg-2,"metrum lægri og",(arg*100)-200,"cm undir") ################################################################################################################## nafn1 = input("gefðu nafn 1:") aldur1= int(input("og aldur:")) nanf2 = input("gefðu nafn 2:") aldur2= int(input("og aldur:")) if aldur1 == aldur2: print(nafn1,"og",nanf2," eru jafn gamlir") elif aldur1 >= aldur2: print(nafn1,"er eldri en",nanf2) elif aldur1 <= aldur2: print(nanf2,"er eldri en",nafn1) #else: # print (nanf,"og",nanu," er ekki sama nafnið") ################################################################################################################# aldur= int(input("fæðingaræár:")) if aldur % 2 == 0: print("slet tala og þú ert",2022-aldur) else: print("ódatala og þú ert",2022-aldur) ################################################################################################################# #100cm í 1metra nanan=input("nafn:") arg=float(input("hæð 1 metrum:")) print(arg) if arg == 2: print(nanan," er 2 metra há 200cm") elif arg >= 2: print(nanan," er",arg-2,"metrum hæri og",(arg*100)-200,"cm ifir") elif arg <= 2: print(nanan,"er",arg-2,"metrum lægri og",(arg*100)-200,"cm undir") ################################################################################################################ print("gefðu 4 tölur") a=int(input()) b=int(input()) c=int(input()) d=int(input()) ax=(a+b+c)-d print(ax) print("(",a,"+",b,"+",c,")","-",d,"=",ax)
# Faca um programa que tenha uma funcao # chamada area(), # que receba as dimensoes de um terreno # retangular(largura e comprimento) e mostre a # area do terreno def area(larg, comp): a = larg * comp print(f'A area de um terreno {larg} x {comp} eh de {a}m2.') print(' Controle de Terrenos') print('-' * 20) l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) area(l, c)
class Solution: def findMinFibonacciNumbers(self, k: int) -> int: fib = [] fib.extend([1, 1]) j = 1 i = 2 # calculate fibonacci number greater than k while j < k: x = fib[i - 1] + fib[i - 2] fib.append(x) i += 1 j = x count = 0 for i in range(len(fib) - 1, -1, -1): print(fib[i], k) if fib[i] == k: count += 1 break elif fib[i] < k: k = k - fib[i] count += 1 return count
input() groups = sorted([ int(i) for i in input().split() ], reverse=True) cars = 0 i = 0 j = len(groups) - 1 while i <= j: g = groups[i] if g == 4: i += 1 cars += 1 continue cur_car = g while groups[j] <= 4 - cur_car and i < j: cur_car += groups[j] j -= 1 i += 1 cars += 1 print(cars)
def auto_newline(text: str, max_line_length: int): def wrap_line_helper(line: str): words = line.split(" ") wrapped_line = [] current_line = "" for word in words: current_line += word if len(current_line) > max_line_length: current_line = " ".join(current_line.split(" ")[:-1]) wrapped_line.append(current_line) current_line = word current_line += " " wrapped_line.append(current_line[:-1]) return "\n".join(wrapped_line) lines = text.split("\n") wrapped_lines = [] for line1 in lines: wrapped_lines.append(wrap_line_helper(line1)) return "\n".join(wrapped_lines)
def explore(lines): y = 0 x = lines[0].index('|') dx = 0 dy = 1 answer = '' steps = 0 while True: x += dx y += dy if lines[y][x] == '+': if x < (len(lines[y]) - 1) and lines[y][x+1].strip() and dx != -1: dx = 1 dy = 0 elif y < (len(lines) - 1) and x < len(lines[y+1]) and lines[y+1][x].strip() and dy != -1: dx = 0 dy = 1 elif y > 0 and x < len(lines[y-1]) and lines[y-1][x].strip() and dy != 1: dx = 0 dy = -1 elif x > 0 and lines[y][x-1].strip() and dx != 1: dx = -1 dy = 0 elif lines[y][x] == ' ': break elif lines[y][x] not in ('-', '|'): answer += lines[y][x] steps += 1 return answer, steps + 1 def test_explore(): assert ('ABCDEF', 38) == explore(open("input/dec19_test").readlines()) if __name__ == "__main__": print(explore(open("input/dec19").readlines()))
# Search in Rotated Sorted Array: https://leetcode.com/problems/search-in-rotated-sorted-array/ # There is an integer array nums sorted in ascending order (with distinct values). # Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. # Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. # You must write an algorithm with O(log n) runtime complexity. # This is a basic binary search the only difference is that we need to check if the values are sorted from high to mid so that we know wether to follow the traditional patern # or to traverse the other way as the shift occurs on the other side class Solution: def search(self, nums, target: int) -> int: lo, hi = 0, len(nums) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if nums[mid] == target: return mid else: # Is it properly sorted? if nums[mid] >= nums[lo]: # Now since we know where it is supposed to be we need to check if it can be here if target >= nums[lo] and target <= nums[mid]: hi = mid - 1 else: lo = mid + 1 else: if target <= nums[hi] and target > nums[mid]: lo = mid + 1 else: hi = mid - 1 return -1 # So this is pretty standard the only weird hiccup is finding whether or not you have a sorted segment or not # this runs in o(logn) and O(1) # Score Card # Did I need hints? N # Did you finish within 30 min? 10 # Was the solution optimal? This is optimal # Were there any bugs? No # 5 5 5 5 = 5
class Solution: def rotate(self, nums: List[int], k: int) -> None: k %= len(nums) if k > 0: for i, v in enumerate(nums[-k:] + nums[0:-k]): nums[i] = v
'''Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.''' #minha resolução #https://escolaeducacao.com.br/condicao-da-existencia-de-um-triangulo/ a = float(input('Digite o primeiro comprimento: ')) b = float(input('Digite o segundo comprimento: ')) c = float(input('Digite o terceiro comprimento: ')) if b + c > a and a + c > b and a + b > c: print('É possível formar um triangulo com essas medidas.') else: print('Não é possível formar um triangulo com essas medidas.') print(''' * * * FIM''') #resolução do curso print('-='*20) print('Analisador de triângulos') print('-='*20) r1 = float(input('Primeiro segmento: ')) r2 = float(input('Segundo segmento: ')) r3 = float(input('Terceiro segmento: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Os segmentos acima PODEM FORMAR triângulo!') else: print('Os segmentos acuma NÃO PODEM FORMAR triângulo!')
# sort given sequence given that the numbers go from 1 to n def cyclic_sort(seq): for i in range(len(seq)): num = seq[i] if num != seq[num-1]: # swap seq[num-1], seq[i] = seq[i], seq[num-1] def main(): seq = [5,4,1,2,3] cyclic_sort(seq) print(f'seq = {seq}') if __name__ == "__main__": main()
class Student: # Using a global base for all the available courses numReg = [] # We will initalise the student class def __init__(self, number, name, family, courses=None): if courses is None: courses = [] self.number = number self.numReg.append(self) self.name = name self.family = family self.courses = courses # This is used to display the student details def displayStudent(self): print('You are logged in as ' + self.name + ' ' + self.family) # This is used to display the number of courses a student takes up during his term/semester def displayStudentCourses(self, numStudent): if self.number == numStudent: if self.courses: print(self.courses) else: print('You have not selected any courses. Please choose a course.') # Using this, the selected course will be added to the student's portfolio/data def studentCourseAdding(self, wantedCourse, numStudent): if self.number == numStudent: self.courses.append(wantedCourse) print('You Added ' + wantedCourse + ' to your schedule, successfully!')
class Task: """ Abstract class defining a task. A task is an atomic action (i.e: switch on/off light, play music, etc ...) It can take arguments which will be defined by the user (i.e: turn off light between 9 am and 1 pm. 9 and 1 can be defined as parameters given by user). """ def __init__(self, name: str): assert len(name) > 0, "A task name can't be empty" self.name = name self.arguments = {} def register_argument(self, name: str, arg_type: dict): """ Registers an argument with the specified name and the specified type. This argument will then be filled up by user. Example: import arg_type register_argument("age", arg_type.integer(min=0)) :param name: the argument name (str) :param arg_type: the argument type (dict: {type: str}), please use arg_type package to specify this argument """ assert "type" in arg_type, "Argument 'arg_type' must contain key 'type'" if name in self.arguments: print("[WARNING] Task {} registers two arguments with the same name ({}). " "Second registration will override first one.".format(self.name, name)) self.arguments[name] = arg_type def on_validation(self, arg_values: dict): """ Called when user entered valid arguments. You can use this method to perform additional checks on values (i.e if an argument correspond to a website url, ping this website to see if it exists). :param arg_values: a dict mapping arguments name to their value :return: a tuple containing two values. The first one indicates if the values for arguments are still valid, the second one is the error message which will be displayed in case the first value is False """ return True, None def execute_task(self, arg_values: dict): """ Executes the action corresponding to the task. :param arg_values: a dict linking each argument name to it's value """ print("The task {} does nothing when ran.".format(self.name))
############################################################################### ############################################################################### #Copyright (c) 2016, Andy Schroder #See the file README.md for licensing information. ############################################################################### ############################################################################### ################################################################################################# #Input parameters ################################################################################################# ########################### #cycle input parameters ########################### CycleInputParameters['MaximumTemperature']=650.0+273.0 CycleInputParameters['StartingProperties']['Temperature']=273.0+47 CycleInputParameters['FluidType']='Carbon Dioxide' CycleInputParameters['PowerOutput']=1.0*10**6 #1MW ########################### #common recuperator parameters DeltaPPerDeltaT=0 ########################### #piston related design assumptions and required pressure ratio ########################### CycleInputParameters['Piston']['MassFraction']=1.0 CycleInputParameters['Piston']['IsentropicEfficiency']=1.0 ########################### #heater related design assumptions ########################### CycleInputParameters['SecondPlusThirdHeating']['MaximumTemperature']=CycleInputParameters['MaximumTemperature'] CycleInputParameters['SecondPlusThirdHeating']['MassFraction']=1 CycleInputParameters['SecondPlusThirdHeating']['DeltaPPerDeltaT']=DeltaPPerDeltaT ########################### #cooler related design assumptions ########################### CycleInputParameters['TotalFractionCooler']['MinimumTemperature']=CycleInputParameters['StartingProperties']['Temperature'] CycleInputParameters['TotalFractionCooler']['MassFraction']=1 CycleInputParameters['TotalFractionCooler']['DeltaPPerDeltaT']=DeltaPPerDeltaT ########################### #recuperator related design assumptions ########################### CycleInputParameters['HTRecuperator']['NumberofTemperatures']=200 #keep in mind that the resolution of the data being interpolated is the real upper limit on the usefulness of this value CycleInputParameters['HTRecuperator']['LowPressure']['MassFraction']=1 CycleInputParameters['HTRecuperator']['HighPressure']['MassFraction']=1 CycleInputParameters['HTRecuperator']['HighPressure']['ConstantVolume']=True CycleInputParameters['HTRecuperator']['DeltaPPerDeltaT']=DeltaPPerDeltaT #maybe this should be different for high and low pressure sides? CycleInputParameters['HTRecuperator']['MinimumDeltaT']=0 ################################################################################################# #end Input parameters #################################################################################################
#D def fibonacci(N :int) -> int: if N == 1: return 1 elif N == 2: return 1 else: return fibonacci(N-2)+fibonacci(N-1) def main(): # input N = int(input()) # compute # output print(fibonacci(N)) if __name__ == '__main__': main()
class Solution: def countVowelStrings(self, n: int) -> int: d = ['a', 'e', 'i', 'o', 'u'] path = [] count = 0 def backtracking(n, start): nonlocal count if n == 0: count += 1 return for i in range(start, 5): path.append(d[i]) backtracking(n-1, i) path.pop() return backtracking(n, 0) return count
class _EventTarget: '''https://developer.mozilla.org/en-US/docs/Web/API/EventTarget''' NotImplemented class _Node(_EventTarget): '''https://developer.mozilla.org/en-US/docs/Web/API/Node''' NotImplemented class _Element(_Node): '''ref of https://developer.mozilla.org/en-US/docs/Web/API/Element''' NotImplemented
# This is function for sorting the array using bubble sort def bubble_sort(length, array): # It takes two arguments -> Length of the array and the array itself. for i in range(length): j = 0 for j in range(0, length-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array #Returns sorted array # This is the main function of the program def main(): length = int(input('Enter the length of the array to be entered : ')) # Taking the length of array array = [int(i) for i in input('Enter Array Elements : ').split()] # Taking array elements sorted_array = bubble_sort(length,array) # Calling the function for sorting the array using bubble sort print("Sorted Array is : ") for i in sorted_array: # Printing the sorted array print(i, end = " ") # Running the main code of the program if __name__ == '__main__': main()
print(type(1)) print(type('runnob')) print(type([2])) print(type({0:'zero'}))
def test(): assert ( len(TRAINING_DATA) == 3 ), "Irgendetwas scheint mit deinen Daten nicht zu stimmen. Erwartet werden 3 Beispiele." assert all( len(entry) == 2 and isinstance(entry[1], dict) for entry in TRAINING_DATA ), "Die Trainingsdaten haben nicht das richtige Format. Erwartet wird eine Liste von Tuples, bestehend aus Text und einem Dictionary als zweites Element." ents = [entry[1].get("entities", []) for entry in TRAINING_DATA] assert len(ents[0]) == 2, "Das erste Beispiel sollte zwei Entitäten enhalten." ent_0_0 = (0, 6, "WEBSITE") ent_0_1 = (11, 18, "WEBSITE") assert ( ents[0][0] == ent_0_0 ), "Überprüfe nochmal die erste Entität im ersten Beispiel." assert ( ents[0][1] == ent_0_1 ), "Überprüfe nochmal die zweite Entität im ersten Beispiel." assert len(ents[1]) == 1, "Das zweite Beispiel sollte eine Entität enthalten." assert ents[1] == [ (28, 35, "WEBSITE",) ], "Überprüfe nochmal die Entität im zweiten Beispiel." assert len(ents[2]) == 1, "Das dritte Beispiel sollte eine Entität enthalten." assert ents[2] == [ (15, 21, "WEBSITE",) ], "Überprüfe nochmal die Entität im dritten Beispiel." __msg__.good("Sehr schön!")
""" Primality testing """ _tiny_primes = [2, 3, 5, 7, 11, 13, 17, 19] _max_tiny_prime = 19 _tiny_primes_set = set(_tiny_primes) def _is_tiny_prime(n): return n <= _max_tiny_prime and n in _tiny_primes_set def _has_tiny_factor(n): for p in _tiny_primes: if n % p == 0: return True return False def _factor_pow2(n): """Factor powers of two from n. Return (s, t), with t odd, such that n = 2**s * t.""" s, t = 0, n while not t & 1: t >>= 1 s += 1 return s, t def _test(n, base): """Miller-Rabin strong pseudoprime test for one base. Return False if n is definitely composite, True if n is probably prime, with a probability greater than 3/4.""" n = int(n) if n < 2: return False s, t = _factor_pow2(n-1) b = pow(base, t, n) if b == 1 or b == n-1: return True else: for j in xrange(1, s): b = (b**2) % n if b == n-1: return True return False def mr(n, bases): """Perform a Miller-Rabin strong pseudoprime test on n using a given list of bases/witnesses. Reference: Richard Crandall & Carl Pomerance (2005), "Prime Numbers: A Computational Perspective", Springer, 2nd edition, 135-138 """ n = int(n) for base in bases: if not _test(n, base): return False return True def mr_safe(n): """For n < 1e16, use the Miller-Rabin test to determine with certainty (unless the code is buggy!) whether n is prime. Reference for the bounds: http://primes.utm.edu/prove/prove2_3.html """ n = int(n) if n < 1373653: return mr(n, [2, 3]) if n < 25326001: return mr(n, [2, 3, 5]) if n < 2152302898747: return mr(n, [2, 3, 5, 7, 11]) if n < 3474749660383: return mr(n, [2, 3, 5, 7, 11, 13]) if n < 341550071728321: return mr(n, [2, 3, 5, 7, 11, 13, 17]) if n < 10000000000000000: return mr(n, [2, 3, 7, 61, 24251]) raise ValueError("n too large") def isprime(n): """ Test whether n is a prime number. Negative primes (e.g. -2) are not considered prime. The function first looks for trivial factors, and if none is found, performs a Miller-Rabin strong pseudoprime test. Example usage ============= >>> isprime(13) True >>> isprime(15) False """ n = int(n) if n < 2: return False if n & 1 == 0: return n == 2 if _is_tiny_prime(n): return True if _has_tiny_factor(n): return False try: return mr_safe(n) except ValueError: # Should be good enough for practical purposes return mr(n, [2,3,5,7,11,13,17,19])
class Solution: def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ result = '' for i in range(0, len(s), 2*k): result += s[i:i+k][::-1] + s[i+k:i+2*k] return result
#Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre #uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite velocidad = float(input("digite a velocidade que o carro esta: ")) if velocidad >80 : velocidad = velocidad-80 multa = velocidad *7 print(" voce ecxedeu o limite de velocidade em {}km/h, o valor da multa é de R${} .".format(velocidad,multa)) else: print("voce esta dentro do limite de velovidade.")
# author: Fei Gao # # Count And Say # # The count-and-say sequence is the sequence of integers beginning as follows: # 1, 11, 21, 1211, 111221, ... # 1 is read off as "one 1" or 11. # 11 is read off as "two 1s" or 21. # 21 is read off as "one 2, then one 1" or 1211. # Given an integer n, generate the nth sequence. # Note: The sequence of integers will be represented as a string. class Solution: # @return a string def countAndSay(self, n): def process(s): l = [] start = 0 for end in range(1, len(s)): if s[end] != s[end-1]: l.append(s[start:end]) start = end l.append(s[start:]) res = '' for ls in l: res += str(len(ls)) + ls[0] return res seq = ['', '1'] for i in range(1, n): seq.append(process(seq[i])) return seq[n] def main(): solver = Solution() for n in range(10): print(n, ': ', solver.countAndSay(n)) pass if __name__ == '__main__': main() pass
file = open('file.txt', 'r') f = file.readlines() readingList = [] for line in f: readingList.append(line.strip()) print(readingList) file.close()
""" Write a Python program to get a single string from two given strings, separated by a space and swap the fisrt two characters of each string sample string: 'abc', 'xyz' expected result: 'xyc abz' """ def swap_char(str1, str2): char1 = str1[0:2] char2 = str2[0:2] str1 = str1.replace(char1, char2) str2 = str2.replace(char2, char1) return str1 + ' ' + str2 print(swap_char("abc", "xyz"))
#right rotation of array #it avoids unnecessary no. of recursions for large no. of rotations. def right_rot(arr,s):# s is the no. of times to rotate n=len(arr) s=s%n #print(s) for a in range(s): store=arr[n-1] for i in range(n-2,-1,-1): arr[i+1]=arr[i] arr[0]=store return(arr) arr = [11,1,2,3,4] s = 1 print(right_rot(arr,s))
""" Continuing from following challenge and using subroutines where appropriate: 1. Create a text file with the following data: James,Jones,01/01/99 Sarah,Smith,12/12/99 Bobby,Ball,04/04/99 Harry.Hall,06/06/99 2. Create a subroutine to ask the user for the name of the file that they wish to read from 3. Use a loop to read and output each line. """ def getFileName(): my_file = input("What is the name of the file you would like to read from?: ") return my_file + ".txt" the_file = getFileName() try: # opens the file fileName = open(the_file, "r") except IOError as e: # the exception is stored in the variable e print("The exception", e, "was raised.") else: fileRead = fileName.readlines() for line in fileRead: print(line, end="") fileName.close()
#Faça um programa que solicite uma senha de acesso do usuário, o sistema deve comparar com a senha “abc123” e:Caso o usuário digite a senha correta, informar “Acesso liberado”, masCaso o usuário digite a senha incorreta, informar “Acesso negado” e perguntar novamente enquanto a senha estiver incorreta. senha_acesso="abc123" senha=input("Informe sua senha\n") while senha!=senha_acesso: print("Acesso negado\n") senha=input("Informe sua senha\n") if senha==senha_acesso: print("Acesso Liberado")
n = 0 try: i = 0 while True: m = input() if m[0] == '+': n += 1 elif m[0] == '-': n -= 1 else: i += (len(m.split(':')[1]) * n) except: pass print(i)
def box(m): m = m.lower() # converting lowercase arr = [0] * len(m) # initializing array with same length as the length i = 0 for n in m: if not ('a' <= n <= 'z'): # excluding special characters continue arr[i] = ord(n) - ord('a') # subtracting ascii character values by a so we can map it to 0-25 i += 1 arr_f = arr[0:i] # array final - to exclude the special character in the array return arr_f def lock(arr_f, y): a = len(arr_f) k = box(y) b = 1 while b < a: # using the loop to make the keys array k.append(k[b - 1]) b += 1 enc = [0] * len(arr_f) # initializing array i = 0 for x in arr_f: enc[i] = (x + k[i]) % 26 # shifting the array to its keys value %26 is for looping from z to a i += 1 enc_f = enc[0:i] return enc_f def unbox(enc_f): m = "" for x in enc_f: m += chr(x + ord('a')) return m def encrypt(m, k): arr = box(m) enc = lock(arr, k) c = unbox(enc) return c def decrypt(c, y): cipher = box(c) a = len(c) k = box(y) b = 1 while b < a: # using the loop to make the keys array k.append(k[b - 1]) b += 1 dec = [0] * len(c) # initializing array i = 0 for x in cipher: dec[i] = (x - k[i]) % 26 # shifting the array to its keys value %26 is for looping from z to a i += 1 dec_f = dec[0:i] plain = unbox(dec_f) return plain def prob(m): a = box(m) b = len(a) arr = [0] * 26 arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.020, 0.061, 0.070, 0.002, 0.008, 0.040, 0.024, 0.067, 0.075, 0.019, 0.001, 0.060, 0.063, 0.091, 0.028, 0.010, 0.023, 0.001, 0.020, 0.001] # arr1 is the probability distribution for general english taken from a study resource (professor's video online) j = 0 while j < 26: #these loops are counting the number of letters in the message ctr = 0 i = 0 while i < b: if a[i] == j: ctr += 1 arr[j] = ctr i += 1 j += 1 k = 0 while k < 26: arr[k] = (arr[k]/b) * (arr1[k]) k += 1 return arr def prob1(m): a = box(m) b = len(a) arr = [0] * 26 arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.020, 0.061, 0.070, 0.002, 0.008, 0.040, 0.024, 0.067, 0.075, 0.019, 0.001, 0.060, 0.063, 0.091, 0.028, 0.010, 0.023, 0.001, 0.020, 0.001] # arr1 is the probability distribution for general english taken from a study resource (professor's video online) j = 0 while j < 26: #these loops are counting the number of letters in the message ctr = 0 i = 0 while i < b: if a[i] == j: ctr += 1 arr[j] = ctr i += 1 j += 1 k = 0 while k < 26: arr[k] = (arr[k]/b) * (arr[k]/b) k += 1 return arr def sum_prob(arr): s = 0 for i in arr: s = s + i return s def seperate(m, size): source = box(m) # putting the message in the array return [source[i::size] for i in range(size)] # (Condensed everything in one line) seperating that array into a nested array of the specified size chunks
# coding=utf-8 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- class Job: def __init__(self, job: dict): self.display_name = job.get("displayName") self.id = job.get("id") self.group = job.get("group") self.status = job.get("status") self.data = job.get("data") self.description = job.get("description") self.batch = job.get("batch") self.cancellation_threshold = job.get("cancellationThreshold")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def grpc_rules_repository(): http_archive( name = "rules_proto_grpc", urls = ["https://github.com/rules-proto-grpc/rules_proto_grpc/archive/2.0.0.tar.gz"], sha256 = "d771584bbff98698e7cb3cb31c132ee206a972569f4dc8b65acbdd934d156b33", strip_prefix = "rules_proto_grpc-2.0.0", )
''' 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 示例: 给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5. 说明: 给定的 n 保证是有效的。 进阶: 你能尝试使用一趟扫描实现吗? ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: if not head: return head dummy = ListNode(0) dummy.next = head first = second = dummy while n + 1: first = first.next while first: first = first.next second = second.next second.next = second.next.next return dummy.next
class Embed: def __init__(self, **kwargs): allowed_args = ("title", "description", "color") for key, value in kwargs.items(): if key in allowed_args: setattr(self, key, value) def set_image(self, *, url: str): self.image = {"url": url} def set_thumbnail(self, *, url: str): self.thumbnail = {"url": url} def set_footer(self, *, text: str, icon_url: str = None): self.footer = {"text": text} if icon_url: self.footer["icon_url"] = icon_url def set_author(self, *, name: str, icon_url: str = None): self.author = {"name": name} if icon_url: self.author["icon_url"] = icon_url def add_field(self, *, name: str, value: str, inline: bool = False): if not hasattr(self, "fields"): self.fields = [] self.fields.append({ "name": name, "value": value, "inline": inline })
a = 7 b = 3 def func1(c,d): e = c + d e += c e *= d return e f = func1(a,b) print (f)
a: str a: bool = True my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA = 1
""" Exercise 1 Write a program to create a list with random data types elements. input l = [0, "hello", 3.14, [1,2,3],{'ime':'John'}] output result = [<class 'int'>, <class 'str'>, <class 'float'>, <class 'list'>, <class 'dict'>] for item in list: # do something """ l = [0, "hello", 3.14, [1,2,3],{'ime':'John'}] print(l) ### your solution here result = [] for item in l: # print(item, type(item)) tip_itema = type(item) result.append(tip_itema) print(result) # print(result) [<class 'int'>, <class 'str'>, <class 'float'>, <class 'list'>, <class 'dict'>] # ali so vsi element različni....
class Edge(object): def __init__(self, u, v, w): self.__orig = u self.__dest = v self.__w = w def getOrig(self): return self.__orig def getDest(self): return self.__dest def getW(self): return self.__w
""" Subtree of Another Tree: Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. https://leetcode.com/problems/subtree-of-another-tree/ """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: return self.traverse(s, t) def traverse(self, s, t): if self.checkSubTreeFunction(s, t) == True: return True if s is None: return False return self.traverse(s.left, t) or self.traverse(s.right, t) def checkSubTreeFunction(self, s, t): if s == None and t == None: return True elif s == None or t == None or s.val != t.val: return False return self.checkSubTreeFunction(s.left, t.left) and self.checkSubTreeFunction(s.right, t.right)
class UltrasonicSensor: def __init__(self, megapi, slot): self._megapi = megapi self._slot = slot self._last_val = 400 def read(self): self._megapi.ultrasonicSensorRead(self._slot, self._on_forward_ultrasonic_read) def get_value(self): return self._last_val def _on_forward_ultrasonic_read(self, val): self._last_val = val
def f(t): # relation between f and t return value def rxn1(C,t): return np.array([f(t)*C0/v-f(t)*C[0]/v-k*C[0], f(t)*C[0]/v-f(t)*C[1]/v-k*C[1]])
#Three Restaurant: class Restaurant(): """A simple attempt to make class restaurant. """ def __init__(self, restaurant_name, cuisine_type): """ This is to initialize name and type of restaurant""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): """ This method describes the Restaurant""" print("Restaurant name :",self.restaurant_name.title()) print("Its Cuisine Type:",self.cuisine_type.title()) def open_restaurant(self): print("The restaurant is open.") restaurant1 = Restaurant('startbucks','coffee') restaurant2 = Restaurant('macdonalds','burger') restaurant3 = Restaurant('meghana','biryani') restaurant1.describe_restaurant() restaurant2.describe_restaurant() restaurant3.describe_restaurant()
name = input("what is your name? ") age = int(input("how old are you {0}? ".format(name))) if (18 <= age < 31): print("welcome to holiday") else: print("you are not 18-30")
"""The code template to supply to the front end. This is what the user will be asked to complete and submit for grading. Do not include any imports. This is not a REPL environment so include explicit 'print' statements for any outputs you want to be displayed back to the user. Use triple single quotes to enclose the formatted code block. """ challenge_code = '''aux = [0, 1] main = 2 all_bits = range(3) dev = qml.device("default.qubit", wires=all_bits) # Part (i) @qml.qnode(dev) def first_approx(t): ################## # YOUR CODE HERE # ################## return qml.state() # Part (ii) @qml.qnode(dev) def second_approx(t): ################## # YOUR CODE HERE # ################## return qml.state() # Part (iii) @qml.qnode(dev) def full_series(t): ################## # YOUR CODE HERE # ################## return qml.state() ################## # HIT SUBMIT FOR # # PLOTTING MAGIC # ################## '''
a,b = map(int,input().split()) def multiply(a,b): return a*b print(multiply(a,b))
class CoordLinkedList: # a linked list object def __init__ (self,node=None,y=None,x=None,up=None,down=None,left=None,right=None): self.up = up self.down = down self.left = left self.right = right if isinstance(node,(list,set,tuple)) and len(node) == 2: self.node = tuple(node) elif x and y: self.node = (y,x) def receive (self,nodes): if not isinstance(nodes,(list,set,tuple)): nodes = {nodes} for n in nodes: if isinstance(n,(tuple)) and len(n) == 2: if n == (self.node[0]-1,self.node[1]): self.up = n elif n == (self.node[0]+1,self.node[1]): self.down = n elif n == (self.node[0],self.node[1]+1): self.right = n elif n == (self.node[0],self.node[1]-1): self.left = n def send(self,nodes=None): if not nodes: nodes = [] returnlist = [] if self.down: returnlist.append(self.down) if self.up: returnlist.append(self.up) if self.left: returnlist.append(self.left) if self.right: returnlist.append(self.right) return [x for x in returnlist if x not in nodes]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: data = [] def traverse(node): if node.left: traverse(node.left) data.append(node.val) if node.right: traverse(node.right) traverse(root) return data[k - 1]
# List custom images def list_custom_images_subparser(subparser): list_images = subparser.add_parser( 'list-custom-images', description=('***List custom' ' saved images of' ' producers/consumers' ' account'), help=('List custom' ' saved images of' ' producers/consumers' ' account')) group_key = list_images.add_mutually_exclusive_group(required=True) group_key.add_argument('-pn', '--producer-username', help="Producer\'s(source account) username") group_key.add_argument('-cn', '--consumer-username', dest='producer_username', metavar='CONSUMER_USERNAME', help="Consumer\'s(destination account) username") group_apikey = list_images.add_mutually_exclusive_group(required=True) group_apikey.add_argument('-pa', '--producer-apikey', help="Producer\'s(source account) apikey") group_apikey.add_argument('-ca', '--consumer-apikey', dest='producer_apikey', metavar='CONSUMER_APIKEY', help="Consumer\'s(destination account) apikey") list_images.add_argument('-u', '--uuid', help="Image ID number")
""" Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix. There's actually a cool trick for this! Feel free to look at the solutions if you can't figure it out. """ data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)) # 0 1 2 # 3 4 5 # 6 7 8 # 9 10 11 # # Transpose : [data]^T # # 0 3 6 9 # 1 4 7 10 # 2 5 8 11 data_transpose = tuple(zip(*data)) print(data) print(data_transpose)
# # @lc app=leetcode id=543 lang=python3 # # [543] Diameter of Binary Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def diameterOfBinaryTree(self, root): self.ans = 0 self.pathfinder(root) return self.ans def pathfinder(self, root): if root is None: return 0 lh = self.pathfinder(root.left) rh = self.pathfinder(root.right) self.ans = max(self.ans, lh + rh) return max(lh, rh) + 1 # @lc code=end
VISUALIZATION_CONFIG = { 'requirements': ['d3', 'datagramas', 'topojson', 'cartogram'], 'visualization_name': 'datagramas.cartogram', 'figure_id': None, 'container_type': 'svg', 'data': { 'geometry': None, 'area_dataframe': None, }, 'options': { }, 'variables': { 'width': 960, 'height': 500, 'padding': {'left': 0, 'top': 0, 'right': 0, 'bottom': 0}, 'feature_id': 'id', 'label': True, 'path_opacity': 1.0, 'path_stroke': 'gray', 'path_stroke_width': 1.0, 'fill_color': 'none', 'area_value': 'value', 'area_feature_name': 'id', 'area_opacity': 0.75, 'area_transition_delay': 0, 'feature_name': None, 'label_font_size': 10, 'label_color': 'black', 'bounding_box': None, 'na_value': 0.000001 }, 'colorables': { 'area_color': {'value': None, 'palette': None, 'scale': None, 'n_colors': None, 'legend': False}, }, 'auxiliary': { 'path', 'projection', 'original_geometry', 'area_colors', 'area_carto_values' } }
class Solution(object): def reconstructQueue(self, people): people.sort(key=lambda x: (-x[0], x[1])) output = [] for p in people: output.insert(p[1], p) return output m = int(input()) k = Solution() array_input = [] for x in range(m): array_input.append([int(y) for y in input().split()]) gh =k.reconstructQueue(array_input) for s in gh: print(*s)
def pent_d(n=1, pents=set()): while True: p_n = n*(3*n - 1)//2 for p in pents: if p_n - p in pents and 2*p - p_n in pents: return 2*p - p_n pents.add(p_n) n += 1 print(pent_d()) # Copyright Junipyr. All rights reserved. # https://github.com/Junipyr
#author: n01 """ This files contains the avaiable number settings for the OptionManager P.S. postpend a _VALUES to avoid confiusion with variable name """ # from constants.lang import LANGS AVAIABLE_TROUPS_VALUES = [10, 20, 30, 40, 50] TURN_LIMIT_VALUES = [25, 50, 75, 100, "∞"] GAMEMODE_VALUES = [0, 1] #World domination - Enemy elimination CONTINENTAL_BONUS_VALUES = [0, 1] #OFF - ON # LANGUAGES_VALUES = LANGS #Alias, case I don't remember
n = int(input()) for i in range(n): vet = list(map(int, input().split())) partida = vet[0] qtd = vet[1] if partida % 2 == 0: partida += 1 soma = 0 for j in range(qtd): soma += partida partida += 2 print(soma)
# Scrapy settings for Scrapy project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'scrapy_demo' SPIDER_MODULES = ['Scrapy.spiders'] # look for spiders here NEWSPIDER_MODULE = 'Scrapy.spiders' # create new spiders here LOG_LEVEL='INFO' # enable following lines for testing --- CLOSESPIDER_PAGECOUNT = 20 # test a few pages # --- # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'Scrapy Demo' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Image pipelin settings IMAGES_EXPIRES = 1 # 1 days of delay for images expiration IMAGES_STORE = './images' # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'scrapy.pipelines.images.ImagesPipeline': 1, 'Scrapy.pipelines.BookPipeline': 300 }