text
stringlengths
37
1.41M
# Code heavily inspired by: # 'Introduction to Monte Carlo Tree Search' # 07 September 2015, Jeff Bradberry # http://jeffbradberry.com/posts/2015/09/intro-to-monte-carlo-tree-search/ # # Adapter for Connect-4 by Maxime Cannoodt & Felix Guo import numpy as np import datetime from random import choice from math import l...
import random import numpy as np from tkinter import * import copy # create array of size m*n, for example: m=10 n=10 array = np.zeros((m,n)) #the first and last rows, and the first and last columns, are only used for boundary conditions #place bombs: 1) each cell contains a bomb with given probability, for example p...
""" Types can be named, for re-use (and readability!) """ from typing import Tuple Coordinate = Tuple[int, int] # Coordinate is a "type alias" def move_northwest(x: int, y: int) -> Coordinate: return x-1, y+1 def move_east(x: int, y: int) -> Coordinate: return x+1, y assert move_northwest(0, 0) == (-1, 1) ...
""" Unions can allow any member of a set of possible types """ from typing import Union Multiplicable = Union[str, int, float] def multiply(value: Multiplicable, factor: int) -> Multiplicable: result = value * factor return result assert multiply(1, 3) == 3 assert multiply("Foo", 3) == "FooFooFoo" assert mul...
def gcd(n1, n2): if n2 > n1: return gcd(n2, n1) if n1 % n2 == 0: return n2 return gcd(n2, n1 % n2) if __name__=="__main__": n1 = input("Enter First Number:") n2 = input("Enter Second Number:") res = gcd(n1,n2) print("GCD of {0} and {1} is - {2}".format(n1, n2, res))
#PROBLEM 27 #Considering quadratics of the form: # n² + an + b, where |a| < 1000 and |b| < 1000 import math def isPrime(num): if num <= 1: return False for i in range(2, int(math.sqrt(num)+1)): if num % i == 0: return False return True highest = [0,0,0] def countPrim...
#6 def squaresum(limit): count = 1 sum = 0 while count <= limit: sum += (count)**2 count += 1 return sum def sumsquare(limit): sum = 1/2 * (limit) * (limit+1) return int(sum**2) print (sumsquare(100) - squaresum(100))
""" AssignmentWriter.py @authors: Group H contains functions for reading images and creating new stegoimages """ from PIL import Image """ A function to convert a given text string to binary """ def userInputToBinary(message): binaryMessage = '' for i in message: binaryMessage += "{0:b}".format(ord(i...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 16:06:26 2018 @author: CJJ """ class BiTNode: def __init__(self): self.data=None self.lchild=None self.rchild=None """ 方法功能:查找值最小的结点 输入参数:root:根结点 返回值:值最小的结点 """ def getMinNode(root): if root==None: return root ...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 12:39:46 2018 @author: CJJ """ from collections import deque class LRU: def __init__(self,cacheSize): self.cacheSize=cacheSize self.queue=deque() self.hashSet=set() # 判断缓存队列是否已满 def isQueueFull(self): return len(self...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 17:13:17 2018 @author: Administrator """ def getMinPath(arr,i,j): #print("i,j",i,j) # 倒着走到了第一个结点,递归结束 if i == 0 and j == 0: print("i",i,"j",j) return arr[i][j] # 选取两条可能路径上的最小值 elif i > 0 and j > 0: if getMinPath(arr, i -...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 12:18:14 2018 @author: Administrator """ class LNode: def __init__(self,x): self.data=x self.next=None # 方法功能:对单链表进行逆序 输入参数:head:链表头结点 def Reverse(head): # 判断链表是否为空 if head == None or head.next == None: return pre = Non...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 16:21:36 2018 @author: CJJ """ def findWithBinary(array,data): if array==None: return False #书中是首字母小写 false # 从二维数组右上角元素开始遍历 i = 0 rows=len(array) columns = len(array[0]) j = columns - 1 while i< rows and j >= 0: # 在数组中...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 12:34:38 2018 @author: CJJ """ class MyStack: # 模拟栈 def __init__(self): self.items= [] # 判断栈是否为空 def isEmpty(self): return len(self.items) ==0 # 返回栈的大小 def size(self): return len(self.items) # 返回栈...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 12:35:22 2018 @author: CJJ """ class LNode: def __new__(self,x): self.data=x self.next=None class MyStack: def __init__(self): # pHead=LNode() self.data=None self.next=None # 判断stack是否为空,如果为空返回true,否则返回false ...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 12:25:10 2018 @author: CJJ """ class LNode: def __new__(self,x): self.data=x self.next=None """ 方法功能:对两个带头结点的单链表所代表的数相加 输入参数:h1:第一个链表头结点;h2:第二个链表头结点 返回值:相加后链表的头结点 """ def add(h1,h2): if h1 is None or h1.next is None: r...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 17:27:24 2018 @author: CJJ """ """ 方法功能:用+=实现加法操作(限制条件:至少有一个非负数) 输入参数:a,b都是整数,且有一个非负数 返回值: a+b """ def add(a,b): if a<0 and b<0: print "无法用+=操作实现" return -1 if b>=0: i=0 while i<b: a +=1 i +=1 ...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 17:17:34 2018 @author: CJJ """ def isPower(n): low=1 high=n while low<high: mid=(low+high)/2 power=mid*mid # 接着在1~mid-1区间查找 if power>n: high=mid-1 # 接着在mid+1到n区间内查找 elif power<n: l...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 16:27:09 2018 @author: CJJ """ class MySet: def __init__(self,mins,maxs): self.mins=mins self.maxs= maxs def getMin(self) : return self.mins def setMin(self,mins): self.mins=mins def ge...
# -*- coding: utf-8 -*- """ Created on Sat Nov 10 16:18:25 2018 @author: CJJ """ class Test: def __init__(self ): self.begin =0 # 记录最大子数组起始位置 self.end = 0 # 记录最大子数组结束位置 def maxSubArray(self,arr): n=len(arr) maxSum = -2**31 # 子数组最大值 nSum = 0 # 包含子数组最后一位的最大值...
def Output(Texto): print(Texto) def Tamanho(Texto): TamanhoTexto = len(Texto) return TamanhoTexto def Maiusculo(Texto): MaiusculoTexto = Texto.upper() return MaiusculoTexto def Minusculo(Texto): MinusculoTexto = Texto.lower() return MinusculoTexto def Contador(Letra,Texto): aux = 0 f...
import numpy as np ficheros = np.random.randint(1,21,6) peticiones = np.random.randint(1,11,6) listaArchivos = "" class Archivo: def __init__(self, l, a): self.longitud = l self.accesos = a self.longitudporaccesos = l/a listaArchivos = [] def crearArray(listaArchivos): for i in rang...
#!/usr/bin/python def front_x(li): all = [] l1 = [] l2 = [] for s in li: if s[0]=="x": l1.append(s) else: l2.append(s) all = sorted(l1) + sorted(l2) return all print front_x(['ba', 'xyz', 'aa', 'x', 'bbb']) print front_x(['a', 'x', 'xy', 'xyx', 'xx']) print front_x...
#!/usr/bin/python def fb(n): str = "" if n%5 == 0: str = str + "Buzz" if n%3 == 0: str = "Fizz" + str return str i = 1 while i <=20: print i, fb(i) i = i + 1
#!/usr/bin/python li=["gutenberg","a","all","alice","project"] def foo(s): return s[-1] def cmp_len(a, b): return cmp(len(a), len(b)) print sorted(li, cmp=cmp_len) print sorted(li, key=len)
def solution(A): A.sort() for num, i in enumerate(A): if i != num + 1: return num + 1 if __name__ == '__main__': assert solution([2, 3, 4, 6]) == 1 assert solution([1, 3]) == 2 assert solution([1, 2, 3, 4, 6]) == 5 assert solution([1, 2, 3, 4, 4]) == 5
class Atm: def __init__(self,cardnumber,pin): self.cardnumber = cardnumber self.pin = pin def check_balance(self): print("Your balance is 50000") def withdrawl(self,new_amount): new_amount = 50000 - amount print("you have withdrawn amount "+str(amount)...
#ECM1414 Continuous Assessment 2021 #Author - Alperen Turkmen import sys from datetime import datetime import json # This class is a node tree class. class NodeTree(object): ''' This class has attributes of: children: a node can have 2 children, left and right. nodes: a node can have 2 children nodes, l...
from random import * words = ('cat', 'dog', 'shark') def get_random_word(wordlist): return list( wordlist[randint(0, len(wordlist))] ) def create_hidden_word(word): hidden_word = [] for char in word: hidden_word.append('-') return hidden_word def update_hidden_word(index, let...
import random from art import logo,vs from game_data import data # from replit import clear print(logo) # compare the followers for a and b def compare_followers(CompareA, AgainstB, user_guess): if CompareA['follower_count'] > AgainstB['follower_count']: more_followers='A' elif CompareA['follower_count'] < ...
from replit import clear #HINT: You can call clear() to clear the output in the console. from art import logo print(logo) def highest_bid(auction): highest=0 winner="" for name in auction: bid_amt=auction[name] if bid_amt > highest: highest=bid_amt winner=name print(f"{winner} is the highes...
## rushhour.py ## Maayez Imam 915342727 import numpy as np import copy from queue import PriorityQueue from queue import Queue # class for the cars, their coordinates on the board, # their placement on the board (horizontal, vertical) # and character of the car # DID NOT END UP USING class Car: def __init__(self,...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Jul 13 20:14:31 2017 @author: adi """ flag = 0 def points(result): global flag global num while flag == 0: flag = 1 num = 0 if result == 1: num = num + 10 elif result == 2: num = num ...
from cs50 import get_int # prompting for number number = get_int("Credit card number: ") # counting the number of digits ndigits = 0 n = number while n != 0: n = int(n / 10) ndigits += 1 # last to second (even) digits digit = 0 multi = 0 multidigit = 0 sumeven = 0 for i in range(1, ndigits, 2): # take ...
import unittest def fibo_1(n): fibo = 0 if n == 1: fibo = 0 elif n == 2: fibo = 1 else: fibo = fibo_1(n-1) + fibo_1(n-2) return fibo def fibo_2(n): fibo = [0, 1] if n < 3: return fibo[n-1] for i in range(3, n+1): fibo.append(fibo[len(fibo)-1] + fibo[len(fibo)-2]) return fibo[len(fibo)-1] def f...
import unittest def method1(unsorted): minus_items = gather_minus(unsorted) plus_items = gather_plus(unsorted) sorted = minus_items + plus_items return sorted def gather_plus(items): plus_items = [item for item in items if item > 0] return plus_items def gather_minus(items): minus_items = [item for item in ...
''' 프로그래머스 소수 찾기 url : https://programmers.co.kr/learn/courses/30/lessons/42839 ''' prime_numbers = [] def is_demical_num(arr): # 소수 판단 함수 num_str = "" for val in arr: if type(val) == str: # solution에서 만들어진 result함수의 [0]제거 num_str += val num = int(num_str...
from utils.trivia import QuestionAnswer, QuestionList, Trivia from utils.lists import load_trivia_questions ## @story{9} def test_QuestionAnswer(): obj = QuestionAnswer("test question", "test answer") assert obj.question == "test question" assert obj.answer == "test answer" ## @story{9} def test_QuestionL...
# -*- coding: utf-8 -*- ''' Author: SunFeng About: course 1: neural network and deeplearning week 3: shallow neural network Programming Assignment: Planar data classfication with a hidden layer Date: 2019/7/26 ''' import numpy as np import matplotlib.pyplot as plt from testCases import * import sklearn i...
from __future__ import annotations from typing import Dict, Any from abc import ABC, abstractmethod import random import uuid import time class Animal(ABC): def __init__(self, power: int, speed: int): self.id = None self.max_power = power self.current_power = power self.speed = spe...
from math import sqrt print("Giải phương trình bậc 2") a= float(input("Nhập a:")) b= float(input("Nhập b:")) c= float(input("Nhập c:")) if a == 0: if b == 0 and c == 0: print("Vô số nghiệm") elif b==0 and c!=0: print("Vô nghiệm") else: x=-c/b print("No x", x) else: delta...
toan = float(input("Nhập điểm toán:")) ly = float(input("Nhập điểm lý:")) hoa = float(input("Nhập điểm hóa:")) dtb = (toan+ly+hoa)/3 print("Điểm trung binh=", round(dtb,2))
# Given a sorted array of strings which is interspersed with empty strings, write a method to find the location of a given string. #Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”, “dad”, “”, “”] will return 4 #Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”...
print("Selamat datang di rollercoaster Kami!") tinggi = int(input("Berapakah tinggi anda dalam cm? ")) tiket = 0 if tinggi >= 120: print("Anda bisa menaiki rollercoaster!") usia = int(input("Berapa usia anda? ")) if usia < 12: tiket = 5000 print("Tiket anak-anak adalah Rp.5000.") elif usia <= 18: t...
#### Random Module #### import random # Integer number acak antara 1 hingga 3 random_Integer = random.randint(1, 3) print(random_Integer) # Float Number acak menggunakan random.random() randomFloat = random.random() * 5 print(f"Ini adalah float number acak >>> {randomFloat}") # Love score menggunakan integer rando...
n = int(input("Enter n: ")) for i in range(n): #Controls lines for j in range(n-i-1): #Controlds spaces print(" ",end='') for k in range(i+1): #Controls stars print("*",end='') print() #Going to the next line #Easier way of doing this :) #for i in range(n): # print(" "*(n-i-1) + "*"*(i+1))
x = int(input("Enter an integer: ")) summ = 0 counter = 0 while (x != -1): summ += x counter += 1 x = int(input("Enter an integer: ")) print("Sum is : %d\tAverage is : %.2f" %(summ,(summ/counter)))
#Python 3 Solution #We get user's age age = int(input("Enter your age:").strip()) #Compare the age of the user to 50 if(age < 50): print("You are under 50") elif(age > 50): print("You are over 50") else: #Since there are no posibilities than user being 50, it okay to use else print("You are 50")
""" akkapop prasompon 640631128 quiz 14 - quiz 16 """ ############# ## quiz 14 ## ############# import numpy as np from scipy.linalg import solve A = np.array([[1,2],[3,4]]) B = np.array([1,4]) x = solve(A , B) print(x) ############# ## quiz 15 ## ############# M = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) pr...
'''Search functions''' import os def search_files(directory='.', extension=''): '''Search for files with a given extension in a certain directory, recursively''' all_files = [] extension = extension.lower() for dirpath, _, files in os.walk(directory): for name in files: if extens...
class SpanningMixin(object): """Provides methods for checking whether an entity which has a defined start and end point over a single dimension contains or overlaps with another entity in that same dimension. """ def __contains__(self, i): """Tests for point inclusion, `start <= i <= e...
import random class Thief: sneaky = True def __init__(self, name, sneaky=True, **kwargs): self.name = name self.sneaky = sneaky for key, value in kwargs.items(): setattr(self, key, value) def pickpoket(self): if self.sneaky: return bool(random.ra...
import requests import json import datetime from IataCode import IataCode class Query(): # Set attributes to parameters needed for API call, # then use attributes for the call def __init__(self): """Initialize Query object""" print("Welcome to my flight search application\n") # At...
#Iterate 0 to 10 using for loop, do the same using while loop. #using for loop print("iterate using for loop :") for i in range(0,11): print(i,end=" ") print() print() print() #using while loop i=0 a=10 print("iterate using while loop :") while i<=a: print(i,end=" ") i+=1
######################################################################## # Jason Baumbach # # Classifier: # K-Nearest Neighbor (KNN) # # Note: this code is available on GitHub # https://github.com/jatlast/Classifier/ # sub directory KNN/KNN.py # #########################################...
num = [] for i in range(1,1000): if i % 3 == 0 or i % 5 == 0: num.append(i) print "The sum all the multiples of 3 or 5 below 1000 is ", sum(num)
''' 이진 탐색하기 - binary search 알고리즘 문제를 풀다 보면 이진 탐색1 을 써야할 때가 많습니다. 이런 문제를 풀 때마다 이진 탐색 알고리즘을 작성하는 건 비효율적이지요. 이번 시간엔 Python의 이진 탐색 모듈, bisect를 알아봅시다. 다른 언어에서는..(또는 이 기능을 모르시는 분은) 직접 반복문을 만들어, 이진 탐색 알고리즘을 구현합니다. ''' def bisect(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if h...
"""#The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python #NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers""" import operator import numpy as n...
from .base import Foundation class Measure(Foundation): """ An instance of this class is a measure on a given set `supp`. The support is either + a python variable of type `set`, or + a list of tuples which represents a box in euclidean space. Initializes a measure object according...
import time import timeit import itertools from functools import lru_cache NUMBER_OF_ELEMENTS = 1000 NUMBER_OF_LOOPS = 3 def expensive_function(value): time.sleep(value / (NUMBER_OF_ELEMENTS * NUMBER_OF_ELEMENTS)) def non_expensive_function(value): return value + 1 def bad_cache_testing(number_of_loops):...
#Lee-Roy Dobson Week 9 Work jellyBeans = raw_input('Input your jellybeans[r][g]: ') def countColour(beans, returnval): red = 0 green = 0 for colour in beans: if colour.lower() == 'r': red += 1 elif colour.lower() == 'g': green += 1 if returnval == 'red': ...
#!/usr/bin/env python # encoding: utf-8 import urllib import re import time import cPickle as pickle import os.path import sys # Oystein Kapperud, 2015 """ OBS: NOTE THAT THIS PROGRAM WAS WRITTEN FOR PYTHON 2.7 TO RUN PY.TEST TESTS AND DOCTESTS: RUN THE SCRIPT weather_test.py LIKE AN ORDINARY PYTHON SCRIPT FROM THE ...
while True: value = input('please input:\n') try: print(float(value)) except ValueError: print(ValueError) if value == 'ok': break
#!/usr/bin/python3 """the module make request from Reddits API""" import requests def top_ten(subreddit): """the function prints the titles of the first 10 hot posts""" url = 'https://www.reddit.com/r/{}/.json'.format(subreddit) header = {'User-Agent': 'Reddit API test'} response = requests.get(url, h...
def input(): a=raw_input("enter a") b=raw_input("enter b") return a, b def area(): int a,int b = input(); print(a, b) c=a*b;
a,b = 1,2 # single condition if a == 1: print('a is equal to 1') else: print('a is not equal to 1') # multiple condition if a < b and b > a: print('success') else: print('False') if a < b or b > a: print('success') else: print('False')
# Functions - Assigns a set of code or variables (known as parameters) to a single call or name # Define - Notifies python of impending function definition def example(): x = 1 y = 3 print (x+y) if x < y: print(x,'is less than',y) example() # Most commonly to execute the whole script is the following def main(...
""" String Rotation: Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, S1 and S2, write code to check if S2 is a rotation of S1 using only one call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). Hints: #34, #88, #104 """ from collections ...
class Node: def __init__(self, data): self.data = data self.next = None def append_to_tail(self, data): end_node = Node(data) node = self while(node.next != None): node = node.next node.next = end_node class linkedlist: def __init__(self, ...
#opdracht Python oefening 3 #getal in voorbeeld wordt maal 1 gedaan en geprint, de print wordt genomen en maal 2 gedaan, die print wordt genomen en maal 3 gedaan enz. #getal*1 7*2 14*3 enz. startGetal = int(input("Geef een getal in:")) aantalGetallenOpScherm = int(input("Geef het aantal weer te geven getalen in:")) afd...
# jumhek 14 agustus 2020 # Beban untuk keledai def convertToInt(payload): item = [] for i in payload: item.append(int(i)) return item def main(payload): item = payload.split( ) intItem = convertToInt(item) # check min and max length item if len(intItem) < 2 or len(intItem) > ...
#problem 6 d = dict() for i in range(1,4): name = input("Enter name : ") usn = input("Enter usn :") d[usn] = name print(d)
"""This program will crawl through files in a given directory finding and replacing text in each file """ import os import time # Main function def start(): """This program does bulk find/replace in text Files. All function calls are in if statements. When a user wants to return to the main program conti...
<<<<<<< HEAD def allindex(list,a): i = 0 re =[] for x in list: if x == a: re.append(i) i +=1 return re lis = [1,2,3,1,4,2,1] print(allindex(lis,1)) def func(*args): for arg in args: print(arg) func(1) func(1,2,3,4,5) def funcc(a,*argss): print(a,end=" ") ...
class Board: """create a prepopulated Sudoku game board""" def __init__(self): self._board = [ [1, 'X', 'X', 9, 'X', 4, 'X', 8, 2], ['X', 5, 2, 6, 8, 'X', 3, 'X', 'X'], [8, 6, 4, 2, 'X', 'X', 9, 1, 'X'], ['X', 1, 'X', 'X', 4, 9, 8, 'X', 6], ...
# Implements a self-selecting multilayer perceptron for multiclass classification # Notation used mostly follows Andrew Ng's deeplearning.ai course # Author: Ryan Kingery (rkinger@g.clemson.edu) # Last Updated: April 2018 # License: BSD 3 clause #!/usr/bin/env python2 # -*- coding: utf-8 -*- import os import numpy as...
# Problem 3: Largest prime factor import itertools def is_prime(num): if num == 1: return False for i in itertools.count(2): if num == i: break if num % i == 0: return False return True def largest_prime_factor(num): start = int(num ** 0.5) + 1 if start % 2 == 0: start -= 1 fo...
##Agricola Data class player: item_list = ["Fields", "Pastures", "Grain", "Vegetables", "Sheep", "Wild Boar", "Cattle", "Unused Spaces", "Fenced Stables", "Clay Hut Rooms", "Stone House Rooms", "Family Members", "Points for Cards", "Bonus Points"] def __init__(self, name): ...
class Solution: def findMinStep(self, board, hand): """ :type board: str :type hand: str :rtype: int """ def DFS(board,hand): #print(board,hand) if (len(board)==0): return 0 if (len(hand)==0): return -1 resul...
class Solution: def catMouseGame(self, graph): """ :type graph: List[List[int]] :rtype: int """ N = len(graph) color = [[[0]*3 for _ in range(N)] for _ in range(N)] q = collections.deque() for i in range(1,N): for t in r...
import tkinter import tkinter.messagebox import random import sqlite3 from datetime import datetime class Combination: def __init__(self): alphabet = self.addChars() newList = self.addChars() self.shuffle(newList) combination = self.makeDict(alphabet, ne...
class ChessPiece(object): def __init__(self, color, x, y): """This method initiliaze chess piece attributes (color and position). Parameters ---------- color : string Color of chess piece. x : int Location x of chess piece. y : int ...
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) TRIG1 = 16 ECHO1 = 18 TRIG2 = 26 ECHO2= 24 GPIO.setup(TRIG1,GPIO.OUT) GPIO.setup(TRIG2,GPIO.OUT) GPIO.output(TRIG1, 0) GPIO.output(TRIG2, 0) GPIO.setup(ECHO1, GPIO.IN) GPIO.setup(ECHO2, GPIO.IN) time.sleep(0.1) def obstructionDetection(): GPIO.setu...
# Implementation of the Palindrome ADT using a singly linked list. class Palindrome : # Creates an empty stack. def __init__( self ): self._top = None self._size = 0 # Returns True if the stack is empty or False otherwise. def isEmpty( self ): return self._top is None # Re...
# -*- coding: utf-8 -*- """ Created on Tue Dec 22 22:44:29 2020 @author: Lenovo """ print('\nВведите целое положительное число:') a=int(input()) max_dig=0 while a>0: max_dig=max(max_dig,a%10) a=a//10 print('Максимальная цифра: {0}'.format(max_dig))
#!/usr/bin/env python3 ''' Trabalho Pratico 1: Inteligência Artificial Autor: Hugo Araujo de Sousa (2013007463) BestFirst.py: Best first search. ''' from GraphSearch import GraphSearch from heapq import * from Node import Node class BestFirst(GraphSearch): def __init__(self, initial, goal, problem_map): ''' ...
with open("input") as file: program = [] for line in file: op, arg = line.split() program.append((op, int(arg))) def execute(program): """ execute the given program. returns an (acc, reason) tuple. acc is the value of the accumulator. reason is either 'loop' or 'suc...
""" Вам дана последовательность строк. Выведите строки, содержащие "cat" в качестве подстроки хотя бы два раза. Примечание: Считать все строки по одной из стандартного потока ввода вы можете, например, так import sys for line in sys.stdin: line = line.rstrip() # process line """ import sys import re pattern=...
val = input() val = int(val) s = 0 for i in range(1, val + 1): s += i print(s)
# PLOTTING (with matplotlib) import matplotlib.pyplot as plt import random ''' plt.figure(1) # creates a new window plt.plot([1, 2, 4, 4]) # plots y and x against the index plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) # plot(x_data, y_data) plt.figure(2) # make a second window x1 = [x for x in range(1, 101)] y1 = [y ...
import re # This function takes in a line of text and returns # a list of words in the line. from typing import List def split_line(line): return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line) ''' Complete the following 3 searching problems using techniques from class and from Ch15 of the textbook website ''' #1...
class Category: # create the constuctor with parameters: name and balance def __init__(self,name, balance): self.name = name self.balance = balance # create deposit() method def deposit(self , d ): self.balance = self.balance + d # create withdrawal method ...
import datetime name = input("What is your username? \n") allowedUsers = ['Seyi', 'Mike', 'Love'] allowedPassword = ['passwordSeyi', 'passwordMike', 'passwordLove'] Current_Date = datetime.datetime.today() if(name in allowedUsers): password = input("Your password? \n") userId = allowedUsers.index(name) ...
# In[0]: Importa as bibliotecas # -*- coding: utf-8 -*- import pandas as pd import os import matplotlib.pyplot as plt # In[1]: Lê o arquivo df = pd.read_csv('../dados/viagens.csv') # In[2]: Trata os dados def dataAnalyze(par): #Define os valores como string dfe = par.astype(str) aux = {} aux['a...
# magic 8 ball import random, time answers = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", ...
api_key = "18a6aa9fb9dda14a3d31836e84eced7f" web = "http://api.openweathermap.org/data/2.5/weather?" import numpy as np import requests, json # api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key} def forecast(): api_key = "18a6aa9fb9dda14a3d31836e84eced7f" web = "http://api.openwea...
from abc import ABC, abstractmethod class Command(ABC): @abstractmethod def execute()-> None: pass @abstractmethod def unexecute()-> None: pass class Document(): def __init__(self): self.text = "" def getText(self): return self.text def insertText...
from abc import ABC, abstractmethod from math import floor class Handler(ABC): @abstractmethod def set_next(self): pass @abstractmethod def handle(self): pass class AbstractHandler(Handler): _next_handler: Handler = None def set_next(self, handler: Handler) -> Handler: ...
# Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) my_dict={} for i in range(n): key,val= list(map(str,input().split())) my_dict[key]=val try: while True: q=input() if q in my_dict: print("{}={}".format(q,my_dict[q])) else: ...
import textract import PyPDF2 def read_pdf(file_name: str = '') -> str: """ Reader for .pdf files :param file_name: file name :return: text from a file """ pdf_reader = PyPDF2.PdfFileReader(file_name) page_obj = pdf_reader.getPage(0) raw_text = page_obj.extractText() return raw_tex...